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": "ns', ($window, permissions) ->\n VISIBILITY_KEY ='hypothesis.visibility'\n VISIBILITY_PUBLIC = 'public'\n VISIBILITY_PRIV",
"end": 103,
"score": 0.993683397769928,
"start": 82,
"tag": "KEY",
"value": "hypothesis.visibility"
},
{
"context": " cookies and local storage\n # https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/loc",
"end": 623,
"score": 0.9989673495292664,
"start": 614,
"tag": "USERNAME",
"value": "Modernizr"
},
{
"context": "rage/localstorage.js\n storage = do ->\n key = 'hypothesis.testKey'\n try\n $window.localStorage.setItem key,",
"end": 733,
"score": 0.971416175365448,
"start": 715,
"tag": "KEY",
"value": "hypothesis.testKey"
}
] | h/static/scripts/directives/privacy.coffee | Treora/h | 0 | privacy = ['$window', 'permissions', ($window, permissions) ->
VISIBILITY_KEY ='hypothesis.visibility'
VISIBILITY_PUBLIC = 'public'
VISIBILITY_PRIVATE = 'private'
levels = [
{name: VISIBILITY_PUBLIC, text: 'Public'}
{name: VISIBILITY_PRIVATE, text: 'Only Me'}
]
getLevel = (name) ->
for level in levels
if level.name == name
return level
undefined
isPublic = (level) -> level == VISIBILITY_PUBLIC
# Detection is needed because we run often as a third party widget and
# third party storage blocking often blocks cookies and local storage
# https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
storage = do ->
key = 'hypothesis.testKey'
try
$window.localStorage.setItem key, key
$window.localStorage.removeItem key
$window.localStorage
catch
memoryStorage = {}
getItem: (key) ->
if key of memoryStorage then memoryStorage[key] else null
setItem: (key, value) ->
memoryStorage[key] = value
removeItem: (key) ->
delete memoryStorage[key]
link: (scope, elem, attrs, controller) ->
return unless controller?
controller.$formatters.push (selectedPermissions) ->
return unless selectedPermissions?
if permissions.isPublic(selectedPermissions)
getLevel(VISIBILITY_PUBLIC)
else
getLevel(VISIBILITY_PRIVATE)
controller.$parsers.push (privacy) ->
return unless privacy?
if isPublic(privacy.name)
newPermissions = permissions.public()
else
newPermissions = permissions.private()
# Cannot change the $modelValue into a new object
# Just update its properties
for key,val of newPermissions
controller.$modelValue[key] = val
controller.$modelValue
controller.$render = ->
unless controller.$modelValue.read?.length
name = storage.getItem VISIBILITY_KEY
name ?= VISIBILITY_PUBLIC
level = getLevel(name)
controller.$setViewValue level
scope.level = controller.$viewValue
scope.levels = levels
scope.setLevel = (level) ->
storage.setItem VISIBILITY_KEY, level.name
controller.$setViewValue level
controller.$render()
scope.isPublic = isPublic
require: '?ngModel'
restrict: 'E'
scope: {}
templateUrl: 'privacy.html'
]
angular.module('h')
.directive('privacy', privacy)
| 17904 | privacy = ['$window', 'permissions', ($window, permissions) ->
VISIBILITY_KEY ='<KEY>'
VISIBILITY_PUBLIC = 'public'
VISIBILITY_PRIVATE = 'private'
levels = [
{name: VISIBILITY_PUBLIC, text: 'Public'}
{name: VISIBILITY_PRIVATE, text: 'Only Me'}
]
getLevel = (name) ->
for level in levels
if level.name == name
return level
undefined
isPublic = (level) -> level == VISIBILITY_PUBLIC
# Detection is needed because we run often as a third party widget and
# third party storage blocking often blocks cookies and local storage
# https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
storage = do ->
key = '<KEY>'
try
$window.localStorage.setItem key, key
$window.localStorage.removeItem key
$window.localStorage
catch
memoryStorage = {}
getItem: (key) ->
if key of memoryStorage then memoryStorage[key] else null
setItem: (key, value) ->
memoryStorage[key] = value
removeItem: (key) ->
delete memoryStorage[key]
link: (scope, elem, attrs, controller) ->
return unless controller?
controller.$formatters.push (selectedPermissions) ->
return unless selectedPermissions?
if permissions.isPublic(selectedPermissions)
getLevel(VISIBILITY_PUBLIC)
else
getLevel(VISIBILITY_PRIVATE)
controller.$parsers.push (privacy) ->
return unless privacy?
if isPublic(privacy.name)
newPermissions = permissions.public()
else
newPermissions = permissions.private()
# Cannot change the $modelValue into a new object
# Just update its properties
for key,val of newPermissions
controller.$modelValue[key] = val
controller.$modelValue
controller.$render = ->
unless controller.$modelValue.read?.length
name = storage.getItem VISIBILITY_KEY
name ?= VISIBILITY_PUBLIC
level = getLevel(name)
controller.$setViewValue level
scope.level = controller.$viewValue
scope.levels = levels
scope.setLevel = (level) ->
storage.setItem VISIBILITY_KEY, level.name
controller.$setViewValue level
controller.$render()
scope.isPublic = isPublic
require: '?ngModel'
restrict: 'E'
scope: {}
templateUrl: 'privacy.html'
]
angular.module('h')
.directive('privacy', privacy)
| true | privacy = ['$window', 'permissions', ($window, permissions) ->
VISIBILITY_KEY ='PI:KEY:<KEY>END_PI'
VISIBILITY_PUBLIC = 'public'
VISIBILITY_PRIVATE = 'private'
levels = [
{name: VISIBILITY_PUBLIC, text: 'Public'}
{name: VISIBILITY_PRIVATE, text: 'Only Me'}
]
getLevel = (name) ->
for level in levels
if level.name == name
return level
undefined
isPublic = (level) -> level == VISIBILITY_PUBLIC
# Detection is needed because we run often as a third party widget and
# third party storage blocking often blocks cookies and local storage
# https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
storage = do ->
key = 'PI:KEY:<KEY>END_PI'
try
$window.localStorage.setItem key, key
$window.localStorage.removeItem key
$window.localStorage
catch
memoryStorage = {}
getItem: (key) ->
if key of memoryStorage then memoryStorage[key] else null
setItem: (key, value) ->
memoryStorage[key] = value
removeItem: (key) ->
delete memoryStorage[key]
link: (scope, elem, attrs, controller) ->
return unless controller?
controller.$formatters.push (selectedPermissions) ->
return unless selectedPermissions?
if permissions.isPublic(selectedPermissions)
getLevel(VISIBILITY_PUBLIC)
else
getLevel(VISIBILITY_PRIVATE)
controller.$parsers.push (privacy) ->
return unless privacy?
if isPublic(privacy.name)
newPermissions = permissions.public()
else
newPermissions = permissions.private()
# Cannot change the $modelValue into a new object
# Just update its properties
for key,val of newPermissions
controller.$modelValue[key] = val
controller.$modelValue
controller.$render = ->
unless controller.$modelValue.read?.length
name = storage.getItem VISIBILITY_KEY
name ?= VISIBILITY_PUBLIC
level = getLevel(name)
controller.$setViewValue level
scope.level = controller.$viewValue
scope.levels = levels
scope.setLevel = (level) ->
storage.setItem VISIBILITY_KEY, level.name
controller.$setViewValue level
controller.$render()
scope.isPublic = isPublic
require: '?ngModel'
restrict: 'E'
scope: {}
templateUrl: 'privacy.html'
]
angular.module('h')
.directive('privacy', privacy)
|
[
{
"context": "dminConfig =\n name: 'Dashboard'\n adminEmails: ['maxim@jssolutionsdev.com']\n collections:\n Activities: {}\n Companies",
"end": 76,
"score": 0.9999241828918457,
"start": 52,
"tag": "EMAIL",
"value": "maxim@jssolutionsdev.com"
}
] | app/lib/admin-panel.coffee | JSSolutions-Academy/Team-A | 0 | @AdminConfig =
name: 'Dashboard'
adminEmails: ['maxim@jssolutionsdev.com']
collections:
Activities: {}
Companies: {}
Invitations: {}
| 47342 | @AdminConfig =
name: 'Dashboard'
adminEmails: ['<EMAIL>']
collections:
Activities: {}
Companies: {}
Invitations: {}
| true | @AdminConfig =
name: 'Dashboard'
adminEmails: ['PI:EMAIL:<EMAIL>END_PI']
collections:
Activities: {}
Companies: {}
Invitations: {}
|
[
{
"context": "r templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ\n\n templateData: # Specify some s",
"end": 599,
"score": 0.9598326683044434,
"start": 594,
"tag": "USERNAME",
"value": "bevry"
},
{
"context": "\"\n\n # The website author's name\n author: \"Your Name\"\n\n # The website author's email\n email: \"",
"end": 1422,
"score": 0.9944345355033875,
"start": 1413,
"tag": "NAME",
"value": "Your Name"
},
{
"context": "\"\n\n # The website author's email\n email: \"your@email.com\"\n\n # Your company's name\n copyright: \"© Y",
"end": 1486,
"score": 0.9999070167541504,
"start": 1472,
"tag": "EMAIL",
"value": "your@email.com"
}
] | docpad.coffee | me6iaton/docapp-ghpages-test | 0 | # The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON
docpadConfig =
# =================================
# Paths Configuration
# Root Path
# The root path of our our project
databaseCache: false
regenerateDelay: 100
# logLevel: 9
catchExceptions: false
growl: false
# skipUnsupportedPlugins: false
# enabledUnlistedPlugins: true
# enabledPlugins:
# docpad: true
# Template Data
# =============
# These are variables that will be accessible via our templates
# To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ
templateData: # Specify some site properties
site: # The production url of our website
url: "http://me6iaton.github.io/docapp-ghpages-test"
# Here are some old site urls that you would like to redirect from
# oldUrls: ['www.website.com', 'website.herokuapp.com']
# The default title of our website
title: "Your Website"
# The website description (for SEO)
description: """
When your website appears in search results in say Google, the text here will be shown underneath your website's title.
"""
# The website keywords (for SEO) separated by commas
keywords: """
place, your, website, keywoards, here, keep, them, related, to, the, content, of, your, website
"""
# The website author's name
author: "Your Name"
# The website author's email
email: "your@email.com"
# Your company's name
copyright: "© Your Company 2013"
# Helper Functions
# ----------------
# Get the prepared site/document title
# Often we would like to specify particular formatting to our page's title
# we can apply that formatting here
getPreparedTitle: ->
# if we have a document title, then we should use that and suffix the site's title onto it
if @document.title
"#{@document.title} | #{@site.title}"
# if our document does not have it's own title, then we should just use the site's title
else
@site.title
# Get the prepared site/document description
getPreparedDescription: ->
# if we have a document description, then we should use that, otherwise use the site's description
@document.description or @site.description
# Get the prepared site/document keywords
getPreparedKeywords: ->
# Merge the document keywords with the site keywords
@site.keywords.concat(@document.keywords or []).join(', ')
# Collections
# ===========
# These are special collections that our website makes available to us
collections: # For instance, this one will fetch in all documents that have pageOrder set within their meta data
pages: (database) ->
database.findAllLive({
pageOrder:
$exists: true
}, [pageOrder: 1, title: 1])
# This one, will fetch in all documents that will be outputted to the posts directory
posts: (database) ->
database.findAllLive({relativeOutDirPath: 'posts'}, [date: -1])
# DocPad Events
# =============
# Here we can define handlers for events that DocPad fires
# You can find a full listing of events on the DocPad Wiki
events:
# Generate After
# generateAfter: ->
# emitter = require('events')
# emitter.emit 'generateAfter', 'test'
# debugger
# Server Extend
# Used to add our own custom routes to the server before the docpad routes are added
serverExtend: (opts) ->
# Extract the server from the options
{server} = opts
docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it
latestConfig = docpad.getConfig()
oldUrls = latestConfig.templateData.site.oldUrls or []
newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url
server.use (req, res, next) ->
if req.headers.host in oldUrls
res.redirect 301, newUrl + req.url
else
next() # Export our DocPad Configuration
# Plugins configurations
plugins:
ghpages:
deployRemote: 'deploy'
deployBranch: 'gh-pages'
environment: 'static'
livereload:
inject: false
environments:
production:
enabled: false
# Environments
# =================================
environments:
production:
templateData:
site:
url: 'http://localhost:9778'
module.exports = docpadConfig
| 41524 | # The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON
docpadConfig =
# =================================
# Paths Configuration
# Root Path
# The root path of our our project
databaseCache: false
regenerateDelay: 100
# logLevel: 9
catchExceptions: false
growl: false
# skipUnsupportedPlugins: false
# enabledUnlistedPlugins: true
# enabledPlugins:
# docpad: true
# Template Data
# =============
# These are variables that will be accessible via our templates
# To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ
templateData: # Specify some site properties
site: # The production url of our website
url: "http://me6iaton.github.io/docapp-ghpages-test"
# Here are some old site urls that you would like to redirect from
# oldUrls: ['www.website.com', 'website.herokuapp.com']
# The default title of our website
title: "Your Website"
# The website description (for SEO)
description: """
When your website appears in search results in say Google, the text here will be shown underneath your website's title.
"""
# The website keywords (for SEO) separated by commas
keywords: """
place, your, website, keywoards, here, keep, them, related, to, the, content, of, your, website
"""
# The website author's name
author: "<NAME>"
# The website author's email
email: "<EMAIL>"
# Your company's name
copyright: "© Your Company 2013"
# Helper Functions
# ----------------
# Get the prepared site/document title
# Often we would like to specify particular formatting to our page's title
# we can apply that formatting here
getPreparedTitle: ->
# if we have a document title, then we should use that and suffix the site's title onto it
if @document.title
"#{@document.title} | #{@site.title}"
# if our document does not have it's own title, then we should just use the site's title
else
@site.title
# Get the prepared site/document description
getPreparedDescription: ->
# if we have a document description, then we should use that, otherwise use the site's description
@document.description or @site.description
# Get the prepared site/document keywords
getPreparedKeywords: ->
# Merge the document keywords with the site keywords
@site.keywords.concat(@document.keywords or []).join(', ')
# Collections
# ===========
# These are special collections that our website makes available to us
collections: # For instance, this one will fetch in all documents that have pageOrder set within their meta data
pages: (database) ->
database.findAllLive({
pageOrder:
$exists: true
}, [pageOrder: 1, title: 1])
# This one, will fetch in all documents that will be outputted to the posts directory
posts: (database) ->
database.findAllLive({relativeOutDirPath: 'posts'}, [date: -1])
# DocPad Events
# =============
# Here we can define handlers for events that DocPad fires
# You can find a full listing of events on the DocPad Wiki
events:
# Generate After
# generateAfter: ->
# emitter = require('events')
# emitter.emit 'generateAfter', 'test'
# debugger
# Server Extend
# Used to add our own custom routes to the server before the docpad routes are added
serverExtend: (opts) ->
# Extract the server from the options
{server} = opts
docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it
latestConfig = docpad.getConfig()
oldUrls = latestConfig.templateData.site.oldUrls or []
newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url
server.use (req, res, next) ->
if req.headers.host in oldUrls
res.redirect 301, newUrl + req.url
else
next() # Export our DocPad Configuration
# Plugins configurations
plugins:
ghpages:
deployRemote: 'deploy'
deployBranch: 'gh-pages'
environment: 'static'
livereload:
inject: false
environments:
production:
enabled: false
# Environments
# =================================
environments:
production:
templateData:
site:
url: 'http://localhost:9778'
module.exports = docpadConfig
| true | # The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON
docpadConfig =
# =================================
# Paths Configuration
# Root Path
# The root path of our our project
databaseCache: false
regenerateDelay: 100
# logLevel: 9
catchExceptions: false
growl: false
# skipUnsupportedPlugins: false
# enabledUnlistedPlugins: true
# enabledPlugins:
# docpad: true
# Template Data
# =============
# These are variables that will be accessible via our templates
# To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ
templateData: # Specify some site properties
site: # The production url of our website
url: "http://me6iaton.github.io/docapp-ghpages-test"
# Here are some old site urls that you would like to redirect from
# oldUrls: ['www.website.com', 'website.herokuapp.com']
# The default title of our website
title: "Your Website"
# The website description (for SEO)
description: """
When your website appears in search results in say Google, the text here will be shown underneath your website's title.
"""
# The website keywords (for SEO) separated by commas
keywords: """
place, your, website, keywoards, here, keep, them, related, to, the, content, of, your, website
"""
# The website author's name
author: "PI:NAME:<NAME>END_PI"
# The website author's email
email: "PI:EMAIL:<EMAIL>END_PI"
# Your company's name
copyright: "© Your Company 2013"
# Helper Functions
# ----------------
# Get the prepared site/document title
# Often we would like to specify particular formatting to our page's title
# we can apply that formatting here
getPreparedTitle: ->
# if we have a document title, then we should use that and suffix the site's title onto it
if @document.title
"#{@document.title} | #{@site.title}"
# if our document does not have it's own title, then we should just use the site's title
else
@site.title
# Get the prepared site/document description
getPreparedDescription: ->
# if we have a document description, then we should use that, otherwise use the site's description
@document.description or @site.description
# Get the prepared site/document keywords
getPreparedKeywords: ->
# Merge the document keywords with the site keywords
@site.keywords.concat(@document.keywords or []).join(', ')
# Collections
# ===========
# These are special collections that our website makes available to us
collections: # For instance, this one will fetch in all documents that have pageOrder set within their meta data
pages: (database) ->
database.findAllLive({
pageOrder:
$exists: true
}, [pageOrder: 1, title: 1])
# This one, will fetch in all documents that will be outputted to the posts directory
posts: (database) ->
database.findAllLive({relativeOutDirPath: 'posts'}, [date: -1])
# DocPad Events
# =============
# Here we can define handlers for events that DocPad fires
# You can find a full listing of events on the DocPad Wiki
events:
# Generate After
# generateAfter: ->
# emitter = require('events')
# emitter.emit 'generateAfter', 'test'
# debugger
# Server Extend
# Used to add our own custom routes to the server before the docpad routes are added
serverExtend: (opts) ->
# Extract the server from the options
{server} = opts
docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it
latestConfig = docpad.getConfig()
oldUrls = latestConfig.templateData.site.oldUrls or []
newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url
server.use (req, res, next) ->
if req.headers.host in oldUrls
res.redirect 301, newUrl + req.url
else
next() # Export our DocPad Configuration
# Plugins configurations
plugins:
ghpages:
deployRemote: 'deploy'
deployBranch: 'gh-pages'
environment: 'static'
livereload:
inject: false
environments:
production:
enabled: false
# Environments
# =================================
environments:
production:
templateData:
site:
url: 'http://localhost:9778'
module.exports = docpadConfig
|
[
{
"context": " cb(0)\n\n return process\n )\n\n email = \"deploy@nrt.io\"\n Git.setEmail(email).then(->\n try\n setE",
"end": 2446,
"score": 0.999918520450592,
"start": 2433,
"tag": "EMAIL",
"value": "deploy@nrt.io"
}
] | server/test/units/git.coffee | unepwcmc/NRT | 0 | assert = require('chai').assert
sinon = require 'sinon'
Git = require '../../lib/git'
CommandRunner = require '../../lib/command_runner'
suite('Git')
test('createTag creates a new tag for the given name and description', (done)->
newTagName = "fancy-banana"
newDescription = "Fancy Banana"
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
process =
on: (event, cb) ->
if event is 'close'
cb(0)
return process
)
Git.createTag(newTagName, newDescription).then(->
try
createTagCall = spawnStub.firstCall
assert.isNotNull createTagCall, "Expected a process to be spawn"
createTagArgs = createTagCall.args
assert.strictEqual(
"git",
createTagArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"tag",
"-a",
"-m",
"'#{newDescription}'",
"#{newTagName}"
]
assert.deepEqual createTagArgs[1], expectedGitArgs,
"""
Expected the git to be called with #{expectedGitArgs},
but called with #{createTagArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.push pushes the given item', (done)->
tagName = "fancy-banana"
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
process =
on: (event, cb) ->
if event is 'close'
cb(0)
return process
)
Git.push(tagName).then(->
try
pushCall = spawnStub.firstCall
assert.isNotNull pushCall, "Expected a process to be spawned"
pushTagArgs = pushCall.args
assert.strictEqual(
"git",
pushTagArgs[0],
"Expected push task to spawn a git command"
)
expectedGitArgs = [
"push",
"origin",
"#{tagName}"
]
assert.deepEqual pushTagArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{pushTagArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('setEmail sets the git user email config', (done)->
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
process =
on: (event, cb) ->
if event is 'close'
cb(0)
return process
)
email = "deploy@nrt.io"
Git.setEmail(email).then(->
try
setEmailCall = spawnStub.firstCall
assert.isNotNull setEmailCall, "Expected a process to be spawned"
setEmailArgs = setEmailCall.args
assert.strictEqual(
"git",
setEmailArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"config",
"user.email",
"'#{email}'"
]
assert.deepEqual setEmailArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{setEmailArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.fetch runs git fetch', (done)->
tagName = 'corporate-banana'
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
return {
on: (event, cb) ->
if event is 'close'
cb(0)
}
)
Git.fetch().then(->
try
fetchCall = spawnStub.firstCall
assert.isNotNull fetchCall, "Expected a process to be spawned"
gitFetchArgs = fetchCall.args
assert.strictEqual(
"git",
gitFetchArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"fetch"
]
assert.deepEqual gitFetchArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{gitFetchArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.checkout checkouts the given tag', (done)->
tagName = 'corporate-banana'
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
return {
on: (event, cb) ->
if event is 'close'
cb(0)
}
)
Git.checkout(tagName).then(->
try
fetchCall = spawnStub.firstCall
assert.isNotNull fetchCall, "Expected a process to be spawned"
gitFetchArgs = fetchCall.args
assert.strictEqual(
"git",
gitFetchArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"checkout",
tagName
]
assert.deepEqual gitFetchArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{gitFetchArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.checkout rejects with an error if it fails', (done) ->
tagName = 'corporate-banana'
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
return {
on: (event, cb) ->
if event is 'close'
cb(1)
}
)
Git.checkout(tagName).then(->
spawnStub.restore()
done(new Error("Expected command to fail"))
).catch((err)->
try
assert.strictEqual err.constructor.name, "Error",
"Expect checkout to reject with an error"
assert.strictEqual err.message, "Failed to checkout tag #{tagName}"
done()
catch assertErr
done(assertErr)
finally
spawnStub.restore()
)
)
| 173250 | assert = require('chai').assert
sinon = require 'sinon'
Git = require '../../lib/git'
CommandRunner = require '../../lib/command_runner'
suite('Git')
test('createTag creates a new tag for the given name and description', (done)->
newTagName = "fancy-banana"
newDescription = "Fancy Banana"
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
process =
on: (event, cb) ->
if event is 'close'
cb(0)
return process
)
Git.createTag(newTagName, newDescription).then(->
try
createTagCall = spawnStub.firstCall
assert.isNotNull createTagCall, "Expected a process to be spawn"
createTagArgs = createTagCall.args
assert.strictEqual(
"git",
createTagArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"tag",
"-a",
"-m",
"'#{newDescription}'",
"#{newTagName}"
]
assert.deepEqual createTagArgs[1], expectedGitArgs,
"""
Expected the git to be called with #{expectedGitArgs},
but called with #{createTagArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.push pushes the given item', (done)->
tagName = "fancy-banana"
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
process =
on: (event, cb) ->
if event is 'close'
cb(0)
return process
)
Git.push(tagName).then(->
try
pushCall = spawnStub.firstCall
assert.isNotNull pushCall, "Expected a process to be spawned"
pushTagArgs = pushCall.args
assert.strictEqual(
"git",
pushTagArgs[0],
"Expected push task to spawn a git command"
)
expectedGitArgs = [
"push",
"origin",
"#{tagName}"
]
assert.deepEqual pushTagArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{pushTagArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('setEmail sets the git user email config', (done)->
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
process =
on: (event, cb) ->
if event is 'close'
cb(0)
return process
)
email = "<EMAIL>"
Git.setEmail(email).then(->
try
setEmailCall = spawnStub.firstCall
assert.isNotNull setEmailCall, "Expected a process to be spawned"
setEmailArgs = setEmailCall.args
assert.strictEqual(
"git",
setEmailArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"config",
"user.email",
"'#{email}'"
]
assert.deepEqual setEmailArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{setEmailArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.fetch runs git fetch', (done)->
tagName = 'corporate-banana'
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
return {
on: (event, cb) ->
if event is 'close'
cb(0)
}
)
Git.fetch().then(->
try
fetchCall = spawnStub.firstCall
assert.isNotNull fetchCall, "Expected a process to be spawned"
gitFetchArgs = fetchCall.args
assert.strictEqual(
"git",
gitFetchArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"fetch"
]
assert.deepEqual gitFetchArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{gitFetchArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.checkout checkouts the given tag', (done)->
tagName = 'corporate-banana'
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
return {
on: (event, cb) ->
if event is 'close'
cb(0)
}
)
Git.checkout(tagName).then(->
try
fetchCall = spawnStub.firstCall
assert.isNotNull fetchCall, "Expected a process to be spawned"
gitFetchArgs = fetchCall.args
assert.strictEqual(
"git",
gitFetchArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"checkout",
tagName
]
assert.deepEqual gitFetchArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{gitFetchArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.checkout rejects with an error if it fails', (done) ->
tagName = 'corporate-banana'
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
return {
on: (event, cb) ->
if event is 'close'
cb(1)
}
)
Git.checkout(tagName).then(->
spawnStub.restore()
done(new Error("Expected command to fail"))
).catch((err)->
try
assert.strictEqual err.constructor.name, "Error",
"Expect checkout to reject with an error"
assert.strictEqual err.message, "Failed to checkout tag #{tagName}"
done()
catch assertErr
done(assertErr)
finally
spawnStub.restore()
)
)
| true | assert = require('chai').assert
sinon = require 'sinon'
Git = require '../../lib/git'
CommandRunner = require '../../lib/command_runner'
suite('Git')
test('createTag creates a new tag for the given name and description', (done)->
newTagName = "fancy-banana"
newDescription = "Fancy Banana"
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
process =
on: (event, cb) ->
if event is 'close'
cb(0)
return process
)
Git.createTag(newTagName, newDescription).then(->
try
createTagCall = spawnStub.firstCall
assert.isNotNull createTagCall, "Expected a process to be spawn"
createTagArgs = createTagCall.args
assert.strictEqual(
"git",
createTagArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"tag",
"-a",
"-m",
"'#{newDescription}'",
"#{newTagName}"
]
assert.deepEqual createTagArgs[1], expectedGitArgs,
"""
Expected the git to be called with #{expectedGitArgs},
but called with #{createTagArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.push pushes the given item', (done)->
tagName = "fancy-banana"
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
process =
on: (event, cb) ->
if event is 'close'
cb(0)
return process
)
Git.push(tagName).then(->
try
pushCall = spawnStub.firstCall
assert.isNotNull pushCall, "Expected a process to be spawned"
pushTagArgs = pushCall.args
assert.strictEqual(
"git",
pushTagArgs[0],
"Expected push task to spawn a git command"
)
expectedGitArgs = [
"push",
"origin",
"#{tagName}"
]
assert.deepEqual pushTagArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{pushTagArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('setEmail sets the git user email config', (done)->
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
process =
on: (event, cb) ->
if event is 'close'
cb(0)
return process
)
email = "PI:EMAIL:<EMAIL>END_PI"
Git.setEmail(email).then(->
try
setEmailCall = spawnStub.firstCall
assert.isNotNull setEmailCall, "Expected a process to be spawned"
setEmailArgs = setEmailCall.args
assert.strictEqual(
"git",
setEmailArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"config",
"user.email",
"'#{email}'"
]
assert.deepEqual setEmailArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{setEmailArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.fetch runs git fetch', (done)->
tagName = 'corporate-banana'
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
return {
on: (event, cb) ->
if event is 'close'
cb(0)
}
)
Git.fetch().then(->
try
fetchCall = spawnStub.firstCall
assert.isNotNull fetchCall, "Expected a process to be spawned"
gitFetchArgs = fetchCall.args
assert.strictEqual(
"git",
gitFetchArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"fetch"
]
assert.deepEqual gitFetchArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{gitFetchArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.checkout checkouts the given tag', (done)->
tagName = 'corporate-banana'
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
return {
on: (event, cb) ->
if event is 'close'
cb(0)
}
)
Git.checkout(tagName).then(->
try
fetchCall = spawnStub.firstCall
assert.isNotNull fetchCall, "Expected a process to be spawned"
gitFetchArgs = fetchCall.args
assert.strictEqual(
"git",
gitFetchArgs[0],
"Expected deploy task to spawn a git command"
)
expectedGitArgs = [
"checkout",
tagName
]
assert.deepEqual gitFetchArgs[1], expectedGitArgs,
"""
Expected git to be called with #{expectedGitArgs},
but called with #{gitFetchArgs}"""
done()
catch e
done(e)
finally
spawnStub.restore()
).catch((err)->
spawnStub.restore()
done(err)
)
)
test('.checkout rejects with an error if it fails', (done) ->
tagName = 'corporate-banana'
spawnStub = sinon.stub(CommandRunner, 'spawn', ->
return {
on: (event, cb) ->
if event is 'close'
cb(1)
}
)
Git.checkout(tagName).then(->
spawnStub.restore()
done(new Error("Expected command to fail"))
).catch((err)->
try
assert.strictEqual err.constructor.name, "Error",
"Expect checkout to reject with an error"
assert.strictEqual err.message, "Failed to checkout tag #{tagName}"
done()
catch assertErr
done(assertErr)
finally
spawnStub.restore()
)
)
|
[
{
"context": "#\n# HTML/XML highlighter\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\nColorifier.html = Colorifier.xml = new Class Co",
"end": 65,
"score": 0.9998811483383179,
"start": 48,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | src/lang/html.coffee | MadRabbit/colorifier | 1 | #
# HTML/XML highlighter
#
# Copyright (C) 2011 Nikolay Nemshilov
#
Colorifier.html = Colorifier.xml = new Class Colorifier,
comments: "<!-- -->"
paint: (text, callback)->
text = @_comments(text)
text = @_embedded(text)
text = @_strings(text)
text = @_tags(text)
text = callback.call(@, text) if callback
@_rollback(text)
# protected
# painting embedded javascript/css
_embedded: (text)->
@___ or= []
tokens = @___
text = text.replace /(<script.*?>)([\s\S]*?)(<\/script>)/ig, (m, _1, _2, _3)->
tokens.push(js.paint(_2))
"#{_1}___dummy_#{tokens.length}___#{_3}"
text = text.replace /(<style.*?>)([\s\S]+?)(<\/style>)/ig, (m, _1, _2, _3)->
tokens.push(css.paint(_2))
"#{_1}___dummy_#{tokens.length}___#{_3}"
text
# painting the tags and attributes
_tags: (text)->
@_prepare(text, [
[/(<[\/]*)([a-z]+)/ig, "keyword", "$1 "],
[/(\s+)([a-z_\-]+)(=)/ig, "float", "$1 $3"]
])
js = new Colorifier.js()
css = new Colorifier.css()
| 1056 | #
# HTML/XML highlighter
#
# Copyright (C) 2011 <NAME>
#
Colorifier.html = Colorifier.xml = new Class Colorifier,
comments: "<!-- -->"
paint: (text, callback)->
text = @_comments(text)
text = @_embedded(text)
text = @_strings(text)
text = @_tags(text)
text = callback.call(@, text) if callback
@_rollback(text)
# protected
# painting embedded javascript/css
_embedded: (text)->
@___ or= []
tokens = @___
text = text.replace /(<script.*?>)([\s\S]*?)(<\/script>)/ig, (m, _1, _2, _3)->
tokens.push(js.paint(_2))
"#{_1}___dummy_#{tokens.length}___#{_3}"
text = text.replace /(<style.*?>)([\s\S]+?)(<\/style>)/ig, (m, _1, _2, _3)->
tokens.push(css.paint(_2))
"#{_1}___dummy_#{tokens.length}___#{_3}"
text
# painting the tags and attributes
_tags: (text)->
@_prepare(text, [
[/(<[\/]*)([a-z]+)/ig, "keyword", "$1 "],
[/(\s+)([a-z_\-]+)(=)/ig, "float", "$1 $3"]
])
js = new Colorifier.js()
css = new Colorifier.css()
| true | #
# HTML/XML highlighter
#
# Copyright (C) 2011 PI:NAME:<NAME>END_PI
#
Colorifier.html = Colorifier.xml = new Class Colorifier,
comments: "<!-- -->"
paint: (text, callback)->
text = @_comments(text)
text = @_embedded(text)
text = @_strings(text)
text = @_tags(text)
text = callback.call(@, text) if callback
@_rollback(text)
# protected
# painting embedded javascript/css
_embedded: (text)->
@___ or= []
tokens = @___
text = text.replace /(<script.*?>)([\s\S]*?)(<\/script>)/ig, (m, _1, _2, _3)->
tokens.push(js.paint(_2))
"#{_1}___dummy_#{tokens.length}___#{_3}"
text = text.replace /(<style.*?>)([\s\S]+?)(<\/style>)/ig, (m, _1, _2, _3)->
tokens.push(css.paint(_2))
"#{_1}___dummy_#{tokens.length}___#{_3}"
text
# painting the tags and attributes
_tags: (text)->
@_prepare(text, [
[/(<[\/]*)([a-z]+)/ig, "keyword", "$1 "],
[/(\s+)([a-z_\-]+)(=)/ig, "float", "$1 $3"]
])
js = new Colorifier.js()
css = new Colorifier.css()
|
[
{
"context": "meta:\n name: \"shiptag\"\n version: \"2018/12/27/02\"\n\ndata:\n mapname: [\n ",
"end": 22,
"score": 0.687608540058136,
"start": 15,
"tag": "NAME",
"value": "shiptag"
}
] | fcd/shiptag.cson | Flourite/poi | 0 | meta:
name: "shiptag"
version: "2018/12/27/02"
data:
mapname: [
"E1"
"E2"
"E2"
"E3"
]
color: [
"#9E9E9E"
"#569E44"
"#03A9F4"
"#FFEA00"
]
fleetname:
"zh-CN": [
"鼠输送部队"
"拉包尔舰队"
"联合舰队"
"布因派遣队"
]
"zh-TW": [
"鼠輸送部隊"
"拉包爾艦隊"
"聯合艦隊"
"布因派遣隊"
]
"ja-JP": [
"鼠輸送部隊"
"ラバウル艦隊"
"連合艦隊"
"ブイン派遣隊"
]
"en-US": [
"Rat Transportation Force"
"Rabaul Fleet"
"Combined Fleet"
"Buin Deployment Fleet"
]
| 55266 | meta:
name: "<NAME>"
version: "2018/12/27/02"
data:
mapname: [
"E1"
"E2"
"E2"
"E3"
]
color: [
"#9E9E9E"
"#569E44"
"#03A9F4"
"#FFEA00"
]
fleetname:
"zh-CN": [
"鼠输送部队"
"拉包尔舰队"
"联合舰队"
"布因派遣队"
]
"zh-TW": [
"鼠輸送部隊"
"拉包爾艦隊"
"聯合艦隊"
"布因派遣隊"
]
"ja-JP": [
"鼠輸送部隊"
"ラバウル艦隊"
"連合艦隊"
"ブイン派遣隊"
]
"en-US": [
"Rat Transportation Force"
"Rabaul Fleet"
"Combined Fleet"
"Buin Deployment Fleet"
]
| true | meta:
name: "PI:NAME:<NAME>END_PI"
version: "2018/12/27/02"
data:
mapname: [
"E1"
"E2"
"E2"
"E3"
]
color: [
"#9E9E9E"
"#569E44"
"#03A9F4"
"#FFEA00"
]
fleetname:
"zh-CN": [
"鼠输送部队"
"拉包尔舰队"
"联合舰队"
"布因派遣队"
]
"zh-TW": [
"鼠輸送部隊"
"拉包爾艦隊"
"聯合艦隊"
"布因派遣隊"
]
"ja-JP": [
"鼠輸送部隊"
"ラバウル艦隊"
"連合艦隊"
"ブイン派遣隊"
]
"en-US": [
"Rat Transportation Force"
"Rabaul Fleet"
"Combined Fleet"
"Buin Deployment Fleet"
]
|
[
{
"context": "###\ncas-analyser.coffee\n\nCopyright (c) 2015 Jeongbin Park\n\nGNU General Public License\n\nThis program is free",
"end": 57,
"score": 0.9997098445892334,
"start": 44,
"tag": "NAME",
"value": "Jeongbin Park"
}
] | coffee/miseq-analyzer.coffee | Gue-ho/Be_Analyzer | 0 | ###
cas-analyser.coffee
Copyright (c) 2015 Jeongbin Park
GNU General Public License
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
pri_len = 15 # Constant
s_seq = ''
seq_range = ''
joins_length = 0
seq_count = {}
pri_for_patterns = []
pri_back_patterns = []
set_primer_patterns = (_pri_for_patterns, _pri_back_patterns) ->
pri_for_patterns = _pri_for_patterns
pri_back_patterns = _pri_back_patterns
empty_cache = ->
joins_length = 0
seq_count = {}
return
process_chunk = (seqs) ->
for seq in seqs
flag_for = 0
flag_back = 0
for pattern in pri_for_patterns
pattern = new RegExp(pattern)
m = pattern.exec(seq)
if m
start_pos = m.index
flag_for = 1
for pattern in pri_back_patterns
pattern = new RegExp(pattern)
m = pattern.exec(seq)
if m
end_pos = m.index
flag_back = 1
if flag_for and flag_back
cut_seq = seq[start_pos...(end_pos+pri_len)]
if cut_seq.length == 0
postMessage(msgtype: 1, error: "Indicator sequences are found in wrong position. Please try another R value for this sample.")
if cut_seq of seq_count
seq_count[cut_seq] += 1
else
seq_count[cut_seq] = 1
joins_length += 1
return
parse_file = (file, pgcallback, chunkcallback) ->
seq_list = []
bufsize = 10000
gzipped = 0
if file.name.split('.').pop() == 'gz'
gzipped = 1
f = new jbfilereadersync(file, gzipped)
linecnt = 0
line = f.readline()
while line.length > 0
if linecnt %% 4 == 1
seq_list.push(line)
if seq_list.length == bufsize
chunkcallback(seq_list)
seq_list = []
if linecnt %% 1000 == 0
pgcallback(f.fpos*100/f.filesize)
line = f.readline()
linecnt += 1
if seq_list.length > 0
chunkcallback(seq_list)
pgcallback(f.fpos*100/f.filesize)
return
revcompstr = (s) ->
l = s.split('').reverse()
for i in [0...l.length] by 1
if l[i] == 'A'
l[i] = 'T'
else if l[i] == 'T'
l[i] = 'A'
else if l[i] == 'G'
l[i] = 'C'
else if l[i] == 'C'
l[i] = 'G'
else if l[i] == 'a'
l[i] = 't'
else if l[i] == 't'
l[i] = 'a'
else if l[i] == 'g'
l[i] = 'c'
else if l[i] == 'c'
l[i] = 'g'
return l.join('')
run_cas_analyser = (seq_range, seq_hdr, filt_n, filt_r, pgcallback)->
tot_results = []
mut_results = []
count_seqs = []
totlr_count = 0
tot_count = 0
length_range = seq_range.length
n = Object.keys(seq_count).length//20
i = 0
for seq of seq_count
if !seq_count.hasOwnProperty(seq)
continue
item_cnt = seq_count[seq]
totlr_count += item_cnt
if item_cnt > filt_n
count_seqs.push( {"seq": seq, "count": item_cnt} )
tot_count += item_cnt
if i % n == 0
pgcallback(i/Object.keys(seq_count).length*50)
i += 1
pgcallback(50)
query_cnt = 0
compare = (a, b) ->
if (a.count < b.count)
return 1
if (a.count > b.count)
return -1
return 0
count_seqs.sort(compare)
data = {table: [], il: [], dl: [], is: [], ds: [], hdr: 0}
cnt_hdr = 0
cnt_ins = 0
cnt_del = 0
dscnt = 1
iscnt = 1
re_gap = /-+/g
for i in [0..seq_range.length] by 1
data.il.push( [i, 0] )
data.dl.push( [i, 0] )
n = count_seqs.length // 20
for i in [0...count_seqs.length] by 1
if (count_seqs[i].seq.length == 0)
continue
entry = []
p = needle(seq_range, count_seqs[i].seq, 10, 0.5, 10, 0.5)
entry[0] = i + 1
entry[1] = p[0]
entry[2] = p[2]
entry[3] = p[1]
entry[4] = count_seqs[i].seq.length
entry[5] = count_seqs[i].count
if seq_range.length == entry[4]
entry[6] = 0 # WT
else
if filt_r > 0 and s_seq != '' and count_seqs[i].seq.indexOf(s_seq) > 0
entry[6] = 0
else
if entry[4] > seq_range.length
entry[6] = 1 # Insertion
cnt_ins += entry[5]
else
entry[6] = 2 # Deletion
cnt_del += entry[5]
if seq_hdr == ''
entry[7] = -2
else
entry[7] = count_seqs[i].seq.indexOf(seq_hdr)
if entry[7] > 0
cnt_hdr += entry[5]
data.table.push(entry)
cpos = 0
if entry[6] == 1
loop
m = re_gap.exec(entry[1])
if m
gap = m[0]
if data.is.length < gap.length
for j in [0..gap.length - data.is.length] by 1
data.is.push([iscnt++, 0])
data.is[gap.length-1][1] += count_seqs[i].count
else
break
for j in [0..entry[1].length - 1] by 1
if entry[1][j] != '-'
cpos += 1
if cpos >= seq_range.length
break
if entry[1][j+1] == '-'
data.il[cpos][1] += count_seqs[i].count
else if entry[6] == 2
loop
m = re_gap.exec(entry[2])
if m
gap = m[0]
if data.ds.length < gap.length
for j in [0..gap.length - data.ds.length] by 1
data.ds.push([dscnt++, 0])
data.ds[gap.length-1][1] += count_seqs[i].count
else
break
for j in [0..entry[1].length] by 1
if entry[2][j] == '-'
data.dl[cpos][1] += count_seqs[i].count
if entry[1][j] != '-'
cpos += 1
if i % n == 0
pgcallback(50+50*i/(count_seqs.length-1))
for i in [0..seq_range.length] by 1
data.il[i][1] /= tot_count
data.dl[i][1] /= tot_count
data.il[i][1] *= 100
data.dl[i][1] *= 100
data.hdr = cnt_hdr
data.joins_length = joins_length
data.totlr_count = totlr_count
data.tot_count = tot_count
data.cnt_ins = cnt_ins
data.cnt_del = cnt_del
pgcallback(100)
return data
parse_joined = ->
reader = new FileReader()
chunksize = 1024*1024*10
noncomplete_line = ''
fpos = 0
fstep = 200
nline = 0
feof = 0
getchunk = ->
if fpos >= joinedfile.size
feof = 1
readline()
if fpos + chunksize >= joinedfile.size
endpos = joinedfile.size
else
endpos = fpos + chunksize
blob = joinedfile.slice(fpos, endpos)
fpos += endpos - fpos
reader.readAsText(blob)
reader.onload = ->
chunk_lines = reader.result.replace(/\r\n|\n\r|\r/, '\n').split('\n')
chunk_lines[0] = noncomplete_line + chunk_lines[0]
noncomplete_line = chunk_lines[chunk_lines.length-1]
chunk_lines = chunk_lines[...chunk_lines.length-1]
readline()
readline = ->
if nline >= chunk_lines.length
if feof
return ''
else
getchunk()
return
return chunk_lines[nline++]
line = readline()
| 92568 | ###
cas-analyser.coffee
Copyright (c) 2015 <NAME>
GNU General Public License
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
pri_len = 15 # Constant
s_seq = ''
seq_range = ''
joins_length = 0
seq_count = {}
pri_for_patterns = []
pri_back_patterns = []
set_primer_patterns = (_pri_for_patterns, _pri_back_patterns) ->
pri_for_patterns = _pri_for_patterns
pri_back_patterns = _pri_back_patterns
empty_cache = ->
joins_length = 0
seq_count = {}
return
process_chunk = (seqs) ->
for seq in seqs
flag_for = 0
flag_back = 0
for pattern in pri_for_patterns
pattern = new RegExp(pattern)
m = pattern.exec(seq)
if m
start_pos = m.index
flag_for = 1
for pattern in pri_back_patterns
pattern = new RegExp(pattern)
m = pattern.exec(seq)
if m
end_pos = m.index
flag_back = 1
if flag_for and flag_back
cut_seq = seq[start_pos...(end_pos+pri_len)]
if cut_seq.length == 0
postMessage(msgtype: 1, error: "Indicator sequences are found in wrong position. Please try another R value for this sample.")
if cut_seq of seq_count
seq_count[cut_seq] += 1
else
seq_count[cut_seq] = 1
joins_length += 1
return
parse_file = (file, pgcallback, chunkcallback) ->
seq_list = []
bufsize = 10000
gzipped = 0
if file.name.split('.').pop() == 'gz'
gzipped = 1
f = new jbfilereadersync(file, gzipped)
linecnt = 0
line = f.readline()
while line.length > 0
if linecnt %% 4 == 1
seq_list.push(line)
if seq_list.length == bufsize
chunkcallback(seq_list)
seq_list = []
if linecnt %% 1000 == 0
pgcallback(f.fpos*100/f.filesize)
line = f.readline()
linecnt += 1
if seq_list.length > 0
chunkcallback(seq_list)
pgcallback(f.fpos*100/f.filesize)
return
revcompstr = (s) ->
l = s.split('').reverse()
for i in [0...l.length] by 1
if l[i] == 'A'
l[i] = 'T'
else if l[i] == 'T'
l[i] = 'A'
else if l[i] == 'G'
l[i] = 'C'
else if l[i] == 'C'
l[i] = 'G'
else if l[i] == 'a'
l[i] = 't'
else if l[i] == 't'
l[i] = 'a'
else if l[i] == 'g'
l[i] = 'c'
else if l[i] == 'c'
l[i] = 'g'
return l.join('')
run_cas_analyser = (seq_range, seq_hdr, filt_n, filt_r, pgcallback)->
tot_results = []
mut_results = []
count_seqs = []
totlr_count = 0
tot_count = 0
length_range = seq_range.length
n = Object.keys(seq_count).length//20
i = 0
for seq of seq_count
if !seq_count.hasOwnProperty(seq)
continue
item_cnt = seq_count[seq]
totlr_count += item_cnt
if item_cnt > filt_n
count_seqs.push( {"seq": seq, "count": item_cnt} )
tot_count += item_cnt
if i % n == 0
pgcallback(i/Object.keys(seq_count).length*50)
i += 1
pgcallback(50)
query_cnt = 0
compare = (a, b) ->
if (a.count < b.count)
return 1
if (a.count > b.count)
return -1
return 0
count_seqs.sort(compare)
data = {table: [], il: [], dl: [], is: [], ds: [], hdr: 0}
cnt_hdr = 0
cnt_ins = 0
cnt_del = 0
dscnt = 1
iscnt = 1
re_gap = /-+/g
for i in [0..seq_range.length] by 1
data.il.push( [i, 0] )
data.dl.push( [i, 0] )
n = count_seqs.length // 20
for i in [0...count_seqs.length] by 1
if (count_seqs[i].seq.length == 0)
continue
entry = []
p = needle(seq_range, count_seqs[i].seq, 10, 0.5, 10, 0.5)
entry[0] = i + 1
entry[1] = p[0]
entry[2] = p[2]
entry[3] = p[1]
entry[4] = count_seqs[i].seq.length
entry[5] = count_seqs[i].count
if seq_range.length == entry[4]
entry[6] = 0 # WT
else
if filt_r > 0 and s_seq != '' and count_seqs[i].seq.indexOf(s_seq) > 0
entry[6] = 0
else
if entry[4] > seq_range.length
entry[6] = 1 # Insertion
cnt_ins += entry[5]
else
entry[6] = 2 # Deletion
cnt_del += entry[5]
if seq_hdr == ''
entry[7] = -2
else
entry[7] = count_seqs[i].seq.indexOf(seq_hdr)
if entry[7] > 0
cnt_hdr += entry[5]
data.table.push(entry)
cpos = 0
if entry[6] == 1
loop
m = re_gap.exec(entry[1])
if m
gap = m[0]
if data.is.length < gap.length
for j in [0..gap.length - data.is.length] by 1
data.is.push([iscnt++, 0])
data.is[gap.length-1][1] += count_seqs[i].count
else
break
for j in [0..entry[1].length - 1] by 1
if entry[1][j] != '-'
cpos += 1
if cpos >= seq_range.length
break
if entry[1][j+1] == '-'
data.il[cpos][1] += count_seqs[i].count
else if entry[6] == 2
loop
m = re_gap.exec(entry[2])
if m
gap = m[0]
if data.ds.length < gap.length
for j in [0..gap.length - data.ds.length] by 1
data.ds.push([dscnt++, 0])
data.ds[gap.length-1][1] += count_seqs[i].count
else
break
for j in [0..entry[1].length] by 1
if entry[2][j] == '-'
data.dl[cpos][1] += count_seqs[i].count
if entry[1][j] != '-'
cpos += 1
if i % n == 0
pgcallback(50+50*i/(count_seqs.length-1))
for i in [0..seq_range.length] by 1
data.il[i][1] /= tot_count
data.dl[i][1] /= tot_count
data.il[i][1] *= 100
data.dl[i][1] *= 100
data.hdr = cnt_hdr
data.joins_length = joins_length
data.totlr_count = totlr_count
data.tot_count = tot_count
data.cnt_ins = cnt_ins
data.cnt_del = cnt_del
pgcallback(100)
return data
parse_joined = ->
reader = new FileReader()
chunksize = 1024*1024*10
noncomplete_line = ''
fpos = 0
fstep = 200
nline = 0
feof = 0
getchunk = ->
if fpos >= joinedfile.size
feof = 1
readline()
if fpos + chunksize >= joinedfile.size
endpos = joinedfile.size
else
endpos = fpos + chunksize
blob = joinedfile.slice(fpos, endpos)
fpos += endpos - fpos
reader.readAsText(blob)
reader.onload = ->
chunk_lines = reader.result.replace(/\r\n|\n\r|\r/, '\n').split('\n')
chunk_lines[0] = noncomplete_line + chunk_lines[0]
noncomplete_line = chunk_lines[chunk_lines.length-1]
chunk_lines = chunk_lines[...chunk_lines.length-1]
readline()
readline = ->
if nline >= chunk_lines.length
if feof
return ''
else
getchunk()
return
return chunk_lines[nline++]
line = readline()
| true | ###
cas-analyser.coffee
Copyright (c) 2015 PI:NAME:<NAME>END_PI
GNU General Public License
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
pri_len = 15 # Constant
s_seq = ''
seq_range = ''
joins_length = 0
seq_count = {}
pri_for_patterns = []
pri_back_patterns = []
set_primer_patterns = (_pri_for_patterns, _pri_back_patterns) ->
pri_for_patterns = _pri_for_patterns
pri_back_patterns = _pri_back_patterns
empty_cache = ->
joins_length = 0
seq_count = {}
return
process_chunk = (seqs) ->
for seq in seqs
flag_for = 0
flag_back = 0
for pattern in pri_for_patterns
pattern = new RegExp(pattern)
m = pattern.exec(seq)
if m
start_pos = m.index
flag_for = 1
for pattern in pri_back_patterns
pattern = new RegExp(pattern)
m = pattern.exec(seq)
if m
end_pos = m.index
flag_back = 1
if flag_for and flag_back
cut_seq = seq[start_pos...(end_pos+pri_len)]
if cut_seq.length == 0
postMessage(msgtype: 1, error: "Indicator sequences are found in wrong position. Please try another R value for this sample.")
if cut_seq of seq_count
seq_count[cut_seq] += 1
else
seq_count[cut_seq] = 1
joins_length += 1
return
parse_file = (file, pgcallback, chunkcallback) ->
seq_list = []
bufsize = 10000
gzipped = 0
if file.name.split('.').pop() == 'gz'
gzipped = 1
f = new jbfilereadersync(file, gzipped)
linecnt = 0
line = f.readline()
while line.length > 0
if linecnt %% 4 == 1
seq_list.push(line)
if seq_list.length == bufsize
chunkcallback(seq_list)
seq_list = []
if linecnt %% 1000 == 0
pgcallback(f.fpos*100/f.filesize)
line = f.readline()
linecnt += 1
if seq_list.length > 0
chunkcallback(seq_list)
pgcallback(f.fpos*100/f.filesize)
return
revcompstr = (s) ->
l = s.split('').reverse()
for i in [0...l.length] by 1
if l[i] == 'A'
l[i] = 'T'
else if l[i] == 'T'
l[i] = 'A'
else if l[i] == 'G'
l[i] = 'C'
else if l[i] == 'C'
l[i] = 'G'
else if l[i] == 'a'
l[i] = 't'
else if l[i] == 't'
l[i] = 'a'
else if l[i] == 'g'
l[i] = 'c'
else if l[i] == 'c'
l[i] = 'g'
return l.join('')
run_cas_analyser = (seq_range, seq_hdr, filt_n, filt_r, pgcallback)->
tot_results = []
mut_results = []
count_seqs = []
totlr_count = 0
tot_count = 0
length_range = seq_range.length
n = Object.keys(seq_count).length//20
i = 0
for seq of seq_count
if !seq_count.hasOwnProperty(seq)
continue
item_cnt = seq_count[seq]
totlr_count += item_cnt
if item_cnt > filt_n
count_seqs.push( {"seq": seq, "count": item_cnt} )
tot_count += item_cnt
if i % n == 0
pgcallback(i/Object.keys(seq_count).length*50)
i += 1
pgcallback(50)
query_cnt = 0
compare = (a, b) ->
if (a.count < b.count)
return 1
if (a.count > b.count)
return -1
return 0
count_seqs.sort(compare)
data = {table: [], il: [], dl: [], is: [], ds: [], hdr: 0}
cnt_hdr = 0
cnt_ins = 0
cnt_del = 0
dscnt = 1
iscnt = 1
re_gap = /-+/g
for i in [0..seq_range.length] by 1
data.il.push( [i, 0] )
data.dl.push( [i, 0] )
n = count_seqs.length // 20
for i in [0...count_seqs.length] by 1
if (count_seqs[i].seq.length == 0)
continue
entry = []
p = needle(seq_range, count_seqs[i].seq, 10, 0.5, 10, 0.5)
entry[0] = i + 1
entry[1] = p[0]
entry[2] = p[2]
entry[3] = p[1]
entry[4] = count_seqs[i].seq.length
entry[5] = count_seqs[i].count
if seq_range.length == entry[4]
entry[6] = 0 # WT
else
if filt_r > 0 and s_seq != '' and count_seqs[i].seq.indexOf(s_seq) > 0
entry[6] = 0
else
if entry[4] > seq_range.length
entry[6] = 1 # Insertion
cnt_ins += entry[5]
else
entry[6] = 2 # Deletion
cnt_del += entry[5]
if seq_hdr == ''
entry[7] = -2
else
entry[7] = count_seqs[i].seq.indexOf(seq_hdr)
if entry[7] > 0
cnt_hdr += entry[5]
data.table.push(entry)
cpos = 0
if entry[6] == 1
loop
m = re_gap.exec(entry[1])
if m
gap = m[0]
if data.is.length < gap.length
for j in [0..gap.length - data.is.length] by 1
data.is.push([iscnt++, 0])
data.is[gap.length-1][1] += count_seqs[i].count
else
break
for j in [0..entry[1].length - 1] by 1
if entry[1][j] != '-'
cpos += 1
if cpos >= seq_range.length
break
if entry[1][j+1] == '-'
data.il[cpos][1] += count_seqs[i].count
else if entry[6] == 2
loop
m = re_gap.exec(entry[2])
if m
gap = m[0]
if data.ds.length < gap.length
for j in [0..gap.length - data.ds.length] by 1
data.ds.push([dscnt++, 0])
data.ds[gap.length-1][1] += count_seqs[i].count
else
break
for j in [0..entry[1].length] by 1
if entry[2][j] == '-'
data.dl[cpos][1] += count_seqs[i].count
if entry[1][j] != '-'
cpos += 1
if i % n == 0
pgcallback(50+50*i/(count_seqs.length-1))
for i in [0..seq_range.length] by 1
data.il[i][1] /= tot_count
data.dl[i][1] /= tot_count
data.il[i][1] *= 100
data.dl[i][1] *= 100
data.hdr = cnt_hdr
data.joins_length = joins_length
data.totlr_count = totlr_count
data.tot_count = tot_count
data.cnt_ins = cnt_ins
data.cnt_del = cnt_del
pgcallback(100)
return data
parse_joined = ->
reader = new FileReader()
chunksize = 1024*1024*10
noncomplete_line = ''
fpos = 0
fstep = 200
nline = 0
feof = 0
getchunk = ->
if fpos >= joinedfile.size
feof = 1
readline()
if fpos + chunksize >= joinedfile.size
endpos = joinedfile.size
else
endpos = fpos + chunksize
blob = joinedfile.slice(fpos, endpos)
fpos += endpos - fpos
reader.readAsText(blob)
reader.onload = ->
chunk_lines = reader.result.replace(/\r\n|\n\r|\r/, '\n').split('\n')
chunk_lines[0] = noncomplete_line + chunk_lines[0]
noncomplete_line = chunk_lines[chunk_lines.length-1]
chunk_lines = chunk_lines[...chunk_lines.length-1]
readline()
readline = ->
if nline >= chunk_lines.length
if feof
return ''
else
getchunk()
return
return chunk_lines[nline++]
line = readline()
|
[
{
"context": " process.env.URELEASE_USER_ID\nurelease_password = process.env.URELEASE_PASSWORD\n\n\nmodule.exports = (robot) ->\n\trobo",
"end": 917,
"score": 0.950055718421936,
"start": 902,
"tag": "PASSWORD",
"value": "process.env.URE"
},
{
"context": "USER_ID\nurelease_password = process.env.URELEASE_PASSWORD\n\n\nmodule.exports = (robot) ->\n\trobot.respond /sta",
"end": 931,
"score": 0.5371279716491699,
"start": 923,
"tag": "PASSWORD",
"value": "PASSWORD"
}
] | scripts/urelease/scripts-slack/notify_urelease.coffee | akash1233/OnBot_Demo | 4 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# 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.
#-------------------------------------------------------------------------------
notify = require('./notify.js');
urelease_url = process.env.URELEASE_URL
urelease_user_id = process.env.URELEASE_USER_ID
urelease_password = process.env.URELEASE_PASSWORD
module.exports = (robot) ->
robot.respond /start watching/i, (msg) ->
msg.send 'Started watching Urelease for you. I will keep you informed.';
val = ['application', 'release', 'initiative', 'users', 'roles'];
for scale in [0..val.length-1]
console.log(val[scale]);
notify.notify urelease_url, urelease_user_id, urelease_password, val[scale], (error, stdout, stderr) ->
if error == "null"
msg.send stdout;
else
msg.send error;
| 143412 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# 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.
#-------------------------------------------------------------------------------
notify = require('./notify.js');
urelease_url = process.env.URELEASE_URL
urelease_user_id = process.env.URELEASE_USER_ID
urelease_password = <PASSWORD>LEASE_<PASSWORD>
module.exports = (robot) ->
robot.respond /start watching/i, (msg) ->
msg.send 'Started watching Urelease for you. I will keep you informed.';
val = ['application', 'release', 'initiative', 'users', 'roles'];
for scale in [0..val.length-1]
console.log(val[scale]);
notify.notify urelease_url, urelease_user_id, urelease_password, val[scale], (error, stdout, stderr) ->
if error == "null"
msg.send stdout;
else
msg.send error;
| true | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# 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.
#-------------------------------------------------------------------------------
notify = require('./notify.js');
urelease_url = process.env.URELEASE_URL
urelease_user_id = process.env.URELEASE_USER_ID
urelease_password = PI:PASSWORD:<PASSWORD>END_PILEASE_PI:PASSWORD:<PASSWORD>END_PI
module.exports = (robot) ->
robot.respond /start watching/i, (msg) ->
msg.send 'Started watching Urelease for you. I will keep you informed.';
val = ['application', 'release', 'initiative', 'users', 'roles'];
for scale in [0..val.length-1]
console.log(val[scale]);
notify.notify urelease_url, urelease_user_id, urelease_password, val[scale], (error, stdout, stderr) ->
if error == "null"
msg.send stdout;
else
msg.send error;
|
[
{
"context": "implements exclusive ItwayIO plugins.\n#\n# @Author nilsenj\n# @Email ni_cole@i.ua\n# @version 0.1\n###\n\n### -",
"end": 219,
"score": 0.9996095299720764,
"start": 212,
"tag": "USERNAME",
"value": "nilsenj"
},
{
"context": "e ItwayIO plugins.\n#\n# @Author nilsenj\n# @Email ni_cole@i.ua\n# @version 0.1\n###\n\n### -------------------------",
"end": 243,
"score": 0.9999310970306396,
"start": 231,
"tag": "EMAIL",
"value": "ni_cole@i.ua"
}
] | resources/assets/coffee/app.coffee | itway/itway | 3 | ###! ItwayIO app.js
# ================
# Main JS application file for ItwayIO This file
# should be included in all pages. It controls some layout
# options and implements exclusive ItwayIO plugins.
#
# @Author nilsenj
# @Email ni_cole@i.ua
# @version 0.1
###
### ----------------------------------
# - Initialize the ItwayIO Object -
# ----------------------------------
# All ItwayIO functions are implemented below.
###
_init = (o) ->
$.ItwayIO.csrf =
activate: ->
$.ajaxSetup headers: 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
$.ItwayIO.blog =
activate: ->
_this = this
### Search functionality ###
timer = undefined
$.ItwayIO.search =
selectors: $.ItwayIO.options.search
activate: ->
_this = this
searchBTN = @selectors.searchBTN
searchResult = @selectors.searchResult
searchBTN.click (e) ->
e.preventDefault()
_this.search()
return
$('.tag-search').on 'click', (e) ->
e.preventDefault()
_this.tagSearch()
return
$('a.search-button').on 'click', (event) ->
event.preventDefault()
$('#search input[type="search"]').focus()
$('#search').addClass('active')
$('body').css 'overflow': 'hidden'
return
$('#search, #search button.close').on 'click keyup', (event) ->
if event.target == this or event.target.className == 'close' or event.target.className == 'icon-close' or event.keyCode == 27
$(this).removeClass 'active'
searchResult.html ''
$('#search .search-input').val('')
$('body').css 'overflow': 'auto'
_this.stopSearch()
return
#Do not include! This prevents the form from submitting for DEMO purposes only!
$('#search form').submit (event) ->
event.preventDefault()
false
$('#search > form > input[type="search"]').keyup (e) ->
if (e.keyCode == 13 and $('#search .search-input').val().length > 0) or $('#search .search-input').val().length > 0
_this.search()
else
_this.stopSearch()
return
return
search: ->
_this = this
searchResult = @selectors.searchResult
timer = setTimeout((->
$.ajax
url: APP_URL+'/search'
data: 'keywords': $('#search .search-input').val()
method: 'post'
success: (markup) ->
searchResult.html markup
return
error: (err) ->
searchResult.html '<h3 class="text-danger"> try once more... </h3>'
console.log err.type
_this.stopSearch()
return
return
), 500)
return
tagSearch: ->
_this = this
searchResult = @selectors.searchResult
timer = setTimeout((->
$.ajax
url: APP_URL+'/getAllExistingTags'
method: 'post'
success: (markup) ->
searchResult.html markup
return
error: (err) ->
searchResult.html '<h3 class="text-danger"> try once more... </h3>'
console.log err.type
_this.stopSearch()
return
return
), 500)
return
stopSearch: ->
clearTimeout timer
return
# generate images live rendering
$.ItwayIO.imageLoad =
activate: ->
_this = this
_this.initiateInstanceImage()
_this.initiateProfileImage()
return
renderInstanceImage: (file, fileinput, settings) ->
# generate a new FileReader object
_this = this
reader = new FileReader
image = new Image
reader.onload = (_file) ->
image.src = _file.target.result
# url.createObjectURL(file);
image.onload = ->
w = @width
h = @height
t = file.type
n = file.name
s = ~ ~(file.size / 1024) / 1024
scaleWidth = settings.thumbnail_size
$('.p').append '<div class=\'s-12 m-12 l-12 xs-12\'><div class=\'thumbnail\' style=\'background: #ffffff\'><img class="img-responsive" src=\'' + image.src + '\' /><div class=\'caption\' style=\'position: absolute;right: 10px;top:10px;\'> <h4 style=\'background: black;padding: 4px; color: white\'>' + s.toFixed(2) + ' Mb </h4></div></div> </div> '
_this.renderLabelFileName n, 'success'
return
image.onerror = ->
alert 'Invalid file type: ' + file.type
_this.renderLabelFileName file.name, "error"
fileinput.val null
return
return
reader.readAsDataURL file
return
renderProfileImage: (file, fileinput, settings) ->
# generate a new FileReader object
_this = this
reader = new FileReader
image = new Image
reader.onload = (_file) ->
image.src = _file.target.result
# url.createObjectURL(file);
image.onload = ->
w = @width
h = @height
t = file.type
n = file.name
s = ~ ~(file.size / 1024) / 1024
scaleWidth = settings.thumbnail_size
$('.profile-img').attr("src", image.src).css(position: 'relative')
_this.renderLabelFileProfile(n, "success")
_this.downButton("success")
return
image.onerror = ->
alert 'Invalid file type: ' + file.type
_this.renderLabelFileProfile file.name, file.type
_this.downButton("error")
fileinput.val null
return
return
reader.readAsDataURL file
return
downButton: (message) ->
_this = this
button = $('#upload-button')
button.removeClass "text-info"
button.removeClass "text-danger"
if message == "success"
button.removeClass "hidden"
button.addClass "block"
button.val('to download press').addClass("text-info")
else
button.addClass "hidden"
button.removeClass "block"
button.addClass("text-danger")
button.val('wrong file format')
button.bind "click", ( event ) ->
event.preventDefault()
$(this).unbind( event )
renderLabelFileName: (filename, message)->
_this = this
fileLabel = $('.filelabel')
if fileLabel.find("span.text-info").length > 0 || fileLabel.find("span.text-danger").length > 0
fileLabel.find("span.text-info").remove()
fileLabel.find("span.text-danger").remove()
if message == "success"
$('.filelabel').append $('<span>').addClass('text-info').css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
else
$('.filelabel').append $('<span>').addClass('text-danger').text(" format is not valid").css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
renderLabelFileProfile: (filename, message)->
_this = this
fileLabel = $('.label')
ImgBlock = $('.profile-img')
if ImgBlock.next("span.text-info").length > 0 || ImgBlock.next("span.text-danger").length > 0
console.log(ImgBlock.next())
ImgBlock.next("span.text-info").remove()
ImgBlock.next("span.text-danger").remove()
if message == "success"
ImgBlock.after $('<span>').addClass('text-info').css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
else
ImgBlock.after $('<span>').addClass('text-danger').html("<br/><b>format is not valid </b>").css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
initiateInstanceImage: ->
_this = this
fileinput = $('#fileupload').attr('accept', 'image/jpeg,image/png,image/gif')
settings =
thumbnail_size: 460
thumbnail_bg_color: '#ddd'
thumbnail_border: '1px solid #fff'
thumbnail_shadow: '0 0 0px rgba(0, 0, 0, 0.5)'
label_text: ''
warning_message: 'Not an image file.'
warning_text_color: '#f00'
input_class: 'custom-file-input button button-primary button-block'
# when the file is read it triggers the onload event above.
# handle input changes
fileinput.change (e) ->
$('.p').html ''
if @disabled
return alert('File upload not supported!')
F = @files
if F and F[0]
i = 0
while i < F.length
if F[i].type.match('image.*')
_this.renderInstanceImage F[i], fileinput, settings
else _this.renderLabelFileName F[i].name, "error"
i++
return
return
initiateProfileImage: ->
_this = this
fileElement = $('#file').attr('accept', 'image/jpeg,image/png,image/gif')
settings =
thumbnail_size: 100
thumbnail_bg_color: '#ddd'
thumbnail_border: '3px solid white'
thumbnail_border_radius: '3px'
label_text: ''
warning_message: 'Not an image file.'
warning_text_color: '#f00'
input_class: 'custom-file-input button button-primary button-block'
# when the file is read it triggers the onload event above.
# handle input changes
fileElement.change (e) ->
$('.profile-img-block').html ''
if @disabled
return alert('File upload not supported!')
F = @files
if F and F[0]
i = 0
while i < F.length
if F[i].type.match('image.*')
_this.renderProfileImage F[i], fileElement, settings
_this.renderLabelFileProfile F[i].name, "success"
else
_this.renderLabelFileProfile F[i].name, 'error'
_this.downButton("error")
fileElement.val(null)
i++
return
return
$.ItwayIO.messenger =
activate: ->
_this = this
#_this.chatConnected();
_this.scrollToBottom()
_this.noRoom()
_this.createNewRoom()
o.socket.on 'chat-connected:itway\\Events\\UserEnteredChatEvent', (message) ->
jqxhr = $.ajax(
url: '/chat/' + user_id + '/rooms'
type: 'GET'
dataType: 'json')
jqxhr.done (data) ->
if data.success and data.result.length > 0
console.log data.result
$.each data.result, (index, conversation) ->
o.socket.emit 'join', room: conversation.id
return
return
o.socket.on 'welcome', (data) ->
console.log data.message
o.socket.emit 'join', room: current_thread
return
o.socket.on 'joined', (data) ->
console.log data.message
return
o.socket.on 'userCount', (data) ->
chatRightPanel = $('#chatRightPanel')
if $('#chatRightPanel .numUsers').length >= 1
chatRightPanel.find('small.numUsers').remove()
chatRightPanel.append '<small class="numUsers">' + 'online users count ' + data.userCount + '</small>'
else
chatRightPanel.append '<small class="numUsers">' + 'online users count ' + data.userCount + '</small>'
return
o.socket.on 'userJoined', (data) ->
userList = $('#users')
commentUserList = $('.message-wrap')
userList.find('.media-body .online').remove()
userList.removeClass 'active'
commentUserList.find('.comment .online').remove()
$.each data.users, (index, user) ->
currentUser = userList.find('a[data-userid=\'' + user.customId + '\']')
currentCommentUser = commentUserList.find('.comment[data-comment-user=\'' + user.customId + '\']')
currentUser.addClass 'active'
currentUser.find('.media-body').append '<span class="online"></span>'
currentCommentUser.append '<span class="online">online</span>'
return
return
o.socket.on 'connect', (data) ->
o.socket.emit 'storeClientInfo', customId: user_id
console.log data
return
o.socket.on 'chat.messages:itway\\Events\\ChatMessageCreated', (message) ->
data = message.data
$messageList = $('.msg-wrap .comments')
$conversation = $('.conversation-wrap a[data-room=\'' + data.room + '\']')
message = data.message.body
from_user_id = data.message.user_id
conversation = data.room
_this.getMessages(from_user_id, conversation).done (data) ->
$conversation.find('.last-message-body').text message
if conversation == current_thread
$messageList.append data
_this.scrollToBottom()
if from_user_id != user_id and conversation != current_thread
_this.updateConversationCounter $conversation
return
return
o.socket.on 'chat.rooms:itway\\Events\\ChatRoomCreated', (message) ->
$conversationList = $('.rooms .conversation-wrap')
data = message.data
$messageList = $('.msg-wrap .comments')
$conversationTab = $('.button-panel-conversation a[data-tab=\'rooms\']')
message = data.message.body
from_user_id = data.message.user_id
conversation = data.room
_this.getConversations(user_id, conversation, current_thread).done (data) ->
if !data.notInRoom
$conversationList.prepend data
$conversation = $('.conversation-wrap a[data-room=\'' + conversation + '\']')
_this.notifyNewRoom $conversationTab
_this.updateConversationCounter $conversation
return
return
_this.events()
return
noRoom: ->
noRoom = $('#no-room')
createRoom = $('#create-room')
if noRoom.length >= 1
noRoom.addClass 'hidden'
createRoom.on 'click', (e) ->
e.preventDefault()
noRoom.removeClass('hidden').addClass 'active'
return
return
createNewRoom: ->
$('#chatDropdown').dropdown
onChange: (value, text, $selectedItem) ->
console.log value, text, $selectedItem
return
transition: 'drop'
$('#create-room').on 'click', ->
jqxhr = $.ajax(
url: '/chat/create'
type: 'GET'
dataType: 'html')
msgWrap = $('.message-wrap')
jqxhr.done (data) ->
msgWrap.find('.msg-wrap').addClass 'hidden'
msgWrap.find('.send-wrap').addClass 'hidden'
msgWrap.prepend data
return
return
return
notifyNewRoom: ($conversation) ->
$badge = $conversation.find('.badge')
counter = Number($badge.text())
if $badge.length
$badge.text counter + 1
else
$conversation.append '<span class="badge">1</span>'
return
notifyUsers: (user) ->
usersBlock = $('#users')
usersBlock.prepend '<div class="user" id=' + user.id + '>' + user.name + '</div>'
return
getConversations: (user_id, conversation, current_thread) ->
jqxhr = $.ajax(
url: '/chat/conversations'
type: 'GET'
data:
user_id: user_id
conversation: conversation
current_thread: current_thread)
jqxhr
getMessages: (from_user_id, conversation) ->
jqxhr = $.ajax(
url: '/room/getMessage'
type: 'GET'
data:
user_id: from_user_id
conversation: conversation
dataType: 'html')
jqxhr
sendMessage: (body, conversation, user_id) ->
jqxhr = $.ajax(
url: '/room/create-message'
type: 'POST'
data:
body: body
conversation: conversation
user_id: user_id
dataType: 'json')
jqxhr
updateConversationCounter: ($conversation) ->
$badge = $conversation.find('.chat-user-name small .badge')
counter = Number($badge.text())
if $badge.length
$badge.text counter + 1
else
$conversation.find('.chat-user-name small').append '<span class="badge">1</span>'
return
scrollToBottom: ->
$messageList = $('.msg-wrap')
if $messageList.length
$messageList.animate { scrollTop: $messageList[0].scrollHeight }, 500
return
events: ->
_this = this
$('#btnSendMessage').on 'click', (evt) ->
$messageBox = $('#messageBox')
evt.preventDefault()
_this.sendMessage($messageBox.val(), current_thread, user_id).done (data) ->
console.log data
$messageBox.val ''
$messageBox.focus()
return
return
$('#btnNewMessage').on 'click', ->
$('#newMessageModal').modal 'show'
return
###*
# ctr+Enter to send message
###
$('#messageBox').keypress (event) ->
if event.keyCode == 13 and event.ctrlKey
event.preventDefault()
$('#btnSendMessage').trigger 'click'
return
return
### Tree()
# ======
# Converts the sidebar into a multilevel
# tree view menu.
#
# @type Function
# @Usage: $.ItwayIO.tree('.sidebar')
###
$.ItwayIO.tree = (menu) ->
_this = this
$('li a', $(menu)).on 'click', (e) ->
#Get the clicked link and the next element
$this = $(this)
checkElement = $this.next()
#Check if the next element is a menu and is visible
if checkElement.is('.treeview-menu') and checkElement.is(':visible')
#Close the menu
checkElement.slideUp 'normal', ->
checkElement.removeClass 'menu-open'
#Fix the layout in case the sidebar stretches over the height of the window
#_this.layout.fix();
return
checkElement.parent('li').removeClass 'active'
else if checkElement.is('.treeview-menu') and !checkElement.is(':visible')
#Get the parent menu
parent = $this.parents('ul').first()
#Close all open menus within the parent
ul = parent.find('ul:visible').slideUp('normal')
#Remove the menu-open class from the parent
ul.removeClass 'menu-open'
#Get the parent li
parent_li = $this.parent('li')
#Open the target menu and add the menu-open class
checkElement.slideDown 'normal', ->
#Add the class active to the parent li
checkElement.addClass 'menu-open'
parent.find('li.active').removeClass 'active'
parent_li.addClass 'active'
#Fix the layout in case the sidebar stretches over the height of the window
_this.layout.fix()
return
#if this isn't a link, prevent the page from being redirected
if checkElement.is('.treeview-menu')
e.preventDefault()
return
return
### BoxWidget
# =========
# BoxWidget is a plugin to handle collapsing and
# removing boxes from the screen.
#
# @type Object
# @usage $.ItwayIO.boxWidget.activate()
# Set all your options in the main $.ItwayIO.options object
###
$.ItwayIO.boxWidget =
selectors: $.ItwayIO.options.boxWidgetOptions.boxWidgetSelectors
icons: $.ItwayIO.options.boxWidgetOptions.boxWidgetIcons
activate: ->
_this = this
#Listen for collapse event triggers
$(_this.selectors.collapse).on 'click', (e) ->
e.preventDefault()
_this.collapse $(this)
return
#Listen for remove event triggers
$(_this.selectors.remove).on 'click', (e) ->
e.preventDefault()
_this.remove $(this)
return
return
collapse: (element) ->
_this = this
#Find the box parent
box = element.parents('.box').first()
#Find the body and the footer
box_content = box.find('> .box-body, > .box-footer')
if !box.hasClass('collapsed-box')
#Convert minus into plus
element.children(':first').removeClass(_this.icons.collapse).addClass _this.icons.open
#Hide the content
box_content.slideUp 300, ->
box.addClass 'collapsed-box'
return
else
#Convert plus into minus
element.children(':first').removeClass(_this.icons.open).addClass _this.icons.collapse
#Show the content
box_content.slideDown 300, ->
box.removeClass 'collapsed-box'
return
return
remove: (element) ->
#Find the box parent
box = element.parents('.box').first()
box.slideUp()
return
return
'use strict'
#Make sure jQuery has been loaded before app.js
if typeof jQuery == 'undefined'
throw new Error('ItwayIO requires jQuery')
### ItwayIO
#
# @type Object
# @description $.ItwayIO is the main object for the template's app.
# It's used for implementing functions and options related
# to the template. Keeping everything wrapped in an object
# prevents conflict with other plugins and is a better
# way to organize our code.
###
$.ItwayIO = {}
### --------------------
# - ItwayIO Options -
# --------------------
# Modify these options to suit your implementation
###
$.ItwayIO.options =
host: 'http://' + window.location.hostname
socket: io(APP_URL+':6378')
navbarMenuSlimscroll: true
navbarMenuSlimscrollWidth: '3px'
navbarMenuHeight: '200px'
sidebarControlWidth: '280px'
sidebarToggleSelector: '[data-toggle=\'offcanvas\']'
sidebarPushMenu: true
sidebarSlimScroll: false
sidebarExpandOnHover: true
enableBoxRefresh: true
enableBSToppltip: true
BSTooltipSelector: '[data-toggle=\'tooltip\']'
enableFastclick: true
enableControlSidebar: true
controlSidebarOptions:
toggleBtnSelector: '[data-toggle=\'control-sidebar\']'
selector: '.control-sidebar'
slide: true
enableBoxWidget: true
boxWidgetOptions:
boxWidgetIcons:
collapse: 'fa-minus'
open: 'fa-plus'
remove: 'fa-times'
boxWidgetSelectors:
remove: '[data-widget="remove"]'
collapse: '[data-widget="collapse"]'
directChat:
enable: true
contactToggleSelector: '[data-widget="chat-pane-toggle"]'
search:
searchBTN : $('#search button')
searchResult : $('.search-result #search-result-body')
colors:
lightBlue: '#3c8dbc'
red: '#f56954'
green: '#00a65a'
aqua: '#00c0ef'
yellow: '#f39c12'
blue: '#0073b7'
navy: '#001F3F'
teal: '#39CCCC'
olive: '#3D9970'
lime: '#01FF70'
orange: '#FF851B'
fuchsia: '#F012BE'
purple: '#8E24AA'
maroon: '#D81B60'
black: '#222222'
gray: '#d2d6de'
screenSizes:
xs: 480
sm: 768
md: 992
lg: 1200
### ------------------
# - Implementation -
# ------------------
# The next block of code implements ItwayIO's
# functions and plugins as specified by the
# options above.
###
$ ->
#Extend options if external options exist
if typeof ItwayIOOptions != 'undefined'
$.extend true, $.ItwayIO.options, ItwayIOOptions
#Easy access to options
o = $.ItwayIO.options
#Set up the object
_init o
# activate csrf token
$.ItwayIO.csrf.activate()
$.ItwayIO.search.activate()
# start of handling events and sockets
#Activate messenger functionality
$.ItwayIO.messenger.activate()
$.ItwayIO.imageLoad.activate()
#Enable sidebar tree view controls
if o.navbarMenuSlimscroll and typeof $.fn.slimscroll != 'undefined'
$('.navbar .menu').slimscroll(
height: o.navbarMenuHeight
alwaysVisible: false
size: o.navbarMenuSlimscrollWidth).css 'width', '100%'
#Activate box widget
if o.enableBoxWidget
$.ItwayIO.boxWidget.activate()
#Activate fast click
if o.enableFastclick and typeof FastClick != 'undefined'
FastClick.attach document.body
#Activate direct chat widget
if o.directChat.enable
$(o.directChat.contactToggleSelector).on 'click', ->
box = $(this).parents('.direct-chat').first()
box.toggleClass 'direct-chat-contacts-open'
return
###
# INITIALIZE BUTTON TOGGLE
# ------------------------
###
$('.button-group[data-toggle="btn-toggle"]').each ->
group = $(this)
$(this).find('.button').on 'click', (e) ->
group.find('.button.active').removeClass 'active'
$(this).addClass 'active'
e.preventDefault()
return
return
return
| 225957 | ###! ItwayIO app.js
# ================
# Main JS application file for ItwayIO This file
# should be included in all pages. It controls some layout
# options and implements exclusive ItwayIO plugins.
#
# @Author nilsenj
# @Email <EMAIL>
# @version 0.1
###
### ----------------------------------
# - Initialize the ItwayIO Object -
# ----------------------------------
# All ItwayIO functions are implemented below.
###
_init = (o) ->
$.ItwayIO.csrf =
activate: ->
$.ajaxSetup headers: 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
$.ItwayIO.blog =
activate: ->
_this = this
### Search functionality ###
timer = undefined
$.ItwayIO.search =
selectors: $.ItwayIO.options.search
activate: ->
_this = this
searchBTN = @selectors.searchBTN
searchResult = @selectors.searchResult
searchBTN.click (e) ->
e.preventDefault()
_this.search()
return
$('.tag-search').on 'click', (e) ->
e.preventDefault()
_this.tagSearch()
return
$('a.search-button').on 'click', (event) ->
event.preventDefault()
$('#search input[type="search"]').focus()
$('#search').addClass('active')
$('body').css 'overflow': 'hidden'
return
$('#search, #search button.close').on 'click keyup', (event) ->
if event.target == this or event.target.className == 'close' or event.target.className == 'icon-close' or event.keyCode == 27
$(this).removeClass 'active'
searchResult.html ''
$('#search .search-input').val('')
$('body').css 'overflow': 'auto'
_this.stopSearch()
return
#Do not include! This prevents the form from submitting for DEMO purposes only!
$('#search form').submit (event) ->
event.preventDefault()
false
$('#search > form > input[type="search"]').keyup (e) ->
if (e.keyCode == 13 and $('#search .search-input').val().length > 0) or $('#search .search-input').val().length > 0
_this.search()
else
_this.stopSearch()
return
return
search: ->
_this = this
searchResult = @selectors.searchResult
timer = setTimeout((->
$.ajax
url: APP_URL+'/search'
data: 'keywords': $('#search .search-input').val()
method: 'post'
success: (markup) ->
searchResult.html markup
return
error: (err) ->
searchResult.html '<h3 class="text-danger"> try once more... </h3>'
console.log err.type
_this.stopSearch()
return
return
), 500)
return
tagSearch: ->
_this = this
searchResult = @selectors.searchResult
timer = setTimeout((->
$.ajax
url: APP_URL+'/getAllExistingTags'
method: 'post'
success: (markup) ->
searchResult.html markup
return
error: (err) ->
searchResult.html '<h3 class="text-danger"> try once more... </h3>'
console.log err.type
_this.stopSearch()
return
return
), 500)
return
stopSearch: ->
clearTimeout timer
return
# generate images live rendering
$.ItwayIO.imageLoad =
activate: ->
_this = this
_this.initiateInstanceImage()
_this.initiateProfileImage()
return
renderInstanceImage: (file, fileinput, settings) ->
# generate a new FileReader object
_this = this
reader = new FileReader
image = new Image
reader.onload = (_file) ->
image.src = _file.target.result
# url.createObjectURL(file);
image.onload = ->
w = @width
h = @height
t = file.type
n = file.name
s = ~ ~(file.size / 1024) / 1024
scaleWidth = settings.thumbnail_size
$('.p').append '<div class=\'s-12 m-12 l-12 xs-12\'><div class=\'thumbnail\' style=\'background: #ffffff\'><img class="img-responsive" src=\'' + image.src + '\' /><div class=\'caption\' style=\'position: absolute;right: 10px;top:10px;\'> <h4 style=\'background: black;padding: 4px; color: white\'>' + s.toFixed(2) + ' Mb </h4></div></div> </div> '
_this.renderLabelFileName n, 'success'
return
image.onerror = ->
alert 'Invalid file type: ' + file.type
_this.renderLabelFileName file.name, "error"
fileinput.val null
return
return
reader.readAsDataURL file
return
renderProfileImage: (file, fileinput, settings) ->
# generate a new FileReader object
_this = this
reader = new FileReader
image = new Image
reader.onload = (_file) ->
image.src = _file.target.result
# url.createObjectURL(file);
image.onload = ->
w = @width
h = @height
t = file.type
n = file.name
s = ~ ~(file.size / 1024) / 1024
scaleWidth = settings.thumbnail_size
$('.profile-img').attr("src", image.src).css(position: 'relative')
_this.renderLabelFileProfile(n, "success")
_this.downButton("success")
return
image.onerror = ->
alert 'Invalid file type: ' + file.type
_this.renderLabelFileProfile file.name, file.type
_this.downButton("error")
fileinput.val null
return
return
reader.readAsDataURL file
return
downButton: (message) ->
_this = this
button = $('#upload-button')
button.removeClass "text-info"
button.removeClass "text-danger"
if message == "success"
button.removeClass "hidden"
button.addClass "block"
button.val('to download press').addClass("text-info")
else
button.addClass "hidden"
button.removeClass "block"
button.addClass("text-danger")
button.val('wrong file format')
button.bind "click", ( event ) ->
event.preventDefault()
$(this).unbind( event )
renderLabelFileName: (filename, message)->
_this = this
fileLabel = $('.filelabel')
if fileLabel.find("span.text-info").length > 0 || fileLabel.find("span.text-danger").length > 0
fileLabel.find("span.text-info").remove()
fileLabel.find("span.text-danger").remove()
if message == "success"
$('.filelabel').append $('<span>').addClass('text-info').css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
else
$('.filelabel').append $('<span>').addClass('text-danger').text(" format is not valid").css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
renderLabelFileProfile: (filename, message)->
_this = this
fileLabel = $('.label')
ImgBlock = $('.profile-img')
if ImgBlock.next("span.text-info").length > 0 || ImgBlock.next("span.text-danger").length > 0
console.log(ImgBlock.next())
ImgBlock.next("span.text-info").remove()
ImgBlock.next("span.text-danger").remove()
if message == "success"
ImgBlock.after $('<span>').addClass('text-info').css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
else
ImgBlock.after $('<span>').addClass('text-danger').html("<br/><b>format is not valid </b>").css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
initiateInstanceImage: ->
_this = this
fileinput = $('#fileupload').attr('accept', 'image/jpeg,image/png,image/gif')
settings =
thumbnail_size: 460
thumbnail_bg_color: '#ddd'
thumbnail_border: '1px solid #fff'
thumbnail_shadow: '0 0 0px rgba(0, 0, 0, 0.5)'
label_text: ''
warning_message: 'Not an image file.'
warning_text_color: '#f00'
input_class: 'custom-file-input button button-primary button-block'
# when the file is read it triggers the onload event above.
# handle input changes
fileinput.change (e) ->
$('.p').html ''
if @disabled
return alert('File upload not supported!')
F = @files
if F and F[0]
i = 0
while i < F.length
if F[i].type.match('image.*')
_this.renderInstanceImage F[i], fileinput, settings
else _this.renderLabelFileName F[i].name, "error"
i++
return
return
initiateProfileImage: ->
_this = this
fileElement = $('#file').attr('accept', 'image/jpeg,image/png,image/gif')
settings =
thumbnail_size: 100
thumbnail_bg_color: '#ddd'
thumbnail_border: '3px solid white'
thumbnail_border_radius: '3px'
label_text: ''
warning_message: 'Not an image file.'
warning_text_color: '#f00'
input_class: 'custom-file-input button button-primary button-block'
# when the file is read it triggers the onload event above.
# handle input changes
fileElement.change (e) ->
$('.profile-img-block').html ''
if @disabled
return alert('File upload not supported!')
F = @files
if F and F[0]
i = 0
while i < F.length
if F[i].type.match('image.*')
_this.renderProfileImage F[i], fileElement, settings
_this.renderLabelFileProfile F[i].name, "success"
else
_this.renderLabelFileProfile F[i].name, 'error'
_this.downButton("error")
fileElement.val(null)
i++
return
return
$.ItwayIO.messenger =
activate: ->
_this = this
#_this.chatConnected();
_this.scrollToBottom()
_this.noRoom()
_this.createNewRoom()
o.socket.on 'chat-connected:itway\\Events\\UserEnteredChatEvent', (message) ->
jqxhr = $.ajax(
url: '/chat/' + user_id + '/rooms'
type: 'GET'
dataType: 'json')
jqxhr.done (data) ->
if data.success and data.result.length > 0
console.log data.result
$.each data.result, (index, conversation) ->
o.socket.emit 'join', room: conversation.id
return
return
o.socket.on 'welcome', (data) ->
console.log data.message
o.socket.emit 'join', room: current_thread
return
o.socket.on 'joined', (data) ->
console.log data.message
return
o.socket.on 'userCount', (data) ->
chatRightPanel = $('#chatRightPanel')
if $('#chatRightPanel .numUsers').length >= 1
chatRightPanel.find('small.numUsers').remove()
chatRightPanel.append '<small class="numUsers">' + 'online users count ' + data.userCount + '</small>'
else
chatRightPanel.append '<small class="numUsers">' + 'online users count ' + data.userCount + '</small>'
return
o.socket.on 'userJoined', (data) ->
userList = $('#users')
commentUserList = $('.message-wrap')
userList.find('.media-body .online').remove()
userList.removeClass 'active'
commentUserList.find('.comment .online').remove()
$.each data.users, (index, user) ->
currentUser = userList.find('a[data-userid=\'' + user.customId + '\']')
currentCommentUser = commentUserList.find('.comment[data-comment-user=\'' + user.customId + '\']')
currentUser.addClass 'active'
currentUser.find('.media-body').append '<span class="online"></span>'
currentCommentUser.append '<span class="online">online</span>'
return
return
o.socket.on 'connect', (data) ->
o.socket.emit 'storeClientInfo', customId: user_id
console.log data
return
o.socket.on 'chat.messages:itway\\Events\\ChatMessageCreated', (message) ->
data = message.data
$messageList = $('.msg-wrap .comments')
$conversation = $('.conversation-wrap a[data-room=\'' + data.room + '\']')
message = data.message.body
from_user_id = data.message.user_id
conversation = data.room
_this.getMessages(from_user_id, conversation).done (data) ->
$conversation.find('.last-message-body').text message
if conversation == current_thread
$messageList.append data
_this.scrollToBottom()
if from_user_id != user_id and conversation != current_thread
_this.updateConversationCounter $conversation
return
return
o.socket.on 'chat.rooms:itway\\Events\\ChatRoomCreated', (message) ->
$conversationList = $('.rooms .conversation-wrap')
data = message.data
$messageList = $('.msg-wrap .comments')
$conversationTab = $('.button-panel-conversation a[data-tab=\'rooms\']')
message = data.message.body
from_user_id = data.message.user_id
conversation = data.room
_this.getConversations(user_id, conversation, current_thread).done (data) ->
if !data.notInRoom
$conversationList.prepend data
$conversation = $('.conversation-wrap a[data-room=\'' + conversation + '\']')
_this.notifyNewRoom $conversationTab
_this.updateConversationCounter $conversation
return
return
_this.events()
return
noRoom: ->
noRoom = $('#no-room')
createRoom = $('#create-room')
if noRoom.length >= 1
noRoom.addClass 'hidden'
createRoom.on 'click', (e) ->
e.preventDefault()
noRoom.removeClass('hidden').addClass 'active'
return
return
createNewRoom: ->
$('#chatDropdown').dropdown
onChange: (value, text, $selectedItem) ->
console.log value, text, $selectedItem
return
transition: 'drop'
$('#create-room').on 'click', ->
jqxhr = $.ajax(
url: '/chat/create'
type: 'GET'
dataType: 'html')
msgWrap = $('.message-wrap')
jqxhr.done (data) ->
msgWrap.find('.msg-wrap').addClass 'hidden'
msgWrap.find('.send-wrap').addClass 'hidden'
msgWrap.prepend data
return
return
return
notifyNewRoom: ($conversation) ->
$badge = $conversation.find('.badge')
counter = Number($badge.text())
if $badge.length
$badge.text counter + 1
else
$conversation.append '<span class="badge">1</span>'
return
notifyUsers: (user) ->
usersBlock = $('#users')
usersBlock.prepend '<div class="user" id=' + user.id + '>' + user.name + '</div>'
return
getConversations: (user_id, conversation, current_thread) ->
jqxhr = $.ajax(
url: '/chat/conversations'
type: 'GET'
data:
user_id: user_id
conversation: conversation
current_thread: current_thread)
jqxhr
getMessages: (from_user_id, conversation) ->
jqxhr = $.ajax(
url: '/room/getMessage'
type: 'GET'
data:
user_id: from_user_id
conversation: conversation
dataType: 'html')
jqxhr
sendMessage: (body, conversation, user_id) ->
jqxhr = $.ajax(
url: '/room/create-message'
type: 'POST'
data:
body: body
conversation: conversation
user_id: user_id
dataType: 'json')
jqxhr
updateConversationCounter: ($conversation) ->
$badge = $conversation.find('.chat-user-name small .badge')
counter = Number($badge.text())
if $badge.length
$badge.text counter + 1
else
$conversation.find('.chat-user-name small').append '<span class="badge">1</span>'
return
scrollToBottom: ->
$messageList = $('.msg-wrap')
if $messageList.length
$messageList.animate { scrollTop: $messageList[0].scrollHeight }, 500
return
events: ->
_this = this
$('#btnSendMessage').on 'click', (evt) ->
$messageBox = $('#messageBox')
evt.preventDefault()
_this.sendMessage($messageBox.val(), current_thread, user_id).done (data) ->
console.log data
$messageBox.val ''
$messageBox.focus()
return
return
$('#btnNewMessage').on 'click', ->
$('#newMessageModal').modal 'show'
return
###*
# ctr+Enter to send message
###
$('#messageBox').keypress (event) ->
if event.keyCode == 13 and event.ctrlKey
event.preventDefault()
$('#btnSendMessage').trigger 'click'
return
return
### Tree()
# ======
# Converts the sidebar into a multilevel
# tree view menu.
#
# @type Function
# @Usage: $.ItwayIO.tree('.sidebar')
###
$.ItwayIO.tree = (menu) ->
_this = this
$('li a', $(menu)).on 'click', (e) ->
#Get the clicked link and the next element
$this = $(this)
checkElement = $this.next()
#Check if the next element is a menu and is visible
if checkElement.is('.treeview-menu') and checkElement.is(':visible')
#Close the menu
checkElement.slideUp 'normal', ->
checkElement.removeClass 'menu-open'
#Fix the layout in case the sidebar stretches over the height of the window
#_this.layout.fix();
return
checkElement.parent('li').removeClass 'active'
else if checkElement.is('.treeview-menu') and !checkElement.is(':visible')
#Get the parent menu
parent = $this.parents('ul').first()
#Close all open menus within the parent
ul = parent.find('ul:visible').slideUp('normal')
#Remove the menu-open class from the parent
ul.removeClass 'menu-open'
#Get the parent li
parent_li = $this.parent('li')
#Open the target menu and add the menu-open class
checkElement.slideDown 'normal', ->
#Add the class active to the parent li
checkElement.addClass 'menu-open'
parent.find('li.active').removeClass 'active'
parent_li.addClass 'active'
#Fix the layout in case the sidebar stretches over the height of the window
_this.layout.fix()
return
#if this isn't a link, prevent the page from being redirected
if checkElement.is('.treeview-menu')
e.preventDefault()
return
return
### BoxWidget
# =========
# BoxWidget is a plugin to handle collapsing and
# removing boxes from the screen.
#
# @type Object
# @usage $.ItwayIO.boxWidget.activate()
# Set all your options in the main $.ItwayIO.options object
###
$.ItwayIO.boxWidget =
selectors: $.ItwayIO.options.boxWidgetOptions.boxWidgetSelectors
icons: $.ItwayIO.options.boxWidgetOptions.boxWidgetIcons
activate: ->
_this = this
#Listen for collapse event triggers
$(_this.selectors.collapse).on 'click', (e) ->
e.preventDefault()
_this.collapse $(this)
return
#Listen for remove event triggers
$(_this.selectors.remove).on 'click', (e) ->
e.preventDefault()
_this.remove $(this)
return
return
collapse: (element) ->
_this = this
#Find the box parent
box = element.parents('.box').first()
#Find the body and the footer
box_content = box.find('> .box-body, > .box-footer')
if !box.hasClass('collapsed-box')
#Convert minus into plus
element.children(':first').removeClass(_this.icons.collapse).addClass _this.icons.open
#Hide the content
box_content.slideUp 300, ->
box.addClass 'collapsed-box'
return
else
#Convert plus into minus
element.children(':first').removeClass(_this.icons.open).addClass _this.icons.collapse
#Show the content
box_content.slideDown 300, ->
box.removeClass 'collapsed-box'
return
return
remove: (element) ->
#Find the box parent
box = element.parents('.box').first()
box.slideUp()
return
return
'use strict'
#Make sure jQuery has been loaded before app.js
if typeof jQuery == 'undefined'
throw new Error('ItwayIO requires jQuery')
### ItwayIO
#
# @type Object
# @description $.ItwayIO is the main object for the template's app.
# It's used for implementing functions and options related
# to the template. Keeping everything wrapped in an object
# prevents conflict with other plugins and is a better
# way to organize our code.
###
$.ItwayIO = {}
### --------------------
# - ItwayIO Options -
# --------------------
# Modify these options to suit your implementation
###
$.ItwayIO.options =
host: 'http://' + window.location.hostname
socket: io(APP_URL+':6378')
navbarMenuSlimscroll: true
navbarMenuSlimscrollWidth: '3px'
navbarMenuHeight: '200px'
sidebarControlWidth: '280px'
sidebarToggleSelector: '[data-toggle=\'offcanvas\']'
sidebarPushMenu: true
sidebarSlimScroll: false
sidebarExpandOnHover: true
enableBoxRefresh: true
enableBSToppltip: true
BSTooltipSelector: '[data-toggle=\'tooltip\']'
enableFastclick: true
enableControlSidebar: true
controlSidebarOptions:
toggleBtnSelector: '[data-toggle=\'control-sidebar\']'
selector: '.control-sidebar'
slide: true
enableBoxWidget: true
boxWidgetOptions:
boxWidgetIcons:
collapse: 'fa-minus'
open: 'fa-plus'
remove: 'fa-times'
boxWidgetSelectors:
remove: '[data-widget="remove"]'
collapse: '[data-widget="collapse"]'
directChat:
enable: true
contactToggleSelector: '[data-widget="chat-pane-toggle"]'
search:
searchBTN : $('#search button')
searchResult : $('.search-result #search-result-body')
colors:
lightBlue: '#3c8dbc'
red: '#f56954'
green: '#00a65a'
aqua: '#00c0ef'
yellow: '#f39c12'
blue: '#0073b7'
navy: '#001F3F'
teal: '#39CCCC'
olive: '#3D9970'
lime: '#01FF70'
orange: '#FF851B'
fuchsia: '#F012BE'
purple: '#8E24AA'
maroon: '#D81B60'
black: '#222222'
gray: '#d2d6de'
screenSizes:
xs: 480
sm: 768
md: 992
lg: 1200
### ------------------
# - Implementation -
# ------------------
# The next block of code implements ItwayIO's
# functions and plugins as specified by the
# options above.
###
$ ->
#Extend options if external options exist
if typeof ItwayIOOptions != 'undefined'
$.extend true, $.ItwayIO.options, ItwayIOOptions
#Easy access to options
o = $.ItwayIO.options
#Set up the object
_init o
# activate csrf token
$.ItwayIO.csrf.activate()
$.ItwayIO.search.activate()
# start of handling events and sockets
#Activate messenger functionality
$.ItwayIO.messenger.activate()
$.ItwayIO.imageLoad.activate()
#Enable sidebar tree view controls
if o.navbarMenuSlimscroll and typeof $.fn.slimscroll != 'undefined'
$('.navbar .menu').slimscroll(
height: o.navbarMenuHeight
alwaysVisible: false
size: o.navbarMenuSlimscrollWidth).css 'width', '100%'
#Activate box widget
if o.enableBoxWidget
$.ItwayIO.boxWidget.activate()
#Activate fast click
if o.enableFastclick and typeof FastClick != 'undefined'
FastClick.attach document.body
#Activate direct chat widget
if o.directChat.enable
$(o.directChat.contactToggleSelector).on 'click', ->
box = $(this).parents('.direct-chat').first()
box.toggleClass 'direct-chat-contacts-open'
return
###
# INITIALIZE BUTTON TOGGLE
# ------------------------
###
$('.button-group[data-toggle="btn-toggle"]').each ->
group = $(this)
$(this).find('.button').on 'click', (e) ->
group.find('.button.active').removeClass 'active'
$(this).addClass 'active'
e.preventDefault()
return
return
return
| true | ###! ItwayIO app.js
# ================
# Main JS application file for ItwayIO This file
# should be included in all pages. It controls some layout
# options and implements exclusive ItwayIO plugins.
#
# @Author nilsenj
# @Email PI:EMAIL:<EMAIL>END_PI
# @version 0.1
###
### ----------------------------------
# - Initialize the ItwayIO Object -
# ----------------------------------
# All ItwayIO functions are implemented below.
###
_init = (o) ->
$.ItwayIO.csrf =
activate: ->
$.ajaxSetup headers: 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
$.ItwayIO.blog =
activate: ->
_this = this
### Search functionality ###
timer = undefined
$.ItwayIO.search =
selectors: $.ItwayIO.options.search
activate: ->
_this = this
searchBTN = @selectors.searchBTN
searchResult = @selectors.searchResult
searchBTN.click (e) ->
e.preventDefault()
_this.search()
return
$('.tag-search').on 'click', (e) ->
e.preventDefault()
_this.tagSearch()
return
$('a.search-button').on 'click', (event) ->
event.preventDefault()
$('#search input[type="search"]').focus()
$('#search').addClass('active')
$('body').css 'overflow': 'hidden'
return
$('#search, #search button.close').on 'click keyup', (event) ->
if event.target == this or event.target.className == 'close' or event.target.className == 'icon-close' or event.keyCode == 27
$(this).removeClass 'active'
searchResult.html ''
$('#search .search-input').val('')
$('body').css 'overflow': 'auto'
_this.stopSearch()
return
#Do not include! This prevents the form from submitting for DEMO purposes only!
$('#search form').submit (event) ->
event.preventDefault()
false
$('#search > form > input[type="search"]').keyup (e) ->
if (e.keyCode == 13 and $('#search .search-input').val().length > 0) or $('#search .search-input').val().length > 0
_this.search()
else
_this.stopSearch()
return
return
search: ->
_this = this
searchResult = @selectors.searchResult
timer = setTimeout((->
$.ajax
url: APP_URL+'/search'
data: 'keywords': $('#search .search-input').val()
method: 'post'
success: (markup) ->
searchResult.html markup
return
error: (err) ->
searchResult.html '<h3 class="text-danger"> try once more... </h3>'
console.log err.type
_this.stopSearch()
return
return
), 500)
return
tagSearch: ->
_this = this
searchResult = @selectors.searchResult
timer = setTimeout((->
$.ajax
url: APP_URL+'/getAllExistingTags'
method: 'post'
success: (markup) ->
searchResult.html markup
return
error: (err) ->
searchResult.html '<h3 class="text-danger"> try once more... </h3>'
console.log err.type
_this.stopSearch()
return
return
), 500)
return
stopSearch: ->
clearTimeout timer
return
# generate images live rendering
$.ItwayIO.imageLoad =
activate: ->
_this = this
_this.initiateInstanceImage()
_this.initiateProfileImage()
return
renderInstanceImage: (file, fileinput, settings) ->
# generate a new FileReader object
_this = this
reader = new FileReader
image = new Image
reader.onload = (_file) ->
image.src = _file.target.result
# url.createObjectURL(file);
image.onload = ->
w = @width
h = @height
t = file.type
n = file.name
s = ~ ~(file.size / 1024) / 1024
scaleWidth = settings.thumbnail_size
$('.p').append '<div class=\'s-12 m-12 l-12 xs-12\'><div class=\'thumbnail\' style=\'background: #ffffff\'><img class="img-responsive" src=\'' + image.src + '\' /><div class=\'caption\' style=\'position: absolute;right: 10px;top:10px;\'> <h4 style=\'background: black;padding: 4px; color: white\'>' + s.toFixed(2) + ' Mb </h4></div></div> </div> '
_this.renderLabelFileName n, 'success'
return
image.onerror = ->
alert 'Invalid file type: ' + file.type
_this.renderLabelFileName file.name, "error"
fileinput.val null
return
return
reader.readAsDataURL file
return
renderProfileImage: (file, fileinput, settings) ->
# generate a new FileReader object
_this = this
reader = new FileReader
image = new Image
reader.onload = (_file) ->
image.src = _file.target.result
# url.createObjectURL(file);
image.onload = ->
w = @width
h = @height
t = file.type
n = file.name
s = ~ ~(file.size / 1024) / 1024
scaleWidth = settings.thumbnail_size
$('.profile-img').attr("src", image.src).css(position: 'relative')
_this.renderLabelFileProfile(n, "success")
_this.downButton("success")
return
image.onerror = ->
alert 'Invalid file type: ' + file.type
_this.renderLabelFileProfile file.name, file.type
_this.downButton("error")
fileinput.val null
return
return
reader.readAsDataURL file
return
downButton: (message) ->
_this = this
button = $('#upload-button')
button.removeClass "text-info"
button.removeClass "text-danger"
if message == "success"
button.removeClass "hidden"
button.addClass "block"
button.val('to download press').addClass("text-info")
else
button.addClass "hidden"
button.removeClass "block"
button.addClass("text-danger")
button.val('wrong file format')
button.bind "click", ( event ) ->
event.preventDefault()
$(this).unbind( event )
renderLabelFileName: (filename, message)->
_this = this
fileLabel = $('.filelabel')
if fileLabel.find("span.text-info").length > 0 || fileLabel.find("span.text-danger").length > 0
fileLabel.find("span.text-info").remove()
fileLabel.find("span.text-danger").remove()
if message == "success"
$('.filelabel').append $('<span>').addClass('text-info').css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
else
$('.filelabel').append $('<span>').addClass('text-danger').text(" format is not valid").css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
renderLabelFileProfile: (filename, message)->
_this = this
fileLabel = $('.label')
ImgBlock = $('.profile-img')
if ImgBlock.next("span.text-info").length > 0 || ImgBlock.next("span.text-danger").length > 0
console.log(ImgBlock.next())
ImgBlock.next("span.text-info").remove()
ImgBlock.next("span.text-danger").remove()
if message == "success"
ImgBlock.after $('<span>').addClass('text-info').css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
else
ImgBlock.after $('<span>').addClass('text-danger').html("<br/><b>format is not valid </b>").css({
'font-size': '100%'
'display': 'inline-block'
'font-weight': 'normal'
'margin-left': '1em'
'font-style': 'normal'})
initiateInstanceImage: ->
_this = this
fileinput = $('#fileupload').attr('accept', 'image/jpeg,image/png,image/gif')
settings =
thumbnail_size: 460
thumbnail_bg_color: '#ddd'
thumbnail_border: '1px solid #fff'
thumbnail_shadow: '0 0 0px rgba(0, 0, 0, 0.5)'
label_text: ''
warning_message: 'Not an image file.'
warning_text_color: '#f00'
input_class: 'custom-file-input button button-primary button-block'
# when the file is read it triggers the onload event above.
# handle input changes
fileinput.change (e) ->
$('.p').html ''
if @disabled
return alert('File upload not supported!')
F = @files
if F and F[0]
i = 0
while i < F.length
if F[i].type.match('image.*')
_this.renderInstanceImage F[i], fileinput, settings
else _this.renderLabelFileName F[i].name, "error"
i++
return
return
initiateProfileImage: ->
_this = this
fileElement = $('#file').attr('accept', 'image/jpeg,image/png,image/gif')
settings =
thumbnail_size: 100
thumbnail_bg_color: '#ddd'
thumbnail_border: '3px solid white'
thumbnail_border_radius: '3px'
label_text: ''
warning_message: 'Not an image file.'
warning_text_color: '#f00'
input_class: 'custom-file-input button button-primary button-block'
# when the file is read it triggers the onload event above.
# handle input changes
fileElement.change (e) ->
$('.profile-img-block').html ''
if @disabled
return alert('File upload not supported!')
F = @files
if F and F[0]
i = 0
while i < F.length
if F[i].type.match('image.*')
_this.renderProfileImage F[i], fileElement, settings
_this.renderLabelFileProfile F[i].name, "success"
else
_this.renderLabelFileProfile F[i].name, 'error'
_this.downButton("error")
fileElement.val(null)
i++
return
return
$.ItwayIO.messenger =
activate: ->
_this = this
#_this.chatConnected();
_this.scrollToBottom()
_this.noRoom()
_this.createNewRoom()
o.socket.on 'chat-connected:itway\\Events\\UserEnteredChatEvent', (message) ->
jqxhr = $.ajax(
url: '/chat/' + user_id + '/rooms'
type: 'GET'
dataType: 'json')
jqxhr.done (data) ->
if data.success and data.result.length > 0
console.log data.result
$.each data.result, (index, conversation) ->
o.socket.emit 'join', room: conversation.id
return
return
o.socket.on 'welcome', (data) ->
console.log data.message
o.socket.emit 'join', room: current_thread
return
o.socket.on 'joined', (data) ->
console.log data.message
return
o.socket.on 'userCount', (data) ->
chatRightPanel = $('#chatRightPanel')
if $('#chatRightPanel .numUsers').length >= 1
chatRightPanel.find('small.numUsers').remove()
chatRightPanel.append '<small class="numUsers">' + 'online users count ' + data.userCount + '</small>'
else
chatRightPanel.append '<small class="numUsers">' + 'online users count ' + data.userCount + '</small>'
return
o.socket.on 'userJoined', (data) ->
userList = $('#users')
commentUserList = $('.message-wrap')
userList.find('.media-body .online').remove()
userList.removeClass 'active'
commentUserList.find('.comment .online').remove()
$.each data.users, (index, user) ->
currentUser = userList.find('a[data-userid=\'' + user.customId + '\']')
currentCommentUser = commentUserList.find('.comment[data-comment-user=\'' + user.customId + '\']')
currentUser.addClass 'active'
currentUser.find('.media-body').append '<span class="online"></span>'
currentCommentUser.append '<span class="online">online</span>'
return
return
o.socket.on 'connect', (data) ->
o.socket.emit 'storeClientInfo', customId: user_id
console.log data
return
o.socket.on 'chat.messages:itway\\Events\\ChatMessageCreated', (message) ->
data = message.data
$messageList = $('.msg-wrap .comments')
$conversation = $('.conversation-wrap a[data-room=\'' + data.room + '\']')
message = data.message.body
from_user_id = data.message.user_id
conversation = data.room
_this.getMessages(from_user_id, conversation).done (data) ->
$conversation.find('.last-message-body').text message
if conversation == current_thread
$messageList.append data
_this.scrollToBottom()
if from_user_id != user_id and conversation != current_thread
_this.updateConversationCounter $conversation
return
return
o.socket.on 'chat.rooms:itway\\Events\\ChatRoomCreated', (message) ->
$conversationList = $('.rooms .conversation-wrap')
data = message.data
$messageList = $('.msg-wrap .comments')
$conversationTab = $('.button-panel-conversation a[data-tab=\'rooms\']')
message = data.message.body
from_user_id = data.message.user_id
conversation = data.room
_this.getConversations(user_id, conversation, current_thread).done (data) ->
if !data.notInRoom
$conversationList.prepend data
$conversation = $('.conversation-wrap a[data-room=\'' + conversation + '\']')
_this.notifyNewRoom $conversationTab
_this.updateConversationCounter $conversation
return
return
_this.events()
return
noRoom: ->
noRoom = $('#no-room')
createRoom = $('#create-room')
if noRoom.length >= 1
noRoom.addClass 'hidden'
createRoom.on 'click', (e) ->
e.preventDefault()
noRoom.removeClass('hidden').addClass 'active'
return
return
createNewRoom: ->
$('#chatDropdown').dropdown
onChange: (value, text, $selectedItem) ->
console.log value, text, $selectedItem
return
transition: 'drop'
$('#create-room').on 'click', ->
jqxhr = $.ajax(
url: '/chat/create'
type: 'GET'
dataType: 'html')
msgWrap = $('.message-wrap')
jqxhr.done (data) ->
msgWrap.find('.msg-wrap').addClass 'hidden'
msgWrap.find('.send-wrap').addClass 'hidden'
msgWrap.prepend data
return
return
return
notifyNewRoom: ($conversation) ->
$badge = $conversation.find('.badge')
counter = Number($badge.text())
if $badge.length
$badge.text counter + 1
else
$conversation.append '<span class="badge">1</span>'
return
notifyUsers: (user) ->
usersBlock = $('#users')
usersBlock.prepend '<div class="user" id=' + user.id + '>' + user.name + '</div>'
return
getConversations: (user_id, conversation, current_thread) ->
jqxhr = $.ajax(
url: '/chat/conversations'
type: 'GET'
data:
user_id: user_id
conversation: conversation
current_thread: current_thread)
jqxhr
getMessages: (from_user_id, conversation) ->
jqxhr = $.ajax(
url: '/room/getMessage'
type: 'GET'
data:
user_id: from_user_id
conversation: conversation
dataType: 'html')
jqxhr
sendMessage: (body, conversation, user_id) ->
jqxhr = $.ajax(
url: '/room/create-message'
type: 'POST'
data:
body: body
conversation: conversation
user_id: user_id
dataType: 'json')
jqxhr
updateConversationCounter: ($conversation) ->
$badge = $conversation.find('.chat-user-name small .badge')
counter = Number($badge.text())
if $badge.length
$badge.text counter + 1
else
$conversation.find('.chat-user-name small').append '<span class="badge">1</span>'
return
scrollToBottom: ->
$messageList = $('.msg-wrap')
if $messageList.length
$messageList.animate { scrollTop: $messageList[0].scrollHeight }, 500
return
events: ->
_this = this
$('#btnSendMessage').on 'click', (evt) ->
$messageBox = $('#messageBox')
evt.preventDefault()
_this.sendMessage($messageBox.val(), current_thread, user_id).done (data) ->
console.log data
$messageBox.val ''
$messageBox.focus()
return
return
$('#btnNewMessage').on 'click', ->
$('#newMessageModal').modal 'show'
return
###*
# ctr+Enter to send message
###
$('#messageBox').keypress (event) ->
if event.keyCode == 13 and event.ctrlKey
event.preventDefault()
$('#btnSendMessage').trigger 'click'
return
return
### Tree()
# ======
# Converts the sidebar into a multilevel
# tree view menu.
#
# @type Function
# @Usage: $.ItwayIO.tree('.sidebar')
###
$.ItwayIO.tree = (menu) ->
_this = this
$('li a', $(menu)).on 'click', (e) ->
#Get the clicked link and the next element
$this = $(this)
checkElement = $this.next()
#Check if the next element is a menu and is visible
if checkElement.is('.treeview-menu') and checkElement.is(':visible')
#Close the menu
checkElement.slideUp 'normal', ->
checkElement.removeClass 'menu-open'
#Fix the layout in case the sidebar stretches over the height of the window
#_this.layout.fix();
return
checkElement.parent('li').removeClass 'active'
else if checkElement.is('.treeview-menu') and !checkElement.is(':visible')
#Get the parent menu
parent = $this.parents('ul').first()
#Close all open menus within the parent
ul = parent.find('ul:visible').slideUp('normal')
#Remove the menu-open class from the parent
ul.removeClass 'menu-open'
#Get the parent li
parent_li = $this.parent('li')
#Open the target menu and add the menu-open class
checkElement.slideDown 'normal', ->
#Add the class active to the parent li
checkElement.addClass 'menu-open'
parent.find('li.active').removeClass 'active'
parent_li.addClass 'active'
#Fix the layout in case the sidebar stretches over the height of the window
_this.layout.fix()
return
#if this isn't a link, prevent the page from being redirected
if checkElement.is('.treeview-menu')
e.preventDefault()
return
return
### BoxWidget
# =========
# BoxWidget is a plugin to handle collapsing and
# removing boxes from the screen.
#
# @type Object
# @usage $.ItwayIO.boxWidget.activate()
# Set all your options in the main $.ItwayIO.options object
###
$.ItwayIO.boxWidget =
selectors: $.ItwayIO.options.boxWidgetOptions.boxWidgetSelectors
icons: $.ItwayIO.options.boxWidgetOptions.boxWidgetIcons
activate: ->
_this = this
#Listen for collapse event triggers
$(_this.selectors.collapse).on 'click', (e) ->
e.preventDefault()
_this.collapse $(this)
return
#Listen for remove event triggers
$(_this.selectors.remove).on 'click', (e) ->
e.preventDefault()
_this.remove $(this)
return
return
collapse: (element) ->
_this = this
#Find the box parent
box = element.parents('.box').first()
#Find the body and the footer
box_content = box.find('> .box-body, > .box-footer')
if !box.hasClass('collapsed-box')
#Convert minus into plus
element.children(':first').removeClass(_this.icons.collapse).addClass _this.icons.open
#Hide the content
box_content.slideUp 300, ->
box.addClass 'collapsed-box'
return
else
#Convert plus into minus
element.children(':first').removeClass(_this.icons.open).addClass _this.icons.collapse
#Show the content
box_content.slideDown 300, ->
box.removeClass 'collapsed-box'
return
return
remove: (element) ->
#Find the box parent
box = element.parents('.box').first()
box.slideUp()
return
return
'use strict'
#Make sure jQuery has been loaded before app.js
if typeof jQuery == 'undefined'
throw new Error('ItwayIO requires jQuery')
### ItwayIO
#
# @type Object
# @description $.ItwayIO is the main object for the template's app.
# It's used for implementing functions and options related
# to the template. Keeping everything wrapped in an object
# prevents conflict with other plugins and is a better
# way to organize our code.
###
$.ItwayIO = {}
### --------------------
# - ItwayIO Options -
# --------------------
# Modify these options to suit your implementation
###
$.ItwayIO.options =
host: 'http://' + window.location.hostname
socket: io(APP_URL+':6378')
navbarMenuSlimscroll: true
navbarMenuSlimscrollWidth: '3px'
navbarMenuHeight: '200px'
sidebarControlWidth: '280px'
sidebarToggleSelector: '[data-toggle=\'offcanvas\']'
sidebarPushMenu: true
sidebarSlimScroll: false
sidebarExpandOnHover: true
enableBoxRefresh: true
enableBSToppltip: true
BSTooltipSelector: '[data-toggle=\'tooltip\']'
enableFastclick: true
enableControlSidebar: true
controlSidebarOptions:
toggleBtnSelector: '[data-toggle=\'control-sidebar\']'
selector: '.control-sidebar'
slide: true
enableBoxWidget: true
boxWidgetOptions:
boxWidgetIcons:
collapse: 'fa-minus'
open: 'fa-plus'
remove: 'fa-times'
boxWidgetSelectors:
remove: '[data-widget="remove"]'
collapse: '[data-widget="collapse"]'
directChat:
enable: true
contactToggleSelector: '[data-widget="chat-pane-toggle"]'
search:
searchBTN : $('#search button')
searchResult : $('.search-result #search-result-body')
colors:
lightBlue: '#3c8dbc'
red: '#f56954'
green: '#00a65a'
aqua: '#00c0ef'
yellow: '#f39c12'
blue: '#0073b7'
navy: '#001F3F'
teal: '#39CCCC'
olive: '#3D9970'
lime: '#01FF70'
orange: '#FF851B'
fuchsia: '#F012BE'
purple: '#8E24AA'
maroon: '#D81B60'
black: '#222222'
gray: '#d2d6de'
screenSizes:
xs: 480
sm: 768
md: 992
lg: 1200
### ------------------
# - Implementation -
# ------------------
# The next block of code implements ItwayIO's
# functions and plugins as specified by the
# options above.
###
$ ->
#Extend options if external options exist
if typeof ItwayIOOptions != 'undefined'
$.extend true, $.ItwayIO.options, ItwayIOOptions
#Easy access to options
o = $.ItwayIO.options
#Set up the object
_init o
# activate csrf token
$.ItwayIO.csrf.activate()
$.ItwayIO.search.activate()
# start of handling events and sockets
#Activate messenger functionality
$.ItwayIO.messenger.activate()
$.ItwayIO.imageLoad.activate()
#Enable sidebar tree view controls
if o.navbarMenuSlimscroll and typeof $.fn.slimscroll != 'undefined'
$('.navbar .menu').slimscroll(
height: o.navbarMenuHeight
alwaysVisible: false
size: o.navbarMenuSlimscrollWidth).css 'width', '100%'
#Activate box widget
if o.enableBoxWidget
$.ItwayIO.boxWidget.activate()
#Activate fast click
if o.enableFastclick and typeof FastClick != 'undefined'
FastClick.attach document.body
#Activate direct chat widget
if o.directChat.enable
$(o.directChat.contactToggleSelector).on 'click', ->
box = $(this).parents('.direct-chat').first()
box.toggleClass 'direct-chat-contacts-open'
return
###
# INITIALIZE BUTTON TOGGLE
# ------------------------
###
$('.button-group[data-toggle="btn-toggle"]').each ->
group = $(this)
$(this).find('.button').on 'click', (e) ->
group.find('.button.active').removeClass 'active'
$(this).addClass 'active'
e.preventDefault()
return
return
return
|
[
{
"context": "\nnikita = require '@nikitajs/core'\n{tags, ssh, scratch} = require '../test'\nth",
"end": 28,
"score": 0.6286169290542603,
"start": 26,
"tag": "USERNAME",
"value": "js"
},
{
"context": "tags.ipa\n\nipa =\n principal: 'admin'\n password: 'admin_pw'\n referer: 'https://ipa.nikita/ipa'\n url: 'http",
"end": 194,
"score": 0.9992360472679138,
"start": 186,
"tag": "PASSWORD",
"value": "admin_pw"
},
{
"context": " 'user_add'\n attributes:\n givenname: 'Firstname'\n sn: 'Lastname'\n mail: [ 'user@nik",
"end": 497,
"score": 0.99834144115448,
"start": 488,
"tag": "NAME",
"value": "Firstname"
},
{
"context": "irstname'\n sn: 'Lastname'\n mail: [ 'user@nikita.js.org' ]\n , (err, {status}) ->\n status.should.b",
"end": 557,
"score": 0.9999075531959534,
"start": 539,
"tag": "EMAIL",
"value": "user@nikita.js.org"
},
{
"context": " 'user_add'\n attributes:\n givenname: 'Firstname'\n sn: 'Lastname'\n mail: [ 'user@nik",
"end": 715,
"score": 0.998877763748169,
"start": 706,
"tag": "NAME",
"value": "Firstname"
},
{
"context": "irstname'\n sn: 'Lastname'\n mail: [ 'user@nikita.js.org' ]\n , (err, {status}) ->\n status.should.b",
"end": 775,
"score": 0.9999120235443115,
"start": 757,
"tag": "EMAIL",
"value": "user@nikita.js.org"
},
{
"context": " 'user_add'\n attributes:\n givenname: 'Firstname 1'\n sn: 'Lastname'\n mail: [ 'user@nik",
"end": 1058,
"score": 0.9959150552749634,
"start": 1047,
"tag": "NAME",
"value": "Firstname 1"
},
{
"context": "es:\n givenname: 'Firstname 1'\n sn: 'Lastname'\n mail: [ 'user@nikita.js.org' ]\n .ipa.",
"end": 1081,
"score": 0.7099984884262085,
"start": 1073,
"tag": "NAME",
"value": "Lastname"
},
{
"context": "stname 1'\n sn: 'Lastname'\n mail: [ 'user@nikita.js.org' ]\n .ipa.user ipa,\n uid: 'user_add'\n ",
"end": 1118,
"score": 0.9999085068702698,
"start": 1100,
"tag": "EMAIL",
"value": "user@nikita.js.org"
},
{
"context": " 'user_add'\n attributes:\n givenname: 'Firstname 2'\n sn: 'Lastname'\n mail: [ 'user@nik",
"end": 1212,
"score": 0.9955042004585266,
"start": 1201,
"tag": "NAME",
"value": "Firstname 2"
},
{
"context": "stname 2'\n sn: 'Lastname'\n mail: [ 'user@nikita.js.org' ]\n , (err, {status}) ->\n status.should.b",
"end": 1272,
"score": 0.9999147057533264,
"start": 1254,
"tag": "EMAIL",
"value": "user@nikita.js.org"
},
{
"context": " {result}) ->\n result.givenname.should.eql ['Firstname 2']\n .promise()\n",
"end": 1458,
"score": 0.9839193820953369,
"start": 1449,
"tag": "NAME",
"value": "Firstname"
},
{
"context": " ->\n result.givenname.should.eql ['Firstname 2']\n .promise()\n",
"end": 1460,
"score": 0.9661022424697876,
"start": 1459,
"tag": "NAME",
"value": "2"
}
] | packages/ipa/test/user/index.coffee | chibanemourad/node-nikita | 0 |
nikita = require '@nikitajs/core'
{tags, ssh, scratch} = require '../test'
they = require('ssh2-they').configure ssh...
return unless tags.ipa
ipa =
principal: 'admin'
password: 'admin_pw'
referer: 'https://ipa.nikita/ipa'
url: 'https://ipa.nikita/ipa/session/json'
describe 'ipa.user', ->
they 'create a user', ({ssh}) ->
nikita
ssh: ssh
.ipa.user.del ipa,
uid: 'user_add'
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: 'Firstname'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
, (err, {status}) ->
status.should.be.true() unless err
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: 'Firstname'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
, (err, {status}) ->
status.should.be.false() unless err
.promise()
they 'modify a user', ({ssh}) ->
nikita
ssh: ssh
.ipa.user.del ipa,
uid: 'user_add'
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: 'Firstname 1'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: 'Firstname 2'
sn: 'Lastname'
mail: [ 'user@nikita.js.org' ]
, (err, {status}) ->
status.should.be.true() unless err
.ipa.user.show ipa,
uid: 'user_add'
, (err, {result}) ->
result.givenname.should.eql ['Firstname 2']
.promise()
| 59478 |
nikita = require '@nikitajs/core'
{tags, ssh, scratch} = require '../test'
they = require('ssh2-they').configure ssh...
return unless tags.ipa
ipa =
principal: 'admin'
password: '<PASSWORD>'
referer: 'https://ipa.nikita/ipa'
url: 'https://ipa.nikita/ipa/session/json'
describe 'ipa.user', ->
they 'create a user', ({ssh}) ->
nikita
ssh: ssh
.ipa.user.del ipa,
uid: 'user_add'
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: '<NAME>'
sn: 'Lastname'
mail: [ '<EMAIL>' ]
, (err, {status}) ->
status.should.be.true() unless err
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: '<NAME>'
sn: 'Lastname'
mail: [ '<EMAIL>' ]
, (err, {status}) ->
status.should.be.false() unless err
.promise()
they 'modify a user', ({ssh}) ->
nikita
ssh: ssh
.ipa.user.del ipa,
uid: 'user_add'
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: '<NAME>'
sn: '<NAME>'
mail: [ '<EMAIL>' ]
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: '<NAME>'
sn: 'Lastname'
mail: [ '<EMAIL>' ]
, (err, {status}) ->
status.should.be.true() unless err
.ipa.user.show ipa,
uid: 'user_add'
, (err, {result}) ->
result.givenname.should.eql ['<NAME> <NAME>']
.promise()
| true |
nikita = require '@nikitajs/core'
{tags, ssh, scratch} = require '../test'
they = require('ssh2-they').configure ssh...
return unless tags.ipa
ipa =
principal: 'admin'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
referer: 'https://ipa.nikita/ipa'
url: 'https://ipa.nikita/ipa/session/json'
describe 'ipa.user', ->
they 'create a user', ({ssh}) ->
nikita
ssh: ssh
.ipa.user.del ipa,
uid: 'user_add'
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: 'PI:NAME:<NAME>END_PI'
sn: 'Lastname'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
, (err, {status}) ->
status.should.be.true() unless err
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: 'PI:NAME:<NAME>END_PI'
sn: 'Lastname'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
, (err, {status}) ->
status.should.be.false() unless err
.promise()
they 'modify a user', ({ssh}) ->
nikita
ssh: ssh
.ipa.user.del ipa,
uid: 'user_add'
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: 'PI:NAME:<NAME>END_PI'
sn: 'PI:NAME:<NAME>END_PI'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
.ipa.user ipa,
uid: 'user_add'
attributes:
givenname: 'PI:NAME:<NAME>END_PI'
sn: 'Lastname'
mail: [ 'PI:EMAIL:<EMAIL>END_PI' ]
, (err, {status}) ->
status.should.be.true() unless err
.ipa.user.show ipa,
uid: 'user_add'
, (err, {result}) ->
result.givenname.should.eql ['PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI']
.promise()
|
[
{
"context": ", and talk about the bot's issues.\n#\n# Author:\n# @brucellino\n\n{ WebClient } = require \"@slack/client\"\n\n\n\nmodul",
"end": 859,
"score": 0.9997433423995972,
"start": 848,
"tag": "USERNAME",
"value": "@brucellino"
},
{
"context": "n'\n repo = 'fitsmbot'\n robot.brain.set 'name', \"Fitty I.T. McMaster\"\n robot.brain.set 'alias', \"FitBot\"\n robot.brai",
"end": 1217,
"score": 0.9994139671325684,
"start": 1198,
"tag": "NAME",
"value": "Fitty I.T. McMaster"
},
{
"context": ".set 'alias', \"FitBot\"\n robot.brain.set 'author', \"@brucellino\"\n robot.brain.set 'description', \"A bot who know",
"end": 1295,
"score": 0.9997327923774719,
"start": 1283,
"tag": "USERNAME",
"value": "\"@brucellino"
}
] | scripts/identity.coffee | brucellino/fitsmbot | 0 | # Description:
# This script gives the robot some identity by setting facts
# in its brain.
#
# Dependencies:
# hubot-redis-brain
#
# Configuration:
# REDIS_URL needs to be set in common.env
#
# Commands:
# hubot make an improvement - open an issue against the repo to ask the
# maintainers to improve the bot.
# This doesn't work yet :)
#
# hubot categories -
# should get back the json of categories from the discussion forum
#
# Notes:
# This script is about the bot itself - it's identity and self-improvement
# It's important to know who you are, after all - but it's far more important
# to listen the advice that others who care about you give you.
#
# People wanting to contribute to the betterment of the bot should be able
# to discuss it (on the forum), and talk about the bot's issues.
#
# Author:
# @brucellino
{ WebClient } = require "@slack/client"
module.exports = (robot) ->
issues_url = process.env.GITHUB_API +
'/repos/' + process.env.GITHUB_ORG + '/' +
process.env.GITHUB_SELF_REPO +
'/issues?state=open'
web = new WebClient robot.adapter.options.token
owner = 'EGI-Foundation'
repo = 'fitsmbot'
robot.brain.set 'name', "Fitty I.T. McMaster"
robot.brain.set 'alias', "FitBot"
robot.brain.set 'author', "@brucellino"
robot.brain.set 'description', "A bot who knows FitSM kung-fu"
robot.brain.set 'fitsm_version', "2.4"
# be nice
no_stress = [
"sure!"
"sure thing"
"no stress"
"don't mention it"
"all in a day's work"
"any time buddy"
"Ah fagheddabouddit"
]
# Keep track of who is thanking you and how much.
# Also respond nicely.
robot.hear /thank(s| you)/i, (res) ->
res.send res.random no_stress
robot.respond /not you\s?/i, (res) ->
res.reply "my bad :bow:"
robot.respond /who are you/i, (res) ->
res.reply "My name is #{robot.brain.get('name')}, \
but you can call me #{robot.brain.get('alias')}"
robot.respond /version/i, (res) ->
try
res.reply "#{robot.brain.get 'fitsm_version' }"
catch error
res.reply error
# Give some hints on how to make and update suggetions
robot.hear /help suggestions/i, (res) ->
res.send "to make a suggestion use
`#{robot.name} make suggestion: \"<suggestion>\"`"
res.send "to list all the suggestions use
`#{robot.name} show suggestionbox`"
# Suggest something to hubot
robot.respond /make suggestion: "(.*)"$/i, (res) ->
console.log res.match.length
suggestion = res.match[1]
# current suggestions
s = robot.brain.get('suggestions') or []
console.log suggestion
console.log s
console.log "adding #{suggestion}"
s.push suggestion
console.log s
robot.brain.set 'suggestions', s
res.reply "Added suggestion \"#{suggestion}\" - there are now
#{robot.brain.get('suggestions').length} suggestions in the box"
# sometimes suggestions are silly
robot.respond /(dismiss|remove) suggestion (\d)/i, (res) ->
console.log "trying to remove suggestion #{res.match[2]}
of #{robot.brain.get('suggestions').length}:" +
robot.brain.get('suggestions')["#{res.match[2]}" - 1]
if res.match[2] <= robot.brain.get('suggestions').length
res.reply "removing suggestion
#{robot.brain.get('suggestions')[res.match[2] - 1]}"
suggestions = robot.brain.get('suggestions')
suggestion = robot.brain.get('suggestions')[res.match[2] - 1]
filtered_suggestions = suggestions.filter (s) -> s != suggestion
robot.brain.set 'suggestions', filtered_suggestions
console.log filtered_suggestions
else
res.reply "The suggestion you want to remove is not known to me.
I only have #{robot.brain.get('suggestions').length} suggestions
in my box"
# Show what's in the suggestionbox
robot.respond ///
(get|how many|show)?\s*
suggestion(s?)\s*
(are there\s*)*
(\s*in the\s*)*
(box)?
///i, (res) ->
res.reply "getting suggestions..."
try
robot.brain.suggestions?
suggestions = robot.brain.get 'suggestions'
res.reply "there are #{suggestions.length}
suggestions in the box:\n" +
("#{value + 1}: #{key}\n" for key, value in suggestions)
catch err
res.reply "there is a shocking lack of suggestions"
robot.respond /get issues/i, (res) ->
res.reply "I don't really like to air my dirty laundry in public,
but you can see my issues at #{issues_url}"
console.log issues_url
ts = res.message.id
ch = res.message.room
console.log "timestamp is #{ts}, room is #{ch}"
res.http(issues_url)
.headers(Authorization: 'token ' + process.env.HUBOT_GITHUB_TOKEN)
.get() (err, res, body) ->
issues = JSON.parse body
atts = [ (
"fallback": issue.title
"color": "#36a64f"
"author_name": issue.user.login
"author_link": issue.user.html_url
"author_icon": issue.user.avatar_url
"title": "#{issue.number} - #{issue.title}"
"title_link": issue.html_url
"text": "#{issue.body}"
# "fields": [
# {
# "title": "Priority",
# "value": "High",
# "short": false
# }
# ],
"ts": ts
) for issue in issues ][0]
console.log atts
web.chat.postMessage(
channel: ch
text: "Open issues"
attachments: atts
)
| 95974 | # Description:
# This script gives the robot some identity by setting facts
# in its brain.
#
# Dependencies:
# hubot-redis-brain
#
# Configuration:
# REDIS_URL needs to be set in common.env
#
# Commands:
# hubot make an improvement - open an issue against the repo to ask the
# maintainers to improve the bot.
# This doesn't work yet :)
#
# hubot categories -
# should get back the json of categories from the discussion forum
#
# Notes:
# This script is about the bot itself - it's identity and self-improvement
# It's important to know who you are, after all - but it's far more important
# to listen the advice that others who care about you give you.
#
# People wanting to contribute to the betterment of the bot should be able
# to discuss it (on the forum), and talk about the bot's issues.
#
# Author:
# @brucellino
{ WebClient } = require "@slack/client"
module.exports = (robot) ->
issues_url = process.env.GITHUB_API +
'/repos/' + process.env.GITHUB_ORG + '/' +
process.env.GITHUB_SELF_REPO +
'/issues?state=open'
web = new WebClient robot.adapter.options.token
owner = 'EGI-Foundation'
repo = 'fitsmbot'
robot.brain.set 'name', "<NAME>"
robot.brain.set 'alias', "FitBot"
robot.brain.set 'author', "@brucellino"
robot.brain.set 'description', "A bot who knows FitSM kung-fu"
robot.brain.set 'fitsm_version', "2.4"
# be nice
no_stress = [
"sure!"
"sure thing"
"no stress"
"don't mention it"
"all in a day's work"
"any time buddy"
"Ah fagheddabouddit"
]
# Keep track of who is thanking you and how much.
# Also respond nicely.
robot.hear /thank(s| you)/i, (res) ->
res.send res.random no_stress
robot.respond /not you\s?/i, (res) ->
res.reply "my bad :bow:"
robot.respond /who are you/i, (res) ->
res.reply "My name is #{robot.brain.get('name')}, \
but you can call me #{robot.brain.get('alias')}"
robot.respond /version/i, (res) ->
try
res.reply "#{robot.brain.get 'fitsm_version' }"
catch error
res.reply error
# Give some hints on how to make and update suggetions
robot.hear /help suggestions/i, (res) ->
res.send "to make a suggestion use
`#{robot.name} make suggestion: \"<suggestion>\"`"
res.send "to list all the suggestions use
`#{robot.name} show suggestionbox`"
# Suggest something to hubot
robot.respond /make suggestion: "(.*)"$/i, (res) ->
console.log res.match.length
suggestion = res.match[1]
# current suggestions
s = robot.brain.get('suggestions') or []
console.log suggestion
console.log s
console.log "adding #{suggestion}"
s.push suggestion
console.log s
robot.brain.set 'suggestions', s
res.reply "Added suggestion \"#{suggestion}\" - there are now
#{robot.brain.get('suggestions').length} suggestions in the box"
# sometimes suggestions are silly
robot.respond /(dismiss|remove) suggestion (\d)/i, (res) ->
console.log "trying to remove suggestion #{res.match[2]}
of #{robot.brain.get('suggestions').length}:" +
robot.brain.get('suggestions')["#{res.match[2]}" - 1]
if res.match[2] <= robot.brain.get('suggestions').length
res.reply "removing suggestion
#{robot.brain.get('suggestions')[res.match[2] - 1]}"
suggestions = robot.brain.get('suggestions')
suggestion = robot.brain.get('suggestions')[res.match[2] - 1]
filtered_suggestions = suggestions.filter (s) -> s != suggestion
robot.brain.set 'suggestions', filtered_suggestions
console.log filtered_suggestions
else
res.reply "The suggestion you want to remove is not known to me.
I only have #{robot.brain.get('suggestions').length} suggestions
in my box"
# Show what's in the suggestionbox
robot.respond ///
(get|how many|show)?\s*
suggestion(s?)\s*
(are there\s*)*
(\s*in the\s*)*
(box)?
///i, (res) ->
res.reply "getting suggestions..."
try
robot.brain.suggestions?
suggestions = robot.brain.get 'suggestions'
res.reply "there are #{suggestions.length}
suggestions in the box:\n" +
("#{value + 1}: #{key}\n" for key, value in suggestions)
catch err
res.reply "there is a shocking lack of suggestions"
robot.respond /get issues/i, (res) ->
res.reply "I don't really like to air my dirty laundry in public,
but you can see my issues at #{issues_url}"
console.log issues_url
ts = res.message.id
ch = res.message.room
console.log "timestamp is #{ts}, room is #{ch}"
res.http(issues_url)
.headers(Authorization: 'token ' + process.env.HUBOT_GITHUB_TOKEN)
.get() (err, res, body) ->
issues = JSON.parse body
atts = [ (
"fallback": issue.title
"color": "#36a64f"
"author_name": issue.user.login
"author_link": issue.user.html_url
"author_icon": issue.user.avatar_url
"title": "#{issue.number} - #{issue.title}"
"title_link": issue.html_url
"text": "#{issue.body}"
# "fields": [
# {
# "title": "Priority",
# "value": "High",
# "short": false
# }
# ],
"ts": ts
) for issue in issues ][0]
console.log atts
web.chat.postMessage(
channel: ch
text: "Open issues"
attachments: atts
)
| true | # Description:
# This script gives the robot some identity by setting facts
# in its brain.
#
# Dependencies:
# hubot-redis-brain
#
# Configuration:
# REDIS_URL needs to be set in common.env
#
# Commands:
# hubot make an improvement - open an issue against the repo to ask the
# maintainers to improve the bot.
# This doesn't work yet :)
#
# hubot categories -
# should get back the json of categories from the discussion forum
#
# Notes:
# This script is about the bot itself - it's identity and self-improvement
# It's important to know who you are, after all - but it's far more important
# to listen the advice that others who care about you give you.
#
# People wanting to contribute to the betterment of the bot should be able
# to discuss it (on the forum), and talk about the bot's issues.
#
# Author:
# @brucellino
{ WebClient } = require "@slack/client"
module.exports = (robot) ->
issues_url = process.env.GITHUB_API +
'/repos/' + process.env.GITHUB_ORG + '/' +
process.env.GITHUB_SELF_REPO +
'/issues?state=open'
web = new WebClient robot.adapter.options.token
owner = 'EGI-Foundation'
repo = 'fitsmbot'
robot.brain.set 'name', "PI:NAME:<NAME>END_PI"
robot.brain.set 'alias', "FitBot"
robot.brain.set 'author', "@brucellino"
robot.brain.set 'description', "A bot who knows FitSM kung-fu"
robot.brain.set 'fitsm_version', "2.4"
# be nice
no_stress = [
"sure!"
"sure thing"
"no stress"
"don't mention it"
"all in a day's work"
"any time buddy"
"Ah fagheddabouddit"
]
# Keep track of who is thanking you and how much.
# Also respond nicely.
robot.hear /thank(s| you)/i, (res) ->
res.send res.random no_stress
robot.respond /not you\s?/i, (res) ->
res.reply "my bad :bow:"
robot.respond /who are you/i, (res) ->
res.reply "My name is #{robot.brain.get('name')}, \
but you can call me #{robot.brain.get('alias')}"
robot.respond /version/i, (res) ->
try
res.reply "#{robot.brain.get 'fitsm_version' }"
catch error
res.reply error
# Give some hints on how to make and update suggetions
robot.hear /help suggestions/i, (res) ->
res.send "to make a suggestion use
`#{robot.name} make suggestion: \"<suggestion>\"`"
res.send "to list all the suggestions use
`#{robot.name} show suggestionbox`"
# Suggest something to hubot
robot.respond /make suggestion: "(.*)"$/i, (res) ->
console.log res.match.length
suggestion = res.match[1]
# current suggestions
s = robot.brain.get('suggestions') or []
console.log suggestion
console.log s
console.log "adding #{suggestion}"
s.push suggestion
console.log s
robot.brain.set 'suggestions', s
res.reply "Added suggestion \"#{suggestion}\" - there are now
#{robot.brain.get('suggestions').length} suggestions in the box"
# sometimes suggestions are silly
robot.respond /(dismiss|remove) suggestion (\d)/i, (res) ->
console.log "trying to remove suggestion #{res.match[2]}
of #{robot.brain.get('suggestions').length}:" +
robot.brain.get('suggestions')["#{res.match[2]}" - 1]
if res.match[2] <= robot.brain.get('suggestions').length
res.reply "removing suggestion
#{robot.brain.get('suggestions')[res.match[2] - 1]}"
suggestions = robot.brain.get('suggestions')
suggestion = robot.brain.get('suggestions')[res.match[2] - 1]
filtered_suggestions = suggestions.filter (s) -> s != suggestion
robot.brain.set 'suggestions', filtered_suggestions
console.log filtered_suggestions
else
res.reply "The suggestion you want to remove is not known to me.
I only have #{robot.brain.get('suggestions').length} suggestions
in my box"
# Show what's in the suggestionbox
robot.respond ///
(get|how many|show)?\s*
suggestion(s?)\s*
(are there\s*)*
(\s*in the\s*)*
(box)?
///i, (res) ->
res.reply "getting suggestions..."
try
robot.brain.suggestions?
suggestions = robot.brain.get 'suggestions'
res.reply "there are #{suggestions.length}
suggestions in the box:\n" +
("#{value + 1}: #{key}\n" for key, value in suggestions)
catch err
res.reply "there is a shocking lack of suggestions"
robot.respond /get issues/i, (res) ->
res.reply "I don't really like to air my dirty laundry in public,
but you can see my issues at #{issues_url}"
console.log issues_url
ts = res.message.id
ch = res.message.room
console.log "timestamp is #{ts}, room is #{ch}"
res.http(issues_url)
.headers(Authorization: 'token ' + process.env.HUBOT_GITHUB_TOKEN)
.get() (err, res, body) ->
issues = JSON.parse body
atts = [ (
"fallback": issue.title
"color": "#36a64f"
"author_name": issue.user.login
"author_link": issue.user.html_url
"author_icon": issue.user.avatar_url
"title": "#{issue.number} - #{issue.title}"
"title_link": issue.html_url
"text": "#{issue.body}"
# "fields": [
# {
# "title": "Priority",
# "value": "High",
# "short": false
# }
# ],
"ts": ts
) for issue in issues ][0]
console.log atts
web.chat.postMessage(
channel: ch
text: "Open issues"
attachments: atts
)
|
[
{
"context": "l ('==') values)\n # list.find({age: 20, name: 'John'})\n # @example Find by string query = find by no",
"end": 4613,
"score": 0.9998061060905457,
"start": 4609,
"tag": "NAME",
"value": "John"
}
] | app/components/list.coffee | pieces-js/pieces-list | 0 | 'use strict'
Base = pi.components.Base
ListEvent = require './events/list_events'
Nod = pi.Nod
utils = pi.utils
Klass = require './utils/klass'
# Basic list component
class List extends Base
merge_classes: [Klass.DISABLED, Klass.ACTIVE, Klass.HIDDEN]
@active_property @::, 'size', default: 0
@active_property @::,
'empty',
default: true,
class: Klass.EMPTY
event: ListEvent.Empty
preinitialize: ->
super
@list_klass = @options.list_klass || Klass.LIST
@item_klass = @options.item_klass || Klass.LIST_ITEM
@items = []
@buffer = document.createDocumentFragment()
initialize: ->
super
@items_cont = @find(".#{ @list_klass }") || @
@parse_html_items()
@
postinitialize: ->
super
@_invalidate_size()
unless @options.noclick?
@listen ".#{ @item_klass }", 'click', (e) =>
unless utils.is_clickable(e.origTarget)
if @_item_clicked(e.target)
e.cancel()
parse_html_items: ->
for node in @items_cont.find_cut(".#{ @item_klass }")
do (node) =>
@add_item Nod.create(node), true
@_flush_buffer()
# Set list elements
# @params [Array, Null] data if null then clear list
data_provider: (data = null, silent = false, remove = true) ->
@clear(silent, remove) if @items.length
if data?
@add_item(item,true) for item in data
@update('load', silent)
@
add_item: (data, silent = false) ->
item = @_create_item data, @items.length
return unless item?
@items.push item
unless silent then @items_cont.append(item) else @buffer.appendChild(item.node)
@_invalidate_size() unless silent
@trigger(ListEvent.Update, {type: ListEvent.ItemAdded, item:item}) unless silent
item
add_item_at: (data, index, silent = false) ->
if @items.length-1 < index
return @add_item(data,silent)
item = @_create_item data, index
@items.splice(index,0,item)
_after = @items[index+1]
# save item index in DOM element
item.record.$index = index
item.record.$num = index+1
_after.insertBefore item
@_need_update_indeces = true
@_invalidate_size()
unless silent
@_update_indeces()
@trigger(ListEvent.Update, {type: ListEvent.ItemAdded, item:item})
item
remove_item: (item, silent = false, destroy = true) ->
index = @items.indexOf(item)
if index > -1
@items.splice(index,1)
if destroy
@_destroy_item(item)
else
item.detach()
@_invalidate_size()
@_need_update_indeces = true
unless silent
@_update_indeces()
@trigger(ListEvent.Update, {type: ListEvent.ItemRemoved,item:item})
true
else
false
remove_item_at: (index, silent = false) ->
if @items.length-1 < index
return
item = @items[index]
@remove_item(item,silent)
remove_items: (items) ->
for item in items
@remove_item(item, true)
@update()
return
# redraw item with new data
# How it works:
# 1. Render new item for new data
# 2. Update item html (merge classes)
# 3. Update item record (by extending it with new item data (overwriting))
update_item: (item, data, silent=false) ->
new_item = @renderer.render data, false
# update associated record
utils.extend item.record, new_item.record, true
# remove_children
item.remove_children()
# update HTML
item.html new_item.html()
#try to remove runtime classes
for klass in item.node.className.split(/\s+/)
item.removeClass(klass) if klass and !(klass in @merge_classes)
#merge classes
item.mergeClasses new_item
# piecify ...
item.piecify()
# ... and postinitialize (because DOM was updated)
item.postinitialize()
@trigger(ListEvent.Update, {type: ListEvent.ItemUpdated, item: item}) unless silent
item
move_item: (item, index) ->
return if (item.record.$index is index) || (index>@items.length-1)
@items.splice @items.indexOf(item), 1
if index is @items.length
@items.push item
@items_cont.append(item)
else
@items.splice(index,0,item)
_after = @items[index+1]
_after.insertBefore item
@_need_update_indeces = true
@_update_indeces()
item
# Find items within list using query
#
# @params [String, Object] query
#
# @example Find items by object mask (would match all objects that have keys and equal ('==') values)
# list.find({age: 20, name: 'John'})
# @example Find by string query = find by nod content
# list.find(".title:keyword") // match all items for which item.nod.find('.title').text().search(/keyword/) > -1
where: (query) ->
matcher = if typeof query == "string" then utils.matchers.nod(query) else utils.matchers.object(query)
item for item in @items when matcher(item)
records: ->
@items.map((item) -> item.record)
update: (type, silent = false) ->
@_flush_buffer()
@_update_indeces() if @_need_update_indeces
@_invalidate_size()
@trigger(ListEvent.Update, {type: type}) unless silent
clear: (silent = false, remove = true) ->
@items_cont.detach_children() unless remove
@items_cont.remove_children() if remove
@items.length = 0
@_invalidate_size()
@trigger(ListEvent.Update, {type: ListEvent.Clear}) unless silent
_update_indeces: ->
for item,i in @items
item.record.$index = i
item.record.$num = i+1
@_need_update_indeces = false
_invalidate_size: ->
@size = @items.length
@empty = @size is 0
_create_item: (data={},index) ->
if data instanceof Nod and data.is_list_item
if data.host is @
data.$index = index
data.$num = index+1
return data
else
return null
if data instanceof Nod
data.data('$index', index)
data.data('$num', index+1)
else
data.$index = index
data.$num = index+1
item = @renderer.render data, true, @
return unless item?
item.record ||={}
item.is_list_item = true
item
_destroy_item: (item) ->
item.remove()
_flush_buffer: (append = true) ->
@items_cont.append @buffer if append
while @buffer.firstChild
@buffer.removeChild(@buffer.firstChild)
_item_clicked: (target) ->
return unless target.is_list_item
item = target
if item and item.host is @
@trigger ListEvent.ItemClick, {item: item}
true
module.exports = List
| 164406 | 'use strict'
Base = pi.components.Base
ListEvent = require './events/list_events'
Nod = pi.Nod
utils = pi.utils
Klass = require './utils/klass'
# Basic list component
class List extends Base
merge_classes: [Klass.DISABLED, Klass.ACTIVE, Klass.HIDDEN]
@active_property @::, 'size', default: 0
@active_property @::,
'empty',
default: true,
class: Klass.EMPTY
event: ListEvent.Empty
preinitialize: ->
super
@list_klass = @options.list_klass || Klass.LIST
@item_klass = @options.item_klass || Klass.LIST_ITEM
@items = []
@buffer = document.createDocumentFragment()
initialize: ->
super
@items_cont = @find(".#{ @list_klass }") || @
@parse_html_items()
@
postinitialize: ->
super
@_invalidate_size()
unless @options.noclick?
@listen ".#{ @item_klass }", 'click', (e) =>
unless utils.is_clickable(e.origTarget)
if @_item_clicked(e.target)
e.cancel()
parse_html_items: ->
for node in @items_cont.find_cut(".#{ @item_klass }")
do (node) =>
@add_item Nod.create(node), true
@_flush_buffer()
# Set list elements
# @params [Array, Null] data if null then clear list
data_provider: (data = null, silent = false, remove = true) ->
@clear(silent, remove) if @items.length
if data?
@add_item(item,true) for item in data
@update('load', silent)
@
add_item: (data, silent = false) ->
item = @_create_item data, @items.length
return unless item?
@items.push item
unless silent then @items_cont.append(item) else @buffer.appendChild(item.node)
@_invalidate_size() unless silent
@trigger(ListEvent.Update, {type: ListEvent.ItemAdded, item:item}) unless silent
item
add_item_at: (data, index, silent = false) ->
if @items.length-1 < index
return @add_item(data,silent)
item = @_create_item data, index
@items.splice(index,0,item)
_after = @items[index+1]
# save item index in DOM element
item.record.$index = index
item.record.$num = index+1
_after.insertBefore item
@_need_update_indeces = true
@_invalidate_size()
unless silent
@_update_indeces()
@trigger(ListEvent.Update, {type: ListEvent.ItemAdded, item:item})
item
remove_item: (item, silent = false, destroy = true) ->
index = @items.indexOf(item)
if index > -1
@items.splice(index,1)
if destroy
@_destroy_item(item)
else
item.detach()
@_invalidate_size()
@_need_update_indeces = true
unless silent
@_update_indeces()
@trigger(ListEvent.Update, {type: ListEvent.ItemRemoved,item:item})
true
else
false
remove_item_at: (index, silent = false) ->
if @items.length-1 < index
return
item = @items[index]
@remove_item(item,silent)
remove_items: (items) ->
for item in items
@remove_item(item, true)
@update()
return
# redraw item with new data
# How it works:
# 1. Render new item for new data
# 2. Update item html (merge classes)
# 3. Update item record (by extending it with new item data (overwriting))
update_item: (item, data, silent=false) ->
new_item = @renderer.render data, false
# update associated record
utils.extend item.record, new_item.record, true
# remove_children
item.remove_children()
# update HTML
item.html new_item.html()
#try to remove runtime classes
for klass in item.node.className.split(/\s+/)
item.removeClass(klass) if klass and !(klass in @merge_classes)
#merge classes
item.mergeClasses new_item
# piecify ...
item.piecify()
# ... and postinitialize (because DOM was updated)
item.postinitialize()
@trigger(ListEvent.Update, {type: ListEvent.ItemUpdated, item: item}) unless silent
item
move_item: (item, index) ->
return if (item.record.$index is index) || (index>@items.length-1)
@items.splice @items.indexOf(item), 1
if index is @items.length
@items.push item
@items_cont.append(item)
else
@items.splice(index,0,item)
_after = @items[index+1]
_after.insertBefore item
@_need_update_indeces = true
@_update_indeces()
item
# Find items within list using query
#
# @params [String, Object] query
#
# @example Find items by object mask (would match all objects that have keys and equal ('==') values)
# list.find({age: 20, name: '<NAME>'})
# @example Find by string query = find by nod content
# list.find(".title:keyword") // match all items for which item.nod.find('.title').text().search(/keyword/) > -1
where: (query) ->
matcher = if typeof query == "string" then utils.matchers.nod(query) else utils.matchers.object(query)
item for item in @items when matcher(item)
records: ->
@items.map((item) -> item.record)
update: (type, silent = false) ->
@_flush_buffer()
@_update_indeces() if @_need_update_indeces
@_invalidate_size()
@trigger(ListEvent.Update, {type: type}) unless silent
clear: (silent = false, remove = true) ->
@items_cont.detach_children() unless remove
@items_cont.remove_children() if remove
@items.length = 0
@_invalidate_size()
@trigger(ListEvent.Update, {type: ListEvent.Clear}) unless silent
_update_indeces: ->
for item,i in @items
item.record.$index = i
item.record.$num = i+1
@_need_update_indeces = false
_invalidate_size: ->
@size = @items.length
@empty = @size is 0
_create_item: (data={},index) ->
if data instanceof Nod and data.is_list_item
if data.host is @
data.$index = index
data.$num = index+1
return data
else
return null
if data instanceof Nod
data.data('$index', index)
data.data('$num', index+1)
else
data.$index = index
data.$num = index+1
item = @renderer.render data, true, @
return unless item?
item.record ||={}
item.is_list_item = true
item
_destroy_item: (item) ->
item.remove()
_flush_buffer: (append = true) ->
@items_cont.append @buffer if append
while @buffer.firstChild
@buffer.removeChild(@buffer.firstChild)
_item_clicked: (target) ->
return unless target.is_list_item
item = target
if item and item.host is @
@trigger ListEvent.ItemClick, {item: item}
true
module.exports = List
| true | 'use strict'
Base = pi.components.Base
ListEvent = require './events/list_events'
Nod = pi.Nod
utils = pi.utils
Klass = require './utils/klass'
# Basic list component
class List extends Base
merge_classes: [Klass.DISABLED, Klass.ACTIVE, Klass.HIDDEN]
@active_property @::, 'size', default: 0
@active_property @::,
'empty',
default: true,
class: Klass.EMPTY
event: ListEvent.Empty
preinitialize: ->
super
@list_klass = @options.list_klass || Klass.LIST
@item_klass = @options.item_klass || Klass.LIST_ITEM
@items = []
@buffer = document.createDocumentFragment()
initialize: ->
super
@items_cont = @find(".#{ @list_klass }") || @
@parse_html_items()
@
postinitialize: ->
super
@_invalidate_size()
unless @options.noclick?
@listen ".#{ @item_klass }", 'click', (e) =>
unless utils.is_clickable(e.origTarget)
if @_item_clicked(e.target)
e.cancel()
parse_html_items: ->
for node in @items_cont.find_cut(".#{ @item_klass }")
do (node) =>
@add_item Nod.create(node), true
@_flush_buffer()
# Set list elements
# @params [Array, Null] data if null then clear list
data_provider: (data = null, silent = false, remove = true) ->
@clear(silent, remove) if @items.length
if data?
@add_item(item,true) for item in data
@update('load', silent)
@
add_item: (data, silent = false) ->
item = @_create_item data, @items.length
return unless item?
@items.push item
unless silent then @items_cont.append(item) else @buffer.appendChild(item.node)
@_invalidate_size() unless silent
@trigger(ListEvent.Update, {type: ListEvent.ItemAdded, item:item}) unless silent
item
add_item_at: (data, index, silent = false) ->
if @items.length-1 < index
return @add_item(data,silent)
item = @_create_item data, index
@items.splice(index,0,item)
_after = @items[index+1]
# save item index in DOM element
item.record.$index = index
item.record.$num = index+1
_after.insertBefore item
@_need_update_indeces = true
@_invalidate_size()
unless silent
@_update_indeces()
@trigger(ListEvent.Update, {type: ListEvent.ItemAdded, item:item})
item
remove_item: (item, silent = false, destroy = true) ->
index = @items.indexOf(item)
if index > -1
@items.splice(index,1)
if destroy
@_destroy_item(item)
else
item.detach()
@_invalidate_size()
@_need_update_indeces = true
unless silent
@_update_indeces()
@trigger(ListEvent.Update, {type: ListEvent.ItemRemoved,item:item})
true
else
false
remove_item_at: (index, silent = false) ->
if @items.length-1 < index
return
item = @items[index]
@remove_item(item,silent)
remove_items: (items) ->
for item in items
@remove_item(item, true)
@update()
return
# redraw item with new data
# How it works:
# 1. Render new item for new data
# 2. Update item html (merge classes)
# 3. Update item record (by extending it with new item data (overwriting))
update_item: (item, data, silent=false) ->
new_item = @renderer.render data, false
# update associated record
utils.extend item.record, new_item.record, true
# remove_children
item.remove_children()
# update HTML
item.html new_item.html()
#try to remove runtime classes
for klass in item.node.className.split(/\s+/)
item.removeClass(klass) if klass and !(klass in @merge_classes)
#merge classes
item.mergeClasses new_item
# piecify ...
item.piecify()
# ... and postinitialize (because DOM was updated)
item.postinitialize()
@trigger(ListEvent.Update, {type: ListEvent.ItemUpdated, item: item}) unless silent
item
move_item: (item, index) ->
return if (item.record.$index is index) || (index>@items.length-1)
@items.splice @items.indexOf(item), 1
if index is @items.length
@items.push item
@items_cont.append(item)
else
@items.splice(index,0,item)
_after = @items[index+1]
_after.insertBefore item
@_need_update_indeces = true
@_update_indeces()
item
# Find items within list using query
#
# @params [String, Object] query
#
# @example Find items by object mask (would match all objects that have keys and equal ('==') values)
# list.find({age: 20, name: 'PI:NAME:<NAME>END_PI'})
# @example Find by string query = find by nod content
# list.find(".title:keyword") // match all items for which item.nod.find('.title').text().search(/keyword/) > -1
where: (query) ->
matcher = if typeof query == "string" then utils.matchers.nod(query) else utils.matchers.object(query)
item for item in @items when matcher(item)
records: ->
@items.map((item) -> item.record)
update: (type, silent = false) ->
@_flush_buffer()
@_update_indeces() if @_need_update_indeces
@_invalidate_size()
@trigger(ListEvent.Update, {type: type}) unless silent
clear: (silent = false, remove = true) ->
@items_cont.detach_children() unless remove
@items_cont.remove_children() if remove
@items.length = 0
@_invalidate_size()
@trigger(ListEvent.Update, {type: ListEvent.Clear}) unless silent
_update_indeces: ->
for item,i in @items
item.record.$index = i
item.record.$num = i+1
@_need_update_indeces = false
_invalidate_size: ->
@size = @items.length
@empty = @size is 0
_create_item: (data={},index) ->
if data instanceof Nod and data.is_list_item
if data.host is @
data.$index = index
data.$num = index+1
return data
else
return null
if data instanceof Nod
data.data('$index', index)
data.data('$num', index+1)
else
data.$index = index
data.$num = index+1
item = @renderer.render data, true, @
return unless item?
item.record ||={}
item.is_list_item = true
item
_destroy_item: (item) ->
item.remove()
_flush_buffer: (append = true) ->
@items_cont.append @buffer if append
while @buffer.firstChild
@buffer.removeChild(@buffer.firstChild)
_item_clicked: (target) ->
return unless target.is_list_item
item = target
if item and item.host is @
@trigger ListEvent.ItemClick, {item: item}
true
module.exports = List
|
[
{
"context": "###\ngrunt-init-grunt-task\nhttps://github.com/weareinteractive/grunt-init-grunt-task\n\nCopyright (c) 2013 We Are ",
"end": 61,
"score": 0.9994125366210938,
"start": 45,
"tag": "USERNAME",
"value": "weareinteractive"
},
{
"context": "eractive/grunt-init-grunt-task\n\nCopyright (c) 2013 We Are Interactive, \"Cowboy\" Ben Alman, contributors\nLicensed under ",
"end": 122,
"score": 0.998776376247406,
"start": 104,
"tag": "NAME",
"value": "We Are Interactive"
},
{
"context": "unt-task\n\nCopyright (c) 2013 We Are Interactive, \"Cowboy\" Ben Alman, contributors\nLicensed under the MIT l",
"end": 131,
"score": 0.9994402527809143,
"start": 125,
"tag": "USERNAME",
"value": "Cowboy"
},
{
"context": "k\n\nCopyright (c) 2013 We Are Interactive, \"Cowboy\" Ben Alman, contributors\nLicensed under the MIT license.\n###",
"end": 142,
"score": 0.9997807145118713,
"start": 133,
"tag": "NAME",
"value": "Ben Alman"
}
] | template.coffee | gruntjs-updater/grunt-init-grunt-task | 0 | ###
grunt-init-grunt-task
https://github.com/weareinteractive/grunt-init-grunt-task
Copyright (c) 2013 We Are Interactive, "Cowboy" Ben Alman, contributors
Licensed under the MIT license.
###
"use strict"
# Basic template description.
exports.description =
"""
Create a Grunt plugin, including CoffeeScript, Mocha tests, Chai and Bump.Creates an ExtendScript project.
"""
# Template-specific notes to be displayed before question prompts.
exports.notes =
"""
For more information about Grunt plugin best practices,
please see the docs at http://gruntjs.com/creating-plugins
"""
# Template-specific notes to be displayed after question prompts.
exports.after =
"""
You should now install project dependencies with _npm install_.
After that, you may execute project tasks with _grunt_.
For more information about installing and configuring Grunt,
please see the Getting Started guide:
http://gruntjs.com/getting-started
"""
# Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = "*"
# The actual init template.
exports.template = (grunt, init, done) ->
init.process({type: "grunt"}, [
# Prompt for these values.
init.prompt("name", (value, props, done) ->
# Prepend grunt- to default name.
name = "grunt-#{value}"
# Replace 'grunt-contrib' with 'grunt' and give a warning
contribRe = /^grunt-contrib/
if contribRe.test(name)
grunt.log.writelns(("Removing 'contrib' from your project's name. The grunt-contrib " + "namespace is reserved for tasks maintained by the grunt team.").red)
name = name.replace(contribRe, "grunt")
done(null, name)
)
init.prompt("description", "The best Grunt plugin ever.")
init.prompt("version")
init.prompt("repository")
init.prompt("homepage")
init.prompt("bugs")
init.prompt("licenses")
init.prompt("author_name")
init.prompt("author_email")
init.prompt("author_url")
init.prompt("grunt_version")
init.prompt("node_version", grunt.package.engines.node)
], (err, props) ->
# Set a few grunt-plugin-specific properties.
props.short_name = props.name.replace(/^grunt[\-_]?/, "").replace(/[\W_]+/g, "_").replace(/^(\d)/, "_$1")
props.main = "Gruntfile.coffee"
props.npm_test = "grunt test"
props.keywords = ["gruntplugin"]
props.devDependencies = {
"chai": "~1.8.0"
"grunt-coffeelint": "0.0.7"
"grunt-contrib-clean": "~0.5.0"
"grunt-mocha-cov": "0.0.7"
"coffee-script": "~1.6.3"
"grunt-bumper": "~1.0.1"
}
props.peerDependencies = { "grunt":props.grunt_version }
# Files to copy (and process).
files = init.filesToCopy(props)
# Add properly-named license files.
init.addLicenseFiles(files, props.licenses)
# Actually copy (and process) files.
init.copyAndProcess(files, props)
# Generate package.json file.
init.writePackageJSON("package.json", props)
# All done!
done()
) | 112868 | ###
grunt-init-grunt-task
https://github.com/weareinteractive/grunt-init-grunt-task
Copyright (c) 2013 <NAME>, "Cowboy" <NAME>, contributors
Licensed under the MIT license.
###
"use strict"
# Basic template description.
exports.description =
"""
Create a Grunt plugin, including CoffeeScript, Mocha tests, Chai and Bump.Creates an ExtendScript project.
"""
# Template-specific notes to be displayed before question prompts.
exports.notes =
"""
For more information about Grunt plugin best practices,
please see the docs at http://gruntjs.com/creating-plugins
"""
# Template-specific notes to be displayed after question prompts.
exports.after =
"""
You should now install project dependencies with _npm install_.
After that, you may execute project tasks with _grunt_.
For more information about installing and configuring Grunt,
please see the Getting Started guide:
http://gruntjs.com/getting-started
"""
# Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = "*"
# The actual init template.
exports.template = (grunt, init, done) ->
init.process({type: "grunt"}, [
# Prompt for these values.
init.prompt("name", (value, props, done) ->
# Prepend grunt- to default name.
name = "grunt-#{value}"
# Replace 'grunt-contrib' with 'grunt' and give a warning
contribRe = /^grunt-contrib/
if contribRe.test(name)
grunt.log.writelns(("Removing 'contrib' from your project's name. The grunt-contrib " + "namespace is reserved for tasks maintained by the grunt team.").red)
name = name.replace(contribRe, "grunt")
done(null, name)
)
init.prompt("description", "The best Grunt plugin ever.")
init.prompt("version")
init.prompt("repository")
init.prompt("homepage")
init.prompt("bugs")
init.prompt("licenses")
init.prompt("author_name")
init.prompt("author_email")
init.prompt("author_url")
init.prompt("grunt_version")
init.prompt("node_version", grunt.package.engines.node)
], (err, props) ->
# Set a few grunt-plugin-specific properties.
props.short_name = props.name.replace(/^grunt[\-_]?/, "").replace(/[\W_]+/g, "_").replace(/^(\d)/, "_$1")
props.main = "Gruntfile.coffee"
props.npm_test = "grunt test"
props.keywords = ["gruntplugin"]
props.devDependencies = {
"chai": "~1.8.0"
"grunt-coffeelint": "0.0.7"
"grunt-contrib-clean": "~0.5.0"
"grunt-mocha-cov": "0.0.7"
"coffee-script": "~1.6.3"
"grunt-bumper": "~1.0.1"
}
props.peerDependencies = { "grunt":props.grunt_version }
# Files to copy (and process).
files = init.filesToCopy(props)
# Add properly-named license files.
init.addLicenseFiles(files, props.licenses)
# Actually copy (and process) files.
init.copyAndProcess(files, props)
# Generate package.json file.
init.writePackageJSON("package.json", props)
# All done!
done()
) | true | ###
grunt-init-grunt-task
https://github.com/weareinteractive/grunt-init-grunt-task
Copyright (c) 2013 PI:NAME:<NAME>END_PI, "Cowboy" PI:NAME:<NAME>END_PI, contributors
Licensed under the MIT license.
###
"use strict"
# Basic template description.
exports.description =
"""
Create a Grunt plugin, including CoffeeScript, Mocha tests, Chai and Bump.Creates an ExtendScript project.
"""
# Template-specific notes to be displayed before question prompts.
exports.notes =
"""
For more information about Grunt plugin best practices,
please see the docs at http://gruntjs.com/creating-plugins
"""
# Template-specific notes to be displayed after question prompts.
exports.after =
"""
You should now install project dependencies with _npm install_.
After that, you may execute project tasks with _grunt_.
For more information about installing and configuring Grunt,
please see the Getting Started guide:
http://gruntjs.com/getting-started
"""
# Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = "*"
# The actual init template.
exports.template = (grunt, init, done) ->
init.process({type: "grunt"}, [
# Prompt for these values.
init.prompt("name", (value, props, done) ->
# Prepend grunt- to default name.
name = "grunt-#{value}"
# Replace 'grunt-contrib' with 'grunt' and give a warning
contribRe = /^grunt-contrib/
if contribRe.test(name)
grunt.log.writelns(("Removing 'contrib' from your project's name. The grunt-contrib " + "namespace is reserved for tasks maintained by the grunt team.").red)
name = name.replace(contribRe, "grunt")
done(null, name)
)
init.prompt("description", "The best Grunt plugin ever.")
init.prompt("version")
init.prompt("repository")
init.prompt("homepage")
init.prompt("bugs")
init.prompt("licenses")
init.prompt("author_name")
init.prompt("author_email")
init.prompt("author_url")
init.prompt("grunt_version")
init.prompt("node_version", grunt.package.engines.node)
], (err, props) ->
# Set a few grunt-plugin-specific properties.
props.short_name = props.name.replace(/^grunt[\-_]?/, "").replace(/[\W_]+/g, "_").replace(/^(\d)/, "_$1")
props.main = "Gruntfile.coffee"
props.npm_test = "grunt test"
props.keywords = ["gruntplugin"]
props.devDependencies = {
"chai": "~1.8.0"
"grunt-coffeelint": "0.0.7"
"grunt-contrib-clean": "~0.5.0"
"grunt-mocha-cov": "0.0.7"
"coffee-script": "~1.6.3"
"grunt-bumper": "~1.0.1"
}
props.peerDependencies = { "grunt":props.grunt_version }
# Files to copy (and process).
files = init.filesToCopy(props)
# Add properly-named license files.
init.addLicenseFiles(files, props.licenses)
# Actually copy (and process) files.
init.copyAndProcess(files, props)
# Generate package.json file.
init.writePackageJSON("package.json", props)
# All done!
done()
) |
[
{
"context": " Cunha\"\n \"SI\":\"Slovenia\"\n \"SJ\":\"Svalbard and Jan Mayen\"\n \"SK\":\"Slovakia\"\n \"SL\":\"Sierra Leone\"\n \"SM\":\"",
"end": 4245,
"score": 0.8620093464851379,
"start": 4240,
"tag": "NAME",
"value": "Mayen"
}
] | app/assets/javascripts/country.coffee | ojny/oj_web | 2 | country_dict =
"AD":"Andorra"
"AE":"United Arab Emirates"
"AF":"Afghanistan"
"AG":"Antigua and Barbuda"
"AI":"Anguilla"
"AL":"Albania"
"AM":"Armenia"
"AO":"Angola"
"AQ":"Antarctica"
"AR":"Argentina"
"AS":"American Samoa"
"AT":"Austria"
"AU":"Australia"
"AW":"Aruba"
"AX":"Aland Islands"
"AZ":"Azerbaijan"
"BA":"Bosnia and Herzegovina"
"BB":"Barbados"
"BD":"Bangladesh"
"BE":"Belgium"
"BF":"Burkina Faso"
"BG":"Bulgaria"
"BH":"Bahrain"
"BI":"Burundi"
"BJ":"Benin"
"BL":"Saint Barthélemy"
"BM":"Bermuda"
"BN":"Brunei Darussalam"
"BO":"Bolivia, Plurinational State of"
"BQ":"Bonaire, Sint Eustatius and Saba"
"BR":"Brazil"
"BS":"Bahamas"
"BT":"Bhutan"
"BV":"Bouvet Island"
"BW":"Botswana"
"BY":"Belarus"
"BZ":"Belize"
"CA":"Canada"
"CC":"Cocos (Keeling) Islands"
"CD":"Congo, the Democratic Republic of the"
"CF":"Central African Republic"
"CG":"Congo"
"CH":"Switzerland"
"CI":"Côte d'Ivoire"
"CK":"Cook Islands"
"CL":"Chile"
"CM":"Cameroon"
"CN":"China"
"CO":"Colombia"
"CR":"Costa Rica"
"CU":"Cuba"
"CV":"Cabo Verde"
"CW":"Curaçao"
"CX":"Christmas Island"
"CY":"Cyprus"
"CZ":"Czech Republic"
"DE":"Germany"
"DJ":"Djibouti"
"DK":"Denmark"
"DM":"Dominica"
"DO":"Dominican Republic"
"DZ":"Algeria"
"EC":"Ecuador"
"EE":"Estonia"
"EG":"Egypt"
"EH":"Western Sahara"
"ER":"Eritrea"
"ES":"Spain"
"ET":"Ethiopia"
"FI":"Finland"
"FJ":"Fiji"
"FK":"Falkland Islands (Malvinas)"
"FM":"Micronesia, Federated States of"
"FO":"Faroe Islands"
"FR":"France"
"GA":"Gabon"
"GB":"United Kingdom of Great Britain and Northern Ireland"
"GD":"Grenada"
"GE":"Georgia"
"GF":"French Guiana"
"GG":"Guernsey"
"GH":"Ghana"
"GI":"Gibraltar"
"GL":"Greenland"
"GM":"Gambia"
"GN":"Guinea"
"GP":"Guadeloupe"
"GQ":"Equatorial Guinea"
"GR":"Greece"
"GS":"South Georgia and the South Sandwich Islands"
"GT":"Guatemala"
"GU":"Guam"
"GW":"Guinea-Bissau"
"GY":"Guyana"
"HK":"Hong Kong"
"HM":"Heard Island and McDonald Islands"
"HN":"Honduras"
"HR":"Croatia"
"HT":"Haiti"
"HU":"Hungary"
"ID":"Indonesia"
"IE":"Ireland"
"IL":"Israel"
"IM":"Isle of Man"
"IN":"India"
"IO":"British Indian Ocean Territory"
"IQ":"Iraq"
"IR":"Iran, Islamic Republic of"
"IS":"Iceland"
"IT":"Italy"
"JE":"Jersey"
"JM":"Jamaica"
"JO":"Jordan"
"JP":"Japan"
"KE":"Kenya"
"KG":"Kyrgyzstan"
"KH":"Cambodia"
"KI":"Kiribati"
"KM":"Comoros"
"KN":"Saint Kitts and Nevis"
"KP":"Korea, Democratic People's Republic of"
"KR":"Korea, Republic of"
"KW":"Kuwait"
"KY":"Cayman Islands"
"KZ":"Kazakhstan"
"LA":"Lao People's Democratic Republic"
"LB":"Lebanon"
"LC":"Saint Lucia"
"LI":"Liechtenstein"
"LK":"Sri Lanka"
"LR":"Liberia"
"LS":"Lesotho"
"LT":"Lithuania"
"LU":"Luxembourg"
"LV":"Latvia"
"LY":"Libya"
"MA":"Morocco"
"MC":"Monaco"
"MD":"Moldova, Republic of"
"ME":"Montenegro"
"MF":"Saint Martin (French part)"
"MG":"Madagascar"
"MH":"Marshall Islands"
"MK":"Macedonia, the former Yugoslav Republic of"
"ML":"Mali"
"MM":"Myanmar"
"MN":"Mongolia"
"MO":"Macao"
"MP":"Northern Mariana Islands"
"MQ":"Martinique"
"MR":"Mauritania"
"MS":"Montserrat"
"MT":"Malta"
"MU":"Mauritius"
"MV":"Maldives"
"MW":"Malawi"
"MX":"Mexico"
"MY":"Malaysia"
"MZ":"Mozambique"
"NA":"Namibia"
"NC":"New Caledonia"
"NE":"Niger"
"NF":"Norfolk Island"
"NG":"Nigeria"
"NI":"Nicaragua"
"NL":"Netherlands"
"NO":"Norway"
"NP":"Nepal"
"NR":"Nauru"
"NU":"Niue"
"NZ":"New Zealand"
"OM":"Oman"
"PA":"Panama"
"PE":"Peru"
"PF":"French Polynesia"
"PG":"Papua New Guinea"
"PH":"Philippines"
"PK":"Pakistan"
"PL":"Poland"
"PM":"Saint Pierre and Miquelon"
"PN":"Pitcairn"
"PR":"Puerto Rico"
"PS":"Palestine, State of"
"PT":"Portugal"
"PW":"Palau"
"PY":"Paraguay"
"QA":"Qatar"
"RE":"Réunion"
"RO":"Romania"
"RS":"Serbia"
"RU":"Russian Federation"
"RW":"Rwanda"
"SA":"Saudi Arabia"
"SB":"Solomon Islands"
"SC":"Seychelles"
"SD":"Sudan"
"SE":"Sweden"
"SG":"Singapore"
"SH":"Saint Helena, Ascension and Tristan da Cunha"
"SI":"Slovenia"
"SJ":"Svalbard and Jan Mayen"
"SK":"Slovakia"
"SL":"Sierra Leone"
"SM":"San Marino"
"SN":"Senegal"
"SO":"Somalia"
"SR":"Suriname"
"SS":"South Sudan"
"ST":"Sao Tome and Principe"
"SV":"El Salvador"
"SX":"Sint Maarten (Dutch part)"
"SY":"Syrian Arab Republic"
"SZ":"Swaziland"
"TC":"Turks and Caicos Islands"
"TD":"Chad"
"TF":"French Southern Territories"
"TG":"Togo"
"TH":"Thailand"
"TJ":"Tajikistan"
"TK":"Tokelau"
"TL":"Timor-Leste"
"TM":"Turkmenistan"
"TN":"Tunisia"
"TO":"Tonga"
"TR":"Turkey"
"TT":"Trinidad and Tobago"
"TV":"Tuvalu"
"TW":"Taiwan, Province of China"
"TZ":"Tanzania, United Republic of"
"UA":"Ukraine"
"UG":"Uganda"
"UM":"United States Minor Outlying Islands"
"US":"United States of America"
"UY":"Uruguay"
"UZ":"Uzbekistan"
"VA":"Holy See"
"VC":"Saint Vincent and the Grenadines"
"VE":"Venezuela, Bolivarian Republic of"
"VG":"Virgin Islands, British"
"VI":"Virgin Islands, U.S."
"VN":"Viet Nam"
"VU":"Vanuatu"
"WF":"Wallis and Futuna"
"WS":"Samoa"
"YE":"Yemen"
"YT":"Mayotte"
"ZA":"South Africa"
"ZM":"Zambia"
"ZW":"Zimbabwe"
window.countries = do ->
countries = []
for code, name of country_dict
countries.push(name)
countries.sort()
window.country_codes = do ->
Object.keys(country_dict).sort()
window.country_to_code = do ->
dict = {}
for code, name of country_dict
dict[name] = code
dict
window.code_to_country = country_dict
| 103919 | country_dict =
"AD":"Andorra"
"AE":"United Arab Emirates"
"AF":"Afghanistan"
"AG":"Antigua and Barbuda"
"AI":"Anguilla"
"AL":"Albania"
"AM":"Armenia"
"AO":"Angola"
"AQ":"Antarctica"
"AR":"Argentina"
"AS":"American Samoa"
"AT":"Austria"
"AU":"Australia"
"AW":"Aruba"
"AX":"Aland Islands"
"AZ":"Azerbaijan"
"BA":"Bosnia and Herzegovina"
"BB":"Barbados"
"BD":"Bangladesh"
"BE":"Belgium"
"BF":"Burkina Faso"
"BG":"Bulgaria"
"BH":"Bahrain"
"BI":"Burundi"
"BJ":"Benin"
"BL":"Saint Barthélemy"
"BM":"Bermuda"
"BN":"Brunei Darussalam"
"BO":"Bolivia, Plurinational State of"
"BQ":"Bonaire, Sint Eustatius and Saba"
"BR":"Brazil"
"BS":"Bahamas"
"BT":"Bhutan"
"BV":"Bouvet Island"
"BW":"Botswana"
"BY":"Belarus"
"BZ":"Belize"
"CA":"Canada"
"CC":"Cocos (Keeling) Islands"
"CD":"Congo, the Democratic Republic of the"
"CF":"Central African Republic"
"CG":"Congo"
"CH":"Switzerland"
"CI":"Côte d'Ivoire"
"CK":"Cook Islands"
"CL":"Chile"
"CM":"Cameroon"
"CN":"China"
"CO":"Colombia"
"CR":"Costa Rica"
"CU":"Cuba"
"CV":"Cabo Verde"
"CW":"Curaçao"
"CX":"Christmas Island"
"CY":"Cyprus"
"CZ":"Czech Republic"
"DE":"Germany"
"DJ":"Djibouti"
"DK":"Denmark"
"DM":"Dominica"
"DO":"Dominican Republic"
"DZ":"Algeria"
"EC":"Ecuador"
"EE":"Estonia"
"EG":"Egypt"
"EH":"Western Sahara"
"ER":"Eritrea"
"ES":"Spain"
"ET":"Ethiopia"
"FI":"Finland"
"FJ":"Fiji"
"FK":"Falkland Islands (Malvinas)"
"FM":"Micronesia, Federated States of"
"FO":"Faroe Islands"
"FR":"France"
"GA":"Gabon"
"GB":"United Kingdom of Great Britain and Northern Ireland"
"GD":"Grenada"
"GE":"Georgia"
"GF":"French Guiana"
"GG":"Guernsey"
"GH":"Ghana"
"GI":"Gibraltar"
"GL":"Greenland"
"GM":"Gambia"
"GN":"Guinea"
"GP":"Guadeloupe"
"GQ":"Equatorial Guinea"
"GR":"Greece"
"GS":"South Georgia and the South Sandwich Islands"
"GT":"Guatemala"
"GU":"Guam"
"GW":"Guinea-Bissau"
"GY":"Guyana"
"HK":"Hong Kong"
"HM":"Heard Island and McDonald Islands"
"HN":"Honduras"
"HR":"Croatia"
"HT":"Haiti"
"HU":"Hungary"
"ID":"Indonesia"
"IE":"Ireland"
"IL":"Israel"
"IM":"Isle of Man"
"IN":"India"
"IO":"British Indian Ocean Territory"
"IQ":"Iraq"
"IR":"Iran, Islamic Republic of"
"IS":"Iceland"
"IT":"Italy"
"JE":"Jersey"
"JM":"Jamaica"
"JO":"Jordan"
"JP":"Japan"
"KE":"Kenya"
"KG":"Kyrgyzstan"
"KH":"Cambodia"
"KI":"Kiribati"
"KM":"Comoros"
"KN":"Saint Kitts and Nevis"
"KP":"Korea, Democratic People's Republic of"
"KR":"Korea, Republic of"
"KW":"Kuwait"
"KY":"Cayman Islands"
"KZ":"Kazakhstan"
"LA":"Lao People's Democratic Republic"
"LB":"Lebanon"
"LC":"Saint Lucia"
"LI":"Liechtenstein"
"LK":"Sri Lanka"
"LR":"Liberia"
"LS":"Lesotho"
"LT":"Lithuania"
"LU":"Luxembourg"
"LV":"Latvia"
"LY":"Libya"
"MA":"Morocco"
"MC":"Monaco"
"MD":"Moldova, Republic of"
"ME":"Montenegro"
"MF":"Saint Martin (French part)"
"MG":"Madagascar"
"MH":"Marshall Islands"
"MK":"Macedonia, the former Yugoslav Republic of"
"ML":"Mali"
"MM":"Myanmar"
"MN":"Mongolia"
"MO":"Macao"
"MP":"Northern Mariana Islands"
"MQ":"Martinique"
"MR":"Mauritania"
"MS":"Montserrat"
"MT":"Malta"
"MU":"Mauritius"
"MV":"Maldives"
"MW":"Malawi"
"MX":"Mexico"
"MY":"Malaysia"
"MZ":"Mozambique"
"NA":"Namibia"
"NC":"New Caledonia"
"NE":"Niger"
"NF":"Norfolk Island"
"NG":"Nigeria"
"NI":"Nicaragua"
"NL":"Netherlands"
"NO":"Norway"
"NP":"Nepal"
"NR":"Nauru"
"NU":"Niue"
"NZ":"New Zealand"
"OM":"Oman"
"PA":"Panama"
"PE":"Peru"
"PF":"French Polynesia"
"PG":"Papua New Guinea"
"PH":"Philippines"
"PK":"Pakistan"
"PL":"Poland"
"PM":"Saint Pierre and Miquelon"
"PN":"Pitcairn"
"PR":"Puerto Rico"
"PS":"Palestine, State of"
"PT":"Portugal"
"PW":"Palau"
"PY":"Paraguay"
"QA":"Qatar"
"RE":"Réunion"
"RO":"Romania"
"RS":"Serbia"
"RU":"Russian Federation"
"RW":"Rwanda"
"SA":"Saudi Arabia"
"SB":"Solomon Islands"
"SC":"Seychelles"
"SD":"Sudan"
"SE":"Sweden"
"SG":"Singapore"
"SH":"Saint Helena, Ascension and Tristan da Cunha"
"SI":"Slovenia"
"SJ":"Svalbard and Jan <NAME>"
"SK":"Slovakia"
"SL":"Sierra Leone"
"SM":"San Marino"
"SN":"Senegal"
"SO":"Somalia"
"SR":"Suriname"
"SS":"South Sudan"
"ST":"Sao Tome and Principe"
"SV":"El Salvador"
"SX":"Sint Maarten (Dutch part)"
"SY":"Syrian Arab Republic"
"SZ":"Swaziland"
"TC":"Turks and Caicos Islands"
"TD":"Chad"
"TF":"French Southern Territories"
"TG":"Togo"
"TH":"Thailand"
"TJ":"Tajikistan"
"TK":"Tokelau"
"TL":"Timor-Leste"
"TM":"Turkmenistan"
"TN":"Tunisia"
"TO":"Tonga"
"TR":"Turkey"
"TT":"Trinidad and Tobago"
"TV":"Tuvalu"
"TW":"Taiwan, Province of China"
"TZ":"Tanzania, United Republic of"
"UA":"Ukraine"
"UG":"Uganda"
"UM":"United States Minor Outlying Islands"
"US":"United States of America"
"UY":"Uruguay"
"UZ":"Uzbekistan"
"VA":"Holy See"
"VC":"Saint Vincent and the Grenadines"
"VE":"Venezuela, Bolivarian Republic of"
"VG":"Virgin Islands, British"
"VI":"Virgin Islands, U.S."
"VN":"Viet Nam"
"VU":"Vanuatu"
"WF":"Wallis and Futuna"
"WS":"Samoa"
"YE":"Yemen"
"YT":"Mayotte"
"ZA":"South Africa"
"ZM":"Zambia"
"ZW":"Zimbabwe"
window.countries = do ->
countries = []
for code, name of country_dict
countries.push(name)
countries.sort()
window.country_codes = do ->
Object.keys(country_dict).sort()
window.country_to_code = do ->
dict = {}
for code, name of country_dict
dict[name] = code
dict
window.code_to_country = country_dict
| true | country_dict =
"AD":"Andorra"
"AE":"United Arab Emirates"
"AF":"Afghanistan"
"AG":"Antigua and Barbuda"
"AI":"Anguilla"
"AL":"Albania"
"AM":"Armenia"
"AO":"Angola"
"AQ":"Antarctica"
"AR":"Argentina"
"AS":"American Samoa"
"AT":"Austria"
"AU":"Australia"
"AW":"Aruba"
"AX":"Aland Islands"
"AZ":"Azerbaijan"
"BA":"Bosnia and Herzegovina"
"BB":"Barbados"
"BD":"Bangladesh"
"BE":"Belgium"
"BF":"Burkina Faso"
"BG":"Bulgaria"
"BH":"Bahrain"
"BI":"Burundi"
"BJ":"Benin"
"BL":"Saint Barthélemy"
"BM":"Bermuda"
"BN":"Brunei Darussalam"
"BO":"Bolivia, Plurinational State of"
"BQ":"Bonaire, Sint Eustatius and Saba"
"BR":"Brazil"
"BS":"Bahamas"
"BT":"Bhutan"
"BV":"Bouvet Island"
"BW":"Botswana"
"BY":"Belarus"
"BZ":"Belize"
"CA":"Canada"
"CC":"Cocos (Keeling) Islands"
"CD":"Congo, the Democratic Republic of the"
"CF":"Central African Republic"
"CG":"Congo"
"CH":"Switzerland"
"CI":"Côte d'Ivoire"
"CK":"Cook Islands"
"CL":"Chile"
"CM":"Cameroon"
"CN":"China"
"CO":"Colombia"
"CR":"Costa Rica"
"CU":"Cuba"
"CV":"Cabo Verde"
"CW":"Curaçao"
"CX":"Christmas Island"
"CY":"Cyprus"
"CZ":"Czech Republic"
"DE":"Germany"
"DJ":"Djibouti"
"DK":"Denmark"
"DM":"Dominica"
"DO":"Dominican Republic"
"DZ":"Algeria"
"EC":"Ecuador"
"EE":"Estonia"
"EG":"Egypt"
"EH":"Western Sahara"
"ER":"Eritrea"
"ES":"Spain"
"ET":"Ethiopia"
"FI":"Finland"
"FJ":"Fiji"
"FK":"Falkland Islands (Malvinas)"
"FM":"Micronesia, Federated States of"
"FO":"Faroe Islands"
"FR":"France"
"GA":"Gabon"
"GB":"United Kingdom of Great Britain and Northern Ireland"
"GD":"Grenada"
"GE":"Georgia"
"GF":"French Guiana"
"GG":"Guernsey"
"GH":"Ghana"
"GI":"Gibraltar"
"GL":"Greenland"
"GM":"Gambia"
"GN":"Guinea"
"GP":"Guadeloupe"
"GQ":"Equatorial Guinea"
"GR":"Greece"
"GS":"South Georgia and the South Sandwich Islands"
"GT":"Guatemala"
"GU":"Guam"
"GW":"Guinea-Bissau"
"GY":"Guyana"
"HK":"Hong Kong"
"HM":"Heard Island and McDonald Islands"
"HN":"Honduras"
"HR":"Croatia"
"HT":"Haiti"
"HU":"Hungary"
"ID":"Indonesia"
"IE":"Ireland"
"IL":"Israel"
"IM":"Isle of Man"
"IN":"India"
"IO":"British Indian Ocean Territory"
"IQ":"Iraq"
"IR":"Iran, Islamic Republic of"
"IS":"Iceland"
"IT":"Italy"
"JE":"Jersey"
"JM":"Jamaica"
"JO":"Jordan"
"JP":"Japan"
"KE":"Kenya"
"KG":"Kyrgyzstan"
"KH":"Cambodia"
"KI":"Kiribati"
"KM":"Comoros"
"KN":"Saint Kitts and Nevis"
"KP":"Korea, Democratic People's Republic of"
"KR":"Korea, Republic of"
"KW":"Kuwait"
"KY":"Cayman Islands"
"KZ":"Kazakhstan"
"LA":"Lao People's Democratic Republic"
"LB":"Lebanon"
"LC":"Saint Lucia"
"LI":"Liechtenstein"
"LK":"Sri Lanka"
"LR":"Liberia"
"LS":"Lesotho"
"LT":"Lithuania"
"LU":"Luxembourg"
"LV":"Latvia"
"LY":"Libya"
"MA":"Morocco"
"MC":"Monaco"
"MD":"Moldova, Republic of"
"ME":"Montenegro"
"MF":"Saint Martin (French part)"
"MG":"Madagascar"
"MH":"Marshall Islands"
"MK":"Macedonia, the former Yugoslav Republic of"
"ML":"Mali"
"MM":"Myanmar"
"MN":"Mongolia"
"MO":"Macao"
"MP":"Northern Mariana Islands"
"MQ":"Martinique"
"MR":"Mauritania"
"MS":"Montserrat"
"MT":"Malta"
"MU":"Mauritius"
"MV":"Maldives"
"MW":"Malawi"
"MX":"Mexico"
"MY":"Malaysia"
"MZ":"Mozambique"
"NA":"Namibia"
"NC":"New Caledonia"
"NE":"Niger"
"NF":"Norfolk Island"
"NG":"Nigeria"
"NI":"Nicaragua"
"NL":"Netherlands"
"NO":"Norway"
"NP":"Nepal"
"NR":"Nauru"
"NU":"Niue"
"NZ":"New Zealand"
"OM":"Oman"
"PA":"Panama"
"PE":"Peru"
"PF":"French Polynesia"
"PG":"Papua New Guinea"
"PH":"Philippines"
"PK":"Pakistan"
"PL":"Poland"
"PM":"Saint Pierre and Miquelon"
"PN":"Pitcairn"
"PR":"Puerto Rico"
"PS":"Palestine, State of"
"PT":"Portugal"
"PW":"Palau"
"PY":"Paraguay"
"QA":"Qatar"
"RE":"Réunion"
"RO":"Romania"
"RS":"Serbia"
"RU":"Russian Federation"
"RW":"Rwanda"
"SA":"Saudi Arabia"
"SB":"Solomon Islands"
"SC":"Seychelles"
"SD":"Sudan"
"SE":"Sweden"
"SG":"Singapore"
"SH":"Saint Helena, Ascension and Tristan da Cunha"
"SI":"Slovenia"
"SJ":"Svalbard and Jan PI:NAME:<NAME>END_PI"
"SK":"Slovakia"
"SL":"Sierra Leone"
"SM":"San Marino"
"SN":"Senegal"
"SO":"Somalia"
"SR":"Suriname"
"SS":"South Sudan"
"ST":"Sao Tome and Principe"
"SV":"El Salvador"
"SX":"Sint Maarten (Dutch part)"
"SY":"Syrian Arab Republic"
"SZ":"Swaziland"
"TC":"Turks and Caicos Islands"
"TD":"Chad"
"TF":"French Southern Territories"
"TG":"Togo"
"TH":"Thailand"
"TJ":"Tajikistan"
"TK":"Tokelau"
"TL":"Timor-Leste"
"TM":"Turkmenistan"
"TN":"Tunisia"
"TO":"Tonga"
"TR":"Turkey"
"TT":"Trinidad and Tobago"
"TV":"Tuvalu"
"TW":"Taiwan, Province of China"
"TZ":"Tanzania, United Republic of"
"UA":"Ukraine"
"UG":"Uganda"
"UM":"United States Minor Outlying Islands"
"US":"United States of America"
"UY":"Uruguay"
"UZ":"Uzbekistan"
"VA":"Holy See"
"VC":"Saint Vincent and the Grenadines"
"VE":"Venezuela, Bolivarian Republic of"
"VG":"Virgin Islands, British"
"VI":"Virgin Islands, U.S."
"VN":"Viet Nam"
"VU":"Vanuatu"
"WF":"Wallis and Futuna"
"WS":"Samoa"
"YE":"Yemen"
"YT":"Mayotte"
"ZA":"South Africa"
"ZM":"Zambia"
"ZW":"Zimbabwe"
window.countries = do ->
countries = []
for code, name of country_dict
countries.push(name)
countries.sort()
window.country_codes = do ->
Object.keys(country_dict).sort()
window.country_to_code = do ->
dict = {}
for code, name of country_dict
dict[name] = code
dict
window.code_to_country = country_dict
|
[
{
"context": "derer.initMap = (el) ->\n L.mapbox.accessToken = 'pk.eyJ1IjoiYWRhbWphY29iYmVja2VyIiwiYSI6Im1SVEQtSm8ifQ.ZgEOSXsv9eLfGQ-9yAmtIg'\n L.mapbox.map(el, 'adamjacobbecker.ja7plkah')\n\n",
"end": 246,
"score": 0.9996926784515381,
"start": 170,
"tag": "KEY",
"value": "pk.eyJ1IjoiYWRhbWphY29iYmVja2VyIiwiYSI6Im1SVEQtSm8ifQ.ZgEOSXsv9eLfGQ-9yAmtIg"
},
{
"context": "m8ifQ.ZgEOSXsv9eLfGQ-9yAmtIg'\n L.mapbox.map(el, 'adamjacobbecker.ja7plkah')\n\nFormRenderer.Models.ResponseFieldMapM",
"end": 283,
"score": 0.9993781447410583,
"start": 268,
"tag": "USERNAME",
"value": "adamjacobbecker"
}
] | src/fields/map_marker.coffee | dobtco/formrenderer-base | 79 | FormRenderer.loadLeaflet = (cb) ->
if L?.GeoJSON?
cb()
else
requireOnce FormRenderer.MAPBOX_URL, cb
FormRenderer.initMap = (el) ->
L.mapbox.accessToken = 'pk.eyJ1IjoiYWRhbWphY29iYmVja2VyIiwiYSI6Im1SVEQtSm8ifQ.ZgEOSXsv9eLfGQ-9yAmtIg'
L.mapbox.map(el, 'adamjacobbecker.ja7plkah')
FormRenderer.Models.ResponseFieldMapMarker = FormRenderer.Models.ResponseField.extend
field_type: 'map_marker'
latLng: ->
@get('value')
defaultLatLng: ->
if (lat = @get('default_lat')) && (lng = @get('default_lng'))
[lat, lng]
FormRenderer.Views.ResponseFieldMapMarker = FormRenderer.Views.ResponseField.extend
events: _.extend {}, FormRenderer.Views.ResponseField::events,
'click .fr_map_cover': 'enable'
'click [data-fr-clear-map]': 'disable'
initialize: ->
FormRenderer.Views.ResponseField::initialize.apply @, arguments
@on 'shown', ->
@refreshing = true
@map?._onResize()
setTimeout =>
@refreshing = false
, 0
render: ->
FormRenderer.Views.ResponseField::render.apply @, arguments
@$cover = @$el.find('.fr_map_cover')
FormRenderer.loadLeaflet =>
@initMap()
if @model.latLng() then @enable()
@
initMap: ->
@map = FormRenderer.initMap(@$el.find('.fr_map_map')[0])
@$el.find('.fr_map_map').data('map', @map)
@map.setView(@model.latLng() || @model.defaultLatLng() || FormRenderer.DEFAULT_LAT_LNG, 13)
@marker = L.marker([0, 0])
@map.on 'move', $.proxy(@_onMove, @)
_onMove: ->
# We're just refreshing the leaflet map, not actually saving anything
return if @refreshing
center = @map.getCenter()
@marker.setLatLng center
@model.set
value: [center.lat.toFixed(7), center.lng.toFixed(7)]
# Rivets doesn't bind to arrays properly
@model.trigger('change:value.0 change:value.1')
enable: ->
return unless @map
@map.addLayer(@marker)
@$cover.hide()
@_onMove()
disable: (e) ->
e.preventDefault()
@map.removeLayer(@marker)
@$el.find('.fr_map_cover').show()
@model.unset('value')
| 174991 | FormRenderer.loadLeaflet = (cb) ->
if L?.GeoJSON?
cb()
else
requireOnce FormRenderer.MAPBOX_URL, cb
FormRenderer.initMap = (el) ->
L.mapbox.accessToken = '<KEY>'
L.mapbox.map(el, 'adamjacobbecker.ja7plkah')
FormRenderer.Models.ResponseFieldMapMarker = FormRenderer.Models.ResponseField.extend
field_type: 'map_marker'
latLng: ->
@get('value')
defaultLatLng: ->
if (lat = @get('default_lat')) && (lng = @get('default_lng'))
[lat, lng]
FormRenderer.Views.ResponseFieldMapMarker = FormRenderer.Views.ResponseField.extend
events: _.extend {}, FormRenderer.Views.ResponseField::events,
'click .fr_map_cover': 'enable'
'click [data-fr-clear-map]': 'disable'
initialize: ->
FormRenderer.Views.ResponseField::initialize.apply @, arguments
@on 'shown', ->
@refreshing = true
@map?._onResize()
setTimeout =>
@refreshing = false
, 0
render: ->
FormRenderer.Views.ResponseField::render.apply @, arguments
@$cover = @$el.find('.fr_map_cover')
FormRenderer.loadLeaflet =>
@initMap()
if @model.latLng() then @enable()
@
initMap: ->
@map = FormRenderer.initMap(@$el.find('.fr_map_map')[0])
@$el.find('.fr_map_map').data('map', @map)
@map.setView(@model.latLng() || @model.defaultLatLng() || FormRenderer.DEFAULT_LAT_LNG, 13)
@marker = L.marker([0, 0])
@map.on 'move', $.proxy(@_onMove, @)
_onMove: ->
# We're just refreshing the leaflet map, not actually saving anything
return if @refreshing
center = @map.getCenter()
@marker.setLatLng center
@model.set
value: [center.lat.toFixed(7), center.lng.toFixed(7)]
# Rivets doesn't bind to arrays properly
@model.trigger('change:value.0 change:value.1')
enable: ->
return unless @map
@map.addLayer(@marker)
@$cover.hide()
@_onMove()
disable: (e) ->
e.preventDefault()
@map.removeLayer(@marker)
@$el.find('.fr_map_cover').show()
@model.unset('value')
| true | FormRenderer.loadLeaflet = (cb) ->
if L?.GeoJSON?
cb()
else
requireOnce FormRenderer.MAPBOX_URL, cb
FormRenderer.initMap = (el) ->
L.mapbox.accessToken = 'PI:KEY:<KEY>END_PI'
L.mapbox.map(el, 'adamjacobbecker.ja7plkah')
FormRenderer.Models.ResponseFieldMapMarker = FormRenderer.Models.ResponseField.extend
field_type: 'map_marker'
latLng: ->
@get('value')
defaultLatLng: ->
if (lat = @get('default_lat')) && (lng = @get('default_lng'))
[lat, lng]
FormRenderer.Views.ResponseFieldMapMarker = FormRenderer.Views.ResponseField.extend
events: _.extend {}, FormRenderer.Views.ResponseField::events,
'click .fr_map_cover': 'enable'
'click [data-fr-clear-map]': 'disable'
initialize: ->
FormRenderer.Views.ResponseField::initialize.apply @, arguments
@on 'shown', ->
@refreshing = true
@map?._onResize()
setTimeout =>
@refreshing = false
, 0
render: ->
FormRenderer.Views.ResponseField::render.apply @, arguments
@$cover = @$el.find('.fr_map_cover')
FormRenderer.loadLeaflet =>
@initMap()
if @model.latLng() then @enable()
@
initMap: ->
@map = FormRenderer.initMap(@$el.find('.fr_map_map')[0])
@$el.find('.fr_map_map').data('map', @map)
@map.setView(@model.latLng() || @model.defaultLatLng() || FormRenderer.DEFAULT_LAT_LNG, 13)
@marker = L.marker([0, 0])
@map.on 'move', $.proxy(@_onMove, @)
_onMove: ->
# We're just refreshing the leaflet map, not actually saving anything
return if @refreshing
center = @map.getCenter()
@marker.setLatLng center
@model.set
value: [center.lat.toFixed(7), center.lng.toFixed(7)]
# Rivets doesn't bind to arrays properly
@model.trigger('change:value.0 change:value.1')
enable: ->
return unless @map
@map.addLayer(@marker)
@$cover.hide()
@_onMove()
disable: (e) ->
e.preventDefault()
@map.removeLayer(@marker)
@$el.find('.fr_map_cover').show()
@model.unset('value')
|
[
{
"context": "###\nCopyright 2016 Resin.io\n\nLicensed under the Apache License, Version 2.0 (",
"end": 27,
"score": 0.8099269270896912,
"start": 22,
"tag": "NAME",
"value": "in.io"
}
] | packages/resin-settings-client/lib/yaml.coffee | resin-io-playground/resin-sdk-lerna | 0 | ###
Copyright 2016 Resin.io
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
_ = require('lodash')
jsYaml = require('js-yaml')
###*
# @summary Parse a YAML string
# @function
# @protected
#
# @param {String} string - input string
# @returns {Object} parsed yaml
#
# @throws Will throw if input is not valid YAML.
#
# @example
# object = yaml.parse('foo: bar')
# console.log(object.foo)
# > bar
###
exports.parse = (string) ->
result = jsYaml.safeLoad(string)
if _.isString(result)
throw new Error("Invalid YAML: #{string}")
return result
| 106672 | ###
Copyright 2016 Res<NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
_ = require('lodash')
jsYaml = require('js-yaml')
###*
# @summary Parse a YAML string
# @function
# @protected
#
# @param {String} string - input string
# @returns {Object} parsed yaml
#
# @throws Will throw if input is not valid YAML.
#
# @example
# object = yaml.parse('foo: bar')
# console.log(object.foo)
# > bar
###
exports.parse = (string) ->
result = jsYaml.safeLoad(string)
if _.isString(result)
throw new Error("Invalid YAML: #{string}")
return result
| true | ###
Copyright 2016 ResPI:NAME:<NAME>END_PI
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
_ = require('lodash')
jsYaml = require('js-yaml')
###*
# @summary Parse a YAML string
# @function
# @protected
#
# @param {String} string - input string
# @returns {Object} parsed yaml
#
# @throws Will throw if input is not valid YAML.
#
# @example
# object = yaml.parse('foo: bar')
# console.log(object.foo)
# > bar
###
exports.parse = (string) ->
result = jsYaml.safeLoad(string)
if _.isString(result)
throw new Error("Invalid YAML: #{string}")
return result
|
[
{
"context": "', 'link')\n selected: new Batman.Object(name: 'crono')\n helpers.render '<select data-bind=\"selected.n",
"end": 900,
"score": 0.8685765266418457,
"start": 895,
"tag": "NAME",
"value": "crono"
},
{
"context": "tman.Set()\n selected: new Batman.Object(name: 'crono')\n helpers.render '<select data-bind=\"selected.n",
"end": 1358,
"score": 0.9299450516700745,
"start": 1353,
"tag": "NAME",
"value": "crono"
},
{
"context": "lue, 'crono'\n deepEqual getContents(node), ['Mario', 'Link', 'Crono']\n equal context.get('selec",
"end": 1761,
"score": 0.7906695604324341,
"start": 1756,
"tag": "NAME",
"value": "Mario"
},
{
"context": "me'), 'crono'\n context.set('selected.name', 'mario')\n equal node[0].value, 'mario'\n deepEq",
"end": 1872,
"score": 0.8541461825370789,
"start": 1867,
"tag": "NAME",
"value": "mario"
},
{
"context": "lue, 'mario'\n deepEqual getContents(node), ['Mario', 'Link', 'Crono']\n\nasyncTest 'it should bind the",
"end": 1952,
"score": 0.7536807656288147,
"start": 1947,
"tag": "NAME",
"value": "Mario"
},
{
"context": "der '<select data-bind=\"something\"><option value=\"mario\" data-bind-selected=\"mario.selected\">Mario</opt",
"end": 2801,
"score": 0.5840649008750916,
"start": 2798,
"tag": "NAME",
"value": "mar"
},
{
"context": "value=\"mario\" data-bind-selected=\"mario.selected\">Mario</option><option value=\"crono\" data-bind-selec",
"end": 2842,
"score": 0.5907920002937317,
"start": 2841,
"tag": "NAME",
"value": "M"
},
{
"context": "ected'), false\n deepEqual getContents(node), ['Mario', 'Crono']\n\n node[0].value = 'mario'\n helpe",
"end": 3124,
"score": 0.7736630439758301,
"start": 3119,
"tag": "NAME",
"value": "Mario"
},
{
"context": "s(node), ['Mario', 'Crono']\n\n node[0].value = 'mario'\n helpers.triggerChange node[0]\n equal co",
"end": 3161,
"score": 0.5147669315338135,
"start": 3158,
"tag": "NAME",
"value": "mar"
},
{
"context": "ected'), false\n deepEqual getContents(node), ['Mario', 'Crono']\n\n QUnit.start()\n\nasyncTest 'it ",
"end": 3328,
"score": 0.8070172071456909,
"start": 3327,
"tag": "NAME",
"value": "M"
},
{
"context": "ce iterated over swaps', ->\n leo = Batman name: 'leo', id: 1\n mikey = Batman name: 'mikey', id: 2\n\n ",
"end": 3508,
"score": 0.727649986743927,
"start": 3505,
"tag": "NAME",
"value": "leo"
},
{
"context": "Batman name: 'leo', id: 1\n mikey = Batman name: 'mikey', id: 2\n\n context = Batman\n heroes: new Batma",
"end": 3546,
"score": 0.8111120462417603,
"start": 3541,
"tag": "NAME",
"value": "mikey"
},
{
"context": "xt = new Batman.Object\n heros: new Batman.Set('mario', 'crono', 'link', 'kirby')\n selected: new Bat",
"end": 4302,
"score": 0.9984720945358276,
"start": 4297,
"tag": "NAME",
"value": "mario"
},
{
"context": "Batman.Object\n heros: new Batman.Set('mario', 'crono', 'link', 'kirby')\n selected: new Batman.Objec",
"end": 4311,
"score": 0.9987383484840393,
"start": 4306,
"tag": "NAME",
"value": "crono"
},
{
"context": "ros: new Batman.Set('mario', 'crono', 'link', 'kirby')\n selected: new Batman.Object(name: ['crono',",
"end": 4328,
"score": 0.558639645576477,
"start": 4326,
"tag": "NAME",
"value": "by"
},
{
"context": " 'kirby')\n selected: new Batman.Object(name: ['crono', 'link'])\n helpers.render '<select multiple=\"mu",
"end": 4376,
"score": 0.9988623857498169,
"start": 4371,
"tag": "NAME",
"value": "crono"
},
{
"context": "\n selected: new Batman.Object(name: ['crono', 'link'])\n helpers.render '<select multiple=\"multiple\" ",
"end": 4384,
"score": 0.7068237066268921,
"start": 4380,
"tag": "NAME",
"value": "link"
},
{
"context": " yes, yes, no]\n deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n\n context.set 'sel",
"end": 4690,
"score": 0.9989832639694214,
"start": 4685,
"tag": "NAME",
"value": "Mario"
},
{
"context": ", no]\n deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n\n context.set 'selected.nam",
"end": 4699,
"score": 0.9976160526275635,
"start": 4694,
"tag": "NAME",
"value": "Crono"
},
{
"context": "nk', 'Kirby']\n\n context.set 'selected.name', ['mario', 'kirby']\n\n deepEqual getSelections(node), [y",
"end": 4760,
"score": 0.999098002910614,
"start": 4755,
"tag": "NAME",
"value": "mario"
},
{
"context": "by']\n\n context.set 'selected.name', ['mario', 'kirby']\n\n deepEqual getSelections(node), [yes, no, n",
"end": 4769,
"score": 0.9962142705917358,
"start": 4764,
"tag": "NAME",
"value": "kirby"
},
{
"context": ", no, no, yes]\n deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n QUnit.start()\n\nas",
"end": 4867,
"score": 0.9982450604438782,
"start": 4862,
"tag": "NAME",
"value": "Mario"
},
{
"context": " yes]\n deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n QUnit.start()\n\nasyncTest '",
"end": 4876,
"score": 0.994825005531311,
"start": 4871,
"tag": "NAME",
"value": "Crono"
},
{
"context": "an.Set()\n selected: new Batman.Object(names: ['crono', 'link'])\n\n source = '''\n <select multiple=\"",
"end": 5125,
"score": 0.9989080429077148,
"start": 5120,
"tag": "NAME",
"value": "crono"
},
{
"context": "->\n deepEqual context.get('selected.names'), ['crono', 'link']\n deepEqual getSelections(node), []\n ",
"end": 5442,
"score": 0.9158785343170166,
"start": 5437,
"tag": "NAME",
"value": "crono"
},
{
"context": "Contents(node), []\n\n context.get('heros').add 'mario', 'crono', 'link', 'kirby'\n delay ->\n dee",
"end": 5563,
"score": 0.9969358444213867,
"start": 5558,
"tag": "NAME",
"value": "mario"
},
{
"context": "node), []\n\n context.get('heros').add 'mario', 'crono', 'link', 'kirby'\n delay ->\n deepEqual ge",
"end": 5572,
"score": 0.9344425201416016,
"start": 5567,
"tag": "NAME",
"value": "crono"
},
{
"context": "es, yes, no]\n deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n\n context.set 's",
"end": 5702,
"score": 0.9980621337890625,
"start": 5697,
"tag": "NAME",
"value": "Mario"
},
{
"context": "no]\n deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n\n context.set 'selected.n",
"end": 5711,
"score": 0.9854331612586975,
"start": 5706,
"tag": "NAME",
"value": "Crono"
},
{
"context": "l getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n\n context.set 'selected.names', ['mario'",
"end": 5726,
"score": 0.5219125151634216,
"start": 5724,
"tag": "NAME",
"value": "ir"
},
{
"context": ", 'Kirby']\n\n context.set 'selected.names', ['mario', 'kirby']\n deepEqual getSelections(node), [",
"end": 5775,
"score": 0.9988470077514648,
"start": 5770,
"tag": "NAME",
"value": "mario"
},
{
"context": "]\n\n context.set 'selected.names', ['mario', 'kirby']\n deepEqual getSelections(node), [yes, no, ",
"end": 5784,
"score": 0.9828048944473267,
"start": 5779,
"tag": "NAME",
"value": "kirby"
},
{
"context": "no, no, yes]\n deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n\n context.get('h",
"end": 5885,
"score": 0.999066948890686,
"start": 5880,
"tag": "NAME",
"value": "Mario"
},
{
"context": "es]\n deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n\n context.get('heros').cl",
"end": 5894,
"score": 0.994630753993988,
"start": 5889,
"tag": "NAME",
"value": "Crono"
},
{
"context": "al getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']\n\n context.get('heros').clear()\n delay",
"end": 5911,
"score": 0.76983642578125,
"start": 5906,
"tag": "NAME",
"value": "Kirby"
},
{
"context": " deepEqual context.get('selected.names'), ['mario', 'kirby']\n deepEqual getContents(node), [",
"end": 6021,
"score": 0.9978986978530884,
"start": 6016,
"tag": "NAME",
"value": "mario"
},
{
"context": "epEqual context.get('selected.names'), ['mario', 'kirby']\n deepEqual getContents(node), []\n\nasyncT",
"end": 6030,
"score": 0.9771504402160645,
"start": 6025,
"tag": "NAME",
"value": "kirby"
},
{
"context": "le=\"multiple\" data-bind=\"selected\"><option value=\"mario\" data-bind-selected=\"mario.selected\"></option><op",
"end": 6416,
"score": 0.8263565301895142,
"start": 6411,
"tag": "NAME",
"value": "mario"
},
{
"context": "selected=\"mario.selected\"></option><option value=\"crono\" data-bind-selected=\"crono.selected\"></option></s",
"end": 6483,
"score": 0.6746652722358704,
"start": 6478,
"tag": "NAME",
"value": "crono"
},
{
"context": "e\n equal context.get('mario.selected'), true, 'mario is selected'\n equal context.get('crono.selecte",
"end": 6913,
"score": 0.9902768731117249,
"start": 6908,
"tag": "NAME",
"value": "mario"
},
{
"context": "mario = new Batman.Object(selected: false, name: 'mario')\n crono: crono = new Batman.Object(selected: ",
"end": 7443,
"score": 0.9988328218460083,
"start": 7438,
"tag": "NAME",
"value": "mario"
},
{
"context": " crono = new Batman.Object(selected: true, name: 'crono')\n heros: new Batman.Set(mario, crono).sortedB",
"end": 7511,
"score": 0.9986988306045532,
"start": 7506,
"tag": "NAME",
"value": "crono"
}
] | tests/batman/view/select_rendering_test.coffee | Shipow/batman | 1 | helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper'
oldIteratorDeferEvery = Batman.DOM.IteratorBinding::deferEvery
oldRendererDeferEvery = Batman.Renderer::deferEvery
getSelections = (node) -> node.find('option').map((i, node) -> !!node.selected).toArray()
getContents = (node) -> node.find('option').map((i, node) -> node.innerHTML).toArray()
QUnit.module 'Batman.View select bindings'
setup: ->
Batman.DOM.IteratorBinding::deferEvery = false
Batman.Renderer::deferEvery = false
teardown: ->
Batman.DOM.IteratorBinding::deferEvery = oldIteratorDeferEvery
Batman.Renderer::deferEvery = oldRendererDeferEvery
asyncTest 'it should bind the value of a select box and update when the javascript land value changes', 2, ->
context = Batman
heros: new Batman.Set('mario', 'crono', 'link')
selected: new Batman.Object(name: 'crono')
helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
equal node[0].value, 'crono'
context.set 'selected.name', 'link'
equal node[0].value, 'link'
QUnit.start()
asyncTest 'it should bind the value of a select box and update when options change', 7, ->
context = Batman
heros: new Batman.Set()
selected: new Batman.Object(name: 'crono')
helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero" data-bind="hero | capitalize"></option></select>', context, (node) ->
equal node[0].value, ''
equal context.get('selected.name'), 'crono'
context.get('heros').add('mario', 'link', 'crono')
delay ->
equal node[0].value, 'crono'
deepEqual getContents(node), ['Mario', 'Link', 'Crono']
equal context.get('selected.name'), 'crono'
context.set('selected.name', 'mario')
equal node[0].value, 'mario'
deepEqual getContents(node), ['Mario', 'Link', 'Crono']
asyncTest 'it should bind the value of a select box and update the javascript land value with the selected option', 3, ->
context = Batman
heros: new Batman.SimpleSet('mario', 'crono', 'link')
selected: 'crono'
helpers.render '<select data-bind="selected"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
equal node[0].value, 'crono'
context.set 'selected', 'link'
equal node[0].value, 'link'
context.set 'selected', 'mario'
equal node[0].value, 'mario'
QUnit.start()
asyncTest 'it binds the options of a select box and updates when the select\'s value changes', ->
context = Batman
something: 'crono'
mario: Batman(selected: null)
crono: Batman(selected: null)
helpers.render '<select data-bind="something"><option value="mario" data-bind-selected="mario.selected">Mario</option><option value="crono" data-bind-selected="crono.selected">Crono</option></select>', context, (node) ->
equal node[0].value, 'crono'
equal context.get('crono.selected'), true
equal context.get('mario.selected'), false
deepEqual getContents(node), ['Mario', 'Crono']
node[0].value = 'mario'
helpers.triggerChange node[0]
equal context.get('mario.selected'), true
equal context.get('crono.selected'), false
deepEqual getContents(node), ['Mario', 'Crono']
QUnit.start()
asyncTest 'it binds options created by a foreach and remains consistent when the set instance iterated over swaps', ->
leo = Batman name: 'leo', id: 1
mikey = Batman name: 'mikey', id: 2
context = Batman
heroes: new Batman.Set(leo, mikey).sortedBy('id')
selected: 1
helpers.render '<select data-bind="selected">' +
'<option data-foreach-hero="heroes" data-bind-value="hero.id" data-bind="hero.name" />' +
'</selected>', context, (node) ->
delay ->
deepEqual getContents(node), ['leo', 'mikey']
equal node[0].value, "1"
context.set 'heroes', new Batman.Set(leo, mikey).sortedBy('id')
delay ->
deepEqual getContents(node), ['leo', 'mikey']
equal node[0].value, "1"
asyncTest 'it binds the value of a multi-select box and updates the options when the bound value changes', ->
context = new Batman.Object
heros: new Batman.Set('mario', 'crono', 'link', 'kirby')
selected: new Batman.Object(name: ['crono', 'link'])
helpers.render '<select multiple="multiple" size="2" data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero" data-bind="hero | capitalize"></option></select>', context, (node) ->
deepEqual getSelections(node), [no, yes, yes, no]
deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']
context.set 'selected.name', ['mario', 'kirby']
deepEqual getSelections(node), [yes, no, no, yes]
deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']
QUnit.start()
asyncTest 'it binds the value of a multi-select box and updates the options when the options changes', ->
context = new Batman.Object
heros: new Batman.Set()
selected: new Batman.Object(names: ['crono', 'link'])
source = '''
<select multiple="multiple" size="2" data-bind="selected.names">
<option data-foreach-hero="heros" data-bind-value="hero" data-bind="hero | capitalize"></option>
</select>
'''
helpers.render source, context, (node) ->
deepEqual context.get('selected.names'), ['crono', 'link']
deepEqual getSelections(node), []
deepEqual getContents(node), []
context.get('heros').add 'mario', 'crono', 'link', 'kirby'
delay ->
deepEqual getSelections(node), [no, yes, yes, no]
deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']
context.set 'selected.names', ['mario', 'kirby']
deepEqual getSelections(node), [yes, no, no, yes]
deepEqual getContents(node), ['Mario', 'Crono', 'Link', 'Kirby']
context.get('heros').clear()
delay ->
deepEqual context.get('selected.names'), ['mario', 'kirby']
deepEqual getContents(node), []
asyncTest 'it binds the value of a multi-select box and updates the value when the selected options change', ->
context = new Batman.Object
selected: 'crono'
mario: new Batman.Object(selected: null)
crono: new Batman.Object(selected: null)
helpers.render '<select multiple="multiple" data-bind="selected"><option value="mario" data-bind-selected="mario.selected"></option><option value="crono" data-bind-selected="crono.selected"></option></select>', context, (node) ->
equal node[0].value, 'crono', 'node value is crono'
equal context.get('selected'), 'crono', 'selected is crono'
equal context.get('crono.selected'), true, 'crono is selected'
equal context.get('mario.selected'), false, 'mario is not selected'
context.set 'mario.selected', true
equal context.get('mario.selected'), true, 'mario is selected'
equal context.get('crono.selected'), true, 'crono is still selected'
deepEqual context.get('selected'), ['mario', 'crono'], 'mario and crono are selected in binding'
for opt in node[0].children
ok opt.selected, "#{opt.value} option is selected"
QUnit.start()
asyncTest 'it binds multiple select options created by a foreach and remains consistent when the set instance iterated over swaps', 4, ->
context = new Batman.Object
mario: mario = new Batman.Object(selected: false, name: 'mario')
crono: crono = new Batman.Object(selected: true, name: 'crono')
heros: new Batman.Set(mario, crono).sortedBy('name')
source = '''
<select multiple="multiple">
<option data-foreach-hero="heros" data-bind-selected="hero.selected" data-bind="hero.name" data-bind-value="hero.name"></option>
</select>
'''
helpers.render source, context, (node) ->
deepEqual getContents(node), ['crono', 'mario']
deepEqual getSelections(node), [true, false]
context.set 'heros', new Batman.Set(context.get('crono'), context.get('mario')).sortedBy('name')
delay ->
deepEqual getContents(node), ['crono', 'mario']
deepEqual getSelections(node), [true, false]
asyncTest 'should be able to destroy bound select nodes', 2, ->
context = new Batman.Object selected: "foo"
helpers.render '<select data-bind="selected"><option value="foo">foo</option></select>', context, (node) ->
Batman.DOM.destroyNode(node[0])
deepEqual Batman.data(node[0]), {}
deepEqual Batman._data(node[0]), {}
QUnit.start()
asyncTest "should select an option with value='' when the data is undefined", ->
context = Batman
current: Batman
bar: 'foo'
source = '''
<select data-bind="current.bar">
<option value="">none</option>
<option value="foo">foo</option>
</select>
'''
helpers.render source, context, (node) ->
equal node[0].value, 'foo'
deepEqual getContents(node), ['none', 'foo']
context.unset 'current.bar'
equal typeof context.get('current.bar'), 'undefined'
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
delay ->
equal typeof context.get('current.bar'), 'undefined'
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
asyncTest "should select an option with value='' when the data is null", ->
context = Batman
current: Batman
bar: 'foo'
source = '''
<select data-bind="current.bar">
<option value="">none</option>
<option value="foo">foo</option>
</select>
'''
helpers.render source, context, (node) ->
equal node[0].value, 'foo'
deepEqual getContents(node), ['none', 'foo']
context.set 'current.bar', null
equal context.get('current.bar'), null
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
delay ->
equal context.get('current.bar'), null
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
asyncTest "should select an option with value='' when the data is ''", ->
context = Batman
current: 'foo'
source = '''
<select data-bind="current">
<option value="">none</option>
<option value="foo">foo</option>
</select>
'''
helpers.render source, context, (node) ->
helpers.render source, context, (node) ->
equal node[0].value, 'foo'
deepEqual getContents(node), ['none', 'foo']
context.set 'current', ''
equal context.get('current'), ''
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
delay ->
equal context.get('current'), ''
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
| 77982 | helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper'
oldIteratorDeferEvery = Batman.DOM.IteratorBinding::deferEvery
oldRendererDeferEvery = Batman.Renderer::deferEvery
getSelections = (node) -> node.find('option').map((i, node) -> !!node.selected).toArray()
getContents = (node) -> node.find('option').map((i, node) -> node.innerHTML).toArray()
QUnit.module 'Batman.View select bindings'
setup: ->
Batman.DOM.IteratorBinding::deferEvery = false
Batman.Renderer::deferEvery = false
teardown: ->
Batman.DOM.IteratorBinding::deferEvery = oldIteratorDeferEvery
Batman.Renderer::deferEvery = oldRendererDeferEvery
asyncTest 'it should bind the value of a select box and update when the javascript land value changes', 2, ->
context = Batman
heros: new Batman.Set('mario', 'crono', 'link')
selected: new Batman.Object(name: '<NAME>')
helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
equal node[0].value, 'crono'
context.set 'selected.name', 'link'
equal node[0].value, 'link'
QUnit.start()
asyncTest 'it should bind the value of a select box and update when options change', 7, ->
context = Batman
heros: new Batman.Set()
selected: new Batman.Object(name: '<NAME>')
helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero" data-bind="hero | capitalize"></option></select>', context, (node) ->
equal node[0].value, ''
equal context.get('selected.name'), 'crono'
context.get('heros').add('mario', 'link', 'crono')
delay ->
equal node[0].value, 'crono'
deepEqual getContents(node), ['<NAME>', 'Link', 'Crono']
equal context.get('selected.name'), 'crono'
context.set('selected.name', '<NAME>')
equal node[0].value, 'mario'
deepEqual getContents(node), ['<NAME>', 'Link', 'Crono']
asyncTest 'it should bind the value of a select box and update the javascript land value with the selected option', 3, ->
context = Batman
heros: new Batman.SimpleSet('mario', 'crono', 'link')
selected: 'crono'
helpers.render '<select data-bind="selected"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
equal node[0].value, 'crono'
context.set 'selected', 'link'
equal node[0].value, 'link'
context.set 'selected', 'mario'
equal node[0].value, 'mario'
QUnit.start()
asyncTest 'it binds the options of a select box and updates when the select\'s value changes', ->
context = Batman
something: 'crono'
mario: Batman(selected: null)
crono: Batman(selected: null)
helpers.render '<select data-bind="something"><option value="<NAME>io" data-bind-selected="mario.selected"><NAME>ario</option><option value="crono" data-bind-selected="crono.selected">Crono</option></select>', context, (node) ->
equal node[0].value, 'crono'
equal context.get('crono.selected'), true
equal context.get('mario.selected'), false
deepEqual getContents(node), ['<NAME>', 'Crono']
node[0].value = '<NAME>io'
helpers.triggerChange node[0]
equal context.get('mario.selected'), true
equal context.get('crono.selected'), false
deepEqual getContents(node), ['<NAME>ario', 'Crono']
QUnit.start()
asyncTest 'it binds options created by a foreach and remains consistent when the set instance iterated over swaps', ->
leo = Batman name: '<NAME>', id: 1
mikey = Batman name: '<NAME>', id: 2
context = Batman
heroes: new Batman.Set(leo, mikey).sortedBy('id')
selected: 1
helpers.render '<select data-bind="selected">' +
'<option data-foreach-hero="heroes" data-bind-value="hero.id" data-bind="hero.name" />' +
'</selected>', context, (node) ->
delay ->
deepEqual getContents(node), ['leo', 'mikey']
equal node[0].value, "1"
context.set 'heroes', new Batman.Set(leo, mikey).sortedBy('id')
delay ->
deepEqual getContents(node), ['leo', 'mikey']
equal node[0].value, "1"
asyncTest 'it binds the value of a multi-select box and updates the options when the bound value changes', ->
context = new Batman.Object
heros: new Batman.Set('<NAME>', '<NAME>', 'link', 'kir<NAME>')
selected: new Batman.Object(name: ['<NAME>', '<NAME>'])
helpers.render '<select multiple="multiple" size="2" data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero" data-bind="hero | capitalize"></option></select>', context, (node) ->
deepEqual getSelections(node), [no, yes, yes, no]
deepEqual getContents(node), ['<NAME>', '<NAME>', 'Link', 'Kirby']
context.set 'selected.name', ['<NAME>', '<NAME>']
deepEqual getSelections(node), [yes, no, no, yes]
deepEqual getContents(node), ['<NAME>', '<NAME>', 'Link', 'Kirby']
QUnit.start()
asyncTest 'it binds the value of a multi-select box and updates the options when the options changes', ->
context = new Batman.Object
heros: new Batman.Set()
selected: new Batman.Object(names: ['<NAME>', 'link'])
source = '''
<select multiple="multiple" size="2" data-bind="selected.names">
<option data-foreach-hero="heros" data-bind-value="hero" data-bind="hero | capitalize"></option>
</select>
'''
helpers.render source, context, (node) ->
deepEqual context.get('selected.names'), ['<NAME>', 'link']
deepEqual getSelections(node), []
deepEqual getContents(node), []
context.get('heros').add '<NAME>', '<NAME>', 'link', 'kirby'
delay ->
deepEqual getSelections(node), [no, yes, yes, no]
deepEqual getContents(node), ['<NAME>', '<NAME>', 'Link', 'K<NAME>by']
context.set 'selected.names', ['<NAME>', '<NAME>']
deepEqual getSelections(node), [yes, no, no, yes]
deepEqual getContents(node), ['<NAME>', '<NAME>', 'Link', '<NAME>']
context.get('heros').clear()
delay ->
deepEqual context.get('selected.names'), ['<NAME>', '<NAME>']
deepEqual getContents(node), []
asyncTest 'it binds the value of a multi-select box and updates the value when the selected options change', ->
context = new Batman.Object
selected: 'crono'
mario: new Batman.Object(selected: null)
crono: new Batman.Object(selected: null)
helpers.render '<select multiple="multiple" data-bind="selected"><option value="<NAME>" data-bind-selected="mario.selected"></option><option value="<NAME>" data-bind-selected="crono.selected"></option></select>', context, (node) ->
equal node[0].value, 'crono', 'node value is crono'
equal context.get('selected'), 'crono', 'selected is crono'
equal context.get('crono.selected'), true, 'crono is selected'
equal context.get('mario.selected'), false, 'mario is not selected'
context.set 'mario.selected', true
equal context.get('mario.selected'), true, '<NAME> is selected'
equal context.get('crono.selected'), true, 'crono is still selected'
deepEqual context.get('selected'), ['mario', 'crono'], 'mario and crono are selected in binding'
for opt in node[0].children
ok opt.selected, "#{opt.value} option is selected"
QUnit.start()
asyncTest 'it binds multiple select options created by a foreach and remains consistent when the set instance iterated over swaps', 4, ->
context = new Batman.Object
mario: mario = new Batman.Object(selected: false, name: '<NAME>')
crono: crono = new Batman.Object(selected: true, name: '<NAME>')
heros: new Batman.Set(mario, crono).sortedBy('name')
source = '''
<select multiple="multiple">
<option data-foreach-hero="heros" data-bind-selected="hero.selected" data-bind="hero.name" data-bind-value="hero.name"></option>
</select>
'''
helpers.render source, context, (node) ->
deepEqual getContents(node), ['crono', 'mario']
deepEqual getSelections(node), [true, false]
context.set 'heros', new Batman.Set(context.get('crono'), context.get('mario')).sortedBy('name')
delay ->
deepEqual getContents(node), ['crono', 'mario']
deepEqual getSelections(node), [true, false]
asyncTest 'should be able to destroy bound select nodes', 2, ->
context = new Batman.Object selected: "foo"
helpers.render '<select data-bind="selected"><option value="foo">foo</option></select>', context, (node) ->
Batman.DOM.destroyNode(node[0])
deepEqual Batman.data(node[0]), {}
deepEqual Batman._data(node[0]), {}
QUnit.start()
asyncTest "should select an option with value='' when the data is undefined", ->
context = Batman
current: Batman
bar: 'foo'
source = '''
<select data-bind="current.bar">
<option value="">none</option>
<option value="foo">foo</option>
</select>
'''
helpers.render source, context, (node) ->
equal node[0].value, 'foo'
deepEqual getContents(node), ['none', 'foo']
context.unset 'current.bar'
equal typeof context.get('current.bar'), 'undefined'
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
delay ->
equal typeof context.get('current.bar'), 'undefined'
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
asyncTest "should select an option with value='' when the data is null", ->
context = Batman
current: Batman
bar: 'foo'
source = '''
<select data-bind="current.bar">
<option value="">none</option>
<option value="foo">foo</option>
</select>
'''
helpers.render source, context, (node) ->
equal node[0].value, 'foo'
deepEqual getContents(node), ['none', 'foo']
context.set 'current.bar', null
equal context.get('current.bar'), null
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
delay ->
equal context.get('current.bar'), null
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
asyncTest "should select an option with value='' when the data is ''", ->
context = Batman
current: 'foo'
source = '''
<select data-bind="current">
<option value="">none</option>
<option value="foo">foo</option>
</select>
'''
helpers.render source, context, (node) ->
helpers.render source, context, (node) ->
equal node[0].value, 'foo'
deepEqual getContents(node), ['none', 'foo']
context.set 'current', ''
equal context.get('current'), ''
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
delay ->
equal context.get('current'), ''
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
| true | helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper'
oldIteratorDeferEvery = Batman.DOM.IteratorBinding::deferEvery
oldRendererDeferEvery = Batman.Renderer::deferEvery
getSelections = (node) -> node.find('option').map((i, node) -> !!node.selected).toArray()
getContents = (node) -> node.find('option').map((i, node) -> node.innerHTML).toArray()
QUnit.module 'Batman.View select bindings'
setup: ->
Batman.DOM.IteratorBinding::deferEvery = false
Batman.Renderer::deferEvery = false
teardown: ->
Batman.DOM.IteratorBinding::deferEvery = oldIteratorDeferEvery
Batman.Renderer::deferEvery = oldRendererDeferEvery
asyncTest 'it should bind the value of a select box and update when the javascript land value changes', 2, ->
context = Batman
heros: new Batman.Set('mario', 'crono', 'link')
selected: new Batman.Object(name: 'PI:NAME:<NAME>END_PI')
helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
equal node[0].value, 'crono'
context.set 'selected.name', 'link'
equal node[0].value, 'link'
QUnit.start()
asyncTest 'it should bind the value of a select box and update when options change', 7, ->
context = Batman
heros: new Batman.Set()
selected: new Batman.Object(name: 'PI:NAME:<NAME>END_PI')
helpers.render '<select data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero" data-bind="hero | capitalize"></option></select>', context, (node) ->
equal node[0].value, ''
equal context.get('selected.name'), 'crono'
context.get('heros').add('mario', 'link', 'crono')
delay ->
equal node[0].value, 'crono'
deepEqual getContents(node), ['PI:NAME:<NAME>END_PI', 'Link', 'Crono']
equal context.get('selected.name'), 'crono'
context.set('selected.name', 'PI:NAME:<NAME>END_PI')
equal node[0].value, 'mario'
deepEqual getContents(node), ['PI:NAME:<NAME>END_PI', 'Link', 'Crono']
asyncTest 'it should bind the value of a select box and update the javascript land value with the selected option', 3, ->
context = Batman
heros: new Batman.SimpleSet('mario', 'crono', 'link')
selected: 'crono'
helpers.render '<select data-bind="selected"><option data-foreach-hero="heros" data-bind-value="hero"></option></select>', context, (node) ->
equal node[0].value, 'crono'
context.set 'selected', 'link'
equal node[0].value, 'link'
context.set 'selected', 'mario'
equal node[0].value, 'mario'
QUnit.start()
asyncTest 'it binds the options of a select box and updates when the select\'s value changes', ->
context = Batman
something: 'crono'
mario: Batman(selected: null)
crono: Batman(selected: null)
helpers.render '<select data-bind="something"><option value="PI:NAME:<NAME>END_PIio" data-bind-selected="mario.selected">PI:NAME:<NAME>END_PIario</option><option value="crono" data-bind-selected="crono.selected">Crono</option></select>', context, (node) ->
equal node[0].value, 'crono'
equal context.get('crono.selected'), true
equal context.get('mario.selected'), false
deepEqual getContents(node), ['PI:NAME:<NAME>END_PI', 'Crono']
node[0].value = 'PI:NAME:<NAME>END_PIio'
helpers.triggerChange node[0]
equal context.get('mario.selected'), true
equal context.get('crono.selected'), false
deepEqual getContents(node), ['PI:NAME:<NAME>END_PIario', 'Crono']
QUnit.start()
asyncTest 'it binds options created by a foreach and remains consistent when the set instance iterated over swaps', ->
leo = Batman name: 'PI:NAME:<NAME>END_PI', id: 1
mikey = Batman name: 'PI:NAME:<NAME>END_PI', id: 2
context = Batman
heroes: new Batman.Set(leo, mikey).sortedBy('id')
selected: 1
helpers.render '<select data-bind="selected">' +
'<option data-foreach-hero="heroes" data-bind-value="hero.id" data-bind="hero.name" />' +
'</selected>', context, (node) ->
delay ->
deepEqual getContents(node), ['leo', 'mikey']
equal node[0].value, "1"
context.set 'heroes', new Batman.Set(leo, mikey).sortedBy('id')
delay ->
deepEqual getContents(node), ['leo', 'mikey']
equal node[0].value, "1"
asyncTest 'it binds the value of a multi-select box and updates the options when the bound value changes', ->
context = new Batman.Object
heros: new Batman.Set('PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'link', 'kirPI:NAME:<NAME>END_PI')
selected: new Batman.Object(name: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'])
helpers.render '<select multiple="multiple" size="2" data-bind="selected.name"><option data-foreach-hero="heros" data-bind-value="hero" data-bind="hero | capitalize"></option></select>', context, (node) ->
deepEqual getSelections(node), [no, yes, yes, no]
deepEqual getContents(node), ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'Link', 'Kirby']
context.set 'selected.name', ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
deepEqual getSelections(node), [yes, no, no, yes]
deepEqual getContents(node), ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'Link', 'Kirby']
QUnit.start()
asyncTest 'it binds the value of a multi-select box and updates the options when the options changes', ->
context = new Batman.Object
heros: new Batman.Set()
selected: new Batman.Object(names: ['PI:NAME:<NAME>END_PI', 'link'])
source = '''
<select multiple="multiple" size="2" data-bind="selected.names">
<option data-foreach-hero="heros" data-bind-value="hero" data-bind="hero | capitalize"></option>
</select>
'''
helpers.render source, context, (node) ->
deepEqual context.get('selected.names'), ['PI:NAME:<NAME>END_PI', 'link']
deepEqual getSelections(node), []
deepEqual getContents(node), []
context.get('heros').add 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'link', 'kirby'
delay ->
deepEqual getSelections(node), [no, yes, yes, no]
deepEqual getContents(node), ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'Link', 'KPI:NAME:<NAME>END_PIby']
context.set 'selected.names', ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
deepEqual getSelections(node), [yes, no, no, yes]
deepEqual getContents(node), ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'Link', 'PI:NAME:<NAME>END_PI']
context.get('heros').clear()
delay ->
deepEqual context.get('selected.names'), ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
deepEqual getContents(node), []
asyncTest 'it binds the value of a multi-select box and updates the value when the selected options change', ->
context = new Batman.Object
selected: 'crono'
mario: new Batman.Object(selected: null)
crono: new Batman.Object(selected: null)
helpers.render '<select multiple="multiple" data-bind="selected"><option value="PI:NAME:<NAME>END_PI" data-bind-selected="mario.selected"></option><option value="PI:NAME:<NAME>END_PI" data-bind-selected="crono.selected"></option></select>', context, (node) ->
equal node[0].value, 'crono', 'node value is crono'
equal context.get('selected'), 'crono', 'selected is crono'
equal context.get('crono.selected'), true, 'crono is selected'
equal context.get('mario.selected'), false, 'mario is not selected'
context.set 'mario.selected', true
equal context.get('mario.selected'), true, 'PI:NAME:<NAME>END_PI is selected'
equal context.get('crono.selected'), true, 'crono is still selected'
deepEqual context.get('selected'), ['mario', 'crono'], 'mario and crono are selected in binding'
for opt in node[0].children
ok opt.selected, "#{opt.value} option is selected"
QUnit.start()
asyncTest 'it binds multiple select options created by a foreach and remains consistent when the set instance iterated over swaps', 4, ->
context = new Batman.Object
mario: mario = new Batman.Object(selected: false, name: 'PI:NAME:<NAME>END_PI')
crono: crono = new Batman.Object(selected: true, name: 'PI:NAME:<NAME>END_PI')
heros: new Batman.Set(mario, crono).sortedBy('name')
source = '''
<select multiple="multiple">
<option data-foreach-hero="heros" data-bind-selected="hero.selected" data-bind="hero.name" data-bind-value="hero.name"></option>
</select>
'''
helpers.render source, context, (node) ->
deepEqual getContents(node), ['crono', 'mario']
deepEqual getSelections(node), [true, false]
context.set 'heros', new Batman.Set(context.get('crono'), context.get('mario')).sortedBy('name')
delay ->
deepEqual getContents(node), ['crono', 'mario']
deepEqual getSelections(node), [true, false]
asyncTest 'should be able to destroy bound select nodes', 2, ->
context = new Batman.Object selected: "foo"
helpers.render '<select data-bind="selected"><option value="foo">foo</option></select>', context, (node) ->
Batman.DOM.destroyNode(node[0])
deepEqual Batman.data(node[0]), {}
deepEqual Batman._data(node[0]), {}
QUnit.start()
asyncTest "should select an option with value='' when the data is undefined", ->
context = Batman
current: Batman
bar: 'foo'
source = '''
<select data-bind="current.bar">
<option value="">none</option>
<option value="foo">foo</option>
</select>
'''
helpers.render source, context, (node) ->
equal node[0].value, 'foo'
deepEqual getContents(node), ['none', 'foo']
context.unset 'current.bar'
equal typeof context.get('current.bar'), 'undefined'
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
delay ->
equal typeof context.get('current.bar'), 'undefined'
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
asyncTest "should select an option with value='' when the data is null", ->
context = Batman
current: Batman
bar: 'foo'
source = '''
<select data-bind="current.bar">
<option value="">none</option>
<option value="foo">foo</option>
</select>
'''
helpers.render source, context, (node) ->
equal node[0].value, 'foo'
deepEqual getContents(node), ['none', 'foo']
context.set 'current.bar', null
equal context.get('current.bar'), null
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
delay ->
equal context.get('current.bar'), null
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
asyncTest "should select an option with value='' when the data is ''", ->
context = Batman
current: 'foo'
source = '''
<select data-bind="current">
<option value="">none</option>
<option value="foo">foo</option>
</select>
'''
helpers.render source, context, (node) ->
helpers.render source, context, (node) ->
equal node[0].value, 'foo'
deepEqual getContents(node), ['none', 'foo']
context.set 'current', ''
equal context.get('current'), ''
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
delay ->
equal context.get('current'), ''
equal node[0].value, ''
deepEqual getContents(node), ['none', 'foo']
|
[
{
"context": " = JSON.parse(data.toString())\n session_key = @scrobblers[params.username]\n if session_key is params.s",
"end": 2062,
"score": 0.9446306228637695,
"start": 2051,
"tag": "KEY",
"value": "@scrobblers"
},
{
"context": "artist_name\n for username, session_key of @scrobblers\n @log.debug \"queuing scrobble: #{track",
"end": 3906,
"score": 0.9946739077568054,
"start": 3895,
"tag": "USERNAME",
"value": "@scrobblers"
},
{
"context": "st\"\n return\n\n for username, session_key of @scrobblers\n @log.debug \"update now playing with session",
"end": 5079,
"score": 0.9944175481796265,
"start": 5068,
"tag": "USERNAME",
"value": "@scrobblers"
}
] | src/server/plugins/lastfm.coffee | joshbedo/groovebasin | 1 | Plugin = require('../plugin').Plugin
LastFmNode = require('lastfm').LastFmNode
exports.Plugin = class LastFm extends Plugin
constructor: ->
super
@lastfm = new LastFmNode
api_key: process.env.npm_package_config_lastfm_api_key
secret: process.env.npm_package_config_lastfm_secret
@previous_now_playing_id = null
@last_playing_item = null
@playing_start = new Date()
@playing_time = 0
@previous_play_state = null
setTimeout @flushScrobbleQueue, 120000
restoreState: (state) =>
@scrobblers = state.lastfm_scrobblers ? {}
@scrobbles = state.scrobbles ? []
saveState: (state) =>
state.lastfm_scrobblers = @scrobblers
state.scrobbles = @scrobbles
state.status.lastfm_api_key = process.env.npm_package_config_lastfm_api_key
setMpd: (@mpd) =>
@mpd.on 'statusupdate', =>
@updateNowPlaying()
@checkScrobble()
onSocketConnection: (socket) =>
socket.on 'LastfmGetSession', (data) =>
@log.debug "getting session with #{data}"
@lastfm.request "auth.getSession",
token: data.toString()
handlers:
success: (data) =>
# clear them from the scrobblers
delete @scrobblers[data?.session?.name]
socket.emit 'LastfmGetSessionSuccess', JSON.stringify(data)
@log.debug "success from last.fm auth.getSession: #{JSON.stringify data}"
error: (error) =>
@log.error "error from last.fm auth.getSession: #{error.message}"
socket.emit 'LastfmGetSessionError', JSON.stringify(error)
socket.on 'LastfmScrobblersAdd', (data) =>
data_str = data.toString()
@log.debug "LastfmScrobblersAdd: #{data_str}"
params = JSON.parse(data_str)
# ignore if scrobbling user already exists. this is a fake request.
return if @scrobblers[params.username]?
@scrobblers[params.username] = params.session_key
@onStateChanged()
socket.on 'LastfmScrobblersRemove', (data) =>
params = JSON.parse(data.toString())
session_key = @scrobblers[params.username]
if session_key is params.session_key
delete @scrobblers[params.username]
@onStateChanged()
else
@log.warn "Invalid session key from user trying to remove scrobbler: #{params.username}"
flushScrobbleQueue: =>
@log.debug "flushing scrobble queue"
max_simultaneous = 10
count = 0
while (params = @scrobbles.shift())? and count++ < max_simultaneous
@log.info "scrobbling #{params.track} for session #{params.sk}"
params.handlers =
error: (error) =>
@log.error "error from last.fm track.scrobble: #{error.message}"
if not error?.code? or error.code is 11 or error.code is 16
# retryable - add to queue
@scrobbles.push params
@onStateChanged()
@lastfm.request 'track.scrobble', params
@onStateChanged()
queueScrobble: (params) =>
@scrobbles.push params
@onStateChanged()
checkTrackNumber: (trackNumber) =>
if parseInt(trackNumber) >= 0 then trackNumber else ""
checkScrobble: =>
this_item = @mpd.status.current_item
if @mpd.status.state is 'play'
if @previous_play_state isnt 'play'
@playing_start = new Date(new Date().getTime() - @playing_time)
@previous_play_state = @mpd.status.state
@playing_time = new Date().getTime() - @playing_start.getTime()
@log.debug "playtime so far: #{@playing_time}"
return unless this_item?.id isnt @last_playing_item?.id
@log.debug "ids are different"
if (track = @last_playing_item?.track)?
# then scrobble it
min_amt = 15 * 1000
max_amt = 4 * 60 * 1000
half_amt = track.time / 2 * 1000
if @playing_time >= min_amt and (@playing_time >= max_amt or @playing_time >= half_amt)
if track.artist_name
for username, session_key of @scrobblers
@log.debug "queuing scrobble: #{track.name} for #{username}"
@queueScrobble
sk: session_key
timestamp: Math.round(@playing_start.getTime() / 1000)
album: track.album?.name or ""
track: track.name or ""
artist: track.artist_name or ""
albumArtist: track.album_artist_name or ""
duration: track.time or ""
trackNumber: @checkTrackNumber track.track
@flushScrobbleQueue()
else
@log.warn "Not scrobbling #{track.name} - missing artist."
@last_playing_item = this_item
@previous_play_state = @mpd.status.state
@playing_start = new Date()
@playing_time = 0
updateNowPlaying: =>
return unless @mpd.status.state is 'play'
return unless (track = @mpd.status.current_item?.track)?
return unless @previous_now_playing_id isnt @mpd.status.current_item.id
@previous_now_playing_id = @mpd.status.current_item.id
if not track.artist_name
@log.warn "Not updating last.fm now playing for #{track.name}: missing artist"
return
for username, session_key of @scrobblers
@log.debug "update now playing with session_key: #{session_key}, track: #{track.name}, artist: #{track.artist_name}, album: #{track.album?.name}"
@lastfm.request "track.updateNowPlaying",
sk: session_key
track: track.name or ""
artist: track.artist_name or ""
album: track.album?.name or ""
albumArtist: track.album_artist_name or ""
trackNumber: @checkTrackNumber track.track
duration: track.time or ""
handlers:
error: (error) =>
@log.error "error from last.fm track.updateNowPlaying: #{error.message}"
| 172448 | Plugin = require('../plugin').Plugin
LastFmNode = require('lastfm').LastFmNode
exports.Plugin = class LastFm extends Plugin
constructor: ->
super
@lastfm = new LastFmNode
api_key: process.env.npm_package_config_lastfm_api_key
secret: process.env.npm_package_config_lastfm_secret
@previous_now_playing_id = null
@last_playing_item = null
@playing_start = new Date()
@playing_time = 0
@previous_play_state = null
setTimeout @flushScrobbleQueue, 120000
restoreState: (state) =>
@scrobblers = state.lastfm_scrobblers ? {}
@scrobbles = state.scrobbles ? []
saveState: (state) =>
state.lastfm_scrobblers = @scrobblers
state.scrobbles = @scrobbles
state.status.lastfm_api_key = process.env.npm_package_config_lastfm_api_key
setMpd: (@mpd) =>
@mpd.on 'statusupdate', =>
@updateNowPlaying()
@checkScrobble()
onSocketConnection: (socket) =>
socket.on 'LastfmGetSession', (data) =>
@log.debug "getting session with #{data}"
@lastfm.request "auth.getSession",
token: data.toString()
handlers:
success: (data) =>
# clear them from the scrobblers
delete @scrobblers[data?.session?.name]
socket.emit 'LastfmGetSessionSuccess', JSON.stringify(data)
@log.debug "success from last.fm auth.getSession: #{JSON.stringify data}"
error: (error) =>
@log.error "error from last.fm auth.getSession: #{error.message}"
socket.emit 'LastfmGetSessionError', JSON.stringify(error)
socket.on 'LastfmScrobblersAdd', (data) =>
data_str = data.toString()
@log.debug "LastfmScrobblersAdd: #{data_str}"
params = JSON.parse(data_str)
# ignore if scrobbling user already exists. this is a fake request.
return if @scrobblers[params.username]?
@scrobblers[params.username] = params.session_key
@onStateChanged()
socket.on 'LastfmScrobblersRemove', (data) =>
params = JSON.parse(data.toString())
session_key = <KEY>[params.username]
if session_key is params.session_key
delete @scrobblers[params.username]
@onStateChanged()
else
@log.warn "Invalid session key from user trying to remove scrobbler: #{params.username}"
flushScrobbleQueue: =>
@log.debug "flushing scrobble queue"
max_simultaneous = 10
count = 0
while (params = @scrobbles.shift())? and count++ < max_simultaneous
@log.info "scrobbling #{params.track} for session #{params.sk}"
params.handlers =
error: (error) =>
@log.error "error from last.fm track.scrobble: #{error.message}"
if not error?.code? or error.code is 11 or error.code is 16
# retryable - add to queue
@scrobbles.push params
@onStateChanged()
@lastfm.request 'track.scrobble', params
@onStateChanged()
queueScrobble: (params) =>
@scrobbles.push params
@onStateChanged()
checkTrackNumber: (trackNumber) =>
if parseInt(trackNumber) >= 0 then trackNumber else ""
checkScrobble: =>
this_item = @mpd.status.current_item
if @mpd.status.state is 'play'
if @previous_play_state isnt 'play'
@playing_start = new Date(new Date().getTime() - @playing_time)
@previous_play_state = @mpd.status.state
@playing_time = new Date().getTime() - @playing_start.getTime()
@log.debug "playtime so far: #{@playing_time}"
return unless this_item?.id isnt @last_playing_item?.id
@log.debug "ids are different"
if (track = @last_playing_item?.track)?
# then scrobble it
min_amt = 15 * 1000
max_amt = 4 * 60 * 1000
half_amt = track.time / 2 * 1000
if @playing_time >= min_amt and (@playing_time >= max_amt or @playing_time >= half_amt)
if track.artist_name
for username, session_key of @scrobblers
@log.debug "queuing scrobble: #{track.name} for #{username}"
@queueScrobble
sk: session_key
timestamp: Math.round(@playing_start.getTime() / 1000)
album: track.album?.name or ""
track: track.name or ""
artist: track.artist_name or ""
albumArtist: track.album_artist_name or ""
duration: track.time or ""
trackNumber: @checkTrackNumber track.track
@flushScrobbleQueue()
else
@log.warn "Not scrobbling #{track.name} - missing artist."
@last_playing_item = this_item
@previous_play_state = @mpd.status.state
@playing_start = new Date()
@playing_time = 0
updateNowPlaying: =>
return unless @mpd.status.state is 'play'
return unless (track = @mpd.status.current_item?.track)?
return unless @previous_now_playing_id isnt @mpd.status.current_item.id
@previous_now_playing_id = @mpd.status.current_item.id
if not track.artist_name
@log.warn "Not updating last.fm now playing for #{track.name}: missing artist"
return
for username, session_key of @scrobblers
@log.debug "update now playing with session_key: #{session_key}, track: #{track.name}, artist: #{track.artist_name}, album: #{track.album?.name}"
@lastfm.request "track.updateNowPlaying",
sk: session_key
track: track.name or ""
artist: track.artist_name or ""
album: track.album?.name or ""
albumArtist: track.album_artist_name or ""
trackNumber: @checkTrackNumber track.track
duration: track.time or ""
handlers:
error: (error) =>
@log.error "error from last.fm track.updateNowPlaying: #{error.message}"
| true | Plugin = require('../plugin').Plugin
LastFmNode = require('lastfm').LastFmNode
exports.Plugin = class LastFm extends Plugin
constructor: ->
super
@lastfm = new LastFmNode
api_key: process.env.npm_package_config_lastfm_api_key
secret: process.env.npm_package_config_lastfm_secret
@previous_now_playing_id = null
@last_playing_item = null
@playing_start = new Date()
@playing_time = 0
@previous_play_state = null
setTimeout @flushScrobbleQueue, 120000
restoreState: (state) =>
@scrobblers = state.lastfm_scrobblers ? {}
@scrobbles = state.scrobbles ? []
saveState: (state) =>
state.lastfm_scrobblers = @scrobblers
state.scrobbles = @scrobbles
state.status.lastfm_api_key = process.env.npm_package_config_lastfm_api_key
setMpd: (@mpd) =>
@mpd.on 'statusupdate', =>
@updateNowPlaying()
@checkScrobble()
onSocketConnection: (socket) =>
socket.on 'LastfmGetSession', (data) =>
@log.debug "getting session with #{data}"
@lastfm.request "auth.getSession",
token: data.toString()
handlers:
success: (data) =>
# clear them from the scrobblers
delete @scrobblers[data?.session?.name]
socket.emit 'LastfmGetSessionSuccess', JSON.stringify(data)
@log.debug "success from last.fm auth.getSession: #{JSON.stringify data}"
error: (error) =>
@log.error "error from last.fm auth.getSession: #{error.message}"
socket.emit 'LastfmGetSessionError', JSON.stringify(error)
socket.on 'LastfmScrobblersAdd', (data) =>
data_str = data.toString()
@log.debug "LastfmScrobblersAdd: #{data_str}"
params = JSON.parse(data_str)
# ignore if scrobbling user already exists. this is a fake request.
return if @scrobblers[params.username]?
@scrobblers[params.username] = params.session_key
@onStateChanged()
socket.on 'LastfmScrobblersRemove', (data) =>
params = JSON.parse(data.toString())
session_key = PI:KEY:<KEY>END_PI[params.username]
if session_key is params.session_key
delete @scrobblers[params.username]
@onStateChanged()
else
@log.warn "Invalid session key from user trying to remove scrobbler: #{params.username}"
flushScrobbleQueue: =>
@log.debug "flushing scrobble queue"
max_simultaneous = 10
count = 0
while (params = @scrobbles.shift())? and count++ < max_simultaneous
@log.info "scrobbling #{params.track} for session #{params.sk}"
params.handlers =
error: (error) =>
@log.error "error from last.fm track.scrobble: #{error.message}"
if not error?.code? or error.code is 11 or error.code is 16
# retryable - add to queue
@scrobbles.push params
@onStateChanged()
@lastfm.request 'track.scrobble', params
@onStateChanged()
queueScrobble: (params) =>
@scrobbles.push params
@onStateChanged()
checkTrackNumber: (trackNumber) =>
if parseInt(trackNumber) >= 0 then trackNumber else ""
checkScrobble: =>
this_item = @mpd.status.current_item
if @mpd.status.state is 'play'
if @previous_play_state isnt 'play'
@playing_start = new Date(new Date().getTime() - @playing_time)
@previous_play_state = @mpd.status.state
@playing_time = new Date().getTime() - @playing_start.getTime()
@log.debug "playtime so far: #{@playing_time}"
return unless this_item?.id isnt @last_playing_item?.id
@log.debug "ids are different"
if (track = @last_playing_item?.track)?
# then scrobble it
min_amt = 15 * 1000
max_amt = 4 * 60 * 1000
half_amt = track.time / 2 * 1000
if @playing_time >= min_amt and (@playing_time >= max_amt or @playing_time >= half_amt)
if track.artist_name
for username, session_key of @scrobblers
@log.debug "queuing scrobble: #{track.name} for #{username}"
@queueScrobble
sk: session_key
timestamp: Math.round(@playing_start.getTime() / 1000)
album: track.album?.name or ""
track: track.name or ""
artist: track.artist_name or ""
albumArtist: track.album_artist_name or ""
duration: track.time or ""
trackNumber: @checkTrackNumber track.track
@flushScrobbleQueue()
else
@log.warn "Not scrobbling #{track.name} - missing artist."
@last_playing_item = this_item
@previous_play_state = @mpd.status.state
@playing_start = new Date()
@playing_time = 0
updateNowPlaying: =>
return unless @mpd.status.state is 'play'
return unless (track = @mpd.status.current_item?.track)?
return unless @previous_now_playing_id isnt @mpd.status.current_item.id
@previous_now_playing_id = @mpd.status.current_item.id
if not track.artist_name
@log.warn "Not updating last.fm now playing for #{track.name}: missing artist"
return
for username, session_key of @scrobblers
@log.debug "update now playing with session_key: #{session_key}, track: #{track.name}, artist: #{track.artist_name}, album: #{track.album?.name}"
@lastfm.request "track.updateNowPlaying",
sk: session_key
track: track.name or ""
artist: track.artist_name or ""
album: track.album?.name or ""
albumArtist: track.album_artist_name or ""
trackNumber: @checkTrackNumber track.track
duration: track.time or ""
handlers:
error: (error) =>
@log.error "error from last.fm track.updateNowPlaying: #{error.message}"
|
[
{
"context": "#\n# Copyright 2014 Carsten Klein\n#\n# Licensed under the Apache License, Version 2.",
"end": 32,
"score": 0.9998596906661987,
"start": 19,
"tag": "NAME",
"value": "Carsten Klein"
}
] | test/coffee-script-only-inheritance-test.coffee | vibejs/vibejs-subclassof | 0 | #
# Copyright 2014 Carsten Klein
#
# 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.
#
vows = require 'vows'
assert = require 'assert'
require '../src/macros'
vows
.describe 'coffee-script only inheritance'
.addBatch
'shallow inheritance tree' :
topic : ->
result =
base : class Super
derived : class Child extends Super
'is subclassof Super' : (topic) ->
assert.subclassOf topic.derived, topic.base
'is also a subclass of Object' : (topic) ->
assert.subclassOf topic.derived, Object
'deep inheritance tree' :
topic : ->
result =
base : class Super
base1 : class Child1 extends Super
base2 : class Child2 extends Child1
derived : class Child3 extends Child2
'is subclassof Child2' : (topic) ->
assert.subclassOf topic.derived, topic.base2
'is subclassof Child1' : (topic) ->
assert.subclassOf topic.derived, topic.base1
'is subclassof Super' : (topic) ->
assert.subclassOf topic.derived, topic.base
'is also a subclass of Object' : (topic) ->
assert.subclassOf topic.derived, Object
.export module
| 76093 | #
# Copyright 2014 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
vows = require 'vows'
assert = require 'assert'
require '../src/macros'
vows
.describe 'coffee-script only inheritance'
.addBatch
'shallow inheritance tree' :
topic : ->
result =
base : class Super
derived : class Child extends Super
'is subclassof Super' : (topic) ->
assert.subclassOf topic.derived, topic.base
'is also a subclass of Object' : (topic) ->
assert.subclassOf topic.derived, Object
'deep inheritance tree' :
topic : ->
result =
base : class Super
base1 : class Child1 extends Super
base2 : class Child2 extends Child1
derived : class Child3 extends Child2
'is subclassof Child2' : (topic) ->
assert.subclassOf topic.derived, topic.base2
'is subclassof Child1' : (topic) ->
assert.subclassOf topic.derived, topic.base1
'is subclassof Super' : (topic) ->
assert.subclassOf topic.derived, topic.base
'is also a subclass of Object' : (topic) ->
assert.subclassOf topic.derived, Object
.export module
| true | #
# Copyright 2014 PI:NAME:<NAME>END_PI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
vows = require 'vows'
assert = require 'assert'
require '../src/macros'
vows
.describe 'coffee-script only inheritance'
.addBatch
'shallow inheritance tree' :
topic : ->
result =
base : class Super
derived : class Child extends Super
'is subclassof Super' : (topic) ->
assert.subclassOf topic.derived, topic.base
'is also a subclass of Object' : (topic) ->
assert.subclassOf topic.derived, Object
'deep inheritance tree' :
topic : ->
result =
base : class Super
base1 : class Child1 extends Super
base2 : class Child2 extends Child1
derived : class Child3 extends Child2
'is subclassof Child2' : (topic) ->
assert.subclassOf topic.derived, topic.base2
'is subclassof Child1' : (topic) ->
assert.subclassOf topic.derived, topic.base1
'is subclassof Super' : (topic) ->
assert.subclassOf topic.derived, topic.base
'is also a subclass of Object' : (topic) ->
assert.subclassOf topic.derived, Object
.export module
|
[
{
"context": "DB\n db : 'use_this'\n authKey : 'not-this'\n password: ''\n\n tdb.acquire (err, conn) ",
"end": 1305,
"score": 0.7604880928993225,
"start": 1301,
"tag": "KEY",
"value": "this"
}
] | test/lib/db.spec.coffee | scull7/uow-store-rethink | 0 | require '../create-db.js'
rethinkdb = require 'rethinkdb'
DB = require '../../lib/db.js'
describe 'Database Connector', ->
db = null
before (done) ->
testDb = DB(rethinkConfig)
testDb.clean()
.then -> testDb.install()
.then -> done()
beforeEach -> db = DB(rethinkConfig)
it 'should throw a type error if a config object is not given', ->
test = -> DB()
expect(test).to.throw TypeError, /DatabaseNotSpecified/
it 'should throw a TypeError if an empty config object is given', ->
test = -> DB {}
expect(test).to.throw TypeError, /DatabaseNotSpecified/
it 'should throw a TypeError if a database is not specified', ->
test = -> DB({ authKey: 'something' })
expect(test).to.throw TypeError, /DatabaseNotSpecified/
it 'should provide access to the rethinkdb query object', ->
r = db.r
expect(r).to.eql rethinkdb
it 'should override the db setting with the database setting', (done) ->
tdb = DB
db : 'not_this'
database: 'use_this'
tdb.acquire (err, conn) ->
if err then return done(err)
expect(conn.db).to.eql 'use_this'
done()
it 'should override the authKey setting with the password setting', (done) ->
tdb = DB
db : 'use_this'
authKey : 'not-this'
password: ''
tdb.acquire (err, conn) ->
if err then return done(err)
expect(conn.authKey).to.eql ''
done()
it 'should return a configured connection pool', (done) ->
db.acquire (err, conn) ->
if err then return done(err)
db.r.db('test_uow_store_rethink').info().run conn, (err, cursor) ->
if err then return done(err)
expect(err).to.be.null
expect(cursor.type).to.eql 'DB'
expect(cursor.name).to.eql 'test_uow_store_rethink'
done()
describe '::install', ->
it 'should create the task table if it doesn\'t exist', (done) ->
db.clean()
.then -> db.clean()
.then -> db.install()
.then ->
query = db.r.tableList().contains('uow_task')
db.run(query)
.then (exists) ->
expect(exists).to.be.true
done()
it 'should be idempotent', (done) ->
insert = db.r.table('uow_task').insert( id: 'this-is-me' )
db.run(insert)
.then -> db.install()
.then ->
select = db.r.table('uow_task').get('this-is-me')
db.run(select)
.then (results) ->
expect(results.id).to.eql 'this-is-me'
del = db.r.table('uow_task').get('this-is-me').delete()
db.run(del)
.then -> done()
.catch done
| 157275 | require '../create-db.js'
rethinkdb = require 'rethinkdb'
DB = require '../../lib/db.js'
describe 'Database Connector', ->
db = null
before (done) ->
testDb = DB(rethinkConfig)
testDb.clean()
.then -> testDb.install()
.then -> done()
beforeEach -> db = DB(rethinkConfig)
it 'should throw a type error if a config object is not given', ->
test = -> DB()
expect(test).to.throw TypeError, /DatabaseNotSpecified/
it 'should throw a TypeError if an empty config object is given', ->
test = -> DB {}
expect(test).to.throw TypeError, /DatabaseNotSpecified/
it 'should throw a TypeError if a database is not specified', ->
test = -> DB({ authKey: 'something' })
expect(test).to.throw TypeError, /DatabaseNotSpecified/
it 'should provide access to the rethinkdb query object', ->
r = db.r
expect(r).to.eql rethinkdb
it 'should override the db setting with the database setting', (done) ->
tdb = DB
db : 'not_this'
database: 'use_this'
tdb.acquire (err, conn) ->
if err then return done(err)
expect(conn.db).to.eql 'use_this'
done()
it 'should override the authKey setting with the password setting', (done) ->
tdb = DB
db : 'use_this'
authKey : 'not-<KEY>'
password: ''
tdb.acquire (err, conn) ->
if err then return done(err)
expect(conn.authKey).to.eql ''
done()
it 'should return a configured connection pool', (done) ->
db.acquire (err, conn) ->
if err then return done(err)
db.r.db('test_uow_store_rethink').info().run conn, (err, cursor) ->
if err then return done(err)
expect(err).to.be.null
expect(cursor.type).to.eql 'DB'
expect(cursor.name).to.eql 'test_uow_store_rethink'
done()
describe '::install', ->
it 'should create the task table if it doesn\'t exist', (done) ->
db.clean()
.then -> db.clean()
.then -> db.install()
.then ->
query = db.r.tableList().contains('uow_task')
db.run(query)
.then (exists) ->
expect(exists).to.be.true
done()
it 'should be idempotent', (done) ->
insert = db.r.table('uow_task').insert( id: 'this-is-me' )
db.run(insert)
.then -> db.install()
.then ->
select = db.r.table('uow_task').get('this-is-me')
db.run(select)
.then (results) ->
expect(results.id).to.eql 'this-is-me'
del = db.r.table('uow_task').get('this-is-me').delete()
db.run(del)
.then -> done()
.catch done
| true | require '../create-db.js'
rethinkdb = require 'rethinkdb'
DB = require '../../lib/db.js'
describe 'Database Connector', ->
db = null
before (done) ->
testDb = DB(rethinkConfig)
testDb.clean()
.then -> testDb.install()
.then -> done()
beforeEach -> db = DB(rethinkConfig)
it 'should throw a type error if a config object is not given', ->
test = -> DB()
expect(test).to.throw TypeError, /DatabaseNotSpecified/
it 'should throw a TypeError if an empty config object is given', ->
test = -> DB {}
expect(test).to.throw TypeError, /DatabaseNotSpecified/
it 'should throw a TypeError if a database is not specified', ->
test = -> DB({ authKey: 'something' })
expect(test).to.throw TypeError, /DatabaseNotSpecified/
it 'should provide access to the rethinkdb query object', ->
r = db.r
expect(r).to.eql rethinkdb
it 'should override the db setting with the database setting', (done) ->
tdb = DB
db : 'not_this'
database: 'use_this'
tdb.acquire (err, conn) ->
if err then return done(err)
expect(conn.db).to.eql 'use_this'
done()
it 'should override the authKey setting with the password setting', (done) ->
tdb = DB
db : 'use_this'
authKey : 'not-PI:KEY:<KEY>END_PI'
password: ''
tdb.acquire (err, conn) ->
if err then return done(err)
expect(conn.authKey).to.eql ''
done()
it 'should return a configured connection pool', (done) ->
db.acquire (err, conn) ->
if err then return done(err)
db.r.db('test_uow_store_rethink').info().run conn, (err, cursor) ->
if err then return done(err)
expect(err).to.be.null
expect(cursor.type).to.eql 'DB'
expect(cursor.name).to.eql 'test_uow_store_rethink'
done()
describe '::install', ->
it 'should create the task table if it doesn\'t exist', (done) ->
db.clean()
.then -> db.clean()
.then -> db.install()
.then ->
query = db.r.tableList().contains('uow_task')
db.run(query)
.then (exists) ->
expect(exists).to.be.true
done()
it 'should be idempotent', (done) ->
insert = db.r.table('uow_task').insert( id: 'this-is-me' )
db.run(insert)
.then -> db.install()
.then ->
select = db.r.table('uow_task').get('this-is-me')
db.run(select)
.then (results) ->
expect(results.id).to.eql 'this-is-me'
del = db.r.table('uow_task').get('this-is-me').delete()
db.run(del)
.then -> done()
.catch done
|
[
{
"context": "should extract the name', ->\n expectedValue = 'John Smith'\n sut = new AddressParser\n sut.parse('John ",
"end": 97,
"score": 0.9998000860214233,
"start": 87,
"tag": "NAME",
"value": "John Smith"
},
{
"context": "Smith'\n sut = new AddressParser\n sut.parse('John Smith, 121 John St., Toronto, Ontario')\n expect(sut.",
"end": 152,
"score": 0.9998338222503662,
"start": 142,
"tag": "NAME",
"value": "John Smith"
},
{
"context": "= new AddressParser\n sut.parse('John Smith, 121 John St., Toronto, Ontario')\n expect(sut.name).toEq",
"end": 162,
"score": 0.9930654168128967,
"start": 158,
"tag": "NAME",
"value": "John"
},
{
"context": "hould extract the email', ->\n expectedValue = 'bob@smith.com'\n sut = new AddressParser\n sut.parse('John ",
"end": 302,
"score": 0.9999262094497681,
"start": 289,
"tag": "EMAIL",
"value": "bob@smith.com"
},
{
"context": "h.com'\n sut = new AddressParser\n sut.parse('John Smith, 121 John St., Toronto, Ontario, bob@smith.com')\n",
"end": 357,
"score": 0.9998470544815063,
"start": 347,
"tag": "NAME",
"value": "John Smith"
},
{
"context": "= new AddressParser\n sut.parse('John Smith, 121 John St., Toronto, Ontario, bob@smith.com')\n expect",
"end": 367,
"score": 0.966307520866394,
"start": 363,
"tag": "NAME",
"value": "John"
},
{
"context": "parse('John Smith, 121 John St., Toronto, Ontario, bob@smith.com')\n expect(sut.email).toEqual(expectedValue)\n\n ",
"end": 404,
"score": 0.9999265670776367,
"start": 391,
"tag": "EMAIL",
"value": "bob@smith.com"
},
{
"context": "-1111'\n sut = new AddressParser\n sut.parse('John Smith, 416.967 1111')\n expect(sut.phone).toEqual(exp",
"end": 599,
"score": 0.9998465180397034,
"start": 589,
"tag": "NAME",
"value": "John Smith"
},
{
"context": "s.com'\n sut = new AddressParser\n sut.parse('John Smith, www.thrustlabs.com')\n expect(sut.website).toE",
"end": 806,
"score": 0.9998058080673218,
"start": 796,
"tag": "NAME",
"value": "John Smith"
},
{
"context": "s', ->\n sut = new AddressParser\n sut.parse('Johnny Smith, 121 John St., Toronto, Ontario, johnny@smith.com",
"end": 976,
"score": 0.9998438954353333,
"start": 964,
"tag": "NAME",
"value": "Johnny Smith"
},
{
"context": "new AddressParser\n sut.parse('Johnny Smith, 121 John St., Toronto, Ontario, johnny@smith.com')\n exp",
"end": 986,
"score": 0.9991251826286316,
"start": 982,
"tag": "NAME",
"value": "John"
},
{
"context": "rse('Johnny Smith, 121 John St., Toronto, Ontario, johnny@smith.com')\n expect(sut.name).toEqual('Johnny Smith') ",
"end": 1026,
"score": 0.9998645782470703,
"start": 1010,
"tag": "EMAIL",
"value": "johnny@smith.com"
},
{
"context": " johnny@smith.com')\n expect(sut.name).toEqual('Johnny Smith') \n expect(sut.email).toEqual('johnny@smith",
"end": 1071,
"score": 0.9997817277908325,
"start": 1059,
"tag": "NAME",
"value": "Johnny Smith"
},
{
"context": "Johnny Smith') \n expect(sut.email).toEqual('johnny@smith.com')\n expect(sut.address).toEqual('121 John St.')",
"end": 1125,
"score": 0.9999281167984009,
"start": 1109,
"tag": "EMAIL",
"value": "johnny@smith.com"
},
{
"context": "y@smith.com')\n expect(sut.address).toEqual('121 John St.') \n expect(sut.city).toEqual('Toronto')",
"end": 1169,
"score": 0.8884875774383545,
"start": 1165,
"tag": "NAME",
"value": "John"
},
{
"context": " \"\"\"\n Amsterdam Brewery\n info@amsterdambeer.com\n 416.504.6882\n http://a",
"end": 1450,
"score": 0.9999300837516785,
"start": 1428,
"tag": "EMAIL",
"value": "info@amsterdambeer.com"
},
{
"context": "rdam Brewery') \n expect(sut.email).toEqual('info@amsterdambeer.com')\n expect(sut.address).toEqual(",
"end": 1727,
"score": 0.9999055862426758,
"start": 1720,
"tag": "EMAIL",
"value": "info@am"
},
{
"context": "2\n Phone: 509.526.5230 \n seccoitalianbubbles@gmail.com \n\n http://www.seccobubbles.com/ \n ",
"end": 2352,
"score": 0.9999240040779114,
"start": 2323,
"tag": "EMAIL",
"value": "seccoitalianbubbles@gmail.com"
},
{
"context": "lian Bubbles') \n expect(sut.email).toEqual('seccoitalianbubbles@gmail.com')\n expect(sut.address).toEqual('19 East Birch ",
"end": 2588,
"score": 0.9999240040779114,
"start": 2559,
"tag": "EMAIL",
"value": "seccoitalianbubbles@gmail.com"
},
{
"context": "ect(sut.phone).toEqual('')\n \n it 'should parse Chamard Vineyards', ->\n address = \"Chamard Vineyards | 115 Cow H",
"end": 3607,
"score": 0.9948140978813171,
"start": 3590,
"tag": "NAME",
"value": "Chamard Vineyards"
},
{
"context": "hould parse Chamard Vineyards', ->\n address = \"Chamard Vineyards | 115 Cow Hill Road | Clinton, CT 06413 Phone: 8",
"end": 3645,
"score": 0.9974169731140137,
"start": 3628,
"tag": "NAME",
"value": "Chamard Vineyards"
},
{
"context": " sut.parse(address)\n expect(sut.name).toEqual('Chamard Vineyards') \n expect(sut.email).toEqual('')\n expec",
"end": 3808,
"score": 0.9998002648353577,
"start": 3791,
"tag": "NAME",
"value": "Chamard Vineyards"
}
] | spec/AddressParserSpec.coffee | thrustlabs/jquery-addressparser | 1 | describe 'Address Parser', ->
it 'should extract the name', ->
expectedValue = 'John Smith'
sut = new AddressParser
sut.parse('John Smith, 121 John St., Toronto, Ontario')
expect(sut.name).toEqual(expectedValue)
it 'should extract the email', ->
expectedValue = 'bob@smith.com'
sut = new AddressParser
sut.parse('John Smith, 121 John St., Toronto, Ontario, bob@smith.com')
expect(sut.email).toEqual(expectedValue)
it 'should reformat North American phone numbers', ->
expectedValue = '(416) 967-1111'
sut = new AddressParser
sut.parse('John Smith, 416.967 1111')
expect(sut.phone).toEqual(expectedValue)
it 'should prefix URLs with http://', ->
expectedValue = 'http://www.thrustlabs.com'
sut = new AddressParser
sut.parse('John Smith, www.thrustlabs.com')
expect(sut.website).toEqual(expectedValue)
it 'should extract the full address', ->
sut = new AddressParser
sut.parse('Johnny Smith, 121 John St., Toronto, Ontario, johnny@smith.com')
expect(sut.name).toEqual('Johnny Smith')
expect(sut.email).toEqual('johnny@smith.com')
expect(sut.address).toEqual('121 John St.')
expect(sut.city).toEqual('Toronto')
expect(sut.province).toEqual('ON')
expect(sut.country).toEqual('Canada')
it 'should parse the Amsterdam brewery', ->
address = """
Amsterdam Brewery
info@amsterdambeer.com
416.504.6882
http://amsterdambeer.com
45 Esandar Dr Toronto, ON M4G 4C5
"""
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Amsterdam Brewery')
expect(sut.email).toEqual('info@amsterdambeer.com')
expect(sut.address).toEqual('45 Esandar Dr')
expect(sut.city).toEqual('Toronto')
expect(sut.province).toEqual('ON')
expect(sut.postal).toEqual('M4G 4C5')
expect(sut.country).toEqual('Canada')
expect(sut.website).toEqual('http://amsterdambeer.com')
expect(sut.phone).toEqual('(416) 504-6882')
it 'should parse Secco Italian Bubbles', ->
address = """
Secco Italian Bubbles
19 East Birch Street, Ste 106
Walla Walla, Washington 99362
Phone: 509.526.5230
seccoitalianbubbles@gmail.com
http://www.seccobubbles.com/
"""
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Secco Italian Bubbles')
expect(sut.email).toEqual('seccoitalianbubbles@gmail.com')
expect(sut.address).toEqual('19 East Birch Street, Ste 106')
expect(sut.city).toEqual('Walla Walla')
expect(sut.province).toEqual('WA')
expect(sut.postal).toEqual('99362')
expect(sut.country).toEqual('USA')
expect(sut.website).toEqual('http://www.seccobubbles.com/')
expect(sut.phone).toEqual('(509) 526-5230')
it 'should parse Saltwater Farm', ->
address = """
Saltwater Farm Vineyard
349 Elm St Stonington, Connecticut 06378
"""
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Saltwater Farm Vineyard')
expect(sut.email).toEqual('')
expect(sut.address).toEqual('349 Elm St')
expect(sut.city).toEqual('Stonington')
expect(sut.province).toEqual('CT')
expect(sut.postal).toEqual('06378')
expect(sut.country).toEqual('USA')
expect(sut.website).toEqual('')
expect(sut.phone).toEqual('')
it 'should parse Chamard Vineyards', ->
address = "Chamard Vineyards | 115 Cow Hill Road | Clinton, CT 06413 Phone: 860-664-0299 |"
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Chamard Vineyards')
expect(sut.email).toEqual('')
expect(sut.address).toEqual('115 Cow Hill Road')
expect(sut.city).toEqual('Clinton')
expect(sut.province).toEqual('CT')
expect(sut.postal).toEqual('06413')
expect(sut.country).toEqual('USA')
expect(sut.website).toEqual('')
expect(sut.phone).toEqual('(860) 664-0299')
###
### | 172283 | describe 'Address Parser', ->
it 'should extract the name', ->
expectedValue = '<NAME>'
sut = new AddressParser
sut.parse('<NAME>, 121 <NAME> St., Toronto, Ontario')
expect(sut.name).toEqual(expectedValue)
it 'should extract the email', ->
expectedValue = '<EMAIL>'
sut = new AddressParser
sut.parse('<NAME>, 121 <NAME> St., Toronto, Ontario, <EMAIL>')
expect(sut.email).toEqual(expectedValue)
it 'should reformat North American phone numbers', ->
expectedValue = '(416) 967-1111'
sut = new AddressParser
sut.parse('<NAME>, 416.967 1111')
expect(sut.phone).toEqual(expectedValue)
it 'should prefix URLs with http://', ->
expectedValue = 'http://www.thrustlabs.com'
sut = new AddressParser
sut.parse('<NAME>, www.thrustlabs.com')
expect(sut.website).toEqual(expectedValue)
it 'should extract the full address', ->
sut = new AddressParser
sut.parse('<NAME>, 121 <NAME> St., Toronto, Ontario, <EMAIL>')
expect(sut.name).toEqual('<NAME>')
expect(sut.email).toEqual('<EMAIL>')
expect(sut.address).toEqual('121 <NAME> St.')
expect(sut.city).toEqual('Toronto')
expect(sut.province).toEqual('ON')
expect(sut.country).toEqual('Canada')
it 'should parse the Amsterdam brewery', ->
address = """
Amsterdam Brewery
<EMAIL>
416.504.6882
http://amsterdambeer.com
45 Esandar Dr Toronto, ON M4G 4C5
"""
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Amsterdam Brewery')
expect(sut.email).toEqual('<EMAIL>sterdambeer.com')
expect(sut.address).toEqual('45 Esandar Dr')
expect(sut.city).toEqual('Toronto')
expect(sut.province).toEqual('ON')
expect(sut.postal).toEqual('M4G 4C5')
expect(sut.country).toEqual('Canada')
expect(sut.website).toEqual('http://amsterdambeer.com')
expect(sut.phone).toEqual('(416) 504-6882')
it 'should parse Secco Italian Bubbles', ->
address = """
Secco Italian Bubbles
19 East Birch Street, Ste 106
Walla Walla, Washington 99362
Phone: 509.526.5230
<EMAIL>
http://www.seccobubbles.com/
"""
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Secco Italian Bubbles')
expect(sut.email).toEqual('<EMAIL>')
expect(sut.address).toEqual('19 East Birch Street, Ste 106')
expect(sut.city).toEqual('Walla Walla')
expect(sut.province).toEqual('WA')
expect(sut.postal).toEqual('99362')
expect(sut.country).toEqual('USA')
expect(sut.website).toEqual('http://www.seccobubbles.com/')
expect(sut.phone).toEqual('(509) 526-5230')
it 'should parse Saltwater Farm', ->
address = """
Saltwater Farm Vineyard
349 Elm St Stonington, Connecticut 06378
"""
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Saltwater Farm Vineyard')
expect(sut.email).toEqual('')
expect(sut.address).toEqual('349 Elm St')
expect(sut.city).toEqual('Stonington')
expect(sut.province).toEqual('CT')
expect(sut.postal).toEqual('06378')
expect(sut.country).toEqual('USA')
expect(sut.website).toEqual('')
expect(sut.phone).toEqual('')
it 'should parse <NAME>', ->
address = "<NAME> | 115 Cow Hill Road | Clinton, CT 06413 Phone: 860-664-0299 |"
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('<NAME>')
expect(sut.email).toEqual('')
expect(sut.address).toEqual('115 Cow Hill Road')
expect(sut.city).toEqual('Clinton')
expect(sut.province).toEqual('CT')
expect(sut.postal).toEqual('06413')
expect(sut.country).toEqual('USA')
expect(sut.website).toEqual('')
expect(sut.phone).toEqual('(860) 664-0299')
###
### | true | describe 'Address Parser', ->
it 'should extract the name', ->
expectedValue = 'PI:NAME:<NAME>END_PI'
sut = new AddressParser
sut.parse('PI:NAME:<NAME>END_PI, 121 PI:NAME:<NAME>END_PI St., Toronto, Ontario')
expect(sut.name).toEqual(expectedValue)
it 'should extract the email', ->
expectedValue = 'PI:EMAIL:<EMAIL>END_PI'
sut = new AddressParser
sut.parse('PI:NAME:<NAME>END_PI, 121 PI:NAME:<NAME>END_PI St., Toronto, Ontario, PI:EMAIL:<EMAIL>END_PI')
expect(sut.email).toEqual(expectedValue)
it 'should reformat North American phone numbers', ->
expectedValue = '(416) 967-1111'
sut = new AddressParser
sut.parse('PI:NAME:<NAME>END_PI, 416.967 1111')
expect(sut.phone).toEqual(expectedValue)
it 'should prefix URLs with http://', ->
expectedValue = 'http://www.thrustlabs.com'
sut = new AddressParser
sut.parse('PI:NAME:<NAME>END_PI, www.thrustlabs.com')
expect(sut.website).toEqual(expectedValue)
it 'should extract the full address', ->
sut = new AddressParser
sut.parse('PI:NAME:<NAME>END_PI, 121 PI:NAME:<NAME>END_PI St., Toronto, Ontario, PI:EMAIL:<EMAIL>END_PI')
expect(sut.name).toEqual('PI:NAME:<NAME>END_PI')
expect(sut.email).toEqual('PI:EMAIL:<EMAIL>END_PI')
expect(sut.address).toEqual('121 PI:NAME:<NAME>END_PI St.')
expect(sut.city).toEqual('Toronto')
expect(sut.province).toEqual('ON')
expect(sut.country).toEqual('Canada')
it 'should parse the Amsterdam brewery', ->
address = """
Amsterdam Brewery
PI:EMAIL:<EMAIL>END_PI
416.504.6882
http://amsterdambeer.com
45 Esandar Dr Toronto, ON M4G 4C5
"""
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Amsterdam Brewery')
expect(sut.email).toEqual('PI:EMAIL:<EMAIL>END_PIsterdambeer.com')
expect(sut.address).toEqual('45 Esandar Dr')
expect(sut.city).toEqual('Toronto')
expect(sut.province).toEqual('ON')
expect(sut.postal).toEqual('M4G 4C5')
expect(sut.country).toEqual('Canada')
expect(sut.website).toEqual('http://amsterdambeer.com')
expect(sut.phone).toEqual('(416) 504-6882')
it 'should parse Secco Italian Bubbles', ->
address = """
Secco Italian Bubbles
19 East Birch Street, Ste 106
Walla Walla, Washington 99362
Phone: 509.526.5230
PI:EMAIL:<EMAIL>END_PI
http://www.seccobubbles.com/
"""
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Secco Italian Bubbles')
expect(sut.email).toEqual('PI:EMAIL:<EMAIL>END_PI')
expect(sut.address).toEqual('19 East Birch Street, Ste 106')
expect(sut.city).toEqual('Walla Walla')
expect(sut.province).toEqual('WA')
expect(sut.postal).toEqual('99362')
expect(sut.country).toEqual('USA')
expect(sut.website).toEqual('http://www.seccobubbles.com/')
expect(sut.phone).toEqual('(509) 526-5230')
it 'should parse Saltwater Farm', ->
address = """
Saltwater Farm Vineyard
349 Elm St Stonington, Connecticut 06378
"""
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('Saltwater Farm Vineyard')
expect(sut.email).toEqual('')
expect(sut.address).toEqual('349 Elm St')
expect(sut.city).toEqual('Stonington')
expect(sut.province).toEqual('CT')
expect(sut.postal).toEqual('06378')
expect(sut.country).toEqual('USA')
expect(sut.website).toEqual('')
expect(sut.phone).toEqual('')
it 'should parse PI:NAME:<NAME>END_PI', ->
address = "PI:NAME:<NAME>END_PI | 115 Cow Hill Road | Clinton, CT 06413 Phone: 860-664-0299 |"
sut = new AddressParser
sut.parse(address)
expect(sut.name).toEqual('PI:NAME:<NAME>END_PI')
expect(sut.email).toEqual('')
expect(sut.address).toEqual('115 Cow Hill Road')
expect(sut.city).toEqual('Clinton')
expect(sut.province).toEqual('CT')
expect(sut.postal).toEqual('06413')
expect(sut.country).toEqual('USA')
expect(sut.website).toEqual('')
expect(sut.phone).toEqual('(860) 664-0299')
###
### |
[
{
"context": "ges', ->\n A = \"\"\"\n {\n \"properties\": { \"name\": \"Example\", \"foo\": \"Baz\", \"bar\": \"Foo\" },\n \"inports\": {\n ",
"end": 4678,
"score": 0.855310320854187,
"start": 4671,
"tag": "NAME",
"value": "Example"
}
] | spec/Journal.coffee | aretecode/noflo-built | 1 | if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/
chai = require 'chai' unless chai
noflo = require '../src/lib/NoFlo.coffee'
else
noflo = require 'noflo'
describe 'Journal', ->
describe 'connected to initialized graph', ->
g = new noflo.graph.Graph
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
j = new noflo.journal.Journal(g)
it 'should have just the initial transaction', ->
chai.expect(j.store.lastRevision).to.equal 0
describe 'following basic graph changes', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
it 'should create one transaction per change', ->
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
chai.expect(j.store.lastRevision).to.equal 3
g.removeNode 'Baz'
chai.expect(j.store.lastRevision).to.equal 4
describe 'pretty printing', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.startTransaction 'test1'
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
g.addInitial 42, 'Foo', 'in'
g.removeNode 'Foo'
g.endTransaction 'test1'
g.startTransaction 'test2'
g.removeNode 'Baz'
g.endTransaction 'test2'
it 'should be human readable', ->
ref = """>>> 0: initial
<<< 0: initial
>>> 1: test1
Foo(Bar)
Baz(Foo)
Foo out -> in Baz
'42' -> in Foo
META Foo out -> in Baz
Foo out -X> in Baz
'42' -X> in Foo
META Foo
DEL Foo(Bar)
<<< 1: test1"""
chai.expect(j.toPrettyString(0,2)).to.equal ref
describe 'jumping to revision', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
g.addInitial 42, 'Foo', 'in'
g.removeNode 'Foo'
it 'should change the graph', ->
j.moveToRevision 0
chai.expect(g.nodes.length).to.equal 0
j.moveToRevision 2
chai.expect(g.nodes.length).to.equal 2
j.moveToRevision 5
chai.expect(g.nodes.length).to.equal 1
describe 'linear undo/redo', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
g.addInitial 42, 'Foo', 'in'
graphBeforeError = g.toJSON()
chai.expect(g.nodes.length).to.equal 2
it 'undo should restore previous revision', ->
g.removeNode 'Foo'
chai.expect(g.nodes.length).to.equal 1
j.undo()
chai.expect(g.nodes.length).to.equal 2
chai.expect(g.toJSON()).to.deep.equal graphBeforeError
it 'redo should apply the same change again', ->
j.redo()
chai.expect(g.nodes.length).to.equal 1
it 'undo should also work multiple revisions back', ->
g.removeNode 'Baz'
j.undo()
j.undo()
chai.expect(g.nodes.length).to.equal 2
chai.expect(g.toJSON()).to.deep.equal graphBeforeError
describe 'undo/redo of metadata changes', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
it 'adding group', ->
g.addGroup 'all', ['Foo', 'Bax'], {'label': 'all nodes'}
chai.expect(g.groups.length).to.equal 1
chai.expect(g.groups[0].name).to.equal 'all'
it 'undoing group add', ->
j.undo()
chai.expect(g.groups.length).to.equal 0
it 'redoing group add', ->
j.redo()
chai.expect(g.groups[0].metadata['label']).to.equal 'all nodes'
it 'changing group metadata adds revision', ->
r = j.store.lastRevision
g.setGroupMetadata 'all', {'label': 'ALL NODES!'}
chai.expect(j.store.lastRevision).to.equal r+1
it 'undoing group metadata change', ->
j.undo()
chai.expect(g.groups[0].metadata['label']).to.equal "all nodes"
it 'redoing group metadata change', ->
j.redo()
chai.expect(g.groups[0].metadata['label']).to.equal "ALL NODES!"
it 'setting node metadata', ->
g.setNodeMetadata 'Foo', {"oneone": 11, 2: "two"}
chai.expect(Object.keys(g.getNode('Foo').metadata).length).to.equal 2
it 'undoing set node metadata', ->
j.undo()
chai.expect(Object.keys(g.getNode('Foo').metadata).length).to.equal 0
it 'redoing set node metadata', ->
j.redo()
chai.expect(g.getNode('Foo').metadata["oneone"]).to.equal 11
describe 'Journalling of graph merges', ->
A = """
{
"properties": { "name": "Example", "foo": "Baz", "bar": "Foo" },
"inports": {
"in": { "process": "Foo", "port": "in", "metadata": { "x": 5, "y": 100 } }
},
"outports": {
"out": { "process": "Bar", "port": "out", "metadata": { "x": 500, "y": 505 } }
},
"groups": [
{ "name": "first", "nodes": [ "Foo" ], "metadata": { "label": "Main" } },
{ "name": "second", "nodes": [ "Foo2", "Bar2" ], "metadata": {} }
],
"processes": {
"Foo": { "component": "Bar", "metadata": { "display": { "x": 100, "y": 200 }, "hello": "World" } },
"Bar": { "component": "Baz", "metadata": {} },
"Foo2": { "component": "foo", "metadata": {} },
"Bar2": { "component": "bar", "metadata": {} }
},
"connections": [
{ "src": { "process": "Foo", "port": "out" }, "tgt": { "process": "Bar", "port": "in" }, "metadata": { "route": "foo", "hello": "World" } },
{ "src": { "process": "Foo", "port": "out2" }, "tgt": { "process": "Bar", "port": "in2" } },
{ "data": "Hello, world!", "tgt": { "process": "Foo", "port": "in" } },
{ "data": "Hello, world, 2!", "tgt": { "process": "Foo", "port": "in2" } },
{ "data": "Cheers, world!", "tgt": { "process": "Foo", "port": "arr" } }
]
}"""
B = """
{
"properties": { "name": "Example", "foo": "Baz", "bar": "Foo" },
"inports": {
"in": { "process": "Foo", "port": "in", "metadata": { "x": 500, "y": 1 } }
},
"outports": {
"out": { "process": "Bar", "port": "out", "metadata": { "x": 500, "y": 505 } }
},
"groups": [
{ "name": "second", "nodes": [ "Foo", "Bar" ] }
],
"processes": {
"Foo": { "component": "Bar", "metadata": { "display": { "x": 100, "y": 200 }, "hello": "World" } },
"Bar": { "component": "Baz", "metadata": {} },
"Bar2": { "component": "bar", "metadata": {} },
"Bar3": { "component": "bar2", "metadata": {} }
},
"connections": [
{ "src": { "process": "Foo", "port": "out" }, "tgt": { "process": "Bar", "port": "in" }, "metadata": { "route": "foo", "hello": "World" } },
{ "src": { "process": "Foo2", "port": "out2" }, "tgt": { "process": "Bar3", "port": "in2" } },
{ "data": "Hello, world!", "tgt": { "process": "Foo", "port": "in" } },
{ "data": "Hello, world, 2!", "tgt": { "process": "Bar3", "port": "in2" } },
{ "data": "Cheers, world!", "tgt": { "process": "Bar2", "port": "arr" } }
]
}"""
a = null
b = null
g = null # one we modify
j = null
describe 'G -> B', ->
it 'G starts out as A', (done) ->
noflo.graph.loadJSON JSON.parse(A), (err, instance) ->
return done err if err
a = instance
noflo.graph.loadJSON JSON.parse(A), (err, instance) ->
return done err if err
g = instance
chai.expect(noflo.graph.equivalent(a, g)).to.equal true
done()
it 'G and B starts out different', (done) ->
noflo.graph.loadJSON JSON.parse(B), (err, instance) ->
return done err if err
b = instance
chai.expect(noflo.graph.equivalent(g, b)).to.equal false
done()
it 'merge should make G equivalent to B', (done) ->
j = new noflo.journal.Journal(g)
g.startTransaction 'merge'
noflo.graph.mergeResolveTheirs g, b
g.endTransaction 'merge'
chai.expect(noflo.graph.equivalent(g, b)).to.equal true
done()
it 'undoing merge should make G equivalent to A again', (done) ->
j.undo()
res = noflo.graph.equivalent g, a
chai.expect(res).to.equal true
done()
# FIXME: add tests for noflo.graph.loadJSON/loadFile, and journal metadata
| 164022 | if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/
chai = require 'chai' unless chai
noflo = require '../src/lib/NoFlo.coffee'
else
noflo = require 'noflo'
describe 'Journal', ->
describe 'connected to initialized graph', ->
g = new noflo.graph.Graph
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
j = new noflo.journal.Journal(g)
it 'should have just the initial transaction', ->
chai.expect(j.store.lastRevision).to.equal 0
describe 'following basic graph changes', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
it 'should create one transaction per change', ->
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
chai.expect(j.store.lastRevision).to.equal 3
g.removeNode 'Baz'
chai.expect(j.store.lastRevision).to.equal 4
describe 'pretty printing', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.startTransaction 'test1'
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
g.addInitial 42, 'Foo', 'in'
g.removeNode 'Foo'
g.endTransaction 'test1'
g.startTransaction 'test2'
g.removeNode 'Baz'
g.endTransaction 'test2'
it 'should be human readable', ->
ref = """>>> 0: initial
<<< 0: initial
>>> 1: test1
Foo(Bar)
Baz(Foo)
Foo out -> in Baz
'42' -> in Foo
META Foo out -> in Baz
Foo out -X> in Baz
'42' -X> in Foo
META Foo
DEL Foo(Bar)
<<< 1: test1"""
chai.expect(j.toPrettyString(0,2)).to.equal ref
describe 'jumping to revision', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
g.addInitial 42, 'Foo', 'in'
g.removeNode 'Foo'
it 'should change the graph', ->
j.moveToRevision 0
chai.expect(g.nodes.length).to.equal 0
j.moveToRevision 2
chai.expect(g.nodes.length).to.equal 2
j.moveToRevision 5
chai.expect(g.nodes.length).to.equal 1
describe 'linear undo/redo', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
g.addInitial 42, 'Foo', 'in'
graphBeforeError = g.toJSON()
chai.expect(g.nodes.length).to.equal 2
it 'undo should restore previous revision', ->
g.removeNode 'Foo'
chai.expect(g.nodes.length).to.equal 1
j.undo()
chai.expect(g.nodes.length).to.equal 2
chai.expect(g.toJSON()).to.deep.equal graphBeforeError
it 'redo should apply the same change again', ->
j.redo()
chai.expect(g.nodes.length).to.equal 1
it 'undo should also work multiple revisions back', ->
g.removeNode 'Baz'
j.undo()
j.undo()
chai.expect(g.nodes.length).to.equal 2
chai.expect(g.toJSON()).to.deep.equal graphBeforeError
describe 'undo/redo of metadata changes', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
it 'adding group', ->
g.addGroup 'all', ['Foo', 'Bax'], {'label': 'all nodes'}
chai.expect(g.groups.length).to.equal 1
chai.expect(g.groups[0].name).to.equal 'all'
it 'undoing group add', ->
j.undo()
chai.expect(g.groups.length).to.equal 0
it 'redoing group add', ->
j.redo()
chai.expect(g.groups[0].metadata['label']).to.equal 'all nodes'
it 'changing group metadata adds revision', ->
r = j.store.lastRevision
g.setGroupMetadata 'all', {'label': 'ALL NODES!'}
chai.expect(j.store.lastRevision).to.equal r+1
it 'undoing group metadata change', ->
j.undo()
chai.expect(g.groups[0].metadata['label']).to.equal "all nodes"
it 'redoing group metadata change', ->
j.redo()
chai.expect(g.groups[0].metadata['label']).to.equal "ALL NODES!"
it 'setting node metadata', ->
g.setNodeMetadata 'Foo', {"oneone": 11, 2: "two"}
chai.expect(Object.keys(g.getNode('Foo').metadata).length).to.equal 2
it 'undoing set node metadata', ->
j.undo()
chai.expect(Object.keys(g.getNode('Foo').metadata).length).to.equal 0
it 'redoing set node metadata', ->
j.redo()
chai.expect(g.getNode('Foo').metadata["oneone"]).to.equal 11
describe 'Journalling of graph merges', ->
A = """
{
"properties": { "name": "<NAME>", "foo": "Baz", "bar": "Foo" },
"inports": {
"in": { "process": "Foo", "port": "in", "metadata": { "x": 5, "y": 100 } }
},
"outports": {
"out": { "process": "Bar", "port": "out", "metadata": { "x": 500, "y": 505 } }
},
"groups": [
{ "name": "first", "nodes": [ "Foo" ], "metadata": { "label": "Main" } },
{ "name": "second", "nodes": [ "Foo2", "Bar2" ], "metadata": {} }
],
"processes": {
"Foo": { "component": "Bar", "metadata": { "display": { "x": 100, "y": 200 }, "hello": "World" } },
"Bar": { "component": "Baz", "metadata": {} },
"Foo2": { "component": "foo", "metadata": {} },
"Bar2": { "component": "bar", "metadata": {} }
},
"connections": [
{ "src": { "process": "Foo", "port": "out" }, "tgt": { "process": "Bar", "port": "in" }, "metadata": { "route": "foo", "hello": "World" } },
{ "src": { "process": "Foo", "port": "out2" }, "tgt": { "process": "Bar", "port": "in2" } },
{ "data": "Hello, world!", "tgt": { "process": "Foo", "port": "in" } },
{ "data": "Hello, world, 2!", "tgt": { "process": "Foo", "port": "in2" } },
{ "data": "Cheers, world!", "tgt": { "process": "Foo", "port": "arr" } }
]
}"""
B = """
{
"properties": { "name": "Example", "foo": "Baz", "bar": "Foo" },
"inports": {
"in": { "process": "Foo", "port": "in", "metadata": { "x": 500, "y": 1 } }
},
"outports": {
"out": { "process": "Bar", "port": "out", "metadata": { "x": 500, "y": 505 } }
},
"groups": [
{ "name": "second", "nodes": [ "Foo", "Bar" ] }
],
"processes": {
"Foo": { "component": "Bar", "metadata": { "display": { "x": 100, "y": 200 }, "hello": "World" } },
"Bar": { "component": "Baz", "metadata": {} },
"Bar2": { "component": "bar", "metadata": {} },
"Bar3": { "component": "bar2", "metadata": {} }
},
"connections": [
{ "src": { "process": "Foo", "port": "out" }, "tgt": { "process": "Bar", "port": "in" }, "metadata": { "route": "foo", "hello": "World" } },
{ "src": { "process": "Foo2", "port": "out2" }, "tgt": { "process": "Bar3", "port": "in2" } },
{ "data": "Hello, world!", "tgt": { "process": "Foo", "port": "in" } },
{ "data": "Hello, world, 2!", "tgt": { "process": "Bar3", "port": "in2" } },
{ "data": "Cheers, world!", "tgt": { "process": "Bar2", "port": "arr" } }
]
}"""
a = null
b = null
g = null # one we modify
j = null
describe 'G -> B', ->
it 'G starts out as A', (done) ->
noflo.graph.loadJSON JSON.parse(A), (err, instance) ->
return done err if err
a = instance
noflo.graph.loadJSON JSON.parse(A), (err, instance) ->
return done err if err
g = instance
chai.expect(noflo.graph.equivalent(a, g)).to.equal true
done()
it 'G and B starts out different', (done) ->
noflo.graph.loadJSON JSON.parse(B), (err, instance) ->
return done err if err
b = instance
chai.expect(noflo.graph.equivalent(g, b)).to.equal false
done()
it 'merge should make G equivalent to B', (done) ->
j = new noflo.journal.Journal(g)
g.startTransaction 'merge'
noflo.graph.mergeResolveTheirs g, b
g.endTransaction 'merge'
chai.expect(noflo.graph.equivalent(g, b)).to.equal true
done()
it 'undoing merge should make G equivalent to A again', (done) ->
j.undo()
res = noflo.graph.equivalent g, a
chai.expect(res).to.equal true
done()
# FIXME: add tests for noflo.graph.loadJSON/loadFile, and journal metadata
| true | if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/
chai = require 'chai' unless chai
noflo = require '../src/lib/NoFlo.coffee'
else
noflo = require 'noflo'
describe 'Journal', ->
describe 'connected to initialized graph', ->
g = new noflo.graph.Graph
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
j = new noflo.journal.Journal(g)
it 'should have just the initial transaction', ->
chai.expect(j.store.lastRevision).to.equal 0
describe 'following basic graph changes', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
it 'should create one transaction per change', ->
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
chai.expect(j.store.lastRevision).to.equal 3
g.removeNode 'Baz'
chai.expect(j.store.lastRevision).to.equal 4
describe 'pretty printing', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.startTransaction 'test1'
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
g.addInitial 42, 'Foo', 'in'
g.removeNode 'Foo'
g.endTransaction 'test1'
g.startTransaction 'test2'
g.removeNode 'Baz'
g.endTransaction 'test2'
it 'should be human readable', ->
ref = """>>> 0: initial
<<< 0: initial
>>> 1: test1
Foo(Bar)
Baz(Foo)
Foo out -> in Baz
'42' -> in Foo
META Foo out -> in Baz
Foo out -X> in Baz
'42' -X> in Foo
META Foo
DEL Foo(Bar)
<<< 1: test1"""
chai.expect(j.toPrettyString(0,2)).to.equal ref
describe 'jumping to revision', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
g.addInitial 42, 'Foo', 'in'
g.removeNode 'Foo'
it 'should change the graph', ->
j.moveToRevision 0
chai.expect(g.nodes.length).to.equal 0
j.moveToRevision 2
chai.expect(g.nodes.length).to.equal 2
j.moveToRevision 5
chai.expect(g.nodes.length).to.equal 1
describe 'linear undo/redo', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
g.addInitial 42, 'Foo', 'in'
graphBeforeError = g.toJSON()
chai.expect(g.nodes.length).to.equal 2
it 'undo should restore previous revision', ->
g.removeNode 'Foo'
chai.expect(g.nodes.length).to.equal 1
j.undo()
chai.expect(g.nodes.length).to.equal 2
chai.expect(g.toJSON()).to.deep.equal graphBeforeError
it 'redo should apply the same change again', ->
j.redo()
chai.expect(g.nodes.length).to.equal 1
it 'undo should also work multiple revisions back', ->
g.removeNode 'Baz'
j.undo()
j.undo()
chai.expect(g.nodes.length).to.equal 2
chai.expect(g.toJSON()).to.deep.equal graphBeforeError
describe 'undo/redo of metadata changes', ->
g = new noflo.graph.Graph
j = new noflo.journal.Journal(g)
g.addNode 'Foo', 'Bar'
g.addNode 'Baz', 'Foo'
g.addEdge 'Foo', 'out', 'Baz', 'in'
it 'adding group', ->
g.addGroup 'all', ['Foo', 'Bax'], {'label': 'all nodes'}
chai.expect(g.groups.length).to.equal 1
chai.expect(g.groups[0].name).to.equal 'all'
it 'undoing group add', ->
j.undo()
chai.expect(g.groups.length).to.equal 0
it 'redoing group add', ->
j.redo()
chai.expect(g.groups[0].metadata['label']).to.equal 'all nodes'
it 'changing group metadata adds revision', ->
r = j.store.lastRevision
g.setGroupMetadata 'all', {'label': 'ALL NODES!'}
chai.expect(j.store.lastRevision).to.equal r+1
it 'undoing group metadata change', ->
j.undo()
chai.expect(g.groups[0].metadata['label']).to.equal "all nodes"
it 'redoing group metadata change', ->
j.redo()
chai.expect(g.groups[0].metadata['label']).to.equal "ALL NODES!"
it 'setting node metadata', ->
g.setNodeMetadata 'Foo', {"oneone": 11, 2: "two"}
chai.expect(Object.keys(g.getNode('Foo').metadata).length).to.equal 2
it 'undoing set node metadata', ->
j.undo()
chai.expect(Object.keys(g.getNode('Foo').metadata).length).to.equal 0
it 'redoing set node metadata', ->
j.redo()
chai.expect(g.getNode('Foo').metadata["oneone"]).to.equal 11
describe 'Journalling of graph merges', ->
A = """
{
"properties": { "name": "PI:NAME:<NAME>END_PI", "foo": "Baz", "bar": "Foo" },
"inports": {
"in": { "process": "Foo", "port": "in", "metadata": { "x": 5, "y": 100 } }
},
"outports": {
"out": { "process": "Bar", "port": "out", "metadata": { "x": 500, "y": 505 } }
},
"groups": [
{ "name": "first", "nodes": [ "Foo" ], "metadata": { "label": "Main" } },
{ "name": "second", "nodes": [ "Foo2", "Bar2" ], "metadata": {} }
],
"processes": {
"Foo": { "component": "Bar", "metadata": { "display": { "x": 100, "y": 200 }, "hello": "World" } },
"Bar": { "component": "Baz", "metadata": {} },
"Foo2": { "component": "foo", "metadata": {} },
"Bar2": { "component": "bar", "metadata": {} }
},
"connections": [
{ "src": { "process": "Foo", "port": "out" }, "tgt": { "process": "Bar", "port": "in" }, "metadata": { "route": "foo", "hello": "World" } },
{ "src": { "process": "Foo", "port": "out2" }, "tgt": { "process": "Bar", "port": "in2" } },
{ "data": "Hello, world!", "tgt": { "process": "Foo", "port": "in" } },
{ "data": "Hello, world, 2!", "tgt": { "process": "Foo", "port": "in2" } },
{ "data": "Cheers, world!", "tgt": { "process": "Foo", "port": "arr" } }
]
}"""
B = """
{
"properties": { "name": "Example", "foo": "Baz", "bar": "Foo" },
"inports": {
"in": { "process": "Foo", "port": "in", "metadata": { "x": 500, "y": 1 } }
},
"outports": {
"out": { "process": "Bar", "port": "out", "metadata": { "x": 500, "y": 505 } }
},
"groups": [
{ "name": "second", "nodes": [ "Foo", "Bar" ] }
],
"processes": {
"Foo": { "component": "Bar", "metadata": { "display": { "x": 100, "y": 200 }, "hello": "World" } },
"Bar": { "component": "Baz", "metadata": {} },
"Bar2": { "component": "bar", "metadata": {} },
"Bar3": { "component": "bar2", "metadata": {} }
},
"connections": [
{ "src": { "process": "Foo", "port": "out" }, "tgt": { "process": "Bar", "port": "in" }, "metadata": { "route": "foo", "hello": "World" } },
{ "src": { "process": "Foo2", "port": "out2" }, "tgt": { "process": "Bar3", "port": "in2" } },
{ "data": "Hello, world!", "tgt": { "process": "Foo", "port": "in" } },
{ "data": "Hello, world, 2!", "tgt": { "process": "Bar3", "port": "in2" } },
{ "data": "Cheers, world!", "tgt": { "process": "Bar2", "port": "arr" } }
]
}"""
a = null
b = null
g = null # one we modify
j = null
describe 'G -> B', ->
it 'G starts out as A', (done) ->
noflo.graph.loadJSON JSON.parse(A), (err, instance) ->
return done err if err
a = instance
noflo.graph.loadJSON JSON.parse(A), (err, instance) ->
return done err if err
g = instance
chai.expect(noflo.graph.equivalent(a, g)).to.equal true
done()
it 'G and B starts out different', (done) ->
noflo.graph.loadJSON JSON.parse(B), (err, instance) ->
return done err if err
b = instance
chai.expect(noflo.graph.equivalent(g, b)).to.equal false
done()
it 'merge should make G equivalent to B', (done) ->
j = new noflo.journal.Journal(g)
g.startTransaction 'merge'
noflo.graph.mergeResolveTheirs g, b
g.endTransaction 'merge'
chai.expect(noflo.graph.equivalent(g, b)).to.equal true
done()
it 'undoing merge should make G equivalent to A again', (done) ->
j.undo()
res = noflo.graph.equivalent g, a
chai.expect(res).to.equal true
done()
# FIXME: add tests for noflo.graph.loadJSON/loadFile, and journal metadata
|
[
{
"context": "ess', ->\n expect(s3.dnsCompatibleBucketName('1.2.3.4')).to.equal(false)\n expect(s3.dnsCompatibleB",
"end": 1627,
"score": 0.9997085332870483,
"start": 1620,
"tag": "IP_ADDRESS",
"value": "1.2.3.4"
},
{
"context": " AWS.Config(s3ForcePathStyle: true, accessKeyId: 'AKID', secretAccessKey: 'SECRET')\n s3 = new AWS.S",
"end": 6638,
"score": 0.9966132044792175,
"start": 6634,
"tag": "KEY",
"value": "AKID"
},
{
"context": "yle: true, accessKeyId: 'AKID', secretAccessKey: 'SECRET')\n s3 = new AWS.S3(config)\n expect(s3.c",
"end": 6665,
"score": 0.9969643950462341,
"start": 6659,
"tag": "KEY",
"value": "SECRET"
},
{
"context": " req = build('getObject', {Bucket: 'foo', Key: 'bar'})\n expect(req.endpoint.hostname).to.equal",
"end": 9220,
"score": 0.7365776896476746,
"start": 9217,
"tag": "KEY",
"value": "bar"
},
{
"context": " req = build('getObject', {Bucket: 'foo', Key: 'baz'})\n expect(req.endpoint.hostname).to.equal",
"end": 9565,
"score": 0.8244054913520813,
"start": 9562,
"tag": "KEY",
"value": "baz"
},
{
"context": "stname\n params = { Bucket: 'bucket', Key: 'a b c', VersionId: 'a&b' }\n req = build('headObj",
"end": 11962,
"score": 0.996880292892456,
"start": 11957,
"tag": "KEY",
"value": "a b c"
},
{
"context": " = build('headObject', {Bucket:'bucket-name',Key:'abc'})\n expect(req.method).to.equal('HEAD')\n",
"end": 19748,
"score": 0.6692426204681396,
"start": 19745,
"tag": "KEY",
"value": "abc"
},
{
"context": "a'\n SSECustomerKey: new AWS.util.Buffer('098f6bcd4621d373cade4e832627b4f6', 'hex')\n SSECustomerAlgorithm: 'AES256'",
"end": 23620,
"score": 0.9996419548988342,
"start": 23588,
"tag": "KEY",
"value": "098f6bcd4621d373cade4e832627b4f6"
},
{
"context": " Bucket: 'Example-Bucket'\n Key: 'Example-Object'\n ETag: '\"3858f62230ac3c915f300c664312c1",
"end": 45276,
"score": 0.9241901636123657,
"start": 45270,
"tag": "KEY",
"value": "Object"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=4mlYnRmz%2BBFEPrgYz5tXcl9Wc",
"end": 60094,
"score": 0.9969828128814697,
"start": 60090,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=60&Signature=kH2pMK%2Fgm7cCZKVG8GHVTRGXKz",
"end": 60398,
"score": 0.9924487471580505,
"start": 60394,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=60&Signature=kH2pMK%2Fgm7cCZKVG8GHVTRGXKz",
"end": 60799,
"score": 0.9965189099311829,
"start": 60795,
"tag": "KEY",
"value": "akid"
},
{
"context": "/bucket.foo.bar.baz:555/prefix/key?AWSAccessKeyId=akid&Expires=60&Signature=zA6k0cQqDkTZgLamfoYLOd%2Bqfg",
"end": 61193,
"score": 0.9979349970817566,
"start": 61189,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=4mlYnRmz%2BBFEPrgYz5tXcl9Wc",
"end": 61496,
"score": 0.9982224106788635,
"start": 61492,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=J%2BnWZ0lPUfLV0kio8ONhJmAtt",
"end": 61811,
"score": 0.9973652362823486,
"start": 61807,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=5Lcbv0WLGWseQhtmNQ8WwIpX6Kw",
"end": 62146,
"score": 0.9980081915855408,
"start": 62142,
"tag": "KEY",
"value": "akid"
},
{
"context": "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Am",
"end": 62620,
"score": 0.7368540167808533,
"start": 62616,
"tag": "KEY",
"value": "akid"
},
{
"context": "gorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=1970",
"end": 62631,
"score": 0.6285961270332336,
"start": 62624,
"tag": "KEY",
"value": "9700101"
},
{
"context": "B%27%3A%22%7B%7D%5B%5D%2C./%3F%60~?AWSAccessKeyId=akid&Expires=900&Signature=9nEltJACZKsriZqU2cmRel6g8LQ",
"end": 63208,
"score": 0.9976153373718262,
"start": 63204,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Content-MD5=hBotaJrYa9FhFEdFPCLG%2FA%3D%3D&Expire",
"end": 63534,
"score": 0.9974182844161987,
"start": 63530,
"tag": "KEY",
"value": "akid"
},
{
"context": " SSECustomerAlgorithm: 'AES256', SSECustomerKey: 'c2FtcGxlIGtleXNhbXBsZSBrZXlzYW1wbGUga2V5c2E=')\n expect(url).to.equal('https://bucket.s3.moc",
"end": 64634,
"score": 0.999761164188385,
"start": 64588,
"tag": "KEY",
"value": "c2FtcGxlIGtleXNhbXBsZSBrZXlzYW1wbGUga2V5c2E=')"
},
{
"context": "key=YzJGdGNHeGxJR3RsZVhOaGJYQnNaU0JyWlhsellXMXdiR1VnYTJWNWMyRT0%3D&x-amz-server-side-encryption-customer",
"end": 65281,
"score": 0.5304244756698608,
"start": 65277,
"tag": "KEY",
"value": "VnYT"
},
{
"context": "zJGdGNHeGxJR3RsZVhOaGJYQnNaU0JyWlhsellXMXdiR1VnYTJWNWMyRT0%3D&x-amz-server-side-encryption-customer-key-M",
"end": 65287,
"score": 0.5347937345504761,
"start": 65282,
"tag": "KEY",
"value": "WNWMy"
},
{
"context": "('https://bucket.s3.amazonaws.com/?AWSAccessKeyId=akid&Expires=900&Signature=8W3pwZPfgucCyPNg1MsoYq8h5zw",
"end": 66230,
"score": 0.9903473854064941,
"start": 66226,
"tag": "KEY",
"value": "akid"
},
{
"context": "undefined)\n params = Bucket: 'bucket', Key: 'object', Expires: 60 * 60 * 24 * 7 + 120\n error = '",
"end": 68317,
"score": 0.9638674259185791,
"start": 68311,
"tag": "KEY",
"value": "object"
},
{
"context": "ity token when present', (done) ->\n token = 'baz'\n credentials =\n accessKeyId: 'foo'\n ",
"end": 70267,
"score": 0.8313737511634827,
"start": 70264,
"tag": "KEY",
"value": "baz"
},
{
"context": "= 'baz'\n credentials =\n accessKeyId: 'foo'\n secretAccessKey: 'bar'\n sessionTo",
"end": 70314,
"score": 0.9173113107681274,
"start": 70311,
"tag": "KEY",
"value": "foo"
},
{
"context": " accessKeyId: 'foo'\n secretAccessKey: 'bar'\n sessionToken: token\n\n s3 = new AWS.",
"end": 70345,
"score": 0.9950679540634155,
"start": 70342,
"tag": "KEY",
"value": "bar"
},
{
"context": "ew AWS.S3()\n fieldsToInclude =\n key: 'users/userId/upload'\n acl: 'public-read',\n 'Content-Typ",
"end": 73549,
"score": 0.9972437024116516,
"start": 73530,
"tag": "KEY",
"value": "users/userId/upload"
}
] | test/services/s3.spec.coffee | ashharrison90/ibm-cos-sdk-js | 0 | helpers = require('../helpers')
AWS = helpers.AWS
Stream = AWS.util.stream
Buffer = AWS.util.Buffer
describe 'AWS.S3', ->
s3 = null
request = (operation, params) -> s3.makeRequest(operation, params)
beforeEach (done) ->
s3 = new AWS.S3(region: undefined)
s3.clearBucketRegionCache()
done()
describe 'dnsCompatibleBucketName', ->
it 'must be at least 3 characters', ->
expect(s3.dnsCompatibleBucketName('aa')).to.equal(false)
it 'must not be longer than 63 characters', ->
b = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
expect(s3.dnsCompatibleBucketName(b)).to.equal(false)
it 'must start with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('Abc')).to.equal(false)
expect(s3.dnsCompatibleBucketName('-bc')).to.equal(false)
expect(s3.dnsCompatibleBucketName('abc')).to.equal(true)
it 'must end with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('abC')).to.equal(false)
expect(s3.dnsCompatibleBucketName('ab-')).to.equal(false)
expect(s3.dnsCompatibleBucketName('abc')).to.equal(true)
it 'may not contain multiple contiguous dots', ->
expect(s3.dnsCompatibleBucketName('abc.123')).to.equal(true)
expect(s3.dnsCompatibleBucketName('abc..123')).to.equal(false)
it 'may only contain letters numbers and dots', ->
expect(s3.dnsCompatibleBucketName('abc123')).to.equal(true)
expect(s3.dnsCompatibleBucketName('abc_123')).to.equal(false)
it 'must not look like an ip address', ->
expect(s3.dnsCompatibleBucketName('1.2.3.4')).to.equal(false)
expect(s3.dnsCompatibleBucketName('a.b.c.d')).to.equal(true)
describe 'constructor', ->
it 'requires endpoint if s3BucketEndpoint is passed', ->
expect(-> new AWS.S3(s3BucketEndpoint: true)).to.throw(
/An endpoint must be provided/)
describe 'endpoint', ->
it 'sets hostname to s3.amazonaws.com when region is un-specified', ->
s3 = new AWS.S3(region: undefined)
expect(s3.endpoint.hostname).to.equal('s3.amazonaws.com')
it 'sets hostname to s3.amazonaws.com when region is us-east-1', ->
s3 = new AWS.S3(region: 'us-east-1')
expect(s3.endpoint.hostname).to.equal('s3.amazonaws.com')
it 'sets region to us-east-1 when unspecified', ->
s3 = new AWS.S3(region: 'us-east-1')
expect(s3.config.region).to.equal('us-east-1')
it 'combines the region with s3 in the endpoint using a - instead of .', ->
s3 = new AWS.S3(region: 'us-west-1')
expect(s3.endpoint.hostname).to.equal('s3-us-west-1.amazonaws.com')
it 'sets a region-specific dualstack endpoint when dualstack enabled', ->
s3 = new AWS.S3(region: 'us-west-1', useDualstack: true)
expect(s3.endpoint.hostname).to.equal('s3.dualstack.us-west-1.amazonaws.com')
s3 = new AWS.S3(region: 'us-east-1', useDualstack: true)
expect(s3.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
describe 'clearing bucket region cache', ->
beforeEach ->
s3.bucketRegionCache = a: 'rg-fake-1', b: 'rg-fake-2', c: 'rg-fake-3'
it 'clears one bucket name', ->
s3.clearBucketRegionCache 'b'
expect(s3.bucketRegionCache).to.eql(a: 'rg-fake-1', c: 'rg-fake-3')
it 'clears a list of bucket names', ->
s3.clearBucketRegionCache ['a', 'c']
expect(s3.bucketRegionCache).to.eql(b: 'rg-fake-2')
it 'clears entire cache', ->
s3.clearBucketRegionCache()
expect(s3.bucketRegionCache).to.eql({})
describe 'getSignerClass', ->
getVersion = (signer) ->
if (signer == AWS.Signers.S3)
return 's3'
else if (signer == AWS.Signers.V4)
return 'v4'
else if (signer == AWS.Signers.V2)
return 'v2'
describe 'when using presigned requests', ->
req = null
beforeEach (done) ->
req = request('mock')
helpers.spyOn(req, 'isPresigned').andReturn(true)
done()
describe 'will return an s3 (v2) signer when', ->
it 'user does not specify a signatureVersion for a region that supports v2', (done) ->
s3 = new AWS.S3(region: 'us-east-1')
expect(getVersion(s3.getSignerClass(req))).to.equal('s3')
done()
it 'user specifies a signatureVersion of s3', (done) ->
s3 = new AWS.S3(signatureVersion: 's3')
expect(getVersion(s3.getSignerClass(req))).to.equal('s3')
done()
it 'user specifies a signatureVersion of v2', (done) ->
s3 = new AWS.S3(signatureVersion: 'v2')
expect(getVersion(s3.getSignerClass(req))).to.equal('s3')
done()
describe 'will return a v4 signer when', ->
it 'user does not specify a signatureVersion for a region that supports only v4', (done) ->
s3 = new AWS.S3(region: 'eu-central-1')
expect(getVersion(s3.getSignerClass(req))).to.equal('v4')
done()
it 'user specifies a signatureVersion of v4', (done) ->
s3 = new AWS.S3(signatureVersion: 'v4')
expect(getVersion(s3.getSignerClass(req))).to.equal('v4')
done()
describe 'when not using presigned requests', ->
describe 'will return an s3 (v2) signer when', ->
it 'user specifies a signatureVersion of s3', (done) ->
s3 = new AWS.S3(signatureVersion: 's3')
expect(getVersion(s3.getSignerClass())).to.equal('s3')
done()
it 'user specifies a signatureVersion of v2', (done) ->
s3 = new AWS.S3(signatureVersion: 'v2')
expect(getVersion(s3.getSignerClass())).to.equal('s3')
done()
it 'user does not specify a signatureVersion and region supports v2', (done) ->
s3 = new AWS.S3({region: 'us-east-1'})
expect(getVersion(s3.getSignerClass())).to.equal('s3')
done()
describe 'will return a v4 signer when', ->
it 'user does not specify a signatureVersion and region only supports v4', (done) ->
s3 = new AWS.S3({region: 'eu-central-1'})
expect(getVersion(s3.getSignerClass())).to.equal('v4')
done()
it 'user specifies a signatureVersion of v4', (done) ->
s3 = new AWS.S3(signatureVersion: 'v4')
expect(getVersion(s3.getSignerClass())).to.equal('v4')
done()
describe 'building a request', ->
build = (operation, params) ->
request(operation, params).build().httpRequest
it 'obeys the configuration for s3ForcePathStyle', ->
config = new AWS.Config(s3ForcePathStyle: true, accessKeyId: 'AKID', secretAccessKey: 'SECRET')
s3 = new AWS.S3(config)
expect(s3.config.s3ForcePathStyle).to.equal(true)
req = build('headObject', {Bucket:'bucket', Key:'key'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket/key')
it 'does not enable path style if endpoint is a bucket', ->
s3 = new AWS.S3(endpoint: 'foo.bar', s3BucketEndpoint: true)
req = build('listObjects', Bucket: 'bucket')
expect(req.endpoint.hostname).to.equal('foo.bar')
expect(req.path).to.equal('/')
expect(req.virtualHostedBucket).to.equal('bucket')
it 'allows user override if an endpoint is specified', ->
s3 = new AWS.S3(endpoint: 'foo.bar', s3ForcePathStyle: true)
req = build('listObjects', Bucket: 'bucket')
expect(req.endpoint.hostname).to.equal('foo.bar')
expect(req.path).to.equal('/bucket')
it 'does not allow non-bucket operations with s3BucketEndpoint set', ->
s3 = new AWS.S3(endpoint: 'foo.bar', s3BucketEndpoint: true, paramValidation: true)
req = s3.listBuckets().build()
expect(req.response.error.code).to.equal('ConfigError')
it 'corrects virtual-hosted bucket region on request if bucket region stored in cache', ->
s3 = new AWS.S3(region: 'us-east-1')
s3.bucketRegionCache.name = 'us-west-2'
param = Bucket: 'name'
req = s3.headBucket(param).build()
httpRequest = req.httpRequest
expect(httpRequest.region).to.equal('us-west-2')
expect(httpRequest.endpoint.hostname).to.equal('name.s3-us-west-2.amazonaws.com')
expect(httpRequest.headers.Host).to.equal('name.s3-us-west-2.amazonaws.com')
expect(httpRequest.path).to.equal('/')
it 'corrects path-style bucket region on request if bucket region stored in cache', ->
s3 = new AWS.S3(region: 'us-east-1', s3ForcePathStyle: true)
s3.bucketRegionCache.name = 'us-west-2'
param = Bucket: 'name'
req = s3.headBucket(param).build()
httpRequest = req.httpRequest
expect(httpRequest.region).to.equal('us-west-2')
expect(httpRequest.endpoint.hostname).to.equal('s3-us-west-2.amazonaws.com')
expect(httpRequest.headers.Host).to.equal('s3-us-west-2.amazonaws.com')
expect(httpRequest.path).to.equal('/name')
describe 'with useAccelerateEndpoint set to true', ->
beforeEach ->
s3 = new AWS.S3(useAccelerateEndpoint: true)
it 'changes the hostname to use s3-accelerate for dns-comaptible buckets', ->
req = build('getObject', {Bucket: 'foo', Key: 'bar'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.amazonaws.com')
it 'overrides s3BucketEndpoint configuration when s3BucketEndpoint is set', ->
s3 = new AWS.S3(useAccelerateEndpoint: true, s3BucketEndpoint: true, endpoint: 'foo.region.amazonaws.com')
req = build('getObject', {Bucket: 'foo', Key: 'baz'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.amazonaws.com')
describe 'does not use s3-accelerate.dualstack or s3-accelerate', ->
it 'on dns-incompatible buckets', ->
req = build('getObject', {Bucket: 'foo.baz', Key: 'bar'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
it 'on excluded operations', ->
req = build('listBuckets')
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('createBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('deleteBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
describe 'with useAccelerateEndpoint and dualstack set to true', ->
beforeEach ->
s3 = new AWS.S3(useAccelerateEndpoint: true, useDualstack: true)
it 'changes the hostname to use s3-accelerate for dns-comaptible buckets', ->
req = build('getObject', {Bucket: 'foo', Key: 'bar'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.dualstack.amazonaws.com')
it 'overrides s3BucketEndpoint configuration when s3BucketEndpoint is set', ->
s3 = new AWS.S3(useAccelerateEndpoint: true, useDualstack: true, s3BucketEndpoint: true, endpoint: 'foo.region.amazonaws.com')
req = build('getObject', {Bucket: 'foo', Key: 'baz'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.dualstack.amazonaws.com')
describe 'does not use s3-accelerate.dualstack or s3-accelerate', ->
it 'on dns-incompatible buckets', ->
req = build('getObject', {Bucket: 'foo.baz', Key: 'bar'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
it 'on excluded operations', ->
req = build('listBuckets')
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('createBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('deleteBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
describe 'uri escaped params', ->
it 'uri-escapes path and querystring params', ->
# bucket param ends up as part of the hostname
params = { Bucket: 'bucket', Key: 'a b c', VersionId: 'a&b' }
req = build('headObject', params)
expect(req.path).to.equal('/a%20b%20c?versionId=a%26b')
it 'does not uri-escape forward slashes in the path', ->
params = { Bucket: 'bucket', Key: 'k e/y' }
req = build('headObject', params)
expect(req.path).to.equal('/k%20e/y')
it 'ensures a single forward slash exists', ->
req = build('listObjects', { Bucket: 'bucket' })
expect(req.path).to.equal('/')
req = build('listObjects', { Bucket: 'bucket', MaxKeys:123 })
expect(req.path).to.equal('/?max-keys=123')
describe 'adding Expect: 100-continue', ->
if AWS.util.isNode()
it 'does not add expect header to payloads less than 1MB', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024 * 1024 - 1))
expect(req.headers['Expect']).not.to.exist
it 'adds expect header to payloads greater than 1MB', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024 * 1024 + 1))
expect(req.headers['Expect']).to.equal('100-continue')
if AWS.util.isBrowser()
beforeEach -> helpers.spyOn(AWS.util, 'isBrowser').andReturn(true)
it 'does not add expect header in the browser', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024 * 1024 + 1))
expect(req.headers['Expect']).not.to.exist
describe 'with s3DisableBodySigning set to true', ->
it 'will disable body signing when using signature version 4 and the endpoint uses https', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 'v4')
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.equal('UNSIGNED-PAYLOAD')
it 'will compute contentMD5', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 'v4')
buf = new Buffer(1024*1024*5)
buf.fill(0)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: buf)
expect(req.headers['Content-MD5']).to.equal('XzY+DlipXwbL6bvGYsXftg==')
it 'will not disable body signing when the endpoint is not https', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 'v4', sslEnabled: false)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.exist
expect(req.headers['X-Amz-Content-Sha256']).to.not.equal('UNSIGNED-PAYLOAD')
it 'will have no effect when sigv2 signing is used', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 's3', sslEnabled: true)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.not.exist
describe 'with s3DisableBodySigning set to false', ->
it 'will sign the body when sigv4 is used', ->
s3 = new AWS.S3(s3DisableBodySigning: false, signatureVersion: 'v4')
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.exist
expect(req.headers['X-Amz-Cotnent-Sha256']).to.not.equal('UNSIGNED-PAYLOAD')
it 'will have no effect when sigv2 signing is used', ->
s3 = new AWS.S3(s3DisableBodySigning: false, signatureVersion: 's3', sslEnabled: true)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.not.exist
describe 'adding Content-Type', ->
beforeEach -> helpers.spyOn(AWS.util, 'isBrowser').andReturn(true)
it 'adds default content-type when not supplied', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: 'body')
expect(req.headers['Content-Type']).to.equal('application/octet-stream; charset=UTF-8')
it 'does not add content-type for GET/HEAD requests', ->
req = build('getObject', Bucket: 'bucket', Key: 'key')
expect(req.headers['Content-Type']).not.to.exist
req = build('headObject', Bucket: 'bucket', Key: 'key')
expect(req.headers['Content-Type']).not.to.exist
it 'adds charset to existing content-type if not supplied', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: 'body', ContentType: 'text/html')
expect(req.headers['Content-Type']).to.equal('text/html; charset=UTF-8')
it 'normalized charset to uppercase', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: 'body', ContentType: 'text/html; charset=utf-8')
expect(req.headers['Content-Type']).to.equal('text/html; charset=UTF-8')
it 'does not add charset to non-string data', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer('body'), ContentType: 'image/png')
expect(req.headers['Content-Type']).to.equal('image/png')
describe 'virtual-hosted vs path-style bucket requests', ->
describe 'HTTPS', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: true, region: undefined)
it 'puts dns-compat bucket names in the hostname', ->
req = build('headObject', {Bucket:'bucket-name',Key:'abc'})
expect(req.method).to.equal('HEAD')
expect(req.endpoint.hostname).to.equal('bucket-name.s3.amazonaws.com')
expect(req.path).to.equal('/abc')
it 'ensures the path contains / at a minimum when moving bucket', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in path if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket.name')
it 'puts dns-compat bucket names in path if configured to do so', ->
s3 = new AWS.S3(sslEnabled: true, s3ForcePathStyle: true, region: undefined)
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket-name')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'HTTP', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: false, region: undefined)
it 'puts dns-compat bucket names in the hostname', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in the hostname if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('bucket.name.s3.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'HTTPS dualstack', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: true, region: undefined, useDualstack: true)
it 'puts dns-compat bucket names in the hostname', ->
req = build('headObject', {Bucket:'bucket-name',Key:'abc'})
expect(req.method).to.equal('HEAD')
expect(req.endpoint.hostname).to.equal('bucket-name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/abc')
it 'ensures the path contains / at a minimum when moving bucket', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in path if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket.name')
it 'puts dns-compat bucket names in path if configured to do so', ->
s3 = new AWS.S3(sslEnabled: true, s3ForcePathStyle: true, region: undefined, useDualstack: true)
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket-name')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'HTTP dualstack', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: false, region: undefined, useDualstack: true)
it 'puts dns-compat bucket names in the hostname', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in the hostname if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('bucket.name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'SSE support', ->
beforeEach -> s3 = new AWS.S3
it 'fails if the scheme is not HTTPS: when SSECustomerKey is provided', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'object'
SSECustomerKey: 'sse-key', SSECustomerAlgorithm: 'AES256'
req.httpRequest.endpoint.protocol = 'http:'
req.build()
expect(req.response.error.code).to.equal('ConfigError')
it 'fails if the scheme is not HTTPS: when CopySourceSSECustomerKey is provided', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'object'
CopySourceSSECustomerKey: 'sse-key', CopySourceSSECustomerAlgorithm: 'AES256'
req.httpRequest.endpoint.protocol = 'http:'
req.build()
expect(req.response.error.code).to.equal('ConfigError')
describe 'SSECustomerKey', ->
it 'encodes strings keys and fills in MD5', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'data'
SSECustomerKey: 'KEY', SSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key']).
to.equal('S0VZ')
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key-MD5']).
to.equal('O1lJ4MJrh3Z6R1Kidt6VcA==')
it 'encodes blob keys and fills in MD5', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'data'
SSECustomerKey: new AWS.util.Buffer('098f6bcd4621d373cade4e832627b4f6', 'hex')
SSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key']).
to.equal('CY9rzUYh03PK3k6DJie09g==')
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key-MD5']).
to.equal('YM1UqSjLvLtue1WVurRqng==')
describe 'CopySourceSSECustomerKey', ->
it 'encodes string keys and fills in MD5', ->
req = s3.copyObject
Bucket: 'bucket', Key: 'key', CopySource: 'bucket/oldkey', Body: 'data'
CopySourceSSECustomerKey: 'KEY', CopySourceSSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key']).
to.equal('S0VZ')
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key-MD5']).
to.equal('O1lJ4MJrh3Z6R1Kidt6VcA==')
it 'encodes blob keys and fills in MD5', ->
req = s3.copyObject
Bucket: 'bucket', Key: 'key', CopySource: 'bucket/oldkey', Body: 'data'
CopySourceSSECustomerKey: new AWS.util.Buffer('098f6bcd4621d373cade4e832627b4f6', 'hex')
CopySourceSSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key']).
to.equal('CY9rzUYh03PK3k6DJie09g==')
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key-MD5']).
to.equal('YM1UqSjLvLtue1WVurRqng==')
describe 'retry behavior', ->
it 'retries RequestTimeout errors', ->
s3.config.maxRetries = 3
helpers.mockHttpResponse 400, {},
'<xml><Code>RequestTimeout</Code><Message>message</Message></xml>'
s3.putObject (err, data) ->
expect(@retryCount).to.equal(s3.config.maxRetries)
# Managed Upload integration point
describe 'upload', ->
it 'accepts parameters in upload() call', ->
helpers.mockResponses [ { data: { ETag: 'ETAG' } } ]
done = false
s3.upload({Bucket: 'bucket', Key: 'key', Body: 'body'}, -> done = true)
expect(done).to.equal(true)
it 'accepts options as a second parameter', ->
helpers.mockResponses [ { data: { ETag: 'ETAG' } } ]
upload = s3.upload({Bucket: 'bucket', Key: 'key', Body: 'body'}, {queueSize: 2}, ->)
expect(upload.queueSize).to.equal(2)
it 'does not send if no callback is supplied', ->
s3.upload(Bucket: 'bucket', Key: 'key', Body: 'body')
describe 'extractData', ->
it 'caches bucket region if found in header', ->
req = request('operation', {Bucket: 'name'})
resp = new AWS.Response(req)
resp.httpResponse.headers = 'x-amz-bucket-region': 'rg-fake-1'
req.emit('extractData', [resp])
expect(s3.bucketRegionCache.name).to.equal('rg-fake-1')
# S3 returns a handful of errors without xml bodies (to match the
# http spec) these tests ensure we give meaningful codes/messages for these.
describe 'errors with no XML body', ->
regionReqOperation = if AWS.util.isNode() then 'headBucket' else 'listObjects'
maxKeysParam = if regionReqOperation == 'listObjects' then 0 else undefined
extractError = (statusCode, body, addHeaders, req) ->
if !req
req = request('operation')
resp = new AWS.Response(req)
resp.httpResponse.body = new Buffer(body || '')
resp.httpResponse.statusCode = statusCode
resp.httpResponse.headers = {'x-amz-request-id': 'RequestId', 'x-amz-id-2': 'ExtendedRequestId'}
for header, value of addHeaders
resp.httpResponse.headers[header] = value
req.emit('extractError', [resp])
resp.error
it 'handles 304 errors', ->
error = extractError(304)
expect(error.code).to.equal('NotModified')
expect(error.message).to.equal(null)
it 'handles 400 errors', ->
error = extractError(400)
expect(error.code).to.equal('BadRequest')
expect(error.message).to.equal(null)
it 'handles 403 errors', ->
error = extractError(403)
expect(error.code).to.equal('Forbidden')
expect(error.message).to.equal(null)
it 'handles 404 errors', ->
error = extractError(404)
expect(error.code).to.equal('NotFound')
expect(error.message).to.equal(null)
it 'extracts the region from body and takes precedence over cache', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
<Region>eu-west-1</Region>
</Error>
"""
error = extractError(400, body, {}, req)
expect(error.region).to.equal('eu-west-1')
expect(s3.bucketRegionCache.name).to.equal('eu-west-1')
it 'extracts the region from header and takes precedence over body and cache', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
<Region>eu-west-1</Region>
</Error>
"""
headers = 'x-amz-bucket-region': 'us-east-1'
error = extractError(400, body, headers, req)
expect(error.region).to.equal('us-east-1')
expect(s3.bucketRegionCache.name).to.equal('us-east-1')
it 'uses cache if region not extracted from body or header', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
</Error>
"""
error = extractError(400, body, {}, req)
expect(error.region).to.equal('us-west-2')
expect(s3.bucketRegionCache.name).to.equal('us-west-2')
it 'does not use cache if not different from current region', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
req.httpRequest.region = 'us-west-2'
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
</Error>
"""
error = extractError(400, body)
expect(error.region).to.not.exist
expect(s3.bucketRegionCache.name).to.equal('us-west-2')
it 'does not make async request for bucket region if error.region is set', ->
regionReq = send: (fn) ->
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>PermanentRedirect</Code>
<Message>Message</Message>
</Error>
"""
headers = 'x-amz-bucket-region': 'us-east-1'
error = extractError(301, body, headers, req)
expect(error.region).to.exist
expect(spy.calls.length).to.equal(0)
expect(regionReq._requestRegionForBucket).to.not.exist
it 'makes async request for bucket region if error.region not set for a region redirect error code', ->
regionReq = send: (fn) ->
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
params = Bucket: 'name'
req = request('operation', params)
body = """
<Error>
<Code>PermanentRedirect</Code>
<Message>Message</Message>
</Error>
"""
error = extractError(301, body, {}, req)
expect(error.region).to.not.exist
expect(spy.calls.length).to.equal(1)
expect(spy.calls[0].arguments[0].Bucket).to.equal('name')
expect(spy.calls[0].arguments[0].MaxKeys).to.equal(maxKeysParam)
expect(regionReq._requestRegionForBucket).to.exist
it 'does not make request for bucket region if error code is not a region redirect code', ->
regionReq = send: (fn) ->
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidCode</Code>
<Message>Message</Message>
</Error>
"""
error = extractError(301, body, {}, req)
expect(error.region).to.not.exist
expect(spy.calls.length).to.equal(0)
expect(regionReq._requestRegionForBucket).to.not.exist
it 'updates error.region if async request adds region to cache', ->
regionReq = send: (fn) ->
s3.bucketRegionCache.name = 'us-west-2'
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>PermanentRedirect</Code>
<Message>Message</Message>
</Error>
"""
error = extractError(301, body, {}, req)
expect(spy.calls.length).to.equal(1)
expect(spy.calls[0].arguments[0].Bucket).to.equal('name')
expect(spy.calls[0].arguments[0].MaxKeys).to.equal(maxKeysParam)
expect(error.region).to.equal('us-west-2')
it 'extracts the request ids', ->
error = extractError(400)
expect(error.requestId).to.equal('RequestId')
expect(error.extendedRequestId).to.equal('ExtendedRequestId')
it 'misc errors not known to return an empty body', ->
error = extractError(412) # made up
expect(error.code).to.equal(412)
expect(error.message).to.equal(null)
it 'uses canned errors only when the body is empty', ->
body = """
<xml>
<Code>ErrorCode</Code>
<Message>ErrorMessage</Message>
</xml>
"""
error = extractError(403, body)
expect(error.code).to.equal('ErrorCode')
expect(error.message).to.equal('ErrorMessage')
describe 'retryableError', ->
it 'should retry on authorization header with updated region', ->
err = {code: 'AuthorizationHeaderMalformed', statusCode:400, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
it 'should retry on bad request with updated region', ->
err = {code: 'BadRequest', statusCode:400, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
it 'should retry on permanent redirect with updated region and endpoint', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'should retry on error code 301 with updated region and endpoint', ->
err = {code: 301, statusCode:301, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'should retry with updated region but not endpoint if non-S3 url endpoint is specified', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(endpoint: 'https://fake-custom-url.com', s3BucketEndpoint: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('fake-custom-url.com')
it 'should retry with updated endpoint if S3 url endpoint is specified', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(endpoint: 'https://name.s3-us-west-2.amazonaws.com', s3BucketEndpoint: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'should retry with updated region but not endpoint if accelerate endpoint is used', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(useAccelerateEndpoint: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-accelerate.amazonaws.com')
it 'should retry with updated endpoint if dualstack endpoint is used', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(useDualstack: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3.dualstack.eu-west-1.amazonaws.com')
it 'should not retry on requests for bucket region once region is obtained', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req._requestRegionForBucket = 'name'
retryable = []
retryable.push s3.retryableError(err, req)
s3.bucketRegionCache.name = 'eu-west-1'
retryable.push s3.retryableError(err, req)
expect(retryable).to.eql([true, false])
describe 'browser NetworkingError due to wrong region', ->
done = ->
spy = null
regionReq = null
callNetworkingErrorListener = (req) ->
if !req
req = request('operation', {Bucket: 'name'})
if req._asm.currentState == 'validate'
req.build()
resp = new AWS.Response(req)
resp.error = code: 'NetworkingError'
s3.reqRegionForNetworkingError(resp, done)
req
beforeEach ->
s3 = new AWS.S3(region: 'us-west-2')
regionReq = request('operation', {Bucket: 'name'})
regionReq.send = (fn) ->
fn()
helpers.spyOn(AWS.util, 'isBrowser').andReturn(true)
spy = helpers.spyOn(s3, 'listObjects').andReturn(regionReq)
it 'updates region to us-east-1 if bucket name not DNS compatible', ->
req = request('operation', {Bucket: 'name!'})
callNetworkingErrorListener(req)
expect(req.httpRequest.region).to.equal('us-east-1')
expect(req.httpRequest.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(s3.bucketRegionCache['name!']).to.equal('us-east-1')
expect(spy.calls.length).to.equal(0)
it 'updates region if cached and not current region', ->
req = request('operation', {Bucket: 'name'})
req.build()
s3.bucketRegionCache.name = 'eu-west-1'
callNetworkingErrorListener(req)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
expect(spy.calls.length).to.equal(0)
it 'makes async request in us-east-1 if not in cache', ->
regionReq.send = (fn) ->
s3.bucketRegionCache.name = 'eu-west-1'
fn()
req = callNetworkingErrorListener()
expect(spy.calls.length).to.equal(1)
expect(regionReq.httpRequest.region).to.equal('us-east-1')
expect(regionReq.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'makes async request in us-east-1 if cached region matches current region', ->
s3.bucketRegionCache.name = 'us-west-2'
regionReq.send = (fn) ->
s3.bucketRegionCache.name = 'eu-west-1'
fn()
req = callNetworkingErrorListener()
expect(spy.calls.length).to.equal(1)
expect(regionReq.httpRequest.region).to.equal('us-east-1')
expect(regionReq.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'does not update region if path-style bucket is dns-compliant and not in cache', ->
s3.config.s3ForcePathStyle = true
regionReq.send = (fn) ->
s3.bucketRegionCache.name = 'eu-west-1'
fn()
req = callNetworkingErrorListener()
expect(spy.calls.length).to.equal(0)
expect(req.httpRequest.region).to.equal('us-west-2')
expect(req.httpRequest.endpoint.hostname).to.equal('s3-us-west-2.amazonaws.com')
# tests from this point on are "special cases" for specific aws operations
describe 'getBucketAcl', ->
it 'correctly parses the ACL XML document', ->
headers = { 'x-amz-request-id' : 'request-id' }
body =
"""
<AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<AccessControlList>
<Grant>
<Grantee xsi:type="CanonicalUser" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Grantee>
<Permission>FULL_CONTROL</Permission>
</Grant>
<Grant>
<Grantee xsi:type="Group" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<URI>uri</URI>
</Grantee>
<Permission>READ</Permission>
</Grant>
</AccessControlList>
<Owner>
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, headers, body
s3.getBucketAcl (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
Owner:
DisplayName: 'aws-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser'
DisplayName: 'aws-sdk'
ID: 'id'
},
{
Permission : 'READ'
Grantee:
Type: 'Group'
URI: 'uri'
}
]
})
describe 'putBucketAcl', ->
it 'correctly builds the ACL XML document', ->
xml =
"""
<AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<AccessControlList>
<Grant>
<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Grantee>
<Permission>FULL_CONTROL</Permission>
</Grant>
<Grant>
<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">
<URI>uri</URI>
</Grantee>
<Permission>READ</Permission>
</Grant>
</AccessControlList>
<Owner>
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, {}, ''
params =
AccessControlPolicy:
Owner:
DisplayName: 'aws-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser',
DisplayName: 'aws-sdk'
ID: 'id'
},
{
Permission : 'READ'
Grantee:
Type: 'Group',
URI: 'uri'
}
]
s3.putBucketAcl params, (err, data) ->
helpers.matchXML(this.request.httpRequest.body, xml)
describe 'completeMultipartUpload', ->
it 'returns data when the resp is 200 with valid response', ->
headers =
'x-amz-id-2': 'Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg=='
'x-amz-request-id': '656c76696e6727732072657175657374'
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<CompleteMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>
<Bucket>Example-Bucket</Bucket>
<Key>Example-Object</Key>
<ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
</CompleteMultipartUploadResult>
"""
helpers.mockHttpResponse 200, headers, body
s3.completeMultipartUpload (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
Location: 'http://Example-Bucket.s3.amazonaws.com/Example-Object'
Bucket: 'Example-Bucket'
Key: 'Example-Object'
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
})
expect(this.requestId).to.equal('656c76696e6727732072657175657374')
it 'returns an error when the resp is 200 with an error xml document', ->
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
<RequestId>656c76696e6727732072657175657374</RequestId>
<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
"""
helpers.mockHttpResponse 200, {}, body
s3.completeMultipartUpload (error, data) ->
expect(error ).to.be.instanceOf(Error)
expect(error.code).to.equal('InternalError')
expect(error.message).to.equal('We encountered an internal error. Please try again.')
expect(error.statusCode).to.equal(200)
expect(error.retryable).to.equal(true)
expect(data).to.equal(null)
describe 'copyObject', ->
it 'returns data when the resp is 200 with valid response', ->
headers =
'x-amz-id-2': 'Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg=='
'x-amz-request-id': '656c76696e6727732072657175657374'
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<CopyObjectResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>
<Bucket>Example-Bucket</Bucket>
<Key>Example-Object</Key>
<ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
</CopyObjectResult>
"""
helpers.mockHttpResponse 200, headers, body
s3.copyObject (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
CopyObjectResult: {
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
}
})
expect(this.requestId).to.equal('656c76696e6727732072657175657374')
it 'returns an error when the resp is 200 with an error xml document', ->
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
<RequestId>656c76696e6727732072657175657374</RequestId>
<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
"""
helpers.mockHttpResponse 200, {}, body
s3.copyObject (error, data) ->
expect(error ).to.be.instanceOf(Error)
expect(error.code).to.equal('InternalError')
expect(error.message).to.equal('We encountered an internal error. Please try again.')
expect(error.statusCode).to.equal(200)
expect(error.retryable).to.equal(true)
expect(data).to.equal(null)
describe 'uploadPartCopy', ->
it 'returns data when the resp is 200 with valid response', ->
headers =
'x-amz-id-2': 'Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg=='
'x-amz-request-id': '656c76696e6727732072657175657374'
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<CopyPartResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>
<Bucket>Example-Bucket</Bucket>
<Key>Example-Object</Key>
<ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
</CopyPartResult>
"""
helpers.mockHttpResponse 200, headers, body
s3.uploadPartCopy {Bucket: 'bucket', Key: 'key', CopySource: 'bucket/key'}, (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
CopyPartResult: {
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
}
})
expect(this.requestId).to.equal('656c76696e6727732072657175657374')
it 'returns an error when the resp is 200 with an error xml document', ->
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
<RequestId>656c76696e6727732072657175657374</RequestId>
<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
"""
helpers.mockHttpResponse 200, {}, body
s3.uploadPartCopy (error, data) ->
expect(error ).to.be.instanceOf(Error)
expect(error.code).to.equal('InternalError')
expect(error.message).to.equal('We encountered an internal error. Please try again.')
expect(error.statusCode).to.equal(200)
expect(error.retryable).to.equal(true)
expect(data).to.equal(null)
describe 'getBucketLocation', ->
it 'returns empty string for the location constraint when not present', ->
body = '<?xml version="1.0" encoding="UTF-8"?>\n<LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>'
helpers.mockHttpResponse 200, {}, body
s3.getBucketLocation (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({LocationConstraint: ''})
it 'parses the location constraint from the root xml', ->
headers = { 'x-amz-request-id': 'abcxyz' }
body = '<?xml version="1.0" encoding="UTF-8"?>\n<LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">EU</LocationConstraint>'
helpers.mockHttpResponse 200, headers, body
s3.getBucketLocation (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql(LocationConstraint: 'EU')
expect(this.requestId).to.equal('abcxyz')
describe 'createBucket', ->
it 'auto-populates the LocationConstraint based on the region', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1')
s3.makeRequest = (op, params) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(Bucket:'name')
expect(loc).to.equal('eu-west-1')
it 'auto-populates the LocationConstraint based on the region when using bound params', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1', Bucket:'name')
s3.makeRequest = (op, params) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(AWS.util.fn.noop)
expect(loc).to.equal('eu-west-1')
it 'auto-populates the LocationConstraint based on the region when using invalid params', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1', Bucket:'name')
s3.makeRequest = (op, params) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(null)
expect(loc).to.equal('eu-west-1')
s3.createBucket(undefined)
expect(loc).to.equal('eu-west-1')
it 'auto-populates the LocationConstraint based on the region when using invalid params and a valid callback', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1', Bucket:'name')
s3.makeRequest = (op, params, cb) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
cb() if typeof cb == 'function'
called = 0
s3.createBucket(undefined, () -> called = 1)
expect(loc).to.equal('eu-west-1')
expect(called).to.equal(1)
it 'caches bucket region based on LocationConstraint upon successful response', ->
s3 = new AWS.S3()
params = Bucket: 'name', CreateBucketConfiguration: LocationConstraint: 'rg-fake-1'
helpers.mockHttpResponse 200, {}, ''
s3.createBucket params, ->
expect(s3.bucketRegionCache.name).to.equal('rg-fake-1')
it 'caches bucket region without LocationConstraint upon successful response', ->
s3 = new AWS.S3(region: 'us-east-1')
params = Bucket: 'name'
helpers.mockHttpResponse 200, {}, ''
s3.createBucket params, ->
expect(params.CreateBucketConfiguration).to.not.exist
expect(s3.bucketRegionCache.name).to.equal('us-east-1')
it 'caches bucket region with LocationConstraint "EU" upon successful response', ->
s3 = new AWS.S3()
params = Bucket: 'name', CreateBucketConfiguration: LocationConstraint: 'EU'
helpers.mockHttpResponse 200, {}, ''
s3.createBucket params, ->
expect(s3.bucketRegionCache.name).to.equal('eu-west-1')
describe 'deleteBucket', ->
it 'removes bucket from region cache on successful response', ->
s3 = new AWS.S3()
params = Bucket: 'name'
s3.bucketRegionCache.name = 'rg-fake-1'
helpers.mockHttpResponse 204, {}, ''
s3.deleteBucket params, ->
expect(s3.bucketRegionCache.name).to.not.exist
AWS.util.each AWS.S3.prototype.computableChecksumOperations, (operation) ->
describe operation, ->
it 'forces Content-MD5 header parameter', ->
req = s3[operation](Bucket: 'bucket', ContentMD5: '000').build()
hash = AWS.util.crypto.md5(req.httpRequest.body, 'base64')
expect(req.httpRequest.headers['Content-MD5']).to.equal(hash)
describe 'willComputeChecksums', ->
willCompute = (operation, opts) ->
compute = opts.computeChecksums
s3 = new AWS.S3(computeChecksums: compute, signatureVersion: 's3')
req = s3.makeRequest(operation, Bucket: 'example', ContentMD5: opts.hash).build()
checksum = req.httpRequest.headers['Content-MD5']
if opts.hash != undefined
if opts.hash == null
expect(checksum).not.to.exist
else
expect(checksum).to.equal(opts.hash)
else
realChecksum = AWS.util.crypto.md5(req.httpRequest.body, 'base64')
expect(checksum).to.equal(realChecksum)
it 'computes checksums if the operation requires it', ->
willCompute 'deleteObjects', computeChecksums: true
willCompute 'putBucketCors', computeChecksums: true
willCompute 'putBucketLifecycle', computeChecksums: true
willCompute 'putBucketLifecycleConfiguration', computeChecksums: true
it 'computes checksums if computeChecksums is off and operation requires it', ->
willCompute 'deleteObjects', computeChecksums: false
willCompute 'putBucketCors', computeChecksums: false
willCompute 'putBucketLifecycle', computeChecksums: false
willCompute 'putBucketLifecycleConfiguration', computeChecksums: false
it 'does not compute checksums if computeChecksums is off', ->
willCompute 'putObject', computeChecksums: false, hash: null
it 'does not compute checksums if computeChecksums is on and ContentMD5 is provided', ->
willCompute 'putBucketAcl', computeChecksums: true, hash: '000'
it 'computes checksums if computeChecksums is on and ContentMD5 is not provided',->
willCompute 'putBucketAcl', computeChecksums: true
if AWS.util.isNode()
it 'does not compute checksums for Stream objects', ->
s3 = new AWS.S3(computeChecksums: true)
req = s3.putObject(Bucket: 'example', Key: 'foo', Body: new Stream.Stream)
expect(req.build(->).httpRequest.headers['Content-MD5']).to.equal(undefined)
it 'throws an error in SigV4, if a non-file stream is provided when body signing enabled', (done) ->
s3 = new AWS.S3({signatureVersion: 'v4', s3DisableBodySigning: false})
req = s3.putObject(Bucket: 'example', Key: 'key', Body: new Stream.Stream)
req.send (err) ->
expect(err.message).to.contain('stream objects are not supported')
done()
it 'does not throw an error in SigV4, if a non-file stream is provided when body signing disabled with ContentLength', (done) ->
s3 = new AWS.S3({signatureVersion: 'v4', s3DisableBodySigning: true})
helpers.mockResponse data: ETag: 'etag'
req = s3.putObject(Bucket: 'example', Key: 'key', Body: new Stream.Stream, ContentLength: 10)
req.send (err) ->
expect(err).not.to.exist
done()
it 'opens separate stream if a file object is provided (signed payload)', (done) ->
hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
helpers.mockResponse data: ETag: 'etag'
fs = require('fs')
mock = helpers.spyOn(fs, 'createReadStream').andCallFake ->
tr = new Stream.Transform
tr._transform = (d,e,c) -> c(null,d)
tr.length = 0
tr.path = 'path/to/file'
tr.push(new Buffer(''))
tr.end()
tr
s3 = new AWS.S3({signatureVersion: 'v4', s3DisableBodySigning: false})
stream = fs.createReadStream('path/to/file')
req = s3.putObject(Bucket: 'example', Key: 'key', Body: stream)
req.send (err) ->
expect(mock.calls[0].arguments).to.eql(['path/to/file'])
expect(mock.calls[1].arguments).to.eql(['path/to/file', {}])
expect(err).not.to.exist
expect(req.httpRequest.headers['X-Amz-Content-Sha256']).to.equal(hash)
done()
it 'opens separate stream with range if a file object is provided', (done) ->
hash = '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
helpers.mockResponse data: ETag: 'etag'
fs = require('fs')
mock = helpers.spyOn(fs, 'createReadStream').andCallFake (path, settings) ->
tr = new Stream.Readable
tr.length = 0
tr.path = 'path/to/file'
tr.start = settings.start
tr.end = settings.end
didRead = false
tr._read = (n) ->
if (didRead)
tr.push(null)
else
didRead = true
tr.push(new Buffer('test'))
tr
s3 = new AWS.S3(signatureVersion: 'v4', s3DisableBodySigning: false)
stream = fs.createReadStream('path/to/file', {start:0, end:5})
req = s3.putObject(Bucket: 'example', Key: 'key', Body: stream)
req.send (err) ->
expect(mock.calls[0].arguments).to.eql(['path/to/file', {start:0, end:5}])
expect(mock.calls[1].arguments).to.eql(['path/to/file', {start:0, end:5}])
expect(err).not.to.exist
expect(req.httpRequest.headers['X-Amz-Content-Sha256']).to.equal(hash)
done()
describe 'getSignedUrl', ->
date = null
beforeEach (done) ->
date = AWS.util.date.getDate
AWS.util.date.getDate = -> new Date(0)
done()
afterEach (done) ->
AWS.util.date.getDate = date
done()
it 'gets a signed URL for getObject', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key')
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=4mlYnRmz%2BBFEPrgYz5tXcl9Wc4w%3D&x-amz-security-token=session')
it 'gets a signed URL with Expires time', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key', Expires: 60)
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=60&Signature=kH2pMK%2Fgm7cCZKVG8GHVTRGXKzY%3D&x-amz-security-token=session')
it 'gets a signed URL with expiration and bound bucket parameters', ->
s3 = new AWS.S3(paramValidation: true, region: undefined, params: Bucket: 'bucket')
url = s3.getSignedUrl('getObject', Key: 'key', Expires: 60)
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=60&Signature=kH2pMK%2Fgm7cCZKVG8GHVTRGXKzY%3D&x-amz-security-token=session')
it 'generates the right URL with a custom endpoint', ->
s3 = new AWS.S3(endpoint: 'https://foo.bar.baz:555/prefix', params: Bucket: 'bucket')
url = s3.getSignedUrl('getObject', Key: 'key', Expires: 60)
expect(url).to.equal('https://bucket.foo.bar.baz:555/prefix/key?AWSAccessKeyId=akid&Expires=60&Signature=zA6k0cQqDkTZgLamfoYLOd%2Bqfg8%3D&x-amz-security-token=session')
it 'gets a signed URL with callback', (done) ->
s3.getSignedUrl 'getObject', Bucket: 'bucket', Key: 'key', (err, url) ->
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=4mlYnRmz%2BBFEPrgYz5tXcl9Wc4w%3D&x-amz-security-token=session')
done()
it 'gets a signed URL for putObject with no body', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key')
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=J%2BnWZ0lPUfLV0kio8ONhJmAttGc%3D&x-amz-security-token=session')
it 'gets a signed URL for putObject with Metadata', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Metadata: {someKey: 'someValue'})
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=5Lcbv0WLGWseQhtmNQ8WwIpX6Kw%3D&x-amz-meta-somekey=someValue&x-amz-security-token=session')
it 'gets a signed URL for putObject with Metadata using Sigv4', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Metadata: {someKey: 'someValue'})
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=0a1ef336042a7a03b8a2e130ac36097cb1fbab54f8ed5105977a863a5139e679&X-Amz-SignedHeaders=host%3Bx-amz-meta-somekey&x-amz-meta-somekey=someValue')
it 'gets a signed URL for putObject with special characters', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: '!@#$%^&*();\':"{}[],./?`~')
expect(url).to.equal('https://bucket.s3.amazonaws.com/%21%40%23%24%25%5E%26%2A%28%29%3B%27%3A%22%7B%7D%5B%5D%2C./%3F%60~?AWSAccessKeyId=akid&Expires=900&Signature=9nEltJACZKsriZqU2cmRel6g8LQ%3D&x-amz-security-token=session')
it 'gets a signed URL for putObject with a body (and checksum)', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Body: 'body')
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Content-MD5=hBotaJrYa9FhFEdFPCLG%2FA%3D%3D&Expires=900&Signature=4ycA2tpHKxfFnNCdqnK1d5BG8gc%3D&x-amz-security-token=session')
it 'gets a signed URL for putObject with a sse-c algorithm', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', SSECustomerAlgorithm: 'AES256')
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=60b08f91f820fa1c698ac477fec7b5e3cec7b682e09e769e1a55a4d5a3b99077&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption-customer-algorithm&x-amz-server-side-encryption-customer-algorithm=AES256');
it 'gets a signed URL for putObject with a sse-c key', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', SSECustomerAlgorithm: 'AES256', SSECustomerKey: 'c2FtcGxlIGtleXNhbXBsZSBrZXlzYW1wbGUga2V5c2E=')
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=e4f57734798fdadc0b2b43ca5a5e1f28824786c3ac74c30d7abb77d6ef59b0da&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption-customer-algorithm%3Bx-amz-server-side-encryption-customer-key%3Bx-amz-server-side-encryption-customer-key-md5&x-amz-server-side-encryption-customer-algorithm=AES256&x-amz-server-side-encryption-customer-key=YzJGdGNHeGxJR3RsZVhOaGJYQnNaU0JyWlhsellXMXdiR1VnYTJWNWMyRT0%3D&x-amz-server-side-encryption-customer-key-MD5=VzaXhwL7H9upBc%2Fb9UqH8g%3D%3D');
it 'gets a signed URL for putObject with CacheControl', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', CacheControl: 'max-age=10000')
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?Cache-Control=max-age%3D10000&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=39ad1f8dc3aa377c2b184a0be7657dfb606628c74796c1a48394ef134ff6233a&X-Amz-SignedHeaders=cache-control%3Bhost')
it 'gets a signed URL and appends to existing query parameters', ->
url = s3.getSignedUrl('listObjects', Bucket: 'bucket', Prefix: 'prefix')
expect(url).to.equal('https://bucket.s3.amazonaws.com/?AWSAccessKeyId=akid&Expires=900&Signature=8W3pwZPfgucCyPNg1MsoYq8h5zw%3D&prefix=prefix&x-amz-security-token=session')
it 'gets a signed URL for getObject using SigV4', ->
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'object')
expect(url).to.equal('https://bucket.s3.amazonaws.com/object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=05ae40d2d22c93549a1de0686232ff56baf556876ec497d0d8349431f98b8dfe&X-Amz-SignedHeaders=host')
it 'gets a signed URL for putObject using SigV4', ->
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'object')
expect(url).to.equal('https://bucket.s3.amazonaws.com/object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=1b6f75301a2e480bcfbb53d47d8940c28c8657ea70f23c24846a5595a53b1dfe&X-Amz-SignedHeaders=host')
it 'gets a signed URL for putObject using SigV4 with body', ->
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'object', Body: 'foo')
expect(url).to.equal('https://bucket.s3.amazonaws.com/object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae&X-Amz-Credential=akid%2F19700101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=600a64aff20c4ea6c28d11fd0639fb33a0107d072f4c2dd1ea38a16d057513f3&X-Amz-SignedHeaders=host%3Bx-amz-content-sha256')
it 'errors when expiry time is greater than a week out on SigV4', (done) ->
err = null; data = null
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
params = Bucket: 'bucket', Key: 'object', Expires: 60 * 60 * 24 * 7 + 120
error = 'Presigning does not support expiry time greater than a week with SigV4 signing.'
s3.getSignedUrl 'getObject', params, (err, data) ->
expect(err).not.to.equal(null)
expect(err.message).to.equal(error)
#expect(-> s3.getSignedUrl('getObject', params)).to.throw(error) # sync mode
done()
it 'errors if ContentLength is passed as parameter', ->
expect(-> s3.getSignedUrl('putObject',
Bucket: 'bucket'
Key: 'key'
ContentLength: 5
)).to.throw(/ContentLength is not supported in pre-signed URLs/)
describe 'createPresignedPost', ->
it 'should include a url and a hash of form fields', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data).to.include.keys('fields', 'url')
expect(data.url).to.be.a.string
expect(data.fields).to.be.an.object
done()
it 'should include a policy, signature, and signing metadata', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data.fields).to.include.keys(
'Policy',
'X-Amz-Signature',
'X-Amz-Algorithm',
'X-Amz-Date',
'X-Amz-Credential'
)
done()
it 'should specify the signing algorithm used', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data.fields['X-Amz-Algorithm']).to.equal('AWS4-HMAC-SHA256')
done()
it 'should use bound parameters for the bucket name', (done) ->
s3 = new AWS.S3(params: {Bucket: 'bucket'})
s3.createPresignedPost {}, (err, data) ->
expect(data.fields).to.include.keys('bucket')
expect(data.fields.bucket).to.equal('bucket')
done()
it 'should include the security token when present', (done) ->
token = 'baz'
credentials =
accessKeyId: 'foo'
secretAccessKey: 'bar'
sessionToken: token
s3 = new AWS.S3(credentials: credentials)
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data.fields['X-Amz-Security-Token']).to.equal(token)
done()
it 'should provide a base64-encoded JSON policy document', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expect(decoded).to.be.an.object
expect(decoded).to.include.key('expiration', 'conditions')
done()
it 'should default to expiration in one hour', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expiration = new Date(decoded.expiration)
validForMs = expiration.valueOf() - (new Date()).valueOf()
# allow one second of leeway
expect(validForMs).to.be.above((60 * 60 - 1) * 1000)
expect(validForMs).to.be.below((60 * 60 + 1) * 1000)
done()
it 'should allow users to provide a custom expiration', (done) ->
customTtl = 900
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket', Expires: customTtl}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expiration = new Date(decoded.expiration)
validForMs = expiration.valueOf() - (new Date()).valueOf()
# allow one second of leeway
expect(validForMs).to.be.above((customTtl - 1) * 1000)
expect(validForMs).to.be.below((customTtl + 1) * 1000)
done()
it 'should include signature metadata as conditions', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expect(decoded.conditions).to.be.an.array
found = {}
for index, condition of decoded.conditions
conditionKey = Object.keys(condition)[0]
found[conditionKey] = true
expect(condition[conditionKey]).to.equal(data.fields[conditionKey])
expect(found['X-Amz-Algorithm']).to.be.true
expect(found['X-Amz-Date']).to.be.true
expect(found['X-Amz-Credential']).to.be.true
done()
it 'should include user-provided conditions in the signed policy', (done) ->
s3 = new AWS.S3()
conditions = [
{'x-amz-server-side-encryption': 'AES256'},
['starts-with', '$x-amz-meta-tag', ''],
{'acl': 'public-read'}
]
s3.createPresignedPost {Bucket: 'bucket', Conditions: conditions}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expect(decoded.conditions).to.be.an.array
expect(conditions[0]).to.deep.equal(decoded.conditions[0])
expect(conditions[1]).to.deep.equal(decoded.conditions[1])
expect(conditions[2]).to.deep.equal(decoded.conditions[2])
done()
it 'should include user-provided fields as policy conditions', (done) ->
s3 = new AWS.S3()
fieldsToInclude =
key: 'users/userId/upload'
acl: 'public-read',
'Content-Type': 'image/jpeg',
'x-amz-meta-foo': 'bar',
'x-amz-tagging': '''<Tagging>
<TagSet>
<Tag>
<Key>foo</Key>
<Value>bar</Value>
</Tag>
</TagSet>
</Tagging>'''
s3.createPresignedPost {Bucket: 'bucket', Fields: fieldsToInclude}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
conditions = {}
decoded.conditions.forEach((condition) ->
if typeof condition == 'object'
conditionKey = Object.keys(condition)[0]
conditions[conditionKey] = condition[conditionKey]
)
Object.keys(fieldsToInclude).forEach((key) ->
expect(data.fields[key]).to.equal(fieldsToInclude[key])
expect(data.fields[key]).to.equal(conditions[key])
)
done()
| 122830 | helpers = require('../helpers')
AWS = helpers.AWS
Stream = AWS.util.stream
Buffer = AWS.util.Buffer
describe 'AWS.S3', ->
s3 = null
request = (operation, params) -> s3.makeRequest(operation, params)
beforeEach (done) ->
s3 = new AWS.S3(region: undefined)
s3.clearBucketRegionCache()
done()
describe 'dnsCompatibleBucketName', ->
it 'must be at least 3 characters', ->
expect(s3.dnsCompatibleBucketName('aa')).to.equal(false)
it 'must not be longer than 63 characters', ->
b = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
expect(s3.dnsCompatibleBucketName(b)).to.equal(false)
it 'must start with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('Abc')).to.equal(false)
expect(s3.dnsCompatibleBucketName('-bc')).to.equal(false)
expect(s3.dnsCompatibleBucketName('abc')).to.equal(true)
it 'must end with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('abC')).to.equal(false)
expect(s3.dnsCompatibleBucketName('ab-')).to.equal(false)
expect(s3.dnsCompatibleBucketName('abc')).to.equal(true)
it 'may not contain multiple contiguous dots', ->
expect(s3.dnsCompatibleBucketName('abc.123')).to.equal(true)
expect(s3.dnsCompatibleBucketName('abc..123')).to.equal(false)
it 'may only contain letters numbers and dots', ->
expect(s3.dnsCompatibleBucketName('abc123')).to.equal(true)
expect(s3.dnsCompatibleBucketName('abc_123')).to.equal(false)
it 'must not look like an ip address', ->
expect(s3.dnsCompatibleBucketName('172.16.58.3')).to.equal(false)
expect(s3.dnsCompatibleBucketName('a.b.c.d')).to.equal(true)
describe 'constructor', ->
it 'requires endpoint if s3BucketEndpoint is passed', ->
expect(-> new AWS.S3(s3BucketEndpoint: true)).to.throw(
/An endpoint must be provided/)
describe 'endpoint', ->
it 'sets hostname to s3.amazonaws.com when region is un-specified', ->
s3 = new AWS.S3(region: undefined)
expect(s3.endpoint.hostname).to.equal('s3.amazonaws.com')
it 'sets hostname to s3.amazonaws.com when region is us-east-1', ->
s3 = new AWS.S3(region: 'us-east-1')
expect(s3.endpoint.hostname).to.equal('s3.amazonaws.com')
it 'sets region to us-east-1 when unspecified', ->
s3 = new AWS.S3(region: 'us-east-1')
expect(s3.config.region).to.equal('us-east-1')
it 'combines the region with s3 in the endpoint using a - instead of .', ->
s3 = new AWS.S3(region: 'us-west-1')
expect(s3.endpoint.hostname).to.equal('s3-us-west-1.amazonaws.com')
it 'sets a region-specific dualstack endpoint when dualstack enabled', ->
s3 = new AWS.S3(region: 'us-west-1', useDualstack: true)
expect(s3.endpoint.hostname).to.equal('s3.dualstack.us-west-1.amazonaws.com')
s3 = new AWS.S3(region: 'us-east-1', useDualstack: true)
expect(s3.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
describe 'clearing bucket region cache', ->
beforeEach ->
s3.bucketRegionCache = a: 'rg-fake-1', b: 'rg-fake-2', c: 'rg-fake-3'
it 'clears one bucket name', ->
s3.clearBucketRegionCache 'b'
expect(s3.bucketRegionCache).to.eql(a: 'rg-fake-1', c: 'rg-fake-3')
it 'clears a list of bucket names', ->
s3.clearBucketRegionCache ['a', 'c']
expect(s3.bucketRegionCache).to.eql(b: 'rg-fake-2')
it 'clears entire cache', ->
s3.clearBucketRegionCache()
expect(s3.bucketRegionCache).to.eql({})
describe 'getSignerClass', ->
getVersion = (signer) ->
if (signer == AWS.Signers.S3)
return 's3'
else if (signer == AWS.Signers.V4)
return 'v4'
else if (signer == AWS.Signers.V2)
return 'v2'
describe 'when using presigned requests', ->
req = null
beforeEach (done) ->
req = request('mock')
helpers.spyOn(req, 'isPresigned').andReturn(true)
done()
describe 'will return an s3 (v2) signer when', ->
it 'user does not specify a signatureVersion for a region that supports v2', (done) ->
s3 = new AWS.S3(region: 'us-east-1')
expect(getVersion(s3.getSignerClass(req))).to.equal('s3')
done()
it 'user specifies a signatureVersion of s3', (done) ->
s3 = new AWS.S3(signatureVersion: 's3')
expect(getVersion(s3.getSignerClass(req))).to.equal('s3')
done()
it 'user specifies a signatureVersion of v2', (done) ->
s3 = new AWS.S3(signatureVersion: 'v2')
expect(getVersion(s3.getSignerClass(req))).to.equal('s3')
done()
describe 'will return a v4 signer when', ->
it 'user does not specify a signatureVersion for a region that supports only v4', (done) ->
s3 = new AWS.S3(region: 'eu-central-1')
expect(getVersion(s3.getSignerClass(req))).to.equal('v4')
done()
it 'user specifies a signatureVersion of v4', (done) ->
s3 = new AWS.S3(signatureVersion: 'v4')
expect(getVersion(s3.getSignerClass(req))).to.equal('v4')
done()
describe 'when not using presigned requests', ->
describe 'will return an s3 (v2) signer when', ->
it 'user specifies a signatureVersion of s3', (done) ->
s3 = new AWS.S3(signatureVersion: 's3')
expect(getVersion(s3.getSignerClass())).to.equal('s3')
done()
it 'user specifies a signatureVersion of v2', (done) ->
s3 = new AWS.S3(signatureVersion: 'v2')
expect(getVersion(s3.getSignerClass())).to.equal('s3')
done()
it 'user does not specify a signatureVersion and region supports v2', (done) ->
s3 = new AWS.S3({region: 'us-east-1'})
expect(getVersion(s3.getSignerClass())).to.equal('s3')
done()
describe 'will return a v4 signer when', ->
it 'user does not specify a signatureVersion and region only supports v4', (done) ->
s3 = new AWS.S3({region: 'eu-central-1'})
expect(getVersion(s3.getSignerClass())).to.equal('v4')
done()
it 'user specifies a signatureVersion of v4', (done) ->
s3 = new AWS.S3(signatureVersion: 'v4')
expect(getVersion(s3.getSignerClass())).to.equal('v4')
done()
describe 'building a request', ->
build = (operation, params) ->
request(operation, params).build().httpRequest
it 'obeys the configuration for s3ForcePathStyle', ->
config = new AWS.Config(s3ForcePathStyle: true, accessKeyId: '<KEY>', secretAccessKey: '<KEY>')
s3 = new AWS.S3(config)
expect(s3.config.s3ForcePathStyle).to.equal(true)
req = build('headObject', {Bucket:'bucket', Key:'key'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket/key')
it 'does not enable path style if endpoint is a bucket', ->
s3 = new AWS.S3(endpoint: 'foo.bar', s3BucketEndpoint: true)
req = build('listObjects', Bucket: 'bucket')
expect(req.endpoint.hostname).to.equal('foo.bar')
expect(req.path).to.equal('/')
expect(req.virtualHostedBucket).to.equal('bucket')
it 'allows user override if an endpoint is specified', ->
s3 = new AWS.S3(endpoint: 'foo.bar', s3ForcePathStyle: true)
req = build('listObjects', Bucket: 'bucket')
expect(req.endpoint.hostname).to.equal('foo.bar')
expect(req.path).to.equal('/bucket')
it 'does not allow non-bucket operations with s3BucketEndpoint set', ->
s3 = new AWS.S3(endpoint: 'foo.bar', s3BucketEndpoint: true, paramValidation: true)
req = s3.listBuckets().build()
expect(req.response.error.code).to.equal('ConfigError')
it 'corrects virtual-hosted bucket region on request if bucket region stored in cache', ->
s3 = new AWS.S3(region: 'us-east-1')
s3.bucketRegionCache.name = 'us-west-2'
param = Bucket: 'name'
req = s3.headBucket(param).build()
httpRequest = req.httpRequest
expect(httpRequest.region).to.equal('us-west-2')
expect(httpRequest.endpoint.hostname).to.equal('name.s3-us-west-2.amazonaws.com')
expect(httpRequest.headers.Host).to.equal('name.s3-us-west-2.amazonaws.com')
expect(httpRequest.path).to.equal('/')
it 'corrects path-style bucket region on request if bucket region stored in cache', ->
s3 = new AWS.S3(region: 'us-east-1', s3ForcePathStyle: true)
s3.bucketRegionCache.name = 'us-west-2'
param = Bucket: 'name'
req = s3.headBucket(param).build()
httpRequest = req.httpRequest
expect(httpRequest.region).to.equal('us-west-2')
expect(httpRequest.endpoint.hostname).to.equal('s3-us-west-2.amazonaws.com')
expect(httpRequest.headers.Host).to.equal('s3-us-west-2.amazonaws.com')
expect(httpRequest.path).to.equal('/name')
describe 'with useAccelerateEndpoint set to true', ->
beforeEach ->
s3 = new AWS.S3(useAccelerateEndpoint: true)
it 'changes the hostname to use s3-accelerate for dns-comaptible buckets', ->
req = build('getObject', {Bucket: 'foo', Key: '<KEY>'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.amazonaws.com')
it 'overrides s3BucketEndpoint configuration when s3BucketEndpoint is set', ->
s3 = new AWS.S3(useAccelerateEndpoint: true, s3BucketEndpoint: true, endpoint: 'foo.region.amazonaws.com')
req = build('getObject', {Bucket: 'foo', Key: '<KEY>'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.amazonaws.com')
describe 'does not use s3-accelerate.dualstack or s3-accelerate', ->
it 'on dns-incompatible buckets', ->
req = build('getObject', {Bucket: 'foo.baz', Key: 'bar'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
it 'on excluded operations', ->
req = build('listBuckets')
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('createBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('deleteBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
describe 'with useAccelerateEndpoint and dualstack set to true', ->
beforeEach ->
s3 = new AWS.S3(useAccelerateEndpoint: true, useDualstack: true)
it 'changes the hostname to use s3-accelerate for dns-comaptible buckets', ->
req = build('getObject', {Bucket: 'foo', Key: 'bar'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.dualstack.amazonaws.com')
it 'overrides s3BucketEndpoint configuration when s3BucketEndpoint is set', ->
s3 = new AWS.S3(useAccelerateEndpoint: true, useDualstack: true, s3BucketEndpoint: true, endpoint: 'foo.region.amazonaws.com')
req = build('getObject', {Bucket: 'foo', Key: 'baz'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.dualstack.amazonaws.com')
describe 'does not use s3-accelerate.dualstack or s3-accelerate', ->
it 'on dns-incompatible buckets', ->
req = build('getObject', {Bucket: 'foo.baz', Key: 'bar'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
it 'on excluded operations', ->
req = build('listBuckets')
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('createBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('deleteBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
describe 'uri escaped params', ->
it 'uri-escapes path and querystring params', ->
# bucket param ends up as part of the hostname
params = { Bucket: 'bucket', Key: '<KEY>', VersionId: 'a&b' }
req = build('headObject', params)
expect(req.path).to.equal('/a%20b%20c?versionId=a%26b')
it 'does not uri-escape forward slashes in the path', ->
params = { Bucket: 'bucket', Key: 'k e/y' }
req = build('headObject', params)
expect(req.path).to.equal('/k%20e/y')
it 'ensures a single forward slash exists', ->
req = build('listObjects', { Bucket: 'bucket' })
expect(req.path).to.equal('/')
req = build('listObjects', { Bucket: 'bucket', MaxKeys:123 })
expect(req.path).to.equal('/?max-keys=123')
describe 'adding Expect: 100-continue', ->
if AWS.util.isNode()
it 'does not add expect header to payloads less than 1MB', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024 * 1024 - 1))
expect(req.headers['Expect']).not.to.exist
it 'adds expect header to payloads greater than 1MB', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024 * 1024 + 1))
expect(req.headers['Expect']).to.equal('100-continue')
if AWS.util.isBrowser()
beforeEach -> helpers.spyOn(AWS.util, 'isBrowser').andReturn(true)
it 'does not add expect header in the browser', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024 * 1024 + 1))
expect(req.headers['Expect']).not.to.exist
describe 'with s3DisableBodySigning set to true', ->
it 'will disable body signing when using signature version 4 and the endpoint uses https', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 'v4')
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.equal('UNSIGNED-PAYLOAD')
it 'will compute contentMD5', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 'v4')
buf = new Buffer(1024*1024*5)
buf.fill(0)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: buf)
expect(req.headers['Content-MD5']).to.equal('XzY+DlipXwbL6bvGYsXftg==')
it 'will not disable body signing when the endpoint is not https', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 'v4', sslEnabled: false)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.exist
expect(req.headers['X-Amz-Content-Sha256']).to.not.equal('UNSIGNED-PAYLOAD')
it 'will have no effect when sigv2 signing is used', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 's3', sslEnabled: true)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.not.exist
describe 'with s3DisableBodySigning set to false', ->
it 'will sign the body when sigv4 is used', ->
s3 = new AWS.S3(s3DisableBodySigning: false, signatureVersion: 'v4')
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.exist
expect(req.headers['X-Amz-Cotnent-Sha256']).to.not.equal('UNSIGNED-PAYLOAD')
it 'will have no effect when sigv2 signing is used', ->
s3 = new AWS.S3(s3DisableBodySigning: false, signatureVersion: 's3', sslEnabled: true)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.not.exist
describe 'adding Content-Type', ->
beforeEach -> helpers.spyOn(AWS.util, 'isBrowser').andReturn(true)
it 'adds default content-type when not supplied', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: 'body')
expect(req.headers['Content-Type']).to.equal('application/octet-stream; charset=UTF-8')
it 'does not add content-type for GET/HEAD requests', ->
req = build('getObject', Bucket: 'bucket', Key: 'key')
expect(req.headers['Content-Type']).not.to.exist
req = build('headObject', Bucket: 'bucket', Key: 'key')
expect(req.headers['Content-Type']).not.to.exist
it 'adds charset to existing content-type if not supplied', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: 'body', ContentType: 'text/html')
expect(req.headers['Content-Type']).to.equal('text/html; charset=UTF-8')
it 'normalized charset to uppercase', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: 'body', ContentType: 'text/html; charset=utf-8')
expect(req.headers['Content-Type']).to.equal('text/html; charset=UTF-8')
it 'does not add charset to non-string data', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer('body'), ContentType: 'image/png')
expect(req.headers['Content-Type']).to.equal('image/png')
describe 'virtual-hosted vs path-style bucket requests', ->
describe 'HTTPS', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: true, region: undefined)
it 'puts dns-compat bucket names in the hostname', ->
req = build('headObject', {Bucket:'bucket-name',Key:'abc'})
expect(req.method).to.equal('HEAD')
expect(req.endpoint.hostname).to.equal('bucket-name.s3.amazonaws.com')
expect(req.path).to.equal('/abc')
it 'ensures the path contains / at a minimum when moving bucket', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in path if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket.name')
it 'puts dns-compat bucket names in path if configured to do so', ->
s3 = new AWS.S3(sslEnabled: true, s3ForcePathStyle: true, region: undefined)
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket-name')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'HTTP', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: false, region: undefined)
it 'puts dns-compat bucket names in the hostname', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in the hostname if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('bucket.name.s3.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'HTTPS dualstack', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: true, region: undefined, useDualstack: true)
it 'puts dns-compat bucket names in the hostname', ->
req = build('headObject', {Bucket:'bucket-name',Key:'<KEY>'})
expect(req.method).to.equal('HEAD')
expect(req.endpoint.hostname).to.equal('bucket-name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/abc')
it 'ensures the path contains / at a minimum when moving bucket', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in path if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket.name')
it 'puts dns-compat bucket names in path if configured to do so', ->
s3 = new AWS.S3(sslEnabled: true, s3ForcePathStyle: true, region: undefined, useDualstack: true)
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket-name')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'HTTP dualstack', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: false, region: undefined, useDualstack: true)
it 'puts dns-compat bucket names in the hostname', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in the hostname if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('bucket.name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'SSE support', ->
beforeEach -> s3 = new AWS.S3
it 'fails if the scheme is not HTTPS: when SSECustomerKey is provided', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'object'
SSECustomerKey: 'sse-key', SSECustomerAlgorithm: 'AES256'
req.httpRequest.endpoint.protocol = 'http:'
req.build()
expect(req.response.error.code).to.equal('ConfigError')
it 'fails if the scheme is not HTTPS: when CopySourceSSECustomerKey is provided', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'object'
CopySourceSSECustomerKey: 'sse-key', CopySourceSSECustomerAlgorithm: 'AES256'
req.httpRequest.endpoint.protocol = 'http:'
req.build()
expect(req.response.error.code).to.equal('ConfigError')
describe 'SSECustomerKey', ->
it 'encodes strings keys and fills in MD5', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'data'
SSECustomerKey: 'KEY', SSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key']).
to.equal('S0VZ')
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key-MD5']).
to.equal('O1lJ4MJrh3Z6R1Kidt6VcA==')
it 'encodes blob keys and fills in MD5', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'data'
SSECustomerKey: new AWS.util.Buffer('<KEY>', 'hex')
SSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key']).
to.equal('CY9rzUYh03PK3k6DJie09g==')
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key-MD5']).
to.equal('YM1UqSjLvLtue1WVurRqng==')
describe 'CopySourceSSECustomerKey', ->
it 'encodes string keys and fills in MD5', ->
req = s3.copyObject
Bucket: 'bucket', Key: 'key', CopySource: 'bucket/oldkey', Body: 'data'
CopySourceSSECustomerKey: 'KEY', CopySourceSSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key']).
to.equal('S0VZ')
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key-MD5']).
to.equal('O1lJ4MJrh3Z6R1Kidt6VcA==')
it 'encodes blob keys and fills in MD5', ->
req = s3.copyObject
Bucket: 'bucket', Key: 'key', CopySource: 'bucket/oldkey', Body: 'data'
CopySourceSSECustomerKey: new AWS.util.Buffer('098f6bcd4621d373cade4e832627b4f6', 'hex')
CopySourceSSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key']).
to.equal('CY9rzUYh03PK3k6DJie09g==')
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key-MD5']).
to.equal('YM1UqSjLvLtue1WVurRqng==')
describe 'retry behavior', ->
it 'retries RequestTimeout errors', ->
s3.config.maxRetries = 3
helpers.mockHttpResponse 400, {},
'<xml><Code>RequestTimeout</Code><Message>message</Message></xml>'
s3.putObject (err, data) ->
expect(@retryCount).to.equal(s3.config.maxRetries)
# Managed Upload integration point
describe 'upload', ->
it 'accepts parameters in upload() call', ->
helpers.mockResponses [ { data: { ETag: 'ETAG' } } ]
done = false
s3.upload({Bucket: 'bucket', Key: 'key', Body: 'body'}, -> done = true)
expect(done).to.equal(true)
it 'accepts options as a second parameter', ->
helpers.mockResponses [ { data: { ETag: 'ETAG' } } ]
upload = s3.upload({Bucket: 'bucket', Key: 'key', Body: 'body'}, {queueSize: 2}, ->)
expect(upload.queueSize).to.equal(2)
it 'does not send if no callback is supplied', ->
s3.upload(Bucket: 'bucket', Key: 'key', Body: 'body')
describe 'extractData', ->
it 'caches bucket region if found in header', ->
req = request('operation', {Bucket: 'name'})
resp = new AWS.Response(req)
resp.httpResponse.headers = 'x-amz-bucket-region': 'rg-fake-1'
req.emit('extractData', [resp])
expect(s3.bucketRegionCache.name).to.equal('rg-fake-1')
# S3 returns a handful of errors without xml bodies (to match the
# http spec) these tests ensure we give meaningful codes/messages for these.
describe 'errors with no XML body', ->
regionReqOperation = if AWS.util.isNode() then 'headBucket' else 'listObjects'
maxKeysParam = if regionReqOperation == 'listObjects' then 0 else undefined
extractError = (statusCode, body, addHeaders, req) ->
if !req
req = request('operation')
resp = new AWS.Response(req)
resp.httpResponse.body = new Buffer(body || '')
resp.httpResponse.statusCode = statusCode
resp.httpResponse.headers = {'x-amz-request-id': 'RequestId', 'x-amz-id-2': 'ExtendedRequestId'}
for header, value of addHeaders
resp.httpResponse.headers[header] = value
req.emit('extractError', [resp])
resp.error
it 'handles 304 errors', ->
error = extractError(304)
expect(error.code).to.equal('NotModified')
expect(error.message).to.equal(null)
it 'handles 400 errors', ->
error = extractError(400)
expect(error.code).to.equal('BadRequest')
expect(error.message).to.equal(null)
it 'handles 403 errors', ->
error = extractError(403)
expect(error.code).to.equal('Forbidden')
expect(error.message).to.equal(null)
it 'handles 404 errors', ->
error = extractError(404)
expect(error.code).to.equal('NotFound')
expect(error.message).to.equal(null)
it 'extracts the region from body and takes precedence over cache', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
<Region>eu-west-1</Region>
</Error>
"""
error = extractError(400, body, {}, req)
expect(error.region).to.equal('eu-west-1')
expect(s3.bucketRegionCache.name).to.equal('eu-west-1')
it 'extracts the region from header and takes precedence over body and cache', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
<Region>eu-west-1</Region>
</Error>
"""
headers = 'x-amz-bucket-region': 'us-east-1'
error = extractError(400, body, headers, req)
expect(error.region).to.equal('us-east-1')
expect(s3.bucketRegionCache.name).to.equal('us-east-1')
it 'uses cache if region not extracted from body or header', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
</Error>
"""
error = extractError(400, body, {}, req)
expect(error.region).to.equal('us-west-2')
expect(s3.bucketRegionCache.name).to.equal('us-west-2')
it 'does not use cache if not different from current region', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
req.httpRequest.region = 'us-west-2'
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
</Error>
"""
error = extractError(400, body)
expect(error.region).to.not.exist
expect(s3.bucketRegionCache.name).to.equal('us-west-2')
it 'does not make async request for bucket region if error.region is set', ->
regionReq = send: (fn) ->
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>PermanentRedirect</Code>
<Message>Message</Message>
</Error>
"""
headers = 'x-amz-bucket-region': 'us-east-1'
error = extractError(301, body, headers, req)
expect(error.region).to.exist
expect(spy.calls.length).to.equal(0)
expect(regionReq._requestRegionForBucket).to.not.exist
it 'makes async request for bucket region if error.region not set for a region redirect error code', ->
regionReq = send: (fn) ->
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
params = Bucket: 'name'
req = request('operation', params)
body = """
<Error>
<Code>PermanentRedirect</Code>
<Message>Message</Message>
</Error>
"""
error = extractError(301, body, {}, req)
expect(error.region).to.not.exist
expect(spy.calls.length).to.equal(1)
expect(spy.calls[0].arguments[0].Bucket).to.equal('name')
expect(spy.calls[0].arguments[0].MaxKeys).to.equal(maxKeysParam)
expect(regionReq._requestRegionForBucket).to.exist
it 'does not make request for bucket region if error code is not a region redirect code', ->
regionReq = send: (fn) ->
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidCode</Code>
<Message>Message</Message>
</Error>
"""
error = extractError(301, body, {}, req)
expect(error.region).to.not.exist
expect(spy.calls.length).to.equal(0)
expect(regionReq._requestRegionForBucket).to.not.exist
it 'updates error.region if async request adds region to cache', ->
regionReq = send: (fn) ->
s3.bucketRegionCache.name = 'us-west-2'
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>PermanentRedirect</Code>
<Message>Message</Message>
</Error>
"""
error = extractError(301, body, {}, req)
expect(spy.calls.length).to.equal(1)
expect(spy.calls[0].arguments[0].Bucket).to.equal('name')
expect(spy.calls[0].arguments[0].MaxKeys).to.equal(maxKeysParam)
expect(error.region).to.equal('us-west-2')
it 'extracts the request ids', ->
error = extractError(400)
expect(error.requestId).to.equal('RequestId')
expect(error.extendedRequestId).to.equal('ExtendedRequestId')
it 'misc errors not known to return an empty body', ->
error = extractError(412) # made up
expect(error.code).to.equal(412)
expect(error.message).to.equal(null)
it 'uses canned errors only when the body is empty', ->
body = """
<xml>
<Code>ErrorCode</Code>
<Message>ErrorMessage</Message>
</xml>
"""
error = extractError(403, body)
expect(error.code).to.equal('ErrorCode')
expect(error.message).to.equal('ErrorMessage')
describe 'retryableError', ->
it 'should retry on authorization header with updated region', ->
err = {code: 'AuthorizationHeaderMalformed', statusCode:400, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
it 'should retry on bad request with updated region', ->
err = {code: 'BadRequest', statusCode:400, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
it 'should retry on permanent redirect with updated region and endpoint', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'should retry on error code 301 with updated region and endpoint', ->
err = {code: 301, statusCode:301, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'should retry with updated region but not endpoint if non-S3 url endpoint is specified', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(endpoint: 'https://fake-custom-url.com', s3BucketEndpoint: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('fake-custom-url.com')
it 'should retry with updated endpoint if S3 url endpoint is specified', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(endpoint: 'https://name.s3-us-west-2.amazonaws.com', s3BucketEndpoint: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'should retry with updated region but not endpoint if accelerate endpoint is used', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(useAccelerateEndpoint: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-accelerate.amazonaws.com')
it 'should retry with updated endpoint if dualstack endpoint is used', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(useDualstack: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3.dualstack.eu-west-1.amazonaws.com')
it 'should not retry on requests for bucket region once region is obtained', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req._requestRegionForBucket = 'name'
retryable = []
retryable.push s3.retryableError(err, req)
s3.bucketRegionCache.name = 'eu-west-1'
retryable.push s3.retryableError(err, req)
expect(retryable).to.eql([true, false])
describe 'browser NetworkingError due to wrong region', ->
done = ->
spy = null
regionReq = null
callNetworkingErrorListener = (req) ->
if !req
req = request('operation', {Bucket: 'name'})
if req._asm.currentState == 'validate'
req.build()
resp = new AWS.Response(req)
resp.error = code: 'NetworkingError'
s3.reqRegionForNetworkingError(resp, done)
req
beforeEach ->
s3 = new AWS.S3(region: 'us-west-2')
regionReq = request('operation', {Bucket: 'name'})
regionReq.send = (fn) ->
fn()
helpers.spyOn(AWS.util, 'isBrowser').andReturn(true)
spy = helpers.spyOn(s3, 'listObjects').andReturn(regionReq)
it 'updates region to us-east-1 if bucket name not DNS compatible', ->
req = request('operation', {Bucket: 'name!'})
callNetworkingErrorListener(req)
expect(req.httpRequest.region).to.equal('us-east-1')
expect(req.httpRequest.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(s3.bucketRegionCache['name!']).to.equal('us-east-1')
expect(spy.calls.length).to.equal(0)
it 'updates region if cached and not current region', ->
req = request('operation', {Bucket: 'name'})
req.build()
s3.bucketRegionCache.name = 'eu-west-1'
callNetworkingErrorListener(req)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
expect(spy.calls.length).to.equal(0)
it 'makes async request in us-east-1 if not in cache', ->
regionReq.send = (fn) ->
s3.bucketRegionCache.name = 'eu-west-1'
fn()
req = callNetworkingErrorListener()
expect(spy.calls.length).to.equal(1)
expect(regionReq.httpRequest.region).to.equal('us-east-1')
expect(regionReq.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'makes async request in us-east-1 if cached region matches current region', ->
s3.bucketRegionCache.name = 'us-west-2'
regionReq.send = (fn) ->
s3.bucketRegionCache.name = 'eu-west-1'
fn()
req = callNetworkingErrorListener()
expect(spy.calls.length).to.equal(1)
expect(regionReq.httpRequest.region).to.equal('us-east-1')
expect(regionReq.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'does not update region if path-style bucket is dns-compliant and not in cache', ->
s3.config.s3ForcePathStyle = true
regionReq.send = (fn) ->
s3.bucketRegionCache.name = 'eu-west-1'
fn()
req = callNetworkingErrorListener()
expect(spy.calls.length).to.equal(0)
expect(req.httpRequest.region).to.equal('us-west-2')
expect(req.httpRequest.endpoint.hostname).to.equal('s3-us-west-2.amazonaws.com')
# tests from this point on are "special cases" for specific aws operations
describe 'getBucketAcl', ->
it 'correctly parses the ACL XML document', ->
headers = { 'x-amz-request-id' : 'request-id' }
body =
"""
<AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<AccessControlList>
<Grant>
<Grantee xsi:type="CanonicalUser" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Grantee>
<Permission>FULL_CONTROL</Permission>
</Grant>
<Grant>
<Grantee xsi:type="Group" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<URI>uri</URI>
</Grantee>
<Permission>READ</Permission>
</Grant>
</AccessControlList>
<Owner>
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, headers, body
s3.getBucketAcl (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
Owner:
DisplayName: 'aws-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser'
DisplayName: 'aws-sdk'
ID: 'id'
},
{
Permission : 'READ'
Grantee:
Type: 'Group'
URI: 'uri'
}
]
})
describe 'putBucketAcl', ->
it 'correctly builds the ACL XML document', ->
xml =
"""
<AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<AccessControlList>
<Grant>
<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Grantee>
<Permission>FULL_CONTROL</Permission>
</Grant>
<Grant>
<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">
<URI>uri</URI>
</Grantee>
<Permission>READ</Permission>
</Grant>
</AccessControlList>
<Owner>
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, {}, ''
params =
AccessControlPolicy:
Owner:
DisplayName: 'aws-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser',
DisplayName: 'aws-sdk'
ID: 'id'
},
{
Permission : 'READ'
Grantee:
Type: 'Group',
URI: 'uri'
}
]
s3.putBucketAcl params, (err, data) ->
helpers.matchXML(this.request.httpRequest.body, xml)
describe 'completeMultipartUpload', ->
it 'returns data when the resp is 200 with valid response', ->
headers =
'x-amz-id-2': 'Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg=='
'x-amz-request-id': '656c76696e6727732072657175657374'
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<CompleteMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>
<Bucket>Example-Bucket</Bucket>
<Key>Example-Object</Key>
<ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
</CompleteMultipartUploadResult>
"""
helpers.mockHttpResponse 200, headers, body
s3.completeMultipartUpload (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
Location: 'http://Example-Bucket.s3.amazonaws.com/Example-Object'
Bucket: 'Example-Bucket'
Key: 'Example-<KEY>'
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
})
expect(this.requestId).to.equal('656c76696e6727732072657175657374')
it 'returns an error when the resp is 200 with an error xml document', ->
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
<RequestId>656c76696e6727732072657175657374</RequestId>
<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
"""
helpers.mockHttpResponse 200, {}, body
s3.completeMultipartUpload (error, data) ->
expect(error ).to.be.instanceOf(Error)
expect(error.code).to.equal('InternalError')
expect(error.message).to.equal('We encountered an internal error. Please try again.')
expect(error.statusCode).to.equal(200)
expect(error.retryable).to.equal(true)
expect(data).to.equal(null)
describe 'copyObject', ->
it 'returns data when the resp is 200 with valid response', ->
headers =
'x-amz-id-2': 'Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg=='
'x-amz-request-id': '656c76696e6727732072657175657374'
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<CopyObjectResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>
<Bucket>Example-Bucket</Bucket>
<Key>Example-Object</Key>
<ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
</CopyObjectResult>
"""
helpers.mockHttpResponse 200, headers, body
s3.copyObject (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
CopyObjectResult: {
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
}
})
expect(this.requestId).to.equal('656c76696e6727732072657175657374')
it 'returns an error when the resp is 200 with an error xml document', ->
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
<RequestId>656c76696e6727732072657175657374</RequestId>
<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
"""
helpers.mockHttpResponse 200, {}, body
s3.copyObject (error, data) ->
expect(error ).to.be.instanceOf(Error)
expect(error.code).to.equal('InternalError')
expect(error.message).to.equal('We encountered an internal error. Please try again.')
expect(error.statusCode).to.equal(200)
expect(error.retryable).to.equal(true)
expect(data).to.equal(null)
describe 'uploadPartCopy', ->
it 'returns data when the resp is 200 with valid response', ->
headers =
'x-amz-id-2': 'Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg=='
'x-amz-request-id': '656c76696e6727732072657175657374'
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<CopyPartResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>
<Bucket>Example-Bucket</Bucket>
<Key>Example-Object</Key>
<ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
</CopyPartResult>
"""
helpers.mockHttpResponse 200, headers, body
s3.uploadPartCopy {Bucket: 'bucket', Key: 'key', CopySource: 'bucket/key'}, (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
CopyPartResult: {
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
}
})
expect(this.requestId).to.equal('656c76696e6727732072657175657374')
it 'returns an error when the resp is 200 with an error xml document', ->
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
<RequestId>656c76696e6727732072657175657374</RequestId>
<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
"""
helpers.mockHttpResponse 200, {}, body
s3.uploadPartCopy (error, data) ->
expect(error ).to.be.instanceOf(Error)
expect(error.code).to.equal('InternalError')
expect(error.message).to.equal('We encountered an internal error. Please try again.')
expect(error.statusCode).to.equal(200)
expect(error.retryable).to.equal(true)
expect(data).to.equal(null)
describe 'getBucketLocation', ->
it 'returns empty string for the location constraint when not present', ->
body = '<?xml version="1.0" encoding="UTF-8"?>\n<LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>'
helpers.mockHttpResponse 200, {}, body
s3.getBucketLocation (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({LocationConstraint: ''})
it 'parses the location constraint from the root xml', ->
headers = { 'x-amz-request-id': 'abcxyz' }
body = '<?xml version="1.0" encoding="UTF-8"?>\n<LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">EU</LocationConstraint>'
helpers.mockHttpResponse 200, headers, body
s3.getBucketLocation (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql(LocationConstraint: 'EU')
expect(this.requestId).to.equal('abcxyz')
describe 'createBucket', ->
it 'auto-populates the LocationConstraint based on the region', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1')
s3.makeRequest = (op, params) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(Bucket:'name')
expect(loc).to.equal('eu-west-1')
it 'auto-populates the LocationConstraint based on the region when using bound params', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1', Bucket:'name')
s3.makeRequest = (op, params) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(AWS.util.fn.noop)
expect(loc).to.equal('eu-west-1')
it 'auto-populates the LocationConstraint based on the region when using invalid params', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1', Bucket:'name')
s3.makeRequest = (op, params) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(null)
expect(loc).to.equal('eu-west-1')
s3.createBucket(undefined)
expect(loc).to.equal('eu-west-1')
it 'auto-populates the LocationConstraint based on the region when using invalid params and a valid callback', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1', Bucket:'name')
s3.makeRequest = (op, params, cb) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
cb() if typeof cb == 'function'
called = 0
s3.createBucket(undefined, () -> called = 1)
expect(loc).to.equal('eu-west-1')
expect(called).to.equal(1)
it 'caches bucket region based on LocationConstraint upon successful response', ->
s3 = new AWS.S3()
params = Bucket: 'name', CreateBucketConfiguration: LocationConstraint: 'rg-fake-1'
helpers.mockHttpResponse 200, {}, ''
s3.createBucket params, ->
expect(s3.bucketRegionCache.name).to.equal('rg-fake-1')
it 'caches bucket region without LocationConstraint upon successful response', ->
s3 = new AWS.S3(region: 'us-east-1')
params = Bucket: 'name'
helpers.mockHttpResponse 200, {}, ''
s3.createBucket params, ->
expect(params.CreateBucketConfiguration).to.not.exist
expect(s3.bucketRegionCache.name).to.equal('us-east-1')
it 'caches bucket region with LocationConstraint "EU" upon successful response', ->
s3 = new AWS.S3()
params = Bucket: 'name', CreateBucketConfiguration: LocationConstraint: 'EU'
helpers.mockHttpResponse 200, {}, ''
s3.createBucket params, ->
expect(s3.bucketRegionCache.name).to.equal('eu-west-1')
describe 'deleteBucket', ->
it 'removes bucket from region cache on successful response', ->
s3 = new AWS.S3()
params = Bucket: 'name'
s3.bucketRegionCache.name = 'rg-fake-1'
helpers.mockHttpResponse 204, {}, ''
s3.deleteBucket params, ->
expect(s3.bucketRegionCache.name).to.not.exist
AWS.util.each AWS.S3.prototype.computableChecksumOperations, (operation) ->
describe operation, ->
it 'forces Content-MD5 header parameter', ->
req = s3[operation](Bucket: 'bucket', ContentMD5: '000').build()
hash = AWS.util.crypto.md5(req.httpRequest.body, 'base64')
expect(req.httpRequest.headers['Content-MD5']).to.equal(hash)
describe 'willComputeChecksums', ->
willCompute = (operation, opts) ->
compute = opts.computeChecksums
s3 = new AWS.S3(computeChecksums: compute, signatureVersion: 's3')
req = s3.makeRequest(operation, Bucket: 'example', ContentMD5: opts.hash).build()
checksum = req.httpRequest.headers['Content-MD5']
if opts.hash != undefined
if opts.hash == null
expect(checksum).not.to.exist
else
expect(checksum).to.equal(opts.hash)
else
realChecksum = AWS.util.crypto.md5(req.httpRequest.body, 'base64')
expect(checksum).to.equal(realChecksum)
it 'computes checksums if the operation requires it', ->
willCompute 'deleteObjects', computeChecksums: true
willCompute 'putBucketCors', computeChecksums: true
willCompute 'putBucketLifecycle', computeChecksums: true
willCompute 'putBucketLifecycleConfiguration', computeChecksums: true
it 'computes checksums if computeChecksums is off and operation requires it', ->
willCompute 'deleteObjects', computeChecksums: false
willCompute 'putBucketCors', computeChecksums: false
willCompute 'putBucketLifecycle', computeChecksums: false
willCompute 'putBucketLifecycleConfiguration', computeChecksums: false
it 'does not compute checksums if computeChecksums is off', ->
willCompute 'putObject', computeChecksums: false, hash: null
it 'does not compute checksums if computeChecksums is on and ContentMD5 is provided', ->
willCompute 'putBucketAcl', computeChecksums: true, hash: '000'
it 'computes checksums if computeChecksums is on and ContentMD5 is not provided',->
willCompute 'putBucketAcl', computeChecksums: true
if AWS.util.isNode()
it 'does not compute checksums for Stream objects', ->
s3 = new AWS.S3(computeChecksums: true)
req = s3.putObject(Bucket: 'example', Key: 'foo', Body: new Stream.Stream)
expect(req.build(->).httpRequest.headers['Content-MD5']).to.equal(undefined)
it 'throws an error in SigV4, if a non-file stream is provided when body signing enabled', (done) ->
s3 = new AWS.S3({signatureVersion: 'v4', s3DisableBodySigning: false})
req = s3.putObject(Bucket: 'example', Key: 'key', Body: new Stream.Stream)
req.send (err) ->
expect(err.message).to.contain('stream objects are not supported')
done()
it 'does not throw an error in SigV4, if a non-file stream is provided when body signing disabled with ContentLength', (done) ->
s3 = new AWS.S3({signatureVersion: 'v4', s3DisableBodySigning: true})
helpers.mockResponse data: ETag: 'etag'
req = s3.putObject(Bucket: 'example', Key: 'key', Body: new Stream.Stream, ContentLength: 10)
req.send (err) ->
expect(err).not.to.exist
done()
it 'opens separate stream if a file object is provided (signed payload)', (done) ->
hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
helpers.mockResponse data: ETag: 'etag'
fs = require('fs')
mock = helpers.spyOn(fs, 'createReadStream').andCallFake ->
tr = new Stream.Transform
tr._transform = (d,e,c) -> c(null,d)
tr.length = 0
tr.path = 'path/to/file'
tr.push(new Buffer(''))
tr.end()
tr
s3 = new AWS.S3({signatureVersion: 'v4', s3DisableBodySigning: false})
stream = fs.createReadStream('path/to/file')
req = s3.putObject(Bucket: 'example', Key: 'key', Body: stream)
req.send (err) ->
expect(mock.calls[0].arguments).to.eql(['path/to/file'])
expect(mock.calls[1].arguments).to.eql(['path/to/file', {}])
expect(err).not.to.exist
expect(req.httpRequest.headers['X-Amz-Content-Sha256']).to.equal(hash)
done()
it 'opens separate stream with range if a file object is provided', (done) ->
hash = '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
helpers.mockResponse data: ETag: 'etag'
fs = require('fs')
mock = helpers.spyOn(fs, 'createReadStream').andCallFake (path, settings) ->
tr = new Stream.Readable
tr.length = 0
tr.path = 'path/to/file'
tr.start = settings.start
tr.end = settings.end
didRead = false
tr._read = (n) ->
if (didRead)
tr.push(null)
else
didRead = true
tr.push(new Buffer('test'))
tr
s3 = new AWS.S3(signatureVersion: 'v4', s3DisableBodySigning: false)
stream = fs.createReadStream('path/to/file', {start:0, end:5})
req = s3.putObject(Bucket: 'example', Key: 'key', Body: stream)
req.send (err) ->
expect(mock.calls[0].arguments).to.eql(['path/to/file', {start:0, end:5}])
expect(mock.calls[1].arguments).to.eql(['path/to/file', {start:0, end:5}])
expect(err).not.to.exist
expect(req.httpRequest.headers['X-Amz-Content-Sha256']).to.equal(hash)
done()
describe 'getSignedUrl', ->
date = null
beforeEach (done) ->
date = AWS.util.date.getDate
AWS.util.date.getDate = -> new Date(0)
done()
afterEach (done) ->
AWS.util.date.getDate = date
done()
it 'gets a signed URL for getObject', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key')
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=900&Signature=4mlYnRmz%2BBFEPrgYz5tXcl9Wc4w%3D&x-amz-security-token=session')
it 'gets a signed URL with Expires time', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key', Expires: 60)
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=60&Signature=kH2pMK%2Fgm7cCZKVG8GHVTRGXKzY%3D&x-amz-security-token=session')
it 'gets a signed URL with expiration and bound bucket parameters', ->
s3 = new AWS.S3(paramValidation: true, region: undefined, params: Bucket: 'bucket')
url = s3.getSignedUrl('getObject', Key: 'key', Expires: 60)
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=60&Signature=kH2pMK%2Fgm7cCZKVG8GHVTRGXKzY%3D&x-amz-security-token=session')
it 'generates the right URL with a custom endpoint', ->
s3 = new AWS.S3(endpoint: 'https://foo.bar.baz:555/prefix', params: Bucket: 'bucket')
url = s3.getSignedUrl('getObject', Key: 'key', Expires: 60)
expect(url).to.equal('https://bucket.foo.bar.baz:555/prefix/key?AWSAccessKeyId=<KEY>&Expires=60&Signature=zA6k0cQqDkTZgLamfoYLOd%2Bqfg8%3D&x-amz-security-token=session')
it 'gets a signed URL with callback', (done) ->
s3.getSignedUrl 'getObject', Bucket: 'bucket', Key: 'key', (err, url) ->
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=900&Signature=4mlYnRmz%2BBFEPrgYz5tXcl9Wc4w%3D&x-amz-security-token=session')
done()
it 'gets a signed URL for putObject with no body', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key')
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=900&Signature=J%2BnWZ0lPUfLV0kio8ONhJmAttGc%3D&x-amz-security-token=session')
it 'gets a signed URL for putObject with Metadata', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Metadata: {someKey: 'someValue'})
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=900&Signature=5Lcbv0WLGWseQhtmNQ8WwIpX6Kw%3D&x-amz-meta-somekey=someValue&x-amz-security-token=session')
it 'gets a signed URL for putObject with Metadata using Sigv4', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Metadata: {someKey: 'someValue'})
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<KEY>%2F1<KEY>%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=0a1ef336042a7a03b8a2e130ac36097cb1fbab54f8ed5105977a863a5139e679&X-Amz-SignedHeaders=host%3Bx-amz-meta-somekey&x-amz-meta-somekey=someValue')
it 'gets a signed URL for putObject with special characters', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: '!@#$%^&*();\':"{}[],./?`~')
expect(url).to.equal('https://bucket.s3.amazonaws.com/%21%40%23%24%25%5E%26%2A%28%29%3B%27%3A%22%7B%7D%5B%5D%2C./%3F%60~?AWSAccessKeyId=<KEY>&Expires=900&Signature=9nEltJACZKsriZqU2cmRel6g8LQ%3D&x-amz-security-token=session')
it 'gets a signed URL for putObject with a body (and checksum)', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Body: 'body')
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Content-MD5=hBotaJrYa9FhFEdFPCLG%2FA%3D%3D&Expires=900&Signature=4ycA2tpHKxfFnNCdqnK1d5BG8gc%3D&x-amz-security-token=session')
it 'gets a signed URL for putObject with a sse-c algorithm', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', SSECustomerAlgorithm: 'AES256')
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=60b08f91f820fa1c698ac477fec7b5e3cec7b682e09e769e1a55a4d5a3b99077&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption-customer-algorithm&x-amz-server-side-encryption-customer-algorithm=AES256');
it 'gets a signed URL for putObject with a sse-c key', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', SSECustomerAlgorithm: 'AES256', SSECustomerKey: '<KEY>
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=e4f57734798fdadc0b2b43ca5a5e1f28824786c3ac74c30d7abb77d6ef59b0da&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption-customer-algorithm%3Bx-amz-server-side-encryption-customer-key%3Bx-amz-server-side-encryption-customer-key-md5&x-amz-server-side-encryption-customer-algorithm=AES256&x-amz-server-side-encryption-customer-key=YzJGdGNHeGxJR3RsZVhOaGJYQnNaU0JyWlhsellXMXdiR1<KEY>J<KEY>RT0%3D&x-amz-server-side-encryption-customer-key-MD5=VzaXhwL7H9upBc%2Fb9UqH8g%3D%3D');
it 'gets a signed URL for putObject with CacheControl', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', CacheControl: 'max-age=10000')
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?Cache-Control=max-age%3D10000&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=39ad1f8dc3aa377c2b184a0be7657dfb606628c74796c1a48394ef134ff6233a&X-Amz-SignedHeaders=cache-control%3Bhost')
it 'gets a signed URL and appends to existing query parameters', ->
url = s3.getSignedUrl('listObjects', Bucket: 'bucket', Prefix: 'prefix')
expect(url).to.equal('https://bucket.s3.amazonaws.com/?AWSAccessKeyId=<KEY>&Expires=900&Signature=8W3pwZPfgucCyPNg1MsoYq8h5zw%3D&prefix=prefix&x-amz-security-token=session')
it 'gets a signed URL for getObject using SigV4', ->
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'object')
expect(url).to.equal('https://bucket.s3.amazonaws.com/object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=05ae40d2d22c93549a1de0686232ff56baf556876ec497d0d8349431f98b8dfe&X-Amz-SignedHeaders=host')
it 'gets a signed URL for putObject using SigV4', ->
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'object')
expect(url).to.equal('https://bucket.s3.amazonaws.com/object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=1b6f75301a2e480bcfbb53d47d8940c28c8657ea70f23c24846a5595a53b1dfe&X-Amz-SignedHeaders=host')
it 'gets a signed URL for putObject using SigV4 with body', ->
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'object', Body: 'foo')
expect(url).to.equal('https://bucket.s3.amazonaws.com/object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae&X-Amz-Credential=akid%2F19700101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=600a64aff20c4ea6c28d11fd0639fb33a0107d072f4c2dd1ea38a16d057513f3&X-Amz-SignedHeaders=host%3Bx-amz-content-sha256')
it 'errors when expiry time is greater than a week out on SigV4', (done) ->
err = null; data = null
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
params = Bucket: 'bucket', Key: '<KEY>', Expires: 60 * 60 * 24 * 7 + 120
error = 'Presigning does not support expiry time greater than a week with SigV4 signing.'
s3.getSignedUrl 'getObject', params, (err, data) ->
expect(err).not.to.equal(null)
expect(err.message).to.equal(error)
#expect(-> s3.getSignedUrl('getObject', params)).to.throw(error) # sync mode
done()
it 'errors if ContentLength is passed as parameter', ->
expect(-> s3.getSignedUrl('putObject',
Bucket: 'bucket'
Key: 'key'
ContentLength: 5
)).to.throw(/ContentLength is not supported in pre-signed URLs/)
describe 'createPresignedPost', ->
it 'should include a url and a hash of form fields', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data).to.include.keys('fields', 'url')
expect(data.url).to.be.a.string
expect(data.fields).to.be.an.object
done()
it 'should include a policy, signature, and signing metadata', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data.fields).to.include.keys(
'Policy',
'X-Amz-Signature',
'X-Amz-Algorithm',
'X-Amz-Date',
'X-Amz-Credential'
)
done()
it 'should specify the signing algorithm used', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data.fields['X-Amz-Algorithm']).to.equal('AWS4-HMAC-SHA256')
done()
it 'should use bound parameters for the bucket name', (done) ->
s3 = new AWS.S3(params: {Bucket: 'bucket'})
s3.createPresignedPost {}, (err, data) ->
expect(data.fields).to.include.keys('bucket')
expect(data.fields.bucket).to.equal('bucket')
done()
it 'should include the security token when present', (done) ->
token = '<KEY>'
credentials =
accessKeyId: '<KEY>'
secretAccessKey: '<KEY>'
sessionToken: token
s3 = new AWS.S3(credentials: credentials)
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data.fields['X-Amz-Security-Token']).to.equal(token)
done()
it 'should provide a base64-encoded JSON policy document', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expect(decoded).to.be.an.object
expect(decoded).to.include.key('expiration', 'conditions')
done()
it 'should default to expiration in one hour', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expiration = new Date(decoded.expiration)
validForMs = expiration.valueOf() - (new Date()).valueOf()
# allow one second of leeway
expect(validForMs).to.be.above((60 * 60 - 1) * 1000)
expect(validForMs).to.be.below((60 * 60 + 1) * 1000)
done()
it 'should allow users to provide a custom expiration', (done) ->
customTtl = 900
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket', Expires: customTtl}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expiration = new Date(decoded.expiration)
validForMs = expiration.valueOf() - (new Date()).valueOf()
# allow one second of leeway
expect(validForMs).to.be.above((customTtl - 1) * 1000)
expect(validForMs).to.be.below((customTtl + 1) * 1000)
done()
it 'should include signature metadata as conditions', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expect(decoded.conditions).to.be.an.array
found = {}
for index, condition of decoded.conditions
conditionKey = Object.keys(condition)[0]
found[conditionKey] = true
expect(condition[conditionKey]).to.equal(data.fields[conditionKey])
expect(found['X-Amz-Algorithm']).to.be.true
expect(found['X-Amz-Date']).to.be.true
expect(found['X-Amz-Credential']).to.be.true
done()
it 'should include user-provided conditions in the signed policy', (done) ->
s3 = new AWS.S3()
conditions = [
{'x-amz-server-side-encryption': 'AES256'},
['starts-with', '$x-amz-meta-tag', ''],
{'acl': 'public-read'}
]
s3.createPresignedPost {Bucket: 'bucket', Conditions: conditions}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expect(decoded.conditions).to.be.an.array
expect(conditions[0]).to.deep.equal(decoded.conditions[0])
expect(conditions[1]).to.deep.equal(decoded.conditions[1])
expect(conditions[2]).to.deep.equal(decoded.conditions[2])
done()
it 'should include user-provided fields as policy conditions', (done) ->
s3 = new AWS.S3()
fieldsToInclude =
key: '<KEY>'
acl: 'public-read',
'Content-Type': 'image/jpeg',
'x-amz-meta-foo': 'bar',
'x-amz-tagging': '''<Tagging>
<TagSet>
<Tag>
<Key>foo</Key>
<Value>bar</Value>
</Tag>
</TagSet>
</Tagging>'''
s3.createPresignedPost {Bucket: 'bucket', Fields: fieldsToInclude}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
conditions = {}
decoded.conditions.forEach((condition) ->
if typeof condition == 'object'
conditionKey = Object.keys(condition)[0]
conditions[conditionKey] = condition[conditionKey]
)
Object.keys(fieldsToInclude).forEach((key) ->
expect(data.fields[key]).to.equal(fieldsToInclude[key])
expect(data.fields[key]).to.equal(conditions[key])
)
done()
| true | helpers = require('../helpers')
AWS = helpers.AWS
Stream = AWS.util.stream
Buffer = AWS.util.Buffer
describe 'AWS.S3', ->
s3 = null
request = (operation, params) -> s3.makeRequest(operation, params)
beforeEach (done) ->
s3 = new AWS.S3(region: undefined)
s3.clearBucketRegionCache()
done()
describe 'dnsCompatibleBucketName', ->
it 'must be at least 3 characters', ->
expect(s3.dnsCompatibleBucketName('aa')).to.equal(false)
it 'must not be longer than 63 characters', ->
b = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
expect(s3.dnsCompatibleBucketName(b)).to.equal(false)
it 'must start with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('Abc')).to.equal(false)
expect(s3.dnsCompatibleBucketName('-bc')).to.equal(false)
expect(s3.dnsCompatibleBucketName('abc')).to.equal(true)
it 'must end with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('abC')).to.equal(false)
expect(s3.dnsCompatibleBucketName('ab-')).to.equal(false)
expect(s3.dnsCompatibleBucketName('abc')).to.equal(true)
it 'may not contain multiple contiguous dots', ->
expect(s3.dnsCompatibleBucketName('abc.123')).to.equal(true)
expect(s3.dnsCompatibleBucketName('abc..123')).to.equal(false)
it 'may only contain letters numbers and dots', ->
expect(s3.dnsCompatibleBucketName('abc123')).to.equal(true)
expect(s3.dnsCompatibleBucketName('abc_123')).to.equal(false)
it 'must not look like an ip address', ->
expect(s3.dnsCompatibleBucketName('PI:IP_ADDRESS:172.16.58.3END_PI')).to.equal(false)
expect(s3.dnsCompatibleBucketName('a.b.c.d')).to.equal(true)
describe 'constructor', ->
it 'requires endpoint if s3BucketEndpoint is passed', ->
expect(-> new AWS.S3(s3BucketEndpoint: true)).to.throw(
/An endpoint must be provided/)
describe 'endpoint', ->
it 'sets hostname to s3.amazonaws.com when region is un-specified', ->
s3 = new AWS.S3(region: undefined)
expect(s3.endpoint.hostname).to.equal('s3.amazonaws.com')
it 'sets hostname to s3.amazonaws.com when region is us-east-1', ->
s3 = new AWS.S3(region: 'us-east-1')
expect(s3.endpoint.hostname).to.equal('s3.amazonaws.com')
it 'sets region to us-east-1 when unspecified', ->
s3 = new AWS.S3(region: 'us-east-1')
expect(s3.config.region).to.equal('us-east-1')
it 'combines the region with s3 in the endpoint using a - instead of .', ->
s3 = new AWS.S3(region: 'us-west-1')
expect(s3.endpoint.hostname).to.equal('s3-us-west-1.amazonaws.com')
it 'sets a region-specific dualstack endpoint when dualstack enabled', ->
s3 = new AWS.S3(region: 'us-west-1', useDualstack: true)
expect(s3.endpoint.hostname).to.equal('s3.dualstack.us-west-1.amazonaws.com')
s3 = new AWS.S3(region: 'us-east-1', useDualstack: true)
expect(s3.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
describe 'clearing bucket region cache', ->
beforeEach ->
s3.bucketRegionCache = a: 'rg-fake-1', b: 'rg-fake-2', c: 'rg-fake-3'
it 'clears one bucket name', ->
s3.clearBucketRegionCache 'b'
expect(s3.bucketRegionCache).to.eql(a: 'rg-fake-1', c: 'rg-fake-3')
it 'clears a list of bucket names', ->
s3.clearBucketRegionCache ['a', 'c']
expect(s3.bucketRegionCache).to.eql(b: 'rg-fake-2')
it 'clears entire cache', ->
s3.clearBucketRegionCache()
expect(s3.bucketRegionCache).to.eql({})
describe 'getSignerClass', ->
getVersion = (signer) ->
if (signer == AWS.Signers.S3)
return 's3'
else if (signer == AWS.Signers.V4)
return 'v4'
else if (signer == AWS.Signers.V2)
return 'v2'
describe 'when using presigned requests', ->
req = null
beforeEach (done) ->
req = request('mock')
helpers.spyOn(req, 'isPresigned').andReturn(true)
done()
describe 'will return an s3 (v2) signer when', ->
it 'user does not specify a signatureVersion for a region that supports v2', (done) ->
s3 = new AWS.S3(region: 'us-east-1')
expect(getVersion(s3.getSignerClass(req))).to.equal('s3')
done()
it 'user specifies a signatureVersion of s3', (done) ->
s3 = new AWS.S3(signatureVersion: 's3')
expect(getVersion(s3.getSignerClass(req))).to.equal('s3')
done()
it 'user specifies a signatureVersion of v2', (done) ->
s3 = new AWS.S3(signatureVersion: 'v2')
expect(getVersion(s3.getSignerClass(req))).to.equal('s3')
done()
describe 'will return a v4 signer when', ->
it 'user does not specify a signatureVersion for a region that supports only v4', (done) ->
s3 = new AWS.S3(region: 'eu-central-1')
expect(getVersion(s3.getSignerClass(req))).to.equal('v4')
done()
it 'user specifies a signatureVersion of v4', (done) ->
s3 = new AWS.S3(signatureVersion: 'v4')
expect(getVersion(s3.getSignerClass(req))).to.equal('v4')
done()
describe 'when not using presigned requests', ->
describe 'will return an s3 (v2) signer when', ->
it 'user specifies a signatureVersion of s3', (done) ->
s3 = new AWS.S3(signatureVersion: 's3')
expect(getVersion(s3.getSignerClass())).to.equal('s3')
done()
it 'user specifies a signatureVersion of v2', (done) ->
s3 = new AWS.S3(signatureVersion: 'v2')
expect(getVersion(s3.getSignerClass())).to.equal('s3')
done()
it 'user does not specify a signatureVersion and region supports v2', (done) ->
s3 = new AWS.S3({region: 'us-east-1'})
expect(getVersion(s3.getSignerClass())).to.equal('s3')
done()
describe 'will return a v4 signer when', ->
it 'user does not specify a signatureVersion and region only supports v4', (done) ->
s3 = new AWS.S3({region: 'eu-central-1'})
expect(getVersion(s3.getSignerClass())).to.equal('v4')
done()
it 'user specifies a signatureVersion of v4', (done) ->
s3 = new AWS.S3(signatureVersion: 'v4')
expect(getVersion(s3.getSignerClass())).to.equal('v4')
done()
describe 'building a request', ->
build = (operation, params) ->
request(operation, params).build().httpRequest
it 'obeys the configuration for s3ForcePathStyle', ->
config = new AWS.Config(s3ForcePathStyle: true, accessKeyId: 'PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI')
s3 = new AWS.S3(config)
expect(s3.config.s3ForcePathStyle).to.equal(true)
req = build('headObject', {Bucket:'bucket', Key:'key'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket/key')
it 'does not enable path style if endpoint is a bucket', ->
s3 = new AWS.S3(endpoint: 'foo.bar', s3BucketEndpoint: true)
req = build('listObjects', Bucket: 'bucket')
expect(req.endpoint.hostname).to.equal('foo.bar')
expect(req.path).to.equal('/')
expect(req.virtualHostedBucket).to.equal('bucket')
it 'allows user override if an endpoint is specified', ->
s3 = new AWS.S3(endpoint: 'foo.bar', s3ForcePathStyle: true)
req = build('listObjects', Bucket: 'bucket')
expect(req.endpoint.hostname).to.equal('foo.bar')
expect(req.path).to.equal('/bucket')
it 'does not allow non-bucket operations with s3BucketEndpoint set', ->
s3 = new AWS.S3(endpoint: 'foo.bar', s3BucketEndpoint: true, paramValidation: true)
req = s3.listBuckets().build()
expect(req.response.error.code).to.equal('ConfigError')
it 'corrects virtual-hosted bucket region on request if bucket region stored in cache', ->
s3 = new AWS.S3(region: 'us-east-1')
s3.bucketRegionCache.name = 'us-west-2'
param = Bucket: 'name'
req = s3.headBucket(param).build()
httpRequest = req.httpRequest
expect(httpRequest.region).to.equal('us-west-2')
expect(httpRequest.endpoint.hostname).to.equal('name.s3-us-west-2.amazonaws.com')
expect(httpRequest.headers.Host).to.equal('name.s3-us-west-2.amazonaws.com')
expect(httpRequest.path).to.equal('/')
it 'corrects path-style bucket region on request if bucket region stored in cache', ->
s3 = new AWS.S3(region: 'us-east-1', s3ForcePathStyle: true)
s3.bucketRegionCache.name = 'us-west-2'
param = Bucket: 'name'
req = s3.headBucket(param).build()
httpRequest = req.httpRequest
expect(httpRequest.region).to.equal('us-west-2')
expect(httpRequest.endpoint.hostname).to.equal('s3-us-west-2.amazonaws.com')
expect(httpRequest.headers.Host).to.equal('s3-us-west-2.amazonaws.com')
expect(httpRequest.path).to.equal('/name')
describe 'with useAccelerateEndpoint set to true', ->
beforeEach ->
s3 = new AWS.S3(useAccelerateEndpoint: true)
it 'changes the hostname to use s3-accelerate for dns-comaptible buckets', ->
req = build('getObject', {Bucket: 'foo', Key: 'PI:KEY:<KEY>END_PI'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.amazonaws.com')
it 'overrides s3BucketEndpoint configuration when s3BucketEndpoint is set', ->
s3 = new AWS.S3(useAccelerateEndpoint: true, s3BucketEndpoint: true, endpoint: 'foo.region.amazonaws.com')
req = build('getObject', {Bucket: 'foo', Key: 'PI:KEY:<KEY>END_PI'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.amazonaws.com')
describe 'does not use s3-accelerate.dualstack or s3-accelerate', ->
it 'on dns-incompatible buckets', ->
req = build('getObject', {Bucket: 'foo.baz', Key: 'bar'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
it 'on excluded operations', ->
req = build('listBuckets')
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('createBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('deleteBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
describe 'with useAccelerateEndpoint and dualstack set to true', ->
beforeEach ->
s3 = new AWS.S3(useAccelerateEndpoint: true, useDualstack: true)
it 'changes the hostname to use s3-accelerate for dns-comaptible buckets', ->
req = build('getObject', {Bucket: 'foo', Key: 'bar'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.dualstack.amazonaws.com')
it 'overrides s3BucketEndpoint configuration when s3BucketEndpoint is set', ->
s3 = new AWS.S3(useAccelerateEndpoint: true, useDualstack: true, s3BucketEndpoint: true, endpoint: 'foo.region.amazonaws.com')
req = build('getObject', {Bucket: 'foo', Key: 'baz'})
expect(req.endpoint.hostname).to.equal('foo.s3-accelerate.dualstack.amazonaws.com')
describe 'does not use s3-accelerate.dualstack or s3-accelerate', ->
it 'on dns-incompatible buckets', ->
req = build('getObject', {Bucket: 'foo.baz', Key: 'bar'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
it 'on excluded operations', ->
req = build('listBuckets')
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('createBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
req = build('deleteBucket', {Bucket: 'foo'})
expect(req.endpoint.hostname).to.not.contain('s3-accelerate')
describe 'uri escaped params', ->
it 'uri-escapes path and querystring params', ->
# bucket param ends up as part of the hostname
params = { Bucket: 'bucket', Key: 'PI:KEY:<KEY>END_PI', VersionId: 'a&b' }
req = build('headObject', params)
expect(req.path).to.equal('/a%20b%20c?versionId=a%26b')
it 'does not uri-escape forward slashes in the path', ->
params = { Bucket: 'bucket', Key: 'k e/y' }
req = build('headObject', params)
expect(req.path).to.equal('/k%20e/y')
it 'ensures a single forward slash exists', ->
req = build('listObjects', { Bucket: 'bucket' })
expect(req.path).to.equal('/')
req = build('listObjects', { Bucket: 'bucket', MaxKeys:123 })
expect(req.path).to.equal('/?max-keys=123')
describe 'adding Expect: 100-continue', ->
if AWS.util.isNode()
it 'does not add expect header to payloads less than 1MB', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024 * 1024 - 1))
expect(req.headers['Expect']).not.to.exist
it 'adds expect header to payloads greater than 1MB', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024 * 1024 + 1))
expect(req.headers['Expect']).to.equal('100-continue')
if AWS.util.isBrowser()
beforeEach -> helpers.spyOn(AWS.util, 'isBrowser').andReturn(true)
it 'does not add expect header in the browser', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024 * 1024 + 1))
expect(req.headers['Expect']).not.to.exist
describe 'with s3DisableBodySigning set to true', ->
it 'will disable body signing when using signature version 4 and the endpoint uses https', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 'v4')
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.equal('UNSIGNED-PAYLOAD')
it 'will compute contentMD5', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 'v4')
buf = new Buffer(1024*1024*5)
buf.fill(0)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: buf)
expect(req.headers['Content-MD5']).to.equal('XzY+DlipXwbL6bvGYsXftg==')
it 'will not disable body signing when the endpoint is not https', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 'v4', sslEnabled: false)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.exist
expect(req.headers['X-Amz-Content-Sha256']).to.not.equal('UNSIGNED-PAYLOAD')
it 'will have no effect when sigv2 signing is used', ->
s3 = new AWS.S3(s3DisableBodySigning: true, signatureVersion: 's3', sslEnabled: true)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.not.exist
describe 'with s3DisableBodySigning set to false', ->
it 'will sign the body when sigv4 is used', ->
s3 = new AWS.S3(s3DisableBodySigning: false, signatureVersion: 'v4')
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.exist
expect(req.headers['X-Amz-Cotnent-Sha256']).to.not.equal('UNSIGNED-PAYLOAD')
it 'will have no effect when sigv2 signing is used', ->
s3 = new AWS.S3(s3DisableBodySigning: false, signatureVersion: 's3', sslEnabled: true)
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer(1024*1024*5))
expect(req.headers['X-Amz-Content-Sha256']).to.not.exist
describe 'adding Content-Type', ->
beforeEach -> helpers.spyOn(AWS.util, 'isBrowser').andReturn(true)
it 'adds default content-type when not supplied', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: 'body')
expect(req.headers['Content-Type']).to.equal('application/octet-stream; charset=UTF-8')
it 'does not add content-type for GET/HEAD requests', ->
req = build('getObject', Bucket: 'bucket', Key: 'key')
expect(req.headers['Content-Type']).not.to.exist
req = build('headObject', Bucket: 'bucket', Key: 'key')
expect(req.headers['Content-Type']).not.to.exist
it 'adds charset to existing content-type if not supplied', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: 'body', ContentType: 'text/html')
expect(req.headers['Content-Type']).to.equal('text/html; charset=UTF-8')
it 'normalized charset to uppercase', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: 'body', ContentType: 'text/html; charset=utf-8')
expect(req.headers['Content-Type']).to.equal('text/html; charset=UTF-8')
it 'does not add charset to non-string data', ->
req = build('putObject', Bucket: 'bucket', Key: 'key', Body: new Buffer('body'), ContentType: 'image/png')
expect(req.headers['Content-Type']).to.equal('image/png')
describe 'virtual-hosted vs path-style bucket requests', ->
describe 'HTTPS', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: true, region: undefined)
it 'puts dns-compat bucket names in the hostname', ->
req = build('headObject', {Bucket:'bucket-name',Key:'abc'})
expect(req.method).to.equal('HEAD')
expect(req.endpoint.hostname).to.equal('bucket-name.s3.amazonaws.com')
expect(req.path).to.equal('/abc')
it 'ensures the path contains / at a minimum when moving bucket', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in path if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket.name')
it 'puts dns-compat bucket names in path if configured to do so', ->
s3 = new AWS.S3(sslEnabled: true, s3ForcePathStyle: true, region: undefined)
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket-name')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'HTTP', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: false, region: undefined)
it 'puts dns-compat bucket names in the hostname', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in the hostname if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('bucket.name.s3.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'HTTPS dualstack', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: true, region: undefined, useDualstack: true)
it 'puts dns-compat bucket names in the hostname', ->
req = build('headObject', {Bucket:'bucket-name',Key:'PI:KEY:<KEY>END_PI'})
expect(req.method).to.equal('HEAD')
expect(req.endpoint.hostname).to.equal('bucket-name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/abc')
it 'ensures the path contains / at a minimum when moving bucket', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in path if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket.name')
it 'puts dns-compat bucket names in path if configured to do so', ->
s3 = new AWS.S3(sslEnabled: true, s3ForcePathStyle: true, region: undefined, useDualstack: true)
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket-name')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'HTTP dualstack', ->
beforeEach ->
s3 = new AWS.S3(sslEnabled: false, region: undefined, useDualstack: true)
it 'puts dns-compat bucket names in the hostname', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).to.equal('bucket-name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-compat bucket names in the hostname if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).to.equal('bucket.name.s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).to.equal('s3.dualstack.us-east-1.amazonaws.com')
expect(req.path).to.equal('/bucket_name')
describe 'SSE support', ->
beforeEach -> s3 = new AWS.S3
it 'fails if the scheme is not HTTPS: when SSECustomerKey is provided', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'object'
SSECustomerKey: 'sse-key', SSECustomerAlgorithm: 'AES256'
req.httpRequest.endpoint.protocol = 'http:'
req.build()
expect(req.response.error.code).to.equal('ConfigError')
it 'fails if the scheme is not HTTPS: when CopySourceSSECustomerKey is provided', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'object'
CopySourceSSECustomerKey: 'sse-key', CopySourceSSECustomerAlgorithm: 'AES256'
req.httpRequest.endpoint.protocol = 'http:'
req.build()
expect(req.response.error.code).to.equal('ConfigError')
describe 'SSECustomerKey', ->
it 'encodes strings keys and fills in MD5', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'data'
SSECustomerKey: 'KEY', SSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key']).
to.equal('S0VZ')
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key-MD5']).
to.equal('O1lJ4MJrh3Z6R1Kidt6VcA==')
it 'encodes blob keys and fills in MD5', ->
req = s3.putObject
Bucket: 'bucket', Key: 'key', Body: 'data'
SSECustomerKey: new AWS.util.Buffer('PI:KEY:<KEY>END_PI', 'hex')
SSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key']).
to.equal('CY9rzUYh03PK3k6DJie09g==')
expect(req.httpRequest.headers['x-amz-server-side-encryption-customer-key-MD5']).
to.equal('YM1UqSjLvLtue1WVurRqng==')
describe 'CopySourceSSECustomerKey', ->
it 'encodes string keys and fills in MD5', ->
req = s3.copyObject
Bucket: 'bucket', Key: 'key', CopySource: 'bucket/oldkey', Body: 'data'
CopySourceSSECustomerKey: 'KEY', CopySourceSSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key']).
to.equal('S0VZ')
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key-MD5']).
to.equal('O1lJ4MJrh3Z6R1Kidt6VcA==')
it 'encodes blob keys and fills in MD5', ->
req = s3.copyObject
Bucket: 'bucket', Key: 'key', CopySource: 'bucket/oldkey', Body: 'data'
CopySourceSSECustomerKey: new AWS.util.Buffer('098f6bcd4621d373cade4e832627b4f6', 'hex')
CopySourceSSECustomerAlgorithm: 'AES256'
req.build()
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key']).
to.equal('CY9rzUYh03PK3k6DJie09g==')
expect(req.httpRequest.headers['x-amz-copy-source-server-side-encryption-customer-key-MD5']).
to.equal('YM1UqSjLvLtue1WVurRqng==')
describe 'retry behavior', ->
it 'retries RequestTimeout errors', ->
s3.config.maxRetries = 3
helpers.mockHttpResponse 400, {},
'<xml><Code>RequestTimeout</Code><Message>message</Message></xml>'
s3.putObject (err, data) ->
expect(@retryCount).to.equal(s3.config.maxRetries)
# Managed Upload integration point
describe 'upload', ->
it 'accepts parameters in upload() call', ->
helpers.mockResponses [ { data: { ETag: 'ETAG' } } ]
done = false
s3.upload({Bucket: 'bucket', Key: 'key', Body: 'body'}, -> done = true)
expect(done).to.equal(true)
it 'accepts options as a second parameter', ->
helpers.mockResponses [ { data: { ETag: 'ETAG' } } ]
upload = s3.upload({Bucket: 'bucket', Key: 'key', Body: 'body'}, {queueSize: 2}, ->)
expect(upload.queueSize).to.equal(2)
it 'does not send if no callback is supplied', ->
s3.upload(Bucket: 'bucket', Key: 'key', Body: 'body')
describe 'extractData', ->
it 'caches bucket region if found in header', ->
req = request('operation', {Bucket: 'name'})
resp = new AWS.Response(req)
resp.httpResponse.headers = 'x-amz-bucket-region': 'rg-fake-1'
req.emit('extractData', [resp])
expect(s3.bucketRegionCache.name).to.equal('rg-fake-1')
# S3 returns a handful of errors without xml bodies (to match the
# http spec) these tests ensure we give meaningful codes/messages for these.
describe 'errors with no XML body', ->
regionReqOperation = if AWS.util.isNode() then 'headBucket' else 'listObjects'
maxKeysParam = if regionReqOperation == 'listObjects' then 0 else undefined
extractError = (statusCode, body, addHeaders, req) ->
if !req
req = request('operation')
resp = new AWS.Response(req)
resp.httpResponse.body = new Buffer(body || '')
resp.httpResponse.statusCode = statusCode
resp.httpResponse.headers = {'x-amz-request-id': 'RequestId', 'x-amz-id-2': 'ExtendedRequestId'}
for header, value of addHeaders
resp.httpResponse.headers[header] = value
req.emit('extractError', [resp])
resp.error
it 'handles 304 errors', ->
error = extractError(304)
expect(error.code).to.equal('NotModified')
expect(error.message).to.equal(null)
it 'handles 400 errors', ->
error = extractError(400)
expect(error.code).to.equal('BadRequest')
expect(error.message).to.equal(null)
it 'handles 403 errors', ->
error = extractError(403)
expect(error.code).to.equal('Forbidden')
expect(error.message).to.equal(null)
it 'handles 404 errors', ->
error = extractError(404)
expect(error.code).to.equal('NotFound')
expect(error.message).to.equal(null)
it 'extracts the region from body and takes precedence over cache', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
<Region>eu-west-1</Region>
</Error>
"""
error = extractError(400, body, {}, req)
expect(error.region).to.equal('eu-west-1')
expect(s3.bucketRegionCache.name).to.equal('eu-west-1')
it 'extracts the region from header and takes precedence over body and cache', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
<Region>eu-west-1</Region>
</Error>
"""
headers = 'x-amz-bucket-region': 'us-east-1'
error = extractError(400, body, headers, req)
expect(error.region).to.equal('us-east-1')
expect(s3.bucketRegionCache.name).to.equal('us-east-1')
it 'uses cache if region not extracted from body or header', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
</Error>
"""
error = extractError(400, body, {}, req)
expect(error.region).to.equal('us-west-2')
expect(s3.bucketRegionCache.name).to.equal('us-west-2')
it 'does not use cache if not different from current region', ->
s3.bucketRegionCache.name = 'us-west-2'
req = request('operation', {Bucket: 'name'})
req.httpRequest.region = 'us-west-2'
body = """
<Error>
<Code>InvalidArgument</Code>
<Message>Provided param is bad</Message>
</Error>
"""
error = extractError(400, body)
expect(error.region).to.not.exist
expect(s3.bucketRegionCache.name).to.equal('us-west-2')
it 'does not make async request for bucket region if error.region is set', ->
regionReq = send: (fn) ->
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>PermanentRedirect</Code>
<Message>Message</Message>
</Error>
"""
headers = 'x-amz-bucket-region': 'us-east-1'
error = extractError(301, body, headers, req)
expect(error.region).to.exist
expect(spy.calls.length).to.equal(0)
expect(regionReq._requestRegionForBucket).to.not.exist
it 'makes async request for bucket region if error.region not set for a region redirect error code', ->
regionReq = send: (fn) ->
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
params = Bucket: 'name'
req = request('operation', params)
body = """
<Error>
<Code>PermanentRedirect</Code>
<Message>Message</Message>
</Error>
"""
error = extractError(301, body, {}, req)
expect(error.region).to.not.exist
expect(spy.calls.length).to.equal(1)
expect(spy.calls[0].arguments[0].Bucket).to.equal('name')
expect(spy.calls[0].arguments[0].MaxKeys).to.equal(maxKeysParam)
expect(regionReq._requestRegionForBucket).to.exist
it 'does not make request for bucket region if error code is not a region redirect code', ->
regionReq = send: (fn) ->
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>InvalidCode</Code>
<Message>Message</Message>
</Error>
"""
error = extractError(301, body, {}, req)
expect(error.region).to.not.exist
expect(spy.calls.length).to.equal(0)
expect(regionReq._requestRegionForBucket).to.not.exist
it 'updates error.region if async request adds region to cache', ->
regionReq = send: (fn) ->
s3.bucketRegionCache.name = 'us-west-2'
fn()
spy = helpers.spyOn(s3, regionReqOperation).andReturn(regionReq)
req = request('operation', {Bucket: 'name'})
body = """
<Error>
<Code>PermanentRedirect</Code>
<Message>Message</Message>
</Error>
"""
error = extractError(301, body, {}, req)
expect(spy.calls.length).to.equal(1)
expect(spy.calls[0].arguments[0].Bucket).to.equal('name')
expect(spy.calls[0].arguments[0].MaxKeys).to.equal(maxKeysParam)
expect(error.region).to.equal('us-west-2')
it 'extracts the request ids', ->
error = extractError(400)
expect(error.requestId).to.equal('RequestId')
expect(error.extendedRequestId).to.equal('ExtendedRequestId')
it 'misc errors not known to return an empty body', ->
error = extractError(412) # made up
expect(error.code).to.equal(412)
expect(error.message).to.equal(null)
it 'uses canned errors only when the body is empty', ->
body = """
<xml>
<Code>ErrorCode</Code>
<Message>ErrorMessage</Message>
</xml>
"""
error = extractError(403, body)
expect(error.code).to.equal('ErrorCode')
expect(error.message).to.equal('ErrorMessage')
describe 'retryableError', ->
it 'should retry on authorization header with updated region', ->
err = {code: 'AuthorizationHeaderMalformed', statusCode:400, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
it 'should retry on bad request with updated region', ->
err = {code: 'BadRequest', statusCode:400, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
it 'should retry on permanent redirect with updated region and endpoint', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'should retry on error code 301 with updated region and endpoint', ->
err = {code: 301, statusCode:301, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'should retry with updated region but not endpoint if non-S3 url endpoint is specified', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(endpoint: 'https://fake-custom-url.com', s3BucketEndpoint: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('fake-custom-url.com')
it 'should retry with updated endpoint if S3 url endpoint is specified', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(endpoint: 'https://name.s3-us-west-2.amazonaws.com', s3BucketEndpoint: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'should retry with updated region but not endpoint if accelerate endpoint is used', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(useAccelerateEndpoint: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-accelerate.amazonaws.com')
it 'should retry with updated endpoint if dualstack endpoint is used', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
s3 = new AWS.S3(useDualstack: true)
req = request('operation', {Bucket: 'name'})
req.build()
retryable = s3.retryableError(err, req)
expect(retryable).to.equal(true)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3.dualstack.eu-west-1.amazonaws.com')
it 'should not retry on requests for bucket region once region is obtained', ->
err = {code: 'PermanentRedirect', statusCode:301, region: 'eu-west-1'}
req = request('operation', {Bucket: 'name'})
req._requestRegionForBucket = 'name'
retryable = []
retryable.push s3.retryableError(err, req)
s3.bucketRegionCache.name = 'eu-west-1'
retryable.push s3.retryableError(err, req)
expect(retryable).to.eql([true, false])
describe 'browser NetworkingError due to wrong region', ->
done = ->
spy = null
regionReq = null
callNetworkingErrorListener = (req) ->
if !req
req = request('operation', {Bucket: 'name'})
if req._asm.currentState == 'validate'
req.build()
resp = new AWS.Response(req)
resp.error = code: 'NetworkingError'
s3.reqRegionForNetworkingError(resp, done)
req
beforeEach ->
s3 = new AWS.S3(region: 'us-west-2')
regionReq = request('operation', {Bucket: 'name'})
regionReq.send = (fn) ->
fn()
helpers.spyOn(AWS.util, 'isBrowser').andReturn(true)
spy = helpers.spyOn(s3, 'listObjects').andReturn(regionReq)
it 'updates region to us-east-1 if bucket name not DNS compatible', ->
req = request('operation', {Bucket: 'name!'})
callNetworkingErrorListener(req)
expect(req.httpRequest.region).to.equal('us-east-1')
expect(req.httpRequest.endpoint.hostname).to.equal('s3.amazonaws.com')
expect(s3.bucketRegionCache['name!']).to.equal('us-east-1')
expect(spy.calls.length).to.equal(0)
it 'updates region if cached and not current region', ->
req = request('operation', {Bucket: 'name'})
req.build()
s3.bucketRegionCache.name = 'eu-west-1'
callNetworkingErrorListener(req)
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
expect(spy.calls.length).to.equal(0)
it 'makes async request in us-east-1 if not in cache', ->
regionReq.send = (fn) ->
s3.bucketRegionCache.name = 'eu-west-1'
fn()
req = callNetworkingErrorListener()
expect(spy.calls.length).to.equal(1)
expect(regionReq.httpRequest.region).to.equal('us-east-1')
expect(regionReq.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'makes async request in us-east-1 if cached region matches current region', ->
s3.bucketRegionCache.name = 'us-west-2'
regionReq.send = (fn) ->
s3.bucketRegionCache.name = 'eu-west-1'
fn()
req = callNetworkingErrorListener()
expect(spy.calls.length).to.equal(1)
expect(regionReq.httpRequest.region).to.equal('us-east-1')
expect(regionReq.httpRequest.endpoint.hostname).to.equal('name.s3.amazonaws.com')
expect(req.httpRequest.region).to.equal('eu-west-1')
expect(req.httpRequest.endpoint.hostname).to.equal('name.s3-eu-west-1.amazonaws.com')
it 'does not update region if path-style bucket is dns-compliant and not in cache', ->
s3.config.s3ForcePathStyle = true
regionReq.send = (fn) ->
s3.bucketRegionCache.name = 'eu-west-1'
fn()
req = callNetworkingErrorListener()
expect(spy.calls.length).to.equal(0)
expect(req.httpRequest.region).to.equal('us-west-2')
expect(req.httpRequest.endpoint.hostname).to.equal('s3-us-west-2.amazonaws.com')
# tests from this point on are "special cases" for specific aws operations
describe 'getBucketAcl', ->
it 'correctly parses the ACL XML document', ->
headers = { 'x-amz-request-id' : 'request-id' }
body =
"""
<AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<AccessControlList>
<Grant>
<Grantee xsi:type="CanonicalUser" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Grantee>
<Permission>FULL_CONTROL</Permission>
</Grant>
<Grant>
<Grantee xsi:type="Group" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<URI>uri</URI>
</Grantee>
<Permission>READ</Permission>
</Grant>
</AccessControlList>
<Owner>
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, headers, body
s3.getBucketAcl (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
Owner:
DisplayName: 'aws-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser'
DisplayName: 'aws-sdk'
ID: 'id'
},
{
Permission : 'READ'
Grantee:
Type: 'Group'
URI: 'uri'
}
]
})
describe 'putBucketAcl', ->
it 'correctly builds the ACL XML document', ->
xml =
"""
<AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<AccessControlList>
<Grant>
<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Grantee>
<Permission>FULL_CONTROL</Permission>
</Grant>
<Grant>
<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">
<URI>uri</URI>
</Grantee>
<Permission>READ</Permission>
</Grant>
</AccessControlList>
<Owner>
<DisplayName>aws-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, {}, ''
params =
AccessControlPolicy:
Owner:
DisplayName: 'aws-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser',
DisplayName: 'aws-sdk'
ID: 'id'
},
{
Permission : 'READ'
Grantee:
Type: 'Group',
URI: 'uri'
}
]
s3.putBucketAcl params, (err, data) ->
helpers.matchXML(this.request.httpRequest.body, xml)
describe 'completeMultipartUpload', ->
it 'returns data when the resp is 200 with valid response', ->
headers =
'x-amz-id-2': 'Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg=='
'x-amz-request-id': '656c76696e6727732072657175657374'
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<CompleteMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>
<Bucket>Example-Bucket</Bucket>
<Key>Example-Object</Key>
<ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
</CompleteMultipartUploadResult>
"""
helpers.mockHttpResponse 200, headers, body
s3.completeMultipartUpload (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
Location: 'http://Example-Bucket.s3.amazonaws.com/Example-Object'
Bucket: 'Example-Bucket'
Key: 'Example-PI:KEY:<KEY>END_PI'
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
})
expect(this.requestId).to.equal('656c76696e6727732072657175657374')
it 'returns an error when the resp is 200 with an error xml document', ->
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
<RequestId>656c76696e6727732072657175657374</RequestId>
<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
"""
helpers.mockHttpResponse 200, {}, body
s3.completeMultipartUpload (error, data) ->
expect(error ).to.be.instanceOf(Error)
expect(error.code).to.equal('InternalError')
expect(error.message).to.equal('We encountered an internal error. Please try again.')
expect(error.statusCode).to.equal(200)
expect(error.retryable).to.equal(true)
expect(data).to.equal(null)
describe 'copyObject', ->
it 'returns data when the resp is 200 with valid response', ->
headers =
'x-amz-id-2': 'Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg=='
'x-amz-request-id': '656c76696e6727732072657175657374'
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<CopyObjectResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>
<Bucket>Example-Bucket</Bucket>
<Key>Example-Object</Key>
<ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
</CopyObjectResult>
"""
helpers.mockHttpResponse 200, headers, body
s3.copyObject (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
CopyObjectResult: {
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
}
})
expect(this.requestId).to.equal('656c76696e6727732072657175657374')
it 'returns an error when the resp is 200 with an error xml document', ->
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
<RequestId>656c76696e6727732072657175657374</RequestId>
<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
"""
helpers.mockHttpResponse 200, {}, body
s3.copyObject (error, data) ->
expect(error ).to.be.instanceOf(Error)
expect(error.code).to.equal('InternalError')
expect(error.message).to.equal('We encountered an internal error. Please try again.')
expect(error.statusCode).to.equal(200)
expect(error.retryable).to.equal(true)
expect(data).to.equal(null)
describe 'uploadPartCopy', ->
it 'returns data when the resp is 200 with valid response', ->
headers =
'x-amz-id-2': 'Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg=='
'x-amz-request-id': '656c76696e6727732072657175657374'
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<CopyPartResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>
<Bucket>Example-Bucket</Bucket>
<Key>Example-Object</Key>
<ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
</CopyPartResult>
"""
helpers.mockHttpResponse 200, headers, body
s3.uploadPartCopy {Bucket: 'bucket', Key: 'key', CopySource: 'bucket/key'}, (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({
CopyPartResult: {
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
}
})
expect(this.requestId).to.equal('656c76696e6727732072657175657374')
it 'returns an error when the resp is 200 with an error xml document', ->
body =
"""
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InternalError</Code>
<Message>We encountered an internal error. Please try again.</Message>
<RequestId>656c76696e6727732072657175657374</RequestId>
<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>
</Error>
"""
helpers.mockHttpResponse 200, {}, body
s3.uploadPartCopy (error, data) ->
expect(error ).to.be.instanceOf(Error)
expect(error.code).to.equal('InternalError')
expect(error.message).to.equal('We encountered an internal error. Please try again.')
expect(error.statusCode).to.equal(200)
expect(error.retryable).to.equal(true)
expect(data).to.equal(null)
describe 'getBucketLocation', ->
it 'returns empty string for the location constraint when not present', ->
body = '<?xml version="1.0" encoding="UTF-8"?>\n<LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>'
helpers.mockHttpResponse 200, {}, body
s3.getBucketLocation (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql({LocationConstraint: ''})
it 'parses the location constraint from the root xml', ->
headers = { 'x-amz-request-id': 'abcxyz' }
body = '<?xml version="1.0" encoding="UTF-8"?>\n<LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">EU</LocationConstraint>'
helpers.mockHttpResponse 200, headers, body
s3.getBucketLocation (error, data) ->
expect(error).to.equal(null)
expect(data).to.eql(LocationConstraint: 'EU')
expect(this.requestId).to.equal('abcxyz')
describe 'createBucket', ->
it 'auto-populates the LocationConstraint based on the region', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1')
s3.makeRequest = (op, params) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(Bucket:'name')
expect(loc).to.equal('eu-west-1')
it 'auto-populates the LocationConstraint based on the region when using bound params', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1', Bucket:'name')
s3.makeRequest = (op, params) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(AWS.util.fn.noop)
expect(loc).to.equal('eu-west-1')
it 'auto-populates the LocationConstraint based on the region when using invalid params', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1', Bucket:'name')
s3.makeRequest = (op, params) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(null)
expect(loc).to.equal('eu-west-1')
s3.createBucket(undefined)
expect(loc).to.equal('eu-west-1')
it 'auto-populates the LocationConstraint based on the region when using invalid params and a valid callback', ->
loc = null
s3 = new AWS.S3(region:'eu-west-1', Bucket:'name')
s3.makeRequest = (op, params, cb) ->
expect(params).to['be'].a('object')
loc = params.CreateBucketConfiguration.LocationConstraint
cb() if typeof cb == 'function'
called = 0
s3.createBucket(undefined, () -> called = 1)
expect(loc).to.equal('eu-west-1')
expect(called).to.equal(1)
it 'caches bucket region based on LocationConstraint upon successful response', ->
s3 = new AWS.S3()
params = Bucket: 'name', CreateBucketConfiguration: LocationConstraint: 'rg-fake-1'
helpers.mockHttpResponse 200, {}, ''
s3.createBucket params, ->
expect(s3.bucketRegionCache.name).to.equal('rg-fake-1')
it 'caches bucket region without LocationConstraint upon successful response', ->
s3 = new AWS.S3(region: 'us-east-1')
params = Bucket: 'name'
helpers.mockHttpResponse 200, {}, ''
s3.createBucket params, ->
expect(params.CreateBucketConfiguration).to.not.exist
expect(s3.bucketRegionCache.name).to.equal('us-east-1')
it 'caches bucket region with LocationConstraint "EU" upon successful response', ->
s3 = new AWS.S3()
params = Bucket: 'name', CreateBucketConfiguration: LocationConstraint: 'EU'
helpers.mockHttpResponse 200, {}, ''
s3.createBucket params, ->
expect(s3.bucketRegionCache.name).to.equal('eu-west-1')
describe 'deleteBucket', ->
it 'removes bucket from region cache on successful response', ->
s3 = new AWS.S3()
params = Bucket: 'name'
s3.bucketRegionCache.name = 'rg-fake-1'
helpers.mockHttpResponse 204, {}, ''
s3.deleteBucket params, ->
expect(s3.bucketRegionCache.name).to.not.exist
AWS.util.each AWS.S3.prototype.computableChecksumOperations, (operation) ->
describe operation, ->
it 'forces Content-MD5 header parameter', ->
req = s3[operation](Bucket: 'bucket', ContentMD5: '000').build()
hash = AWS.util.crypto.md5(req.httpRequest.body, 'base64')
expect(req.httpRequest.headers['Content-MD5']).to.equal(hash)
describe 'willComputeChecksums', ->
willCompute = (operation, opts) ->
compute = opts.computeChecksums
s3 = new AWS.S3(computeChecksums: compute, signatureVersion: 's3')
req = s3.makeRequest(operation, Bucket: 'example', ContentMD5: opts.hash).build()
checksum = req.httpRequest.headers['Content-MD5']
if opts.hash != undefined
if opts.hash == null
expect(checksum).not.to.exist
else
expect(checksum).to.equal(opts.hash)
else
realChecksum = AWS.util.crypto.md5(req.httpRequest.body, 'base64')
expect(checksum).to.equal(realChecksum)
it 'computes checksums if the operation requires it', ->
willCompute 'deleteObjects', computeChecksums: true
willCompute 'putBucketCors', computeChecksums: true
willCompute 'putBucketLifecycle', computeChecksums: true
willCompute 'putBucketLifecycleConfiguration', computeChecksums: true
it 'computes checksums if computeChecksums is off and operation requires it', ->
willCompute 'deleteObjects', computeChecksums: false
willCompute 'putBucketCors', computeChecksums: false
willCompute 'putBucketLifecycle', computeChecksums: false
willCompute 'putBucketLifecycleConfiguration', computeChecksums: false
it 'does not compute checksums if computeChecksums is off', ->
willCompute 'putObject', computeChecksums: false, hash: null
it 'does not compute checksums if computeChecksums is on and ContentMD5 is provided', ->
willCompute 'putBucketAcl', computeChecksums: true, hash: '000'
it 'computes checksums if computeChecksums is on and ContentMD5 is not provided',->
willCompute 'putBucketAcl', computeChecksums: true
if AWS.util.isNode()
it 'does not compute checksums for Stream objects', ->
s3 = new AWS.S3(computeChecksums: true)
req = s3.putObject(Bucket: 'example', Key: 'foo', Body: new Stream.Stream)
expect(req.build(->).httpRequest.headers['Content-MD5']).to.equal(undefined)
it 'throws an error in SigV4, if a non-file stream is provided when body signing enabled', (done) ->
s3 = new AWS.S3({signatureVersion: 'v4', s3DisableBodySigning: false})
req = s3.putObject(Bucket: 'example', Key: 'key', Body: new Stream.Stream)
req.send (err) ->
expect(err.message).to.contain('stream objects are not supported')
done()
it 'does not throw an error in SigV4, if a non-file stream is provided when body signing disabled with ContentLength', (done) ->
s3 = new AWS.S3({signatureVersion: 'v4', s3DisableBodySigning: true})
helpers.mockResponse data: ETag: 'etag'
req = s3.putObject(Bucket: 'example', Key: 'key', Body: new Stream.Stream, ContentLength: 10)
req.send (err) ->
expect(err).not.to.exist
done()
it 'opens separate stream if a file object is provided (signed payload)', (done) ->
hash = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
helpers.mockResponse data: ETag: 'etag'
fs = require('fs')
mock = helpers.spyOn(fs, 'createReadStream').andCallFake ->
tr = new Stream.Transform
tr._transform = (d,e,c) -> c(null,d)
tr.length = 0
tr.path = 'path/to/file'
tr.push(new Buffer(''))
tr.end()
tr
s3 = new AWS.S3({signatureVersion: 'v4', s3DisableBodySigning: false})
stream = fs.createReadStream('path/to/file')
req = s3.putObject(Bucket: 'example', Key: 'key', Body: stream)
req.send (err) ->
expect(mock.calls[0].arguments).to.eql(['path/to/file'])
expect(mock.calls[1].arguments).to.eql(['path/to/file', {}])
expect(err).not.to.exist
expect(req.httpRequest.headers['X-Amz-Content-Sha256']).to.equal(hash)
done()
it 'opens separate stream with range if a file object is provided', (done) ->
hash = '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
helpers.mockResponse data: ETag: 'etag'
fs = require('fs')
mock = helpers.spyOn(fs, 'createReadStream').andCallFake (path, settings) ->
tr = new Stream.Readable
tr.length = 0
tr.path = 'path/to/file'
tr.start = settings.start
tr.end = settings.end
didRead = false
tr._read = (n) ->
if (didRead)
tr.push(null)
else
didRead = true
tr.push(new Buffer('test'))
tr
s3 = new AWS.S3(signatureVersion: 'v4', s3DisableBodySigning: false)
stream = fs.createReadStream('path/to/file', {start:0, end:5})
req = s3.putObject(Bucket: 'example', Key: 'key', Body: stream)
req.send (err) ->
expect(mock.calls[0].arguments).to.eql(['path/to/file', {start:0, end:5}])
expect(mock.calls[1].arguments).to.eql(['path/to/file', {start:0, end:5}])
expect(err).not.to.exist
expect(req.httpRequest.headers['X-Amz-Content-Sha256']).to.equal(hash)
done()
describe 'getSignedUrl', ->
date = null
beforeEach (done) ->
date = AWS.util.date.getDate
AWS.util.date.getDate = -> new Date(0)
done()
afterEach (done) ->
AWS.util.date.getDate = date
done()
it 'gets a signed URL for getObject', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key')
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=4mlYnRmz%2BBFEPrgYz5tXcl9Wc4w%3D&x-amz-security-token=session')
it 'gets a signed URL with Expires time', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key', Expires: 60)
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=60&Signature=kH2pMK%2Fgm7cCZKVG8GHVTRGXKzY%3D&x-amz-security-token=session')
it 'gets a signed URL with expiration and bound bucket parameters', ->
s3 = new AWS.S3(paramValidation: true, region: undefined, params: Bucket: 'bucket')
url = s3.getSignedUrl('getObject', Key: 'key', Expires: 60)
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=60&Signature=kH2pMK%2Fgm7cCZKVG8GHVTRGXKzY%3D&x-amz-security-token=session')
it 'generates the right URL with a custom endpoint', ->
s3 = new AWS.S3(endpoint: 'https://foo.bar.baz:555/prefix', params: Bucket: 'bucket')
url = s3.getSignedUrl('getObject', Key: 'key', Expires: 60)
expect(url).to.equal('https://bucket.foo.bar.baz:555/prefix/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=60&Signature=zA6k0cQqDkTZgLamfoYLOd%2Bqfg8%3D&x-amz-security-token=session')
it 'gets a signed URL with callback', (done) ->
s3.getSignedUrl 'getObject', Bucket: 'bucket', Key: 'key', (err, url) ->
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=4mlYnRmz%2BBFEPrgYz5tXcl9Wc4w%3D&x-amz-security-token=session')
done()
it 'gets a signed URL for putObject with no body', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key')
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=J%2BnWZ0lPUfLV0kio8ONhJmAttGc%3D&x-amz-security-token=session')
it 'gets a signed URL for putObject with Metadata', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Metadata: {someKey: 'someValue'})
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=5Lcbv0WLGWseQhtmNQ8WwIpX6Kw%3D&x-amz-meta-somekey=someValue&x-amz-security-token=session')
it 'gets a signed URL for putObject with Metadata using Sigv4', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Metadata: {someKey: 'someValue'})
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=PI:KEY:<KEY>END_PI%2F1PI:KEY:<KEY>END_PI%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=0a1ef336042a7a03b8a2e130ac36097cb1fbab54f8ed5105977a863a5139e679&X-Amz-SignedHeaders=host%3Bx-amz-meta-somekey&x-amz-meta-somekey=someValue')
it 'gets a signed URL for putObject with special characters', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: '!@#$%^&*();\':"{}[],./?`~')
expect(url).to.equal('https://bucket.s3.amazonaws.com/%21%40%23%24%25%5E%26%2A%28%29%3B%27%3A%22%7B%7D%5B%5D%2C./%3F%60~?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=9nEltJACZKsriZqU2cmRel6g8LQ%3D&x-amz-security-token=session')
it 'gets a signed URL for putObject with a body (and checksum)', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Body: 'body')
expect(url).to.equal('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Content-MD5=hBotaJrYa9FhFEdFPCLG%2FA%3D%3D&Expires=900&Signature=4ycA2tpHKxfFnNCdqnK1d5BG8gc%3D&x-amz-security-token=session')
it 'gets a signed URL for putObject with a sse-c algorithm', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', SSECustomerAlgorithm: 'AES256')
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=60b08f91f820fa1c698ac477fec7b5e3cec7b682e09e769e1a55a4d5a3b99077&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption-customer-algorithm&x-amz-server-side-encryption-customer-algorithm=AES256');
it 'gets a signed URL for putObject with a sse-c key', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', SSECustomerAlgorithm: 'AES256', SSECustomerKey: 'PI:KEY:<KEY>END_PI
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=e4f57734798fdadc0b2b43ca5a5e1f28824786c3ac74c30d7abb77d6ef59b0da&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption-customer-algorithm%3Bx-amz-server-side-encryption-customer-key%3Bx-amz-server-side-encryption-customer-key-md5&x-amz-server-side-encryption-customer-algorithm=AES256&x-amz-server-side-encryption-customer-key=YzJGdGNHeGxJR3RsZVhOaGJYQnNaU0JyWlhsellXMXdiR1PI:KEY:<KEY>END_PIJPI:KEY:<KEY>END_PIRT0%3D&x-amz-server-side-encryption-customer-key-MD5=VzaXhwL7H9upBc%2Fb9UqH8g%3D%3D');
it 'gets a signed URL for putObject with CacheControl', ->
s3 = new AWS.S3
signatureVersion: 'v4'
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', CacheControl: 'max-age=10000')
expect(url).to.equal('https://bucket.s3.mock-region.amazonaws.com/key?Cache-Control=max-age%3D10000&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fmock-region%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=39ad1f8dc3aa377c2b184a0be7657dfb606628c74796c1a48394ef134ff6233a&X-Amz-SignedHeaders=cache-control%3Bhost')
it 'gets a signed URL and appends to existing query parameters', ->
url = s3.getSignedUrl('listObjects', Bucket: 'bucket', Prefix: 'prefix')
expect(url).to.equal('https://bucket.s3.amazonaws.com/?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=8W3pwZPfgucCyPNg1MsoYq8h5zw%3D&prefix=prefix&x-amz-security-token=session')
it 'gets a signed URL for getObject using SigV4', ->
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'object')
expect(url).to.equal('https://bucket.s3.amazonaws.com/object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=05ae40d2d22c93549a1de0686232ff56baf556876ec497d0d8349431f98b8dfe&X-Amz-SignedHeaders=host')
it 'gets a signed URL for putObject using SigV4', ->
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'object')
expect(url).to.equal('https://bucket.s3.amazonaws.com/object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=akid%2F19700101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=1b6f75301a2e480bcfbb53d47d8940c28c8657ea70f23c24846a5595a53b1dfe&X-Amz-SignedHeaders=host')
it 'gets a signed URL for putObject using SigV4 with body', ->
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'object', Body: 'foo')
expect(url).to.equal('https://bucket.s3.amazonaws.com/object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae&X-Amz-Credential=akid%2F19700101%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=19700101T000000Z&X-Amz-Expires=900&X-Amz-Security-Token=session&X-Amz-Signature=600a64aff20c4ea6c28d11fd0639fb33a0107d072f4c2dd1ea38a16d057513f3&X-Amz-SignedHeaders=host%3Bx-amz-content-sha256')
it 'errors when expiry time is greater than a week out on SigV4', (done) ->
err = null; data = null
s3 = new AWS.S3(signatureVersion: 'v4', region: undefined)
params = Bucket: 'bucket', Key: 'PI:KEY:<KEY>END_PI', Expires: 60 * 60 * 24 * 7 + 120
error = 'Presigning does not support expiry time greater than a week with SigV4 signing.'
s3.getSignedUrl 'getObject', params, (err, data) ->
expect(err).not.to.equal(null)
expect(err.message).to.equal(error)
#expect(-> s3.getSignedUrl('getObject', params)).to.throw(error) # sync mode
done()
it 'errors if ContentLength is passed as parameter', ->
expect(-> s3.getSignedUrl('putObject',
Bucket: 'bucket'
Key: 'key'
ContentLength: 5
)).to.throw(/ContentLength is not supported in pre-signed URLs/)
describe 'createPresignedPost', ->
it 'should include a url and a hash of form fields', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data).to.include.keys('fields', 'url')
expect(data.url).to.be.a.string
expect(data.fields).to.be.an.object
done()
it 'should include a policy, signature, and signing metadata', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data.fields).to.include.keys(
'Policy',
'X-Amz-Signature',
'X-Amz-Algorithm',
'X-Amz-Date',
'X-Amz-Credential'
)
done()
it 'should specify the signing algorithm used', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data.fields['X-Amz-Algorithm']).to.equal('AWS4-HMAC-SHA256')
done()
it 'should use bound parameters for the bucket name', (done) ->
s3 = new AWS.S3(params: {Bucket: 'bucket'})
s3.createPresignedPost {}, (err, data) ->
expect(data.fields).to.include.keys('bucket')
expect(data.fields.bucket).to.equal('bucket')
done()
it 'should include the security token when present', (done) ->
token = 'PI:KEY:<KEY>END_PI'
credentials =
accessKeyId: 'PI:KEY:<KEY>END_PI'
secretAccessKey: 'PI:KEY:<KEY>END_PI'
sessionToken: token
s3 = new AWS.S3(credentials: credentials)
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
expect(data.fields['X-Amz-Security-Token']).to.equal(token)
done()
it 'should provide a base64-encoded JSON policy document', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expect(decoded).to.be.an.object
expect(decoded).to.include.key('expiration', 'conditions')
done()
it 'should default to expiration in one hour', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expiration = new Date(decoded.expiration)
validForMs = expiration.valueOf() - (new Date()).valueOf()
# allow one second of leeway
expect(validForMs).to.be.above((60 * 60 - 1) * 1000)
expect(validForMs).to.be.below((60 * 60 + 1) * 1000)
done()
it 'should allow users to provide a custom expiration', (done) ->
customTtl = 900
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket', Expires: customTtl}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expiration = new Date(decoded.expiration)
validForMs = expiration.valueOf() - (new Date()).valueOf()
# allow one second of leeway
expect(validForMs).to.be.above((customTtl - 1) * 1000)
expect(validForMs).to.be.below((customTtl + 1) * 1000)
done()
it 'should include signature metadata as conditions', (done) ->
s3 = new AWS.S3()
s3.createPresignedPost {Bucket: 'bucket'}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expect(decoded.conditions).to.be.an.array
found = {}
for index, condition of decoded.conditions
conditionKey = Object.keys(condition)[0]
found[conditionKey] = true
expect(condition[conditionKey]).to.equal(data.fields[conditionKey])
expect(found['X-Amz-Algorithm']).to.be.true
expect(found['X-Amz-Date']).to.be.true
expect(found['X-Amz-Credential']).to.be.true
done()
it 'should include user-provided conditions in the signed policy', (done) ->
s3 = new AWS.S3()
conditions = [
{'x-amz-server-side-encryption': 'AES256'},
['starts-with', '$x-amz-meta-tag', ''],
{'acl': 'public-read'}
]
s3.createPresignedPost {Bucket: 'bucket', Conditions: conditions}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
expect(decoded.conditions).to.be.an.array
expect(conditions[0]).to.deep.equal(decoded.conditions[0])
expect(conditions[1]).to.deep.equal(decoded.conditions[1])
expect(conditions[2]).to.deep.equal(decoded.conditions[2])
done()
it 'should include user-provided fields as policy conditions', (done) ->
s3 = new AWS.S3()
fieldsToInclude =
key: 'PI:KEY:<KEY>END_PI'
acl: 'public-read',
'Content-Type': 'image/jpeg',
'x-amz-meta-foo': 'bar',
'x-amz-tagging': '''<Tagging>
<TagSet>
<Tag>
<Key>foo</Key>
<Value>bar</Value>
</Tag>
</TagSet>
</Tagging>'''
s3.createPresignedPost {Bucket: 'bucket', Fields: fieldsToInclude}, (err, data) ->
decoded = JSON.parse(AWS.util.base64.decode(data.fields.Policy))
conditions = {}
decoded.conditions.forEach((condition) ->
if typeof condition == 'object'
conditionKey = Object.keys(condition)[0]
conditions[conditionKey] = condition[conditionKey]
)
Object.keys(fieldsToInclude).forEach((key) ->
expect(data.fields[key]).to.equal(fieldsToInclude[key])
expect(data.fields[key]).to.equal(conditions[key])
)
done()
|
[
{
"context": "ve OverlappingMarkerSpiderfier\nhttps://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet\nCopyright (c)",
"end": 66,
"score": 0.9996458888053894,
"start": 62,
"tag": "USERNAME",
"value": "jawj"
},
{
"context": "MarkerSpiderfier-Leaflet\nCopyright (c) 2011 - 2012 George MacKerron\nReleased under the MIT licence: http://opensource",
"end": 145,
"score": 0.999894917011261,
"start": 129,
"tag": "NAME",
"value": "George MacKerron"
}
] | lib/oms.coffee | emre2038/OverlappingMarkerSpiderfier-Leaflet | 1 | ###* @preserve OverlappingMarkerSpiderfier
https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet
Copyright (c) 2011 - 2012 George MacKerron
Released under the MIT licence: http://opensource.org/licenses/mit-license
Note: The Leaflet maps API must be included *before* this code
###
# NB. string literal properties -- object['key'] -- are for Closure Compiler ADVANCED_OPTIMIZATION
(->
return unless this['L']? # return from wrapper func without doing anything
class @['OverlappingMarkerSpiderfier']
p = @:: # this saves a lot of repetition of .prototype that isn't optimized away
p['VERSION'] = '0.2.6'
twoPi = Math.PI * 2
p['keepSpiderfied'] = no # yes -> don't unspiderfy when a marker is selected
p['nearbyDistance'] = 20 # spiderfy markers within this range of the one clicked, in px
p['circleSpiralSwitchover'] = 9 # show spiral instead of circle from this marker count upwards
# 0 -> always spiral; Infinity -> always circle
p['circleFootSeparation'] = 25 # related to circumference of circle
p['circleStartAngle'] = twoPi / 12
p['spiralFootSeparation'] = 28 # related to size of spiral (experiment!)
p['spiralLengthStart'] = 11 # ditto
p['spiralLengthFactor'] = 5 # ditto
p['legWeight'] = 1.5
p['legColors'] =
'usual': '#222'
'highlighted': '#f00'
# Note: it's OK that this constructor comes after the properties, because of function hoisting
constructor: (@map, opts = {}) ->
(@[k] = v) for own k, v of opts
@initMarkerArrays()
@listeners = {}
@map.addEventListener(e, => @['unspiderfy']()) for e in ['click', 'zoomend']
p.initMarkerArrays = ->
@markers = []
@markerListeners = []
p['addMarker'] = (marker) ->
return @ if marker['_oms']?
marker['_oms'] = yes
markerListener = => @spiderListener(marker)
marker.addEventListener('click', markerListener)
@markerListeners.push(markerListener)
@markers.push(marker)
@ # return self, for chaining
p['getMarkers'] = -> @markers[0..] # returns a copy, so no funny business
p['removeMarker'] = (marker) ->
@['unspiderfy']() if marker['_omsData']? # otherwise it'll be stuck there forever!
i = @arrIndexOf(@markers, marker)
return @ if i < 0
markerListener = @markerListeners.splice(i, 1)[0]
marker.removeEventListener('click', markerListener)
delete marker['_oms']
@markers.splice(i, 1)
@ # return self, for chaining
p['clearMarkers'] = ->
@['unspiderfy']()
for marker, i in @markers
markerListener = @markerListeners[i]
marker.removeEventListener('click', markerListener)
delete marker['_oms']
@initMarkerArrays()
@ # return self, for chaining
# available listeners: click(marker), spiderfy(markers), unspiderfy(markers)
p['addListener'] = (event, func) ->
(@listeners[event] ?= []).push(func)
@ # return self, for chaining
p['removeListener'] = (event, func) ->
i = @arrIndexOf(@listeners[event], func)
@listeners[event].splice(i, 1) unless i < 0
@ # return self, for chaining
p['clearListeners'] = (event) ->
@listeners[event] = []
@ # return self, for chaining
p.trigger = (event, args...) ->
func(args...) for func in (@listeners[event] ? [])
p.generatePtsCircle = (count, centerPt) ->
circumference = @['circleFootSeparation'] * (2 + count)
legLength = circumference / twoPi # = radius from circumference
angleStep = twoPi / count
for i in [0...count]
angle = @['circleStartAngle'] + i * angleStep
new L.Point(centerPt.x + legLength * Math.cos(angle),
centerPt.y + legLength * Math.sin(angle))
p.generatePtsSpiral = (count, centerPt) ->
legLength = @['spiralLengthStart']
angle = 0
for i in [0...count]
angle += @['spiralFootSeparation'] / legLength + i * 0.0005
pt = new L.Point(centerPt.x + legLength * Math.cos(angle),
centerPt.y + legLength * Math.sin(angle))
legLength += twoPi * @['spiralLengthFactor'] / angle
pt
p.spiderListener = (marker) ->
markerSpiderfied = marker['_omsData']?
@['unspiderfy']() unless markerSpiderfied and @['keepSpiderfied']
if markerSpiderfied
@trigger('click', marker)
else
nearbyMarkerData = []
nonNearbyMarkers = []
pxSq = @['nearbyDistance'] * @['nearbyDistance']
markerPt = @map.latLngToLayerPoint(marker.getLatLng())
for m in @markers
continue unless @map.hasLayer(m)
mPt = @map.latLngToLayerPoint(m.getLatLng())
if @ptDistanceSq(mPt, markerPt) < pxSq
nearbyMarkerData.push(marker: m, markerPt: mPt)
else
nonNearbyMarkers.push(m)
if nearbyMarkerData.length is 1 # 1 => the one clicked => none nearby
@trigger('click', marker)
else
@spiderfy(nearbyMarkerData, nonNearbyMarkers)
p.makeHighlightListeners = (marker) ->
highlight: => marker['_omsData'].leg.setStyle(color: @['legColors']['highlighted'])
unhighlight: => marker['_omsData'].leg.setStyle(color: @['legColors']['usual'])
p.spiderfy = (markerData, nonNearbyMarkers) ->
@spiderfying = yes
numFeet = markerData.length
bodyPt = @ptAverage(md.markerPt for md in markerData)
footPts = if numFeet >= @['circleSpiralSwitchover']
@generatePtsSpiral(numFeet, bodyPt).reverse() # match from outside in => less criss-crossing
else
@generatePtsCircle(numFeet, bodyPt)
spiderfiedMarkers = for footPt in footPts
footLl = @map.layerPointToLatLng(footPt)
nearestMarkerDatum = @minExtract(markerData, (md) => @ptDistanceSq(md.markerPt, footPt))
marker = nearestMarkerDatum.marker
leg = new L.Polyline [marker.getLatLng(), footLl], {
color: @['legColors']['usual']
weight: @['legWeight']
clickable: no
}
@map.addLayer(leg)
marker['_omsData'] = {usualPosition: marker.getLatLng(), leg: leg}
unless @['legColors']['highlighted'] is @['legColors']['usual']
mhl = @makeHighlightListeners(marker)
marker['_omsData'].highlightListeners = mhl
marker.addEventListener('mouseover', mhl.highlight)
marker.addEventListener('mouseout', mhl.unhighlight)
marker.setLatLng(footLl)
marker.setZIndexOffset(marker.options.zIndexOffset + 1000000)
marker
delete @spiderfying
@spiderfied = yes
@trigger('spiderfy', spiderfiedMarkers, nonNearbyMarkers)
p['unspiderfy'] = (markerNotToMove = null) ->
return @ unless @spiderfied?
@unspiderfying = yes
unspiderfiedMarkers = []
nonNearbyMarkers = []
for marker in @markers
if marker['_omsData']?
@map.removeLayer(marker['_omsData'].leg)
marker.setLatLng(marker['_omsData'].usualPosition) unless marker is markerNotToMove
marker.setZIndexOffset(marker.options.zIndexOffset - 1000000)
mhl = marker['_omsData'].highlightListeners
if mhl?
marker.removeEventListener('mouseover', mhl.highlight)
marker.removeEventListener('mouseout', mhl.unhighlight)
delete marker['_omsData']
unspiderfiedMarkers.push(marker)
else
nonNearbyMarkers.push(marker)
delete @unspiderfying
delete @spiderfied
@trigger('unspiderfy', unspiderfiedMarkers, nonNearbyMarkers)
@ # return self, for chaining
p.ptDistanceSq = (pt1, pt2) ->
dx = pt1.x - pt2.x
dy = pt1.y - pt2.y
dx * dx + dy * dy
p.ptAverage = (pts) ->
sumX = sumY = 0
for pt in pts
sumX += pt.x; sumY += pt.y
numPts = pts.length
new L.Point(sumX / numPts, sumY / numPts)
p.minExtract = (set, func) -> # destructive! returns minimum, and also removes it from the set
for item, index in set
val = func(item)
if ! bestIndex? || val < bestVal
bestVal = val
bestIndex = index
set.splice(bestIndex, 1)[0]
p.arrIndexOf = (arr, obj) ->
return arr.indexOf(obj) if arr.indexOf?
(return i if o is obj) for o, i in arr
-1
).call(this)
| 65944 | ###* @preserve OverlappingMarkerSpiderfier
https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet
Copyright (c) 2011 - 2012 <NAME>
Released under the MIT licence: http://opensource.org/licenses/mit-license
Note: The Leaflet maps API must be included *before* this code
###
# NB. string literal properties -- object['key'] -- are for Closure Compiler ADVANCED_OPTIMIZATION
(->
return unless this['L']? # return from wrapper func without doing anything
class @['OverlappingMarkerSpiderfier']
p = @:: # this saves a lot of repetition of .prototype that isn't optimized away
p['VERSION'] = '0.2.6'
twoPi = Math.PI * 2
p['keepSpiderfied'] = no # yes -> don't unspiderfy when a marker is selected
p['nearbyDistance'] = 20 # spiderfy markers within this range of the one clicked, in px
p['circleSpiralSwitchover'] = 9 # show spiral instead of circle from this marker count upwards
# 0 -> always spiral; Infinity -> always circle
p['circleFootSeparation'] = 25 # related to circumference of circle
p['circleStartAngle'] = twoPi / 12
p['spiralFootSeparation'] = 28 # related to size of spiral (experiment!)
p['spiralLengthStart'] = 11 # ditto
p['spiralLengthFactor'] = 5 # ditto
p['legWeight'] = 1.5
p['legColors'] =
'usual': '#222'
'highlighted': '#f00'
# Note: it's OK that this constructor comes after the properties, because of function hoisting
constructor: (@map, opts = {}) ->
(@[k] = v) for own k, v of opts
@initMarkerArrays()
@listeners = {}
@map.addEventListener(e, => @['unspiderfy']()) for e in ['click', 'zoomend']
p.initMarkerArrays = ->
@markers = []
@markerListeners = []
p['addMarker'] = (marker) ->
return @ if marker['_oms']?
marker['_oms'] = yes
markerListener = => @spiderListener(marker)
marker.addEventListener('click', markerListener)
@markerListeners.push(markerListener)
@markers.push(marker)
@ # return self, for chaining
p['getMarkers'] = -> @markers[0..] # returns a copy, so no funny business
p['removeMarker'] = (marker) ->
@['unspiderfy']() if marker['_omsData']? # otherwise it'll be stuck there forever!
i = @arrIndexOf(@markers, marker)
return @ if i < 0
markerListener = @markerListeners.splice(i, 1)[0]
marker.removeEventListener('click', markerListener)
delete marker['_oms']
@markers.splice(i, 1)
@ # return self, for chaining
p['clearMarkers'] = ->
@['unspiderfy']()
for marker, i in @markers
markerListener = @markerListeners[i]
marker.removeEventListener('click', markerListener)
delete marker['_oms']
@initMarkerArrays()
@ # return self, for chaining
# available listeners: click(marker), spiderfy(markers), unspiderfy(markers)
p['addListener'] = (event, func) ->
(@listeners[event] ?= []).push(func)
@ # return self, for chaining
p['removeListener'] = (event, func) ->
i = @arrIndexOf(@listeners[event], func)
@listeners[event].splice(i, 1) unless i < 0
@ # return self, for chaining
p['clearListeners'] = (event) ->
@listeners[event] = []
@ # return self, for chaining
p.trigger = (event, args...) ->
func(args...) for func in (@listeners[event] ? [])
p.generatePtsCircle = (count, centerPt) ->
circumference = @['circleFootSeparation'] * (2 + count)
legLength = circumference / twoPi # = radius from circumference
angleStep = twoPi / count
for i in [0...count]
angle = @['circleStartAngle'] + i * angleStep
new L.Point(centerPt.x + legLength * Math.cos(angle),
centerPt.y + legLength * Math.sin(angle))
p.generatePtsSpiral = (count, centerPt) ->
legLength = @['spiralLengthStart']
angle = 0
for i in [0...count]
angle += @['spiralFootSeparation'] / legLength + i * 0.0005
pt = new L.Point(centerPt.x + legLength * Math.cos(angle),
centerPt.y + legLength * Math.sin(angle))
legLength += twoPi * @['spiralLengthFactor'] / angle
pt
p.spiderListener = (marker) ->
markerSpiderfied = marker['_omsData']?
@['unspiderfy']() unless markerSpiderfied and @['keepSpiderfied']
if markerSpiderfied
@trigger('click', marker)
else
nearbyMarkerData = []
nonNearbyMarkers = []
pxSq = @['nearbyDistance'] * @['nearbyDistance']
markerPt = @map.latLngToLayerPoint(marker.getLatLng())
for m in @markers
continue unless @map.hasLayer(m)
mPt = @map.latLngToLayerPoint(m.getLatLng())
if @ptDistanceSq(mPt, markerPt) < pxSq
nearbyMarkerData.push(marker: m, markerPt: mPt)
else
nonNearbyMarkers.push(m)
if nearbyMarkerData.length is 1 # 1 => the one clicked => none nearby
@trigger('click', marker)
else
@spiderfy(nearbyMarkerData, nonNearbyMarkers)
p.makeHighlightListeners = (marker) ->
highlight: => marker['_omsData'].leg.setStyle(color: @['legColors']['highlighted'])
unhighlight: => marker['_omsData'].leg.setStyle(color: @['legColors']['usual'])
p.spiderfy = (markerData, nonNearbyMarkers) ->
@spiderfying = yes
numFeet = markerData.length
bodyPt = @ptAverage(md.markerPt for md in markerData)
footPts = if numFeet >= @['circleSpiralSwitchover']
@generatePtsSpiral(numFeet, bodyPt).reverse() # match from outside in => less criss-crossing
else
@generatePtsCircle(numFeet, bodyPt)
spiderfiedMarkers = for footPt in footPts
footLl = @map.layerPointToLatLng(footPt)
nearestMarkerDatum = @minExtract(markerData, (md) => @ptDistanceSq(md.markerPt, footPt))
marker = nearestMarkerDatum.marker
leg = new L.Polyline [marker.getLatLng(), footLl], {
color: @['legColors']['usual']
weight: @['legWeight']
clickable: no
}
@map.addLayer(leg)
marker['_omsData'] = {usualPosition: marker.getLatLng(), leg: leg}
unless @['legColors']['highlighted'] is @['legColors']['usual']
mhl = @makeHighlightListeners(marker)
marker['_omsData'].highlightListeners = mhl
marker.addEventListener('mouseover', mhl.highlight)
marker.addEventListener('mouseout', mhl.unhighlight)
marker.setLatLng(footLl)
marker.setZIndexOffset(marker.options.zIndexOffset + 1000000)
marker
delete @spiderfying
@spiderfied = yes
@trigger('spiderfy', spiderfiedMarkers, nonNearbyMarkers)
p['unspiderfy'] = (markerNotToMove = null) ->
return @ unless @spiderfied?
@unspiderfying = yes
unspiderfiedMarkers = []
nonNearbyMarkers = []
for marker in @markers
if marker['_omsData']?
@map.removeLayer(marker['_omsData'].leg)
marker.setLatLng(marker['_omsData'].usualPosition) unless marker is markerNotToMove
marker.setZIndexOffset(marker.options.zIndexOffset - 1000000)
mhl = marker['_omsData'].highlightListeners
if mhl?
marker.removeEventListener('mouseover', mhl.highlight)
marker.removeEventListener('mouseout', mhl.unhighlight)
delete marker['_omsData']
unspiderfiedMarkers.push(marker)
else
nonNearbyMarkers.push(marker)
delete @unspiderfying
delete @spiderfied
@trigger('unspiderfy', unspiderfiedMarkers, nonNearbyMarkers)
@ # return self, for chaining
p.ptDistanceSq = (pt1, pt2) ->
dx = pt1.x - pt2.x
dy = pt1.y - pt2.y
dx * dx + dy * dy
p.ptAverage = (pts) ->
sumX = sumY = 0
for pt in pts
sumX += pt.x; sumY += pt.y
numPts = pts.length
new L.Point(sumX / numPts, sumY / numPts)
p.minExtract = (set, func) -> # destructive! returns minimum, and also removes it from the set
for item, index in set
val = func(item)
if ! bestIndex? || val < bestVal
bestVal = val
bestIndex = index
set.splice(bestIndex, 1)[0]
p.arrIndexOf = (arr, obj) ->
return arr.indexOf(obj) if arr.indexOf?
(return i if o is obj) for o, i in arr
-1
).call(this)
| true | ###* @preserve OverlappingMarkerSpiderfier
https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet
Copyright (c) 2011 - 2012 PI:NAME:<NAME>END_PI
Released under the MIT licence: http://opensource.org/licenses/mit-license
Note: The Leaflet maps API must be included *before* this code
###
# NB. string literal properties -- object['key'] -- are for Closure Compiler ADVANCED_OPTIMIZATION
(->
return unless this['L']? # return from wrapper func without doing anything
class @['OverlappingMarkerSpiderfier']
p = @:: # this saves a lot of repetition of .prototype that isn't optimized away
p['VERSION'] = '0.2.6'
twoPi = Math.PI * 2
p['keepSpiderfied'] = no # yes -> don't unspiderfy when a marker is selected
p['nearbyDistance'] = 20 # spiderfy markers within this range of the one clicked, in px
p['circleSpiralSwitchover'] = 9 # show spiral instead of circle from this marker count upwards
# 0 -> always spiral; Infinity -> always circle
p['circleFootSeparation'] = 25 # related to circumference of circle
p['circleStartAngle'] = twoPi / 12
p['spiralFootSeparation'] = 28 # related to size of spiral (experiment!)
p['spiralLengthStart'] = 11 # ditto
p['spiralLengthFactor'] = 5 # ditto
p['legWeight'] = 1.5
p['legColors'] =
'usual': '#222'
'highlighted': '#f00'
# Note: it's OK that this constructor comes after the properties, because of function hoisting
constructor: (@map, opts = {}) ->
(@[k] = v) for own k, v of opts
@initMarkerArrays()
@listeners = {}
@map.addEventListener(e, => @['unspiderfy']()) for e in ['click', 'zoomend']
p.initMarkerArrays = ->
@markers = []
@markerListeners = []
p['addMarker'] = (marker) ->
return @ if marker['_oms']?
marker['_oms'] = yes
markerListener = => @spiderListener(marker)
marker.addEventListener('click', markerListener)
@markerListeners.push(markerListener)
@markers.push(marker)
@ # return self, for chaining
p['getMarkers'] = -> @markers[0..] # returns a copy, so no funny business
p['removeMarker'] = (marker) ->
@['unspiderfy']() if marker['_omsData']? # otherwise it'll be stuck there forever!
i = @arrIndexOf(@markers, marker)
return @ if i < 0
markerListener = @markerListeners.splice(i, 1)[0]
marker.removeEventListener('click', markerListener)
delete marker['_oms']
@markers.splice(i, 1)
@ # return self, for chaining
p['clearMarkers'] = ->
@['unspiderfy']()
for marker, i in @markers
markerListener = @markerListeners[i]
marker.removeEventListener('click', markerListener)
delete marker['_oms']
@initMarkerArrays()
@ # return self, for chaining
# available listeners: click(marker), spiderfy(markers), unspiderfy(markers)
p['addListener'] = (event, func) ->
(@listeners[event] ?= []).push(func)
@ # return self, for chaining
p['removeListener'] = (event, func) ->
i = @arrIndexOf(@listeners[event], func)
@listeners[event].splice(i, 1) unless i < 0
@ # return self, for chaining
p['clearListeners'] = (event) ->
@listeners[event] = []
@ # return self, for chaining
p.trigger = (event, args...) ->
func(args...) for func in (@listeners[event] ? [])
p.generatePtsCircle = (count, centerPt) ->
circumference = @['circleFootSeparation'] * (2 + count)
legLength = circumference / twoPi # = radius from circumference
angleStep = twoPi / count
for i in [0...count]
angle = @['circleStartAngle'] + i * angleStep
new L.Point(centerPt.x + legLength * Math.cos(angle),
centerPt.y + legLength * Math.sin(angle))
p.generatePtsSpiral = (count, centerPt) ->
legLength = @['spiralLengthStart']
angle = 0
for i in [0...count]
angle += @['spiralFootSeparation'] / legLength + i * 0.0005
pt = new L.Point(centerPt.x + legLength * Math.cos(angle),
centerPt.y + legLength * Math.sin(angle))
legLength += twoPi * @['spiralLengthFactor'] / angle
pt
p.spiderListener = (marker) ->
markerSpiderfied = marker['_omsData']?
@['unspiderfy']() unless markerSpiderfied and @['keepSpiderfied']
if markerSpiderfied
@trigger('click', marker)
else
nearbyMarkerData = []
nonNearbyMarkers = []
pxSq = @['nearbyDistance'] * @['nearbyDistance']
markerPt = @map.latLngToLayerPoint(marker.getLatLng())
for m in @markers
continue unless @map.hasLayer(m)
mPt = @map.latLngToLayerPoint(m.getLatLng())
if @ptDistanceSq(mPt, markerPt) < pxSq
nearbyMarkerData.push(marker: m, markerPt: mPt)
else
nonNearbyMarkers.push(m)
if nearbyMarkerData.length is 1 # 1 => the one clicked => none nearby
@trigger('click', marker)
else
@spiderfy(nearbyMarkerData, nonNearbyMarkers)
p.makeHighlightListeners = (marker) ->
highlight: => marker['_omsData'].leg.setStyle(color: @['legColors']['highlighted'])
unhighlight: => marker['_omsData'].leg.setStyle(color: @['legColors']['usual'])
p.spiderfy = (markerData, nonNearbyMarkers) ->
@spiderfying = yes
numFeet = markerData.length
bodyPt = @ptAverage(md.markerPt for md in markerData)
footPts = if numFeet >= @['circleSpiralSwitchover']
@generatePtsSpiral(numFeet, bodyPt).reverse() # match from outside in => less criss-crossing
else
@generatePtsCircle(numFeet, bodyPt)
spiderfiedMarkers = for footPt in footPts
footLl = @map.layerPointToLatLng(footPt)
nearestMarkerDatum = @minExtract(markerData, (md) => @ptDistanceSq(md.markerPt, footPt))
marker = nearestMarkerDatum.marker
leg = new L.Polyline [marker.getLatLng(), footLl], {
color: @['legColors']['usual']
weight: @['legWeight']
clickable: no
}
@map.addLayer(leg)
marker['_omsData'] = {usualPosition: marker.getLatLng(), leg: leg}
unless @['legColors']['highlighted'] is @['legColors']['usual']
mhl = @makeHighlightListeners(marker)
marker['_omsData'].highlightListeners = mhl
marker.addEventListener('mouseover', mhl.highlight)
marker.addEventListener('mouseout', mhl.unhighlight)
marker.setLatLng(footLl)
marker.setZIndexOffset(marker.options.zIndexOffset + 1000000)
marker
delete @spiderfying
@spiderfied = yes
@trigger('spiderfy', spiderfiedMarkers, nonNearbyMarkers)
p['unspiderfy'] = (markerNotToMove = null) ->
return @ unless @spiderfied?
@unspiderfying = yes
unspiderfiedMarkers = []
nonNearbyMarkers = []
for marker in @markers
if marker['_omsData']?
@map.removeLayer(marker['_omsData'].leg)
marker.setLatLng(marker['_omsData'].usualPosition) unless marker is markerNotToMove
marker.setZIndexOffset(marker.options.zIndexOffset - 1000000)
mhl = marker['_omsData'].highlightListeners
if mhl?
marker.removeEventListener('mouseover', mhl.highlight)
marker.removeEventListener('mouseout', mhl.unhighlight)
delete marker['_omsData']
unspiderfiedMarkers.push(marker)
else
nonNearbyMarkers.push(marker)
delete @unspiderfying
delete @spiderfied
@trigger('unspiderfy', unspiderfiedMarkers, nonNearbyMarkers)
@ # return self, for chaining
p.ptDistanceSq = (pt1, pt2) ->
dx = pt1.x - pt2.x
dy = pt1.y - pt2.y
dx * dx + dy * dy
p.ptAverage = (pts) ->
sumX = sumY = 0
for pt in pts
sumX += pt.x; sumY += pt.y
numPts = pts.length
new L.Point(sumX / numPts, sumY / numPts)
p.minExtract = (set, func) -> # destructive! returns minimum, and also removes it from the set
for item, index in set
val = func(item)
if ! bestIndex? || val < bestVal
bestVal = val
bestIndex = index
set.splice(bestIndex, 1)[0]
p.arrIndexOf = (arr, obj) ->
return arr.indexOf(obj) if arr.indexOf?
(return i if o is obj) for o, i in arr
-1
).call(this)
|
[
{
"context": " require 'scaleway'\n\nclient = new Api\n token: '<YOUR_TOKEN>'\n\ndata =\n name: 'c1'\n organization: '<OR",
"end": 59,
"score": 0.5107666254043579,
"start": 55,
"tag": "PASSWORD",
"value": "YOUR"
},
{
"context": "ire 'scaleway'\n\nclient = new Api\n token: '<YOUR_TOKEN>'\n\ndata =\n name: 'c1'\n organization: '<ORGANIZA",
"end": 65,
"score": 0.52315753698349,
"start": 60,
"tag": "KEY",
"value": "TOKEN"
}
] | examples/simple.coffee | moul/node-scaleway | 18 | Api = require 'scaleway'
client = new Api
token: '<YOUR_TOKEN>'
data =
name: 'c1'
organization: '<ORGANIZATION_ID>'
image: '<IMAGE_ID>'
tags: ['test', 'demo']
client.post '/servers', data, (err, res) ->
console.log res.server
| 11938 | Api = require 'scaleway'
client = new Api
token: '<<PASSWORD>_<KEY>>'
data =
name: 'c1'
organization: '<ORGANIZATION_ID>'
image: '<IMAGE_ID>'
tags: ['test', 'demo']
client.post '/servers', data, (err, res) ->
console.log res.server
| true | Api = require 'scaleway'
client = new Api
token: '<PI:PASSWORD:<PASSWORD>END_PI_PI:KEY:<KEY>END_PI>'
data =
name: 'c1'
organization: '<ORGANIZATION_ID>'
image: '<IMAGE_ID>'
tags: ['test', 'demo']
client.post '/servers', data, (err, res) ->
console.log res.server
|
[
{
"context": " ento().use\n greet: ->\n msg += \"Hello, #{@name}\"\n\n new Person(name: \"Jake\").greet()\n e",
"end": 135,
"score": 0.5104079246520996,
"start": 135,
"tag": "NAME",
"value": ""
},
{
"context": "o().use\n greet: ->\n msg += \"Hello, #{@name}\"\n\n new Person(name: \"Jake\").greet()\n expec",
"end": 143,
"score": 0.8061705231666565,
"start": 139,
"tag": "USERNAME",
"value": "name"
},
{
"context": " msg += \"Hello, #{@name}\"\n\n new Person(name: \"Jake\").greet()\n expect(msg).to.eq \"Hello, Jake\"\n\n ",
"end": 173,
"score": 0.9994478225708008,
"start": 169,
"tag": "NAME",
"value": "Jake"
},
{
"context": "ame: \"Jake\").greet()\n expect(msg).to.eq \"Hello, Jake\"\n\n it 'multiple', ->\n Armored = { armor: -> 2",
"end": 218,
"score": 0.9981427192687988,
"start": 214,
"tag": "NAME",
"value": "Jake"
}
] | test/use_test.coffee | rstacruz/ento | 11 | require './setup'
describe 'use', ->
it 'basic use', ->
msg = ''
Person = ento().use
greet: ->
msg += "Hello, #{@name}"
new Person(name: "Jake").greet()
expect(msg).to.eq "Hello, Jake"
it 'multiple', ->
Armored = { armor: -> 200 }
Villain = { alignment: -> 'evil' }
Unit = ento()
.use(Villain)
.use(Armored)
mob = new Unit()
expect(mob.alignment()).eq 'evil'
expect(mob.armor()).eq 200
it 'static props', ->
Unit = ento()
.use(null, foo: true)
expect(Unit.foo).eq true
it 'fn', ->
Armored = (model) ->
model
.attr('armor')
.attr('hasArmor', -> @armor > 0)
Unit = ento().use(Armored)
mob = new Unit(armor: 0)
expect(mob.armor).eq 0
expect(mob.hasArmor).eq false
it 'invalid, null', ->
expect(-> ento().use(null)).throw /invalid arg/
it 'invalid, undefined', ->
expect(-> ento().use(undefined)).throw /invalid arg/
| 143073 | require './setup'
describe 'use', ->
it 'basic use', ->
msg = ''
Person = ento().use
greet: ->
msg += "Hello,<NAME> #{@name}"
new Person(name: "<NAME>").greet()
expect(msg).to.eq "Hello, <NAME>"
it 'multiple', ->
Armored = { armor: -> 200 }
Villain = { alignment: -> 'evil' }
Unit = ento()
.use(Villain)
.use(Armored)
mob = new Unit()
expect(mob.alignment()).eq 'evil'
expect(mob.armor()).eq 200
it 'static props', ->
Unit = ento()
.use(null, foo: true)
expect(Unit.foo).eq true
it 'fn', ->
Armored = (model) ->
model
.attr('armor')
.attr('hasArmor', -> @armor > 0)
Unit = ento().use(Armored)
mob = new Unit(armor: 0)
expect(mob.armor).eq 0
expect(mob.hasArmor).eq false
it 'invalid, null', ->
expect(-> ento().use(null)).throw /invalid arg/
it 'invalid, undefined', ->
expect(-> ento().use(undefined)).throw /invalid arg/
| true | require './setup'
describe 'use', ->
it 'basic use', ->
msg = ''
Person = ento().use
greet: ->
msg += "Hello,PI:NAME:<NAME>END_PI #{@name}"
new Person(name: "PI:NAME:<NAME>END_PI").greet()
expect(msg).to.eq "Hello, PI:NAME:<NAME>END_PI"
it 'multiple', ->
Armored = { armor: -> 200 }
Villain = { alignment: -> 'evil' }
Unit = ento()
.use(Villain)
.use(Armored)
mob = new Unit()
expect(mob.alignment()).eq 'evil'
expect(mob.armor()).eq 200
it 'static props', ->
Unit = ento()
.use(null, foo: true)
expect(Unit.foo).eq true
it 'fn', ->
Armored = (model) ->
model
.attr('armor')
.attr('hasArmor', -> @armor > 0)
Unit = ento().use(Armored)
mob = new Unit(armor: 0)
expect(mob.armor).eq 0
expect(mob.hasArmor).eq false
it 'invalid, null', ->
expect(-> ento().use(null)).throw /invalid arg/
it 'invalid, undefined', ->
expect(-> ento().use(undefined)).throw /invalid arg/
|
[
{
"context": "eturns last meme (text and image).\n#\n# Author:\n# Eunomie\n# Based 9gag.coffee by EnriqueVidal\n\ncheerio = ",
"end": 674,
"score": 0.9749237298965454,
"start": 667,
"tag": "NAME",
"value": "Eunomie"
},
{
"context": ".\n#\n# Author:\n# Eunomie\n# Based 9gag.coffee by EnriqueVidal\n\ncheerio = require('cheerio')\nhe = require('he')\n",
"end": 712,
"score": 0.8289278745651245,
"start": 700,
"tag": "NAME",
"value": "EnriqueVidal"
}
] | node_modules/hubot-codinglove/src/codinglove.coffee | mikelovskij/sauron2 | 18 | # Description:
# Display meme from "The coding love <http://thecodinglove.com>"
# or "les joies du code <http://lesjoiesducode.tumblr.com>".
#
# Dependencies:
# "cheerio": "0.7.0"
# "he": "0.4.1"
#
# Configuration:
# None
#
# Commands:
# hubot [give me some] joy [asshole] - Return a random meme (coding love)
# hubot last joy - Returns last meme (coding love)
# hubot [spread some] love - Return a random meme (coding love)
# hubot last love - Returns last meme (coding love)
# hubot [donne moi de la] joie [bordel] - Returns a random meme (text and image)
# hubot {dernière|derniere} joie - Returns last meme (text and image).
#
# Author:
# Eunomie
# Based 9gag.coffee by EnriqueVidal
cheerio = require('cheerio')
he = require('he')
module.exports = (robot)->
robot.respond /(donne moi de la )?joie( bordel)?/i, (message)->
send_new_meme message, 'http://lesjoiesducode.fr/random', (text)->
message.send text
robot.respond /derni[èe]re joie/i, (message)->
send_new_meme message, 'http://lesjoiesducode.fr', (text)->
message.send text
robot.respond /((give me|spread) some )?(joy|love)( asshole)?/i, (message)->
send_meme message, 'http://thecodinglove.com/random', (text)->
message.send text
robot.respond /last (joy|love)/i, (message)->
send_meme message, 'http://thecodinglove.com', (text)->
message.send text
send_new_meme = (message, location, response_handler)->
url = location
message.http(url).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302 || response.statusCode == 301
location = response.headers['location']
return send_new_meme(message, location, response_handler)
img_src = get_meme_image(body, ".ljdc-posts .blog-post .blog-post-content img")
txt = get_meme_txt(body, ".ljdc-posts .blog-post h1.blog-post-title a")
if txt == ''
txt = get_meme_txt(body, ".ljdc-posts .blog-post h1.blog-post-title")
txt = txt.replace(/[\n\r]/g, '')
response_handler "#{txt}"
response_handler "#{img_src}"
send_meme = (message, location, response_handler)->
url = location
message.http(url).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302 || response.statusCode == 301
location = response.headers['location']
return send_meme(message, location, response_handler)
img_src = get_meme_image(body, ".post img")
txt = get_meme_txt(body, ".post h3")
response_handler "#{txt}"
response_handler "#{img_src}"
get_meme_image = (body, selector)->
$ = cheerio.load(body)
$(selector).first().attr('src').replace(/\.jpe?g/i, '.gif')
get_meme_txt = (body, selector)->
$ = cheerio.load(body)
he.decode $(selector).first().text()
| 78965 | # Description:
# Display meme from "The coding love <http://thecodinglove.com>"
# or "les joies du code <http://lesjoiesducode.tumblr.com>".
#
# Dependencies:
# "cheerio": "0.7.0"
# "he": "0.4.1"
#
# Configuration:
# None
#
# Commands:
# hubot [give me some] joy [asshole] - Return a random meme (coding love)
# hubot last joy - Returns last meme (coding love)
# hubot [spread some] love - Return a random meme (coding love)
# hubot last love - Returns last meme (coding love)
# hubot [donne moi de la] joie [bordel] - Returns a random meme (text and image)
# hubot {dernière|derniere} joie - Returns last meme (text and image).
#
# Author:
# <NAME>
# Based 9gag.coffee by <NAME>
cheerio = require('cheerio')
he = require('he')
module.exports = (robot)->
robot.respond /(donne moi de la )?joie( bordel)?/i, (message)->
send_new_meme message, 'http://lesjoiesducode.fr/random', (text)->
message.send text
robot.respond /derni[èe]re joie/i, (message)->
send_new_meme message, 'http://lesjoiesducode.fr', (text)->
message.send text
robot.respond /((give me|spread) some )?(joy|love)( asshole)?/i, (message)->
send_meme message, 'http://thecodinglove.com/random', (text)->
message.send text
robot.respond /last (joy|love)/i, (message)->
send_meme message, 'http://thecodinglove.com', (text)->
message.send text
send_new_meme = (message, location, response_handler)->
url = location
message.http(url).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302 || response.statusCode == 301
location = response.headers['location']
return send_new_meme(message, location, response_handler)
img_src = get_meme_image(body, ".ljdc-posts .blog-post .blog-post-content img")
txt = get_meme_txt(body, ".ljdc-posts .blog-post h1.blog-post-title a")
if txt == ''
txt = get_meme_txt(body, ".ljdc-posts .blog-post h1.blog-post-title")
txt = txt.replace(/[\n\r]/g, '')
response_handler "#{txt}"
response_handler "#{img_src}"
send_meme = (message, location, response_handler)->
url = location
message.http(url).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302 || response.statusCode == 301
location = response.headers['location']
return send_meme(message, location, response_handler)
img_src = get_meme_image(body, ".post img")
txt = get_meme_txt(body, ".post h3")
response_handler "#{txt}"
response_handler "#{img_src}"
get_meme_image = (body, selector)->
$ = cheerio.load(body)
$(selector).first().attr('src').replace(/\.jpe?g/i, '.gif')
get_meme_txt = (body, selector)->
$ = cheerio.load(body)
he.decode $(selector).first().text()
| true | # Description:
# Display meme from "The coding love <http://thecodinglove.com>"
# or "les joies du code <http://lesjoiesducode.tumblr.com>".
#
# Dependencies:
# "cheerio": "0.7.0"
# "he": "0.4.1"
#
# Configuration:
# None
#
# Commands:
# hubot [give me some] joy [asshole] - Return a random meme (coding love)
# hubot last joy - Returns last meme (coding love)
# hubot [spread some] love - Return a random meme (coding love)
# hubot last love - Returns last meme (coding love)
# hubot [donne moi de la] joie [bordel] - Returns a random meme (text and image)
# hubot {dernière|derniere} joie - Returns last meme (text and image).
#
# Author:
# PI:NAME:<NAME>END_PI
# Based 9gag.coffee by PI:NAME:<NAME>END_PI
cheerio = require('cheerio')
he = require('he')
module.exports = (robot)->
robot.respond /(donne moi de la )?joie( bordel)?/i, (message)->
send_new_meme message, 'http://lesjoiesducode.fr/random', (text)->
message.send text
robot.respond /derni[èe]re joie/i, (message)->
send_new_meme message, 'http://lesjoiesducode.fr', (text)->
message.send text
robot.respond /((give me|spread) some )?(joy|love)( asshole)?/i, (message)->
send_meme message, 'http://thecodinglove.com/random', (text)->
message.send text
robot.respond /last (joy|love)/i, (message)->
send_meme message, 'http://thecodinglove.com', (text)->
message.send text
send_new_meme = (message, location, response_handler)->
url = location
message.http(url).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302 || response.statusCode == 301
location = response.headers['location']
return send_new_meme(message, location, response_handler)
img_src = get_meme_image(body, ".ljdc-posts .blog-post .blog-post-content img")
txt = get_meme_txt(body, ".ljdc-posts .blog-post h1.blog-post-title a")
if txt == ''
txt = get_meme_txt(body, ".ljdc-posts .blog-post h1.blog-post-title")
txt = txt.replace(/[\n\r]/g, '')
response_handler "#{txt}"
response_handler "#{img_src}"
send_meme = (message, location, response_handler)->
url = location
message.http(url).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302 || response.statusCode == 301
location = response.headers['location']
return send_meme(message, location, response_handler)
img_src = get_meme_image(body, ".post img")
txt = get_meme_txt(body, ".post h3")
response_handler "#{txt}"
response_handler "#{img_src}"
get_meme_image = (body, selector)->
$ = cheerio.load(body)
$(selector).first().attr('src').replace(/\.jpe?g/i, '.gif')
get_meme_txt = (body, selector)->
$ = cheerio.load(body)
he.decode $(selector).first().text()
|
[
{
"context": "he latest English versions:\n## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascri",
"end": 185,
"score": 0.9750394821166992,
"start": 175,
"tag": "USERNAME",
"value": "uploadcare"
},
{
"context": " upload: 'No s\\'ha pogut carregar'\n user: 'Carrega cancel·lada'\n info: 'No s\\'ha pogut carregar la informac",
"end": 623,
"score": 0.7081613540649414,
"start": 604,
"tag": "NAME",
"value": "Carrega cancel·lada"
},
{
"context": "tiu.'\n preview:\n unknownName: 'desconegut'\n change: 'Cancel·lar'\n back: '",
"end": 2541,
"score": 0.8877851963043213,
"start": 2534,
"tag": "USERNAME",
"value": "conegut"
}
] | app/assets/javascripts/uploadcare/locale/ca.js.coffee | Tlapi/uploadcare-widget | 0 | ##
## Please, do not use this locale as a reference for new translations.
## It could be outdated or incomplete. Always use the latest English versions:
## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascripts/uploadcare/locale/en.js.coffee
##
## Any fixes are welcome.
##
uploadcare.namespace 'locale.translations', (ns) ->
ns.ca =
uploading: 'Carregant... Si us plau esperi.'
loadingInfo: 'Carregant informació...'
errors:
default: 'Error'
baddata: 'Valor incorrecte'
size: 'Massa gran'
upload: 'No s\'ha pogut carregar'
user: 'Carrega cancel·lada'
info: 'No s\'ha pogut carregar la informació'
image: 'Només es permeten imatges'
createGroup: 'No es pot crear el grup d\'arxius'
deleted: 'Fitxer eliminat'
draghere: 'Arrossega els fitxers fins aquí'
file:
one: '%1 fitxer'
other: '%1 fitxers'
buttons:
cancel: 'Cancel·lar'
remove: 'Eliminar'
choose:
files:
one: 'Escull un fitxer'
other: 'Escull fitxers'
images:
one: 'Escull una imatge'
other: 'Escull imatges'
dialog:
done: 'Fet'
showFiles: 'Mostra fitxers'
tabs:
names:
'empty-pubkey': 'Benvingut'
preview: 'Avanci'
file: 'Ordinador'
url: 'Enllaços arbitraris'
camera: 'Càmera'
file:
drag: 'Arrossega un fitxer aquí'
nodrop: 'Carrega fitxers des del teu ordinador'
cloudsTip: 'Emmagatzematge al núvol<br>i xarxes socials'
or: 'o'
button: 'Escull un fitxer des del teu ordinador'
also: 'També pots seleccionar-lo de'
url:
title: 'Fitxers de la web'
line1: 'Selecciona qualsevol fitxer de la web.'
line2: 'Només proporcioni el link.'
input: 'Copiï el link aquí...'
button: 'Pujar'
camera:
capture: 'Realitza una foto'
mirror: 'Mirall'
retry: 'Demanar permisos una altra vegada'
pleaseAllow:
title: 'Si us plau, permet accés a la teva càmera'
text: 'Aquest lloc t\'ha demanat de permetre accés a la càmera. ' +
'Per tal de realitzar imatges amb la teva càmera has d\'acceptar aquesta petició.'
notFound:
title: 'No s\'ha detectat cap càmera'
text: 'Sembla que no tens cap càmera connectada a aquest dispositiu.'
preview:
unknownName: 'desconegut'
change: 'Cancel·lar'
back: 'Endarrere'
done: 'Pujar'
unknown:
title: 'Carregant. Si us plau esperi per la visualització prèvia.'
done: 'Saltar visualització prèvia i acceptar'
regular:
title: 'Vols pujar aquest fitxer?'
line1: 'Estàs a punt de pujar el fitxer superior.'
line2: 'Confirmi, si us plau.'
image:
title: 'Vols pujar aquesta imatge?'
change: 'Cancel·lar'
crop:
title: 'Tallar i pujar aquesta imatge'
done: 'Fet'
free: 'lliure'
error:
default:
title: 'La pujada ha fallat!'
text: 'S\'ha produït un error durant la pujada.'
back: 'Si us plau, provi-ho de nou.'
image:
title: 'Només s\'accepten fitxers d\'imatges.'
text: 'Si us plau, provi-ho de nou amb un altre fitxer.'
back: 'Escull imatge'
size:
title: 'La mida del fitxer que has seleccionat sobrepassa el límit.'
text: 'Si us plau, provi-ho de nou amb un altre fitxer.'
loadImage:
title: 'Error'
text: 'No s\'ha pogut carregar la imatge'
multiple:
title: 'N\'has escollit %files%'
question: 'Vols afegir tots aquests fitxers?'
tooManyFiles: 'Has escollit massa fitxers. %max% és el màxim.'
tooFewFiles: 'Has escollit %files%. Com a mínim en calen %min%.'
clear: 'Eliminar-los tots'
done: 'Fet'
footer:
text: 'Els fitxers han estat carregats, gestionats i processats per'
# Pluralization rules taken from:
# http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
uploadcare.namespace 'locale.pluralize', (ns) ->
ns.ca = (n) ->
return 'one' if n == 1
'other'
| 202105 | ##
## Please, do not use this locale as a reference for new translations.
## It could be outdated or incomplete. Always use the latest English versions:
## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascripts/uploadcare/locale/en.js.coffee
##
## Any fixes are welcome.
##
uploadcare.namespace 'locale.translations', (ns) ->
ns.ca =
uploading: 'Carregant... Si us plau esperi.'
loadingInfo: 'Carregant informació...'
errors:
default: 'Error'
baddata: 'Valor incorrecte'
size: 'Massa gran'
upload: 'No s\'ha pogut carregar'
user: '<NAME>'
info: 'No s\'ha pogut carregar la informació'
image: 'Només es permeten imatges'
createGroup: 'No es pot crear el grup d\'arxius'
deleted: 'Fitxer eliminat'
draghere: 'Arrossega els fitxers fins aquí'
file:
one: '%1 fitxer'
other: '%1 fitxers'
buttons:
cancel: 'Cancel·lar'
remove: 'Eliminar'
choose:
files:
one: 'Escull un fitxer'
other: 'Escull fitxers'
images:
one: 'Escull una imatge'
other: 'Escull imatges'
dialog:
done: 'Fet'
showFiles: 'Mostra fitxers'
tabs:
names:
'empty-pubkey': 'Benvingut'
preview: 'Avanci'
file: 'Ordinador'
url: 'Enllaços arbitraris'
camera: 'Càmera'
file:
drag: 'Arrossega un fitxer aquí'
nodrop: 'Carrega fitxers des del teu ordinador'
cloudsTip: 'Emmagatzematge al núvol<br>i xarxes socials'
or: 'o'
button: 'Escull un fitxer des del teu ordinador'
also: 'També pots seleccionar-lo de'
url:
title: 'Fitxers de la web'
line1: 'Selecciona qualsevol fitxer de la web.'
line2: 'Només proporcioni el link.'
input: 'Copiï el link aquí...'
button: 'Pujar'
camera:
capture: 'Realitza una foto'
mirror: 'Mirall'
retry: 'Demanar permisos una altra vegada'
pleaseAllow:
title: 'Si us plau, permet accés a la teva càmera'
text: 'Aquest lloc t\'ha demanat de permetre accés a la càmera. ' +
'Per tal de realitzar imatges amb la teva càmera has d\'acceptar aquesta petició.'
notFound:
title: 'No s\'ha detectat cap càmera'
text: 'Sembla que no tens cap càmera connectada a aquest dispositiu.'
preview:
unknownName: 'desconegut'
change: 'Cancel·lar'
back: 'Endarrere'
done: 'Pujar'
unknown:
title: 'Carregant. Si us plau esperi per la visualització prèvia.'
done: 'Saltar visualització prèvia i acceptar'
regular:
title: 'Vols pujar aquest fitxer?'
line1: 'Estàs a punt de pujar el fitxer superior.'
line2: 'Confirmi, si us plau.'
image:
title: 'Vols pujar aquesta imatge?'
change: 'Cancel·lar'
crop:
title: 'Tallar i pujar aquesta imatge'
done: 'Fet'
free: 'lliure'
error:
default:
title: 'La pujada ha fallat!'
text: 'S\'ha produït un error durant la pujada.'
back: 'Si us plau, provi-ho de nou.'
image:
title: 'Només s\'accepten fitxers d\'imatges.'
text: 'Si us plau, provi-ho de nou amb un altre fitxer.'
back: 'Escull imatge'
size:
title: 'La mida del fitxer que has seleccionat sobrepassa el límit.'
text: 'Si us plau, provi-ho de nou amb un altre fitxer.'
loadImage:
title: 'Error'
text: 'No s\'ha pogut carregar la imatge'
multiple:
title: 'N\'has escollit %files%'
question: 'Vols afegir tots aquests fitxers?'
tooManyFiles: 'Has escollit massa fitxers. %max% és el màxim.'
tooFewFiles: 'Has escollit %files%. Com a mínim en calen %min%.'
clear: 'Eliminar-los tots'
done: 'Fet'
footer:
text: 'Els fitxers han estat carregats, gestionats i processats per'
# Pluralization rules taken from:
# http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
uploadcare.namespace 'locale.pluralize', (ns) ->
ns.ca = (n) ->
return 'one' if n == 1
'other'
| true | ##
## Please, do not use this locale as a reference for new translations.
## It could be outdated or incomplete. Always use the latest English versions:
## https://github.com/uploadcare/uploadcare-widget/blob/master/app/assets/javascripts/uploadcare/locale/en.js.coffee
##
## Any fixes are welcome.
##
uploadcare.namespace 'locale.translations', (ns) ->
ns.ca =
uploading: 'Carregant... Si us plau esperi.'
loadingInfo: 'Carregant informació...'
errors:
default: 'Error'
baddata: 'Valor incorrecte'
size: 'Massa gran'
upload: 'No s\'ha pogut carregar'
user: 'PI:NAME:<NAME>END_PI'
info: 'No s\'ha pogut carregar la informació'
image: 'Només es permeten imatges'
createGroup: 'No es pot crear el grup d\'arxius'
deleted: 'Fitxer eliminat'
draghere: 'Arrossega els fitxers fins aquí'
file:
one: '%1 fitxer'
other: '%1 fitxers'
buttons:
cancel: 'Cancel·lar'
remove: 'Eliminar'
choose:
files:
one: 'Escull un fitxer'
other: 'Escull fitxers'
images:
one: 'Escull una imatge'
other: 'Escull imatges'
dialog:
done: 'Fet'
showFiles: 'Mostra fitxers'
tabs:
names:
'empty-pubkey': 'Benvingut'
preview: 'Avanci'
file: 'Ordinador'
url: 'Enllaços arbitraris'
camera: 'Càmera'
file:
drag: 'Arrossega un fitxer aquí'
nodrop: 'Carrega fitxers des del teu ordinador'
cloudsTip: 'Emmagatzematge al núvol<br>i xarxes socials'
or: 'o'
button: 'Escull un fitxer des del teu ordinador'
also: 'També pots seleccionar-lo de'
url:
title: 'Fitxers de la web'
line1: 'Selecciona qualsevol fitxer de la web.'
line2: 'Només proporcioni el link.'
input: 'Copiï el link aquí...'
button: 'Pujar'
camera:
capture: 'Realitza una foto'
mirror: 'Mirall'
retry: 'Demanar permisos una altra vegada'
pleaseAllow:
title: 'Si us plau, permet accés a la teva càmera'
text: 'Aquest lloc t\'ha demanat de permetre accés a la càmera. ' +
'Per tal de realitzar imatges amb la teva càmera has d\'acceptar aquesta petició.'
notFound:
title: 'No s\'ha detectat cap càmera'
text: 'Sembla que no tens cap càmera connectada a aquest dispositiu.'
preview:
unknownName: 'desconegut'
change: 'Cancel·lar'
back: 'Endarrere'
done: 'Pujar'
unknown:
title: 'Carregant. Si us plau esperi per la visualització prèvia.'
done: 'Saltar visualització prèvia i acceptar'
regular:
title: 'Vols pujar aquest fitxer?'
line1: 'Estàs a punt de pujar el fitxer superior.'
line2: 'Confirmi, si us plau.'
image:
title: 'Vols pujar aquesta imatge?'
change: 'Cancel·lar'
crop:
title: 'Tallar i pujar aquesta imatge'
done: 'Fet'
free: 'lliure'
error:
default:
title: 'La pujada ha fallat!'
text: 'S\'ha produït un error durant la pujada.'
back: 'Si us plau, provi-ho de nou.'
image:
title: 'Només s\'accepten fitxers d\'imatges.'
text: 'Si us plau, provi-ho de nou amb un altre fitxer.'
back: 'Escull imatge'
size:
title: 'La mida del fitxer que has seleccionat sobrepassa el límit.'
text: 'Si us plau, provi-ho de nou amb un altre fitxer.'
loadImage:
title: 'Error'
text: 'No s\'ha pogut carregar la imatge'
multiple:
title: 'N\'has escollit %files%'
question: 'Vols afegir tots aquests fitxers?'
tooManyFiles: 'Has escollit massa fitxers. %max% és el màxim.'
tooFewFiles: 'Has escollit %files%. Com a mínim en calen %min%.'
clear: 'Eliminar-los tots'
done: 'Fet'
footer:
text: 'Els fitxers han estat carregats, gestionats i processats per'
# Pluralization rules taken from:
# http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
uploadcare.namespace 'locale.pluralize', (ns) ->
ns.ca = (n) ->
return 'one' if n == 1
'other'
|
[
{
"context": "ealer', ->\n dealer = null\n storage = {}\n id = 'dlr'\n\n beforeEach ->\n dealer = new Dealer(storage",
"end": 250,
"score": 0.9537742137908936,
"start": 247,
"tag": "USERNAME",
"value": "dlr"
},
{
"context": "hould change the game', ->\n dealer.changeGame('chrismo', 'loser')\n expect(dealer.game.constructor",
"end": 861,
"score": 0.786888599395752,
"start": 858,
"tag": "NAME",
"value": "chr"
},
{
"context": "ld change the game', ->\n dealer.changeGame('chrismo', 'loser')\n expect(dealer.game.constructor.nam",
"end": 865,
"score": 0.7863514423370361,
"start": 861,
"tag": "USERNAME",
"value": "ismo"
},
{
"context": "s not found', ->\n expect(-> dealer.changeGame('chrismo', 'nope')).toThrow 'Cannot find a game matchi",
"end": 1034,
"score": 0.7002014517784119,
"start": 1031,
"tag": "NAME",
"value": "chr"
},
{
"context": "ot found', ->\n expect(-> dealer.changeGame('chrismo', 'nope')).toThrow 'Cannot find a game matching <",
"end": 1038,
"score": 0.8510571122169495,
"start": 1034,
"tag": "USERNAME",
"value": "ismo"
},
{
"context": "o many hits', ->\n expect(-> dealer.changeGame('chrismo', 'i')).toThrow 'Be more specific, more than ",
"end": 1190,
"score": 0.7888190150260925,
"start": 1187,
"tag": "NAME",
"value": "chr"
},
{
"context": "any hits', ->\n expect(-> dealer.changeGame('chrismo', 'i')).toThrow 'Be more specific, more than one ",
"end": 1194,
"score": 0.7950718998908997,
"start": 1190,
"tag": "USERNAME",
"value": "ismo"
},
{
"context": "aler.addListener(listener)\n dealer.sendToGame('chrismo', '123123')\n dealer.sendToGame('romer', '1",
"end": 1429,
"score": 0.8665913939476013,
"start": 1426,
"tag": "NAME",
"value": "chr"
},
{
"context": "r.addListener(listener)\n dealer.sendToGame('chrismo', '123123')\n dealer.sendToGame('romer', '12312",
"end": 1433,
"score": 0.7083293199539185,
"start": 1429,
"tag": "USERNAME",
"value": "ismo"
},
{
"context": "oGame('chrismo', '123123')\n dealer.sendToGame('romer', '123123')\n firstGame = dealer.game\n expec",
"end": 1474,
"score": 0.9311512112617493,
"start": 1469,
"tag": "NAME",
"value": "romer"
},
{
"context": "nd.isStarted()).toBe true\n\n dealer.changeGame('chrismo', 'loser')\n expect(dealer.game.constructor",
"end": 1592,
"score": 0.7914745211601257,
"start": 1589,
"tag": "NAME",
"value": "chr"
},
{
"context": "isStarted()).toBe true\n\n dealer.changeGame('chrismo', 'loser')\n expect(dealer.game.constructor.nam",
"end": 1596,
"score": 0.7922821640968323,
"start": 1592,
"tag": "USERNAME",
"value": "ismo"
},
{
"context": "me is already in play', ->\n dealer.sendToGame('chrismo', '123123')\n dealer.sendToGame('romer', '1",
"end": 1853,
"score": 0.8597127199172974,
"start": 1850,
"tag": "NAME",
"value": "chr"
},
{
"context": "oGame('chrismo', '123123')\n dealer.sendToGame('romer', '123123')\n firstGame = dealer.game\n expec",
"end": 1898,
"score": 0.6555581092834473,
"start": 1893,
"tag": "NAME",
"value": "romer"
},
{
"context": "nd.isStarted()).toBe true\n\n dealer.changeGame('chrismo', 'kill')\n expect(firstGame.round.isOver()",
"end": 2016,
"score": 0.6424668431282043,
"start": 2013,
"tag": "NAME",
"value": "chr"
},
{
"context": "et game command', ->\n res = dealer.sendToGame('chrismo', 'bet 12')\n expect(res).toBe 'chrismo bet 12'",
"end": 2429,
"score": 0.7035964131355286,
"start": 2422,
"tag": "NAME",
"value": "chrismo"
},
{
"context": "ToGame('chrismo', 'bet 12')\n expect(res).toBe 'chrismo bet 12'\n\n it 'should handle a second game co",
"end": 2467,
"score": 0.841796875,
"start": 2464,
"tag": "NAME",
"value": "chr"
},
{
"context": "nd game command', ->\n res = dealer.sendToGame('chrismo', 'fund 12')\n expect(res).toBe \"chrismo funded",
"end": 2564,
"score": 0.7373425960540771,
"start": 2557,
"tag": "NAME",
"value": "chrismo"
},
{
"context": "oGame('chrismo', 'fund 12')\n expect(res).toBe \"chrismo funded 12\"\n\n it 'should handle a multiple ar",
"end": 2603,
"score": 0.9123787879943848,
"start": 2600,
"tag": "NAME",
"value": "chr"
},
{
"context": "rgument command', ->\n res = dealer.sendToGame('chrismo', 'many foo bar')\n expect(res).toBe \"chris",
"end": 2705,
"score": 0.8699720501899719,
"start": 2702,
"tag": "NAME",
"value": "chr"
},
{
"context": "('chrismo', 'many foo bar')\n expect(res).toBe \"chrismo foo bar\"\n\n it 'should manage ai players', ->",
"end": 2753,
"score": 0.7828724384307861,
"start": 2750,
"tag": "NAME",
"value": "chr"
}
] | spec/poker/dealer-spec.coffee | robksawyer/hubot-poker | 1 | Game = require('../../js/token-poker/base-game')
Dealer = require('../../js/poker/dealer')
GameCommand = require('../../js/poker/game-command')
Rounds = require('../../js/poker/round')
describe 'Dealer', ->
dealer = null
storage = {}
id = 'dlr'
beforeEach ->
dealer = new Dealer(storage, id, [KillEmAll, LoserWins])
it 'should know about games', ->
game = dealer.listGames()
expect(game[0]).toBe "kill em all"
expect(game[1]).toBe "loser wins"
it 'should default current to first in list', ->
expect(dealer.currentGameClass).toBe KillEmAll
it 'should start a new game by default', ->
expect(dealer.game.constructor.name).toBe 'KillEmAll'
it 'should return status of current game', ->
result = dealer.getStatus()
expect(result).toBe "game status"
it 'should change the game', ->
dealer.changeGame('chrismo', 'loser')
expect(dealer.game.constructor.name).toBe 'LoserWins'
it 'should throw on change game when name is not found', ->
expect(-> dealer.changeGame('chrismo', 'nope')).toThrow 'Cannot find a game matching <nope>'
it 'should throw on change game when too many hits', ->
expect(-> dealer.changeGame('chrismo', 'i')).toThrow 'Be more specific, more than one name matches <i>'
it 'should finishRound on the current game if new game is different', ->
listener = new FakeListener
dealer.addListener(listener)
dealer.sendToGame('chrismo', '123123')
dealer.sendToGame('romer', '123123')
firstGame = dealer.game
expect(firstGame.round.isStarted()).toBe true
dealer.changeGame('chrismo', 'loser')
expect(dealer.game.constructor.name).toBe 'LoserWins'
expect(firstGame.round.isOver()).toBe true
expect(listener.finishRound).toBe true
it 'should do nothing if the requested game is already in play', ->
dealer.sendToGame('chrismo', '123123')
dealer.sendToGame('romer', '123123')
firstGame = dealer.game
expect(firstGame.round.isStarted()).toBe true
dealer.changeGame('chrismo', 'kill')
expect(firstGame.round.isOver()).toBe false
expect(firstGame).toBe dealer.game
it 'should listen to game events and push to its listener', ->
listener = new FakeListener
dealer.addListener(listener)
game = dealer.game
game.pushStatus('foobar')
expect(listener.lastStatus).toBe 'foobar'
it 'should handle a bet game command', ->
res = dealer.sendToGame('chrismo', 'bet 12')
expect(res).toBe 'chrismo bet 12'
it 'should handle a second game command', ->
res = dealer.sendToGame('chrismo', 'fund 12')
expect(res).toBe "chrismo funded 12"
it 'should handle a multiple argument command', ->
res = dealer.sendToGame('chrismo', 'many foo bar')
expect(res).toBe "chrismo foo bar"
it 'should manage ai players', ->
dealer.addAi('foo')
dealer.addAi('bar')
expect(dealer.ais.length).toBe 2
expect(dealer.ais[0].name).toBe 'foo'
expect(dealer.ais[1].name).toBe 'bar'
dealer.killAi('bar')
expect(dealer.ais.length).toBe 1
expect(dealer.ais[0].name).toBe 'foo'
dealer.killAi('foo')
expect(dealer.ais.length).toBe 0
class KillEmAll extends Game.BaseGame
constructor: ->
super
@round = new Rounds.TimedRound(1)
commands: -> [
new GameCommand(/^(\d{6})$/i, this.play),
new GameCommand(/^bet (\d+)$/i, this.bet),
new GameCommand(/^fund (\d+)$/i, this.fundPlayer),
new GameCommand(/^many (\w+) (\w+)/i, this.manyArgumentCommand)
]
isStarted: ->
@round.isStarted()
startRound: ->
super
@round.start()
finishRound: ->
super
@round.end()
abortGame: ->
this.finishRound()
play: (player, hand) ->
this.ensureRoundStarted()
"#{player} played #{hand}"
bet: (player, bet) ->
"#{player} bet #{bet}"
fundPlayer: (player, amount) ->
"#{player} funded #{amount}"
manyArgumentCommand: (player, one, two) ->
"#{player} #{one} #{two}"
getStatus: ->
"game status"
class LoserWins extends Game.BaseGame
class FakeListener
onStatus: (@lastStatus) ->
onStartRound: ->
@startRound = true
onFinishRound: ->
@finishRound = true
| 96623 | Game = require('../../js/token-poker/base-game')
Dealer = require('../../js/poker/dealer')
GameCommand = require('../../js/poker/game-command')
Rounds = require('../../js/poker/round')
describe 'Dealer', ->
dealer = null
storage = {}
id = 'dlr'
beforeEach ->
dealer = new Dealer(storage, id, [KillEmAll, LoserWins])
it 'should know about games', ->
game = dealer.listGames()
expect(game[0]).toBe "kill em all"
expect(game[1]).toBe "loser wins"
it 'should default current to first in list', ->
expect(dealer.currentGameClass).toBe KillEmAll
it 'should start a new game by default', ->
expect(dealer.game.constructor.name).toBe 'KillEmAll'
it 'should return status of current game', ->
result = dealer.getStatus()
expect(result).toBe "game status"
it 'should change the game', ->
dealer.changeGame('<NAME>ismo', 'loser')
expect(dealer.game.constructor.name).toBe 'LoserWins'
it 'should throw on change game when name is not found', ->
expect(-> dealer.changeGame('<NAME>ismo', 'nope')).toThrow 'Cannot find a game matching <nope>'
it 'should throw on change game when too many hits', ->
expect(-> dealer.changeGame('<NAME>ismo', 'i')).toThrow 'Be more specific, more than one name matches <i>'
it 'should finishRound on the current game if new game is different', ->
listener = new FakeListener
dealer.addListener(listener)
dealer.sendToGame('<NAME>ismo', '123123')
dealer.sendToGame('<NAME>', '123123')
firstGame = dealer.game
expect(firstGame.round.isStarted()).toBe true
dealer.changeGame('<NAME>ismo', 'loser')
expect(dealer.game.constructor.name).toBe 'LoserWins'
expect(firstGame.round.isOver()).toBe true
expect(listener.finishRound).toBe true
it 'should do nothing if the requested game is already in play', ->
dealer.sendToGame('<NAME>ismo', '123123')
dealer.sendToGame('<NAME>', '123123')
firstGame = dealer.game
expect(firstGame.round.isStarted()).toBe true
dealer.changeGame('<NAME>ismo', 'kill')
expect(firstGame.round.isOver()).toBe false
expect(firstGame).toBe dealer.game
it 'should listen to game events and push to its listener', ->
listener = new FakeListener
dealer.addListener(listener)
game = dealer.game
game.pushStatus('foobar')
expect(listener.lastStatus).toBe 'foobar'
it 'should handle a bet game command', ->
res = dealer.sendToGame('<NAME>', 'bet 12')
expect(res).toBe '<NAME>ismo bet 12'
it 'should handle a second game command', ->
res = dealer.sendToGame('<NAME>', 'fund 12')
expect(res).toBe "<NAME>ismo funded 12"
it 'should handle a multiple argument command', ->
res = dealer.sendToGame('<NAME>ismo', 'many foo bar')
expect(res).toBe "<NAME>ismo foo bar"
it 'should manage ai players', ->
dealer.addAi('foo')
dealer.addAi('bar')
expect(dealer.ais.length).toBe 2
expect(dealer.ais[0].name).toBe 'foo'
expect(dealer.ais[1].name).toBe 'bar'
dealer.killAi('bar')
expect(dealer.ais.length).toBe 1
expect(dealer.ais[0].name).toBe 'foo'
dealer.killAi('foo')
expect(dealer.ais.length).toBe 0
class KillEmAll extends Game.BaseGame
constructor: ->
super
@round = new Rounds.TimedRound(1)
commands: -> [
new GameCommand(/^(\d{6})$/i, this.play),
new GameCommand(/^bet (\d+)$/i, this.bet),
new GameCommand(/^fund (\d+)$/i, this.fundPlayer),
new GameCommand(/^many (\w+) (\w+)/i, this.manyArgumentCommand)
]
isStarted: ->
@round.isStarted()
startRound: ->
super
@round.start()
finishRound: ->
super
@round.end()
abortGame: ->
this.finishRound()
play: (player, hand) ->
this.ensureRoundStarted()
"#{player} played #{hand}"
bet: (player, bet) ->
"#{player} bet #{bet}"
fundPlayer: (player, amount) ->
"#{player} funded #{amount}"
manyArgumentCommand: (player, one, two) ->
"#{player} #{one} #{two}"
getStatus: ->
"game status"
class LoserWins extends Game.BaseGame
class FakeListener
onStatus: (@lastStatus) ->
onStartRound: ->
@startRound = true
onFinishRound: ->
@finishRound = true
| true | Game = require('../../js/token-poker/base-game')
Dealer = require('../../js/poker/dealer')
GameCommand = require('../../js/poker/game-command')
Rounds = require('../../js/poker/round')
describe 'Dealer', ->
dealer = null
storage = {}
id = 'dlr'
beforeEach ->
dealer = new Dealer(storage, id, [KillEmAll, LoserWins])
it 'should know about games', ->
game = dealer.listGames()
expect(game[0]).toBe "kill em all"
expect(game[1]).toBe "loser wins"
it 'should default current to first in list', ->
expect(dealer.currentGameClass).toBe KillEmAll
it 'should start a new game by default', ->
expect(dealer.game.constructor.name).toBe 'KillEmAll'
it 'should return status of current game', ->
result = dealer.getStatus()
expect(result).toBe "game status"
it 'should change the game', ->
dealer.changeGame('PI:NAME:<NAME>END_PIismo', 'loser')
expect(dealer.game.constructor.name).toBe 'LoserWins'
it 'should throw on change game when name is not found', ->
expect(-> dealer.changeGame('PI:NAME:<NAME>END_PIismo', 'nope')).toThrow 'Cannot find a game matching <nope>'
it 'should throw on change game when too many hits', ->
expect(-> dealer.changeGame('PI:NAME:<NAME>END_PIismo', 'i')).toThrow 'Be more specific, more than one name matches <i>'
it 'should finishRound on the current game if new game is different', ->
listener = new FakeListener
dealer.addListener(listener)
dealer.sendToGame('PI:NAME:<NAME>END_PIismo', '123123')
dealer.sendToGame('PI:NAME:<NAME>END_PI', '123123')
firstGame = dealer.game
expect(firstGame.round.isStarted()).toBe true
dealer.changeGame('PI:NAME:<NAME>END_PIismo', 'loser')
expect(dealer.game.constructor.name).toBe 'LoserWins'
expect(firstGame.round.isOver()).toBe true
expect(listener.finishRound).toBe true
it 'should do nothing if the requested game is already in play', ->
dealer.sendToGame('PI:NAME:<NAME>END_PIismo', '123123')
dealer.sendToGame('PI:NAME:<NAME>END_PI', '123123')
firstGame = dealer.game
expect(firstGame.round.isStarted()).toBe true
dealer.changeGame('PI:NAME:<NAME>END_PIismo', 'kill')
expect(firstGame.round.isOver()).toBe false
expect(firstGame).toBe dealer.game
it 'should listen to game events and push to its listener', ->
listener = new FakeListener
dealer.addListener(listener)
game = dealer.game
game.pushStatus('foobar')
expect(listener.lastStatus).toBe 'foobar'
it 'should handle a bet game command', ->
res = dealer.sendToGame('PI:NAME:<NAME>END_PI', 'bet 12')
expect(res).toBe 'PI:NAME:<NAME>END_PIismo bet 12'
it 'should handle a second game command', ->
res = dealer.sendToGame('PI:NAME:<NAME>END_PI', 'fund 12')
expect(res).toBe "PI:NAME:<NAME>END_PIismo funded 12"
it 'should handle a multiple argument command', ->
res = dealer.sendToGame('PI:NAME:<NAME>END_PIismo', 'many foo bar')
expect(res).toBe "PI:NAME:<NAME>END_PIismo foo bar"
it 'should manage ai players', ->
dealer.addAi('foo')
dealer.addAi('bar')
expect(dealer.ais.length).toBe 2
expect(dealer.ais[0].name).toBe 'foo'
expect(dealer.ais[1].name).toBe 'bar'
dealer.killAi('bar')
expect(dealer.ais.length).toBe 1
expect(dealer.ais[0].name).toBe 'foo'
dealer.killAi('foo')
expect(dealer.ais.length).toBe 0
class KillEmAll extends Game.BaseGame
constructor: ->
super
@round = new Rounds.TimedRound(1)
commands: -> [
new GameCommand(/^(\d{6})$/i, this.play),
new GameCommand(/^bet (\d+)$/i, this.bet),
new GameCommand(/^fund (\d+)$/i, this.fundPlayer),
new GameCommand(/^many (\w+) (\w+)/i, this.manyArgumentCommand)
]
isStarted: ->
@round.isStarted()
startRound: ->
super
@round.start()
finishRound: ->
super
@round.end()
abortGame: ->
this.finishRound()
play: (player, hand) ->
this.ensureRoundStarted()
"#{player} played #{hand}"
bet: (player, bet) ->
"#{player} bet #{bet}"
fundPlayer: (player, amount) ->
"#{player} funded #{amount}"
manyArgumentCommand: (player, one, two) ->
"#{player} #{one} #{two}"
getStatus: ->
"game status"
class LoserWins extends Game.BaseGame
class FakeListener
onStatus: (@lastStatus) ->
onStartRound: ->
@startRound = true
onFinishRound: ->
@finishRound = true
|
[
{
"context": "IN_API_KEY: 'foo'\n\t\t\t\t\tRESIN_SUPERVISOR_API_KEY: 'bar'\n\t\t\t\t\tOTHER_VAR: 'hi'\n\t\t\t\t}\n\t\t}\n\t\t@eventTracker.t",
"end": 2443,
"score": 0.6418049335479736,
"start": 2440,
"tag": "KEY",
"value": "bar"
}
] | test/09-event-tracker.spec.coffee | hippolyt/resin-supervisor | 0 | mixpanel = require 'mixpanel'
m = require 'mochainon'
{ expect } = m.chai
{ stub } = m.sinon
supervisorVersion = require '../src/lib/supervisor-version'
{ EventTracker } = require '../src/event-tracker'
describe 'EventTracker', ->
before ->
stub(mixpanel, 'init').callsFake (token) ->
return {
token: token
track: stub().returns()
}
@eventTrackerOffline = new EventTracker()
@eventTracker = new EventTracker()
stub(EventTracker.prototype, 'logEvent')
after ->
EventTracker.prototype.logEvent.restore()
mixpanel.init.restore()
it 'initializes in offline mode', ->
promise = @eventTrackerOffline.init({
offlineMode: true
uuid: 'foobar'
})
expect(promise).to.be.fulfilled
.then =>
expect(@eventTrackerOffline.client).to.be.null
it 'logs events in offline mode, with the correct properties', ->
@eventTrackerOffline.track('Test event', { appId: 'someValue' })
expect(@eventTrackerOffline.logEvent).to.be.calledWith('Event:', 'Test event', JSON.stringify({ appId: 'someValue' }))
it 'initializes a mixpanel client when not in offline mode', ->
promise = @eventTracker.init({
mixpanelToken: 'someToken'
uuid: 'barbaz'
})
expect(promise).to.be.fulfilled
.then =>
expect(mixpanel.init).to.have.been.calledWith('someToken')
expect(@eventTracker.client.token).to.equal('someToken')
expect(@eventTracker.client.track).to.be.a('function')
it 'calls the mixpanel client track function with the event, properties and uuid as distinct_id', ->
@eventTracker.track('Test event 2', { appId: 'someOtherValue' })
expect(@eventTracker.logEvent).to.be.calledWith('Event:', 'Test event 2', JSON.stringify({ appId: 'someOtherValue' }))
expect(@eventTracker.client.track).to.be.calledWith('Test event 2', {
appId: 'someOtherValue'
uuid: 'barbaz'
distinct_id: 'barbaz'
supervisorVersion
})
it 'can be passed an Error and it is added to the event properties', ->
theError = new Error('something went wrong')
@eventTracker.track('Error event', theError)
expect(@eventTracker.client.track).to.be.calledWith('Error event', {
error:
message: theError.message
stack: theError.stack
uuid: 'barbaz'
distinct_id: 'barbaz'
supervisorVersion
})
it 'hides service environment variables, to avoid logging keys or secrets', ->
props = {
service:
appId: '1'
environment: {
RESIN_API_KEY: 'foo'
RESIN_SUPERVISOR_API_KEY: 'bar'
OTHER_VAR: 'hi'
}
}
@eventTracker.track('Some app event', props)
expect(@eventTracker.client.track).to.be.calledWith('Some app event', {
service: { appId: '1' }
uuid: 'barbaz'
distinct_id: 'barbaz'
supervisorVersion
})
it 'should handle being passed no properties object', ->
expect(@eventTracker.track('no-options')).to.not.throw
describe 'Rate limiting', ->
it 'should rate limit events of the same type', ->
@eventTracker.client.track.reset()
@eventTracker.track('test', { });
@eventTracker.track('test', { });
@eventTracker.track('test', { });
@eventTracker.track('test', { });
@eventTracker.track('test', { });
expect(@eventTracker.client.track).to.have.callCount(1)
it 'should rate limit events of the same type with different arguments', ->
@eventTracker.client.track.reset()
@eventTracker.track('test2', { a: 1 });
@eventTracker.track('test2', { b: 2 });
@eventTracker.track('test2', { c: 3 });
@eventTracker.track('test2', { d: 4 });
@eventTracker.track('test2', { e: 5 });
expect(@eventTracker.client.track).to.have.callCount(1)
it 'should not rate limit events of different types', ->
@eventTracker.client.track.reset()
@eventTracker.track('test3', { a: 1 });
@eventTracker.track('test4', { b: 2 });
@eventTracker.track('test5', { c: 3 });
@eventTracker.track('test6', { d: 4 });
@eventTracker.track('test7', { e: 5 });
expect(@eventTracker.client.track).to.have.callCount(5)
| 141356 | mixpanel = require 'mixpanel'
m = require 'mochainon'
{ expect } = m.chai
{ stub } = m.sinon
supervisorVersion = require '../src/lib/supervisor-version'
{ EventTracker } = require '../src/event-tracker'
describe 'EventTracker', ->
before ->
stub(mixpanel, 'init').callsFake (token) ->
return {
token: token
track: stub().returns()
}
@eventTrackerOffline = new EventTracker()
@eventTracker = new EventTracker()
stub(EventTracker.prototype, 'logEvent')
after ->
EventTracker.prototype.logEvent.restore()
mixpanel.init.restore()
it 'initializes in offline mode', ->
promise = @eventTrackerOffline.init({
offlineMode: true
uuid: 'foobar'
})
expect(promise).to.be.fulfilled
.then =>
expect(@eventTrackerOffline.client).to.be.null
it 'logs events in offline mode, with the correct properties', ->
@eventTrackerOffline.track('Test event', { appId: 'someValue' })
expect(@eventTrackerOffline.logEvent).to.be.calledWith('Event:', 'Test event', JSON.stringify({ appId: 'someValue' }))
it 'initializes a mixpanel client when not in offline mode', ->
promise = @eventTracker.init({
mixpanelToken: 'someToken'
uuid: 'barbaz'
})
expect(promise).to.be.fulfilled
.then =>
expect(mixpanel.init).to.have.been.calledWith('someToken')
expect(@eventTracker.client.token).to.equal('someToken')
expect(@eventTracker.client.track).to.be.a('function')
it 'calls the mixpanel client track function with the event, properties and uuid as distinct_id', ->
@eventTracker.track('Test event 2', { appId: 'someOtherValue' })
expect(@eventTracker.logEvent).to.be.calledWith('Event:', 'Test event 2', JSON.stringify({ appId: 'someOtherValue' }))
expect(@eventTracker.client.track).to.be.calledWith('Test event 2', {
appId: 'someOtherValue'
uuid: 'barbaz'
distinct_id: 'barbaz'
supervisorVersion
})
it 'can be passed an Error and it is added to the event properties', ->
theError = new Error('something went wrong')
@eventTracker.track('Error event', theError)
expect(@eventTracker.client.track).to.be.calledWith('Error event', {
error:
message: theError.message
stack: theError.stack
uuid: 'barbaz'
distinct_id: 'barbaz'
supervisorVersion
})
it 'hides service environment variables, to avoid logging keys or secrets', ->
props = {
service:
appId: '1'
environment: {
RESIN_API_KEY: 'foo'
RESIN_SUPERVISOR_API_KEY: '<KEY>'
OTHER_VAR: 'hi'
}
}
@eventTracker.track('Some app event', props)
expect(@eventTracker.client.track).to.be.calledWith('Some app event', {
service: { appId: '1' }
uuid: 'barbaz'
distinct_id: 'barbaz'
supervisorVersion
})
it 'should handle being passed no properties object', ->
expect(@eventTracker.track('no-options')).to.not.throw
describe 'Rate limiting', ->
it 'should rate limit events of the same type', ->
@eventTracker.client.track.reset()
@eventTracker.track('test', { });
@eventTracker.track('test', { });
@eventTracker.track('test', { });
@eventTracker.track('test', { });
@eventTracker.track('test', { });
expect(@eventTracker.client.track).to.have.callCount(1)
it 'should rate limit events of the same type with different arguments', ->
@eventTracker.client.track.reset()
@eventTracker.track('test2', { a: 1 });
@eventTracker.track('test2', { b: 2 });
@eventTracker.track('test2', { c: 3 });
@eventTracker.track('test2', { d: 4 });
@eventTracker.track('test2', { e: 5 });
expect(@eventTracker.client.track).to.have.callCount(1)
it 'should not rate limit events of different types', ->
@eventTracker.client.track.reset()
@eventTracker.track('test3', { a: 1 });
@eventTracker.track('test4', { b: 2 });
@eventTracker.track('test5', { c: 3 });
@eventTracker.track('test6', { d: 4 });
@eventTracker.track('test7', { e: 5 });
expect(@eventTracker.client.track).to.have.callCount(5)
| true | mixpanel = require 'mixpanel'
m = require 'mochainon'
{ expect } = m.chai
{ stub } = m.sinon
supervisorVersion = require '../src/lib/supervisor-version'
{ EventTracker } = require '../src/event-tracker'
describe 'EventTracker', ->
before ->
stub(mixpanel, 'init').callsFake (token) ->
return {
token: token
track: stub().returns()
}
@eventTrackerOffline = new EventTracker()
@eventTracker = new EventTracker()
stub(EventTracker.prototype, 'logEvent')
after ->
EventTracker.prototype.logEvent.restore()
mixpanel.init.restore()
it 'initializes in offline mode', ->
promise = @eventTrackerOffline.init({
offlineMode: true
uuid: 'foobar'
})
expect(promise).to.be.fulfilled
.then =>
expect(@eventTrackerOffline.client).to.be.null
it 'logs events in offline mode, with the correct properties', ->
@eventTrackerOffline.track('Test event', { appId: 'someValue' })
expect(@eventTrackerOffline.logEvent).to.be.calledWith('Event:', 'Test event', JSON.stringify({ appId: 'someValue' }))
it 'initializes a mixpanel client when not in offline mode', ->
promise = @eventTracker.init({
mixpanelToken: 'someToken'
uuid: 'barbaz'
})
expect(promise).to.be.fulfilled
.then =>
expect(mixpanel.init).to.have.been.calledWith('someToken')
expect(@eventTracker.client.token).to.equal('someToken')
expect(@eventTracker.client.track).to.be.a('function')
it 'calls the mixpanel client track function with the event, properties and uuid as distinct_id', ->
@eventTracker.track('Test event 2', { appId: 'someOtherValue' })
expect(@eventTracker.logEvent).to.be.calledWith('Event:', 'Test event 2', JSON.stringify({ appId: 'someOtherValue' }))
expect(@eventTracker.client.track).to.be.calledWith('Test event 2', {
appId: 'someOtherValue'
uuid: 'barbaz'
distinct_id: 'barbaz'
supervisorVersion
})
it 'can be passed an Error and it is added to the event properties', ->
theError = new Error('something went wrong')
@eventTracker.track('Error event', theError)
expect(@eventTracker.client.track).to.be.calledWith('Error event', {
error:
message: theError.message
stack: theError.stack
uuid: 'barbaz'
distinct_id: 'barbaz'
supervisorVersion
})
it 'hides service environment variables, to avoid logging keys or secrets', ->
props = {
service:
appId: '1'
environment: {
RESIN_API_KEY: 'foo'
RESIN_SUPERVISOR_API_KEY: 'PI:KEY:<KEY>END_PI'
OTHER_VAR: 'hi'
}
}
@eventTracker.track('Some app event', props)
expect(@eventTracker.client.track).to.be.calledWith('Some app event', {
service: { appId: '1' }
uuid: 'barbaz'
distinct_id: 'barbaz'
supervisorVersion
})
it 'should handle being passed no properties object', ->
expect(@eventTracker.track('no-options')).to.not.throw
describe 'Rate limiting', ->
it 'should rate limit events of the same type', ->
@eventTracker.client.track.reset()
@eventTracker.track('test', { });
@eventTracker.track('test', { });
@eventTracker.track('test', { });
@eventTracker.track('test', { });
@eventTracker.track('test', { });
expect(@eventTracker.client.track).to.have.callCount(1)
it 'should rate limit events of the same type with different arguments', ->
@eventTracker.client.track.reset()
@eventTracker.track('test2', { a: 1 });
@eventTracker.track('test2', { b: 2 });
@eventTracker.track('test2', { c: 3 });
@eventTracker.track('test2', { d: 4 });
@eventTracker.track('test2', { e: 5 });
expect(@eventTracker.client.track).to.have.callCount(1)
it 'should not rate limit events of different types', ->
@eventTracker.client.track.reset()
@eventTracker.track('test3', { a: 1 });
@eventTracker.track('test4', { b: 2 });
@eventTracker.track('test5', { c: 3 });
@eventTracker.track('test6', { d: 4 });
@eventTracker.track('test7', { e: 5 });
expect(@eventTracker.client.track).to.have.callCount(5)
|
[
{
"context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 43,
"score": 0.5616934895515442,
"start": 33,
"tag": "NAME",
"value": "Technology"
}
] | community/server/src/main/coffeescript/ribcage/ui/Tooltip.coffee | rebaze/neo4j | 1 | ###
Copyright (c) 2002-2013 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['lib/amd/jQuery', 'lib/amd/Underscore'],
( $ , _ ) ->
class Tooltip
defaultSettings :
hideOnMouseOut : true
css : {}
position : "above"
closeButton : true
constructor : (opts={}) ->
@_tooltip = $("<div class='tooltip-wrap'></div>");
@_tooltipContent = $("<div class='tooltip'></div>");
@_closeButton = $("<div class='tooltip-close'></div>");
@_currentPos = [0,0]
@_currentContent = ""
@_visible = false
@settings = _.extend(@defaultSettings, opts)
if @settings.hideOnMouseOut
@_tooltip.bind "mouseout", @hide
@_tooltip.addClass("tooltip-pos-" + @settings.position)
@_tooltip.css(@settings.css)
@_tooltip.append(@_tooltipContent)
if @settings.closeButton
@_tooltip.append @_closeButton
@_closeButton.bind "click", @hide
@_tooltip.appendTo "body"
$(window).resize @onWindowResized
show : (content, pos, timeout) =>
@_currentPos = pos;
@_currentContent = content;
@_tooltipContent.html(content);
pos = @getTooltipPositionFor(@getPosition(pos));
@_tooltip.css({left: pos[0], top: pos[1] }).show();
@_visible = true;
if timeout
setTimeout @hide, timeout
hide : () =>
@_tooltip.hide()
@_visible = false
remove : () =>
@_tooltip.unbind "mouseout", @hide
@_closeButton.unbind "click", @hide
@_tooltip.remove()
onWindowResized : () =>
if @_visible
updatePosition = () =>
@show(@_currentContent, @_currentPos)
setTimeout( updatePosition, 0 )
getPosition : (pos) =>
if _.isArray(pos)
pos;
else
el = $(pos);
pos = el.offset();
switch @settings.position
when "right"
[pos.left + (el.width()), pos.top + (el.height()/2)]
when "left"
[pos.left, pos.top + (el.height()/2)]
when "above"
[pos.left + (el.width()/2), pos.top]
else
[pos.left + (el.width()/2), pos.top - el.height()]
getTooltipPositionFor: (pointToPosition) =>
switch @settings.position
when "right"
[pointToPosition[0]+10, pointToPosition[1]-(@_tooltip.height()/2)]
when "left"
[pointToPosition[0]-(@_tooltip.width()+10), pointToPosition[1]-(@_tooltip.height()/2)]
when "above"
[pointToPosition[0]-@_tooltip.width()/2, pointToPosition[1]-(@_tooltip.height()+10)]
else
[pointToPosition[0]-this._tooltip.width()/2, pointToPosition[1]+(@_tooltip.height())]
)
| 154300 | ###
Copyright (c) 2002-2013 "Neo <NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['lib/amd/jQuery', 'lib/amd/Underscore'],
( $ , _ ) ->
class Tooltip
defaultSettings :
hideOnMouseOut : true
css : {}
position : "above"
closeButton : true
constructor : (opts={}) ->
@_tooltip = $("<div class='tooltip-wrap'></div>");
@_tooltipContent = $("<div class='tooltip'></div>");
@_closeButton = $("<div class='tooltip-close'></div>");
@_currentPos = [0,0]
@_currentContent = ""
@_visible = false
@settings = _.extend(@defaultSettings, opts)
if @settings.hideOnMouseOut
@_tooltip.bind "mouseout", @hide
@_tooltip.addClass("tooltip-pos-" + @settings.position)
@_tooltip.css(@settings.css)
@_tooltip.append(@_tooltipContent)
if @settings.closeButton
@_tooltip.append @_closeButton
@_closeButton.bind "click", @hide
@_tooltip.appendTo "body"
$(window).resize @onWindowResized
show : (content, pos, timeout) =>
@_currentPos = pos;
@_currentContent = content;
@_tooltipContent.html(content);
pos = @getTooltipPositionFor(@getPosition(pos));
@_tooltip.css({left: pos[0], top: pos[1] }).show();
@_visible = true;
if timeout
setTimeout @hide, timeout
hide : () =>
@_tooltip.hide()
@_visible = false
remove : () =>
@_tooltip.unbind "mouseout", @hide
@_closeButton.unbind "click", @hide
@_tooltip.remove()
onWindowResized : () =>
if @_visible
updatePosition = () =>
@show(@_currentContent, @_currentPos)
setTimeout( updatePosition, 0 )
getPosition : (pos) =>
if _.isArray(pos)
pos;
else
el = $(pos);
pos = el.offset();
switch @settings.position
when "right"
[pos.left + (el.width()), pos.top + (el.height()/2)]
when "left"
[pos.left, pos.top + (el.height()/2)]
when "above"
[pos.left + (el.width()/2), pos.top]
else
[pos.left + (el.width()/2), pos.top - el.height()]
getTooltipPositionFor: (pointToPosition) =>
switch @settings.position
when "right"
[pointToPosition[0]+10, pointToPosition[1]-(@_tooltip.height()/2)]
when "left"
[pointToPosition[0]-(@_tooltip.width()+10), pointToPosition[1]-(@_tooltip.height()/2)]
when "above"
[pointToPosition[0]-@_tooltip.width()/2, pointToPosition[1]-(@_tooltip.height()+10)]
else
[pointToPosition[0]-this._tooltip.width()/2, pointToPosition[1]+(@_tooltip.height())]
)
| true | ###
Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['lib/amd/jQuery', 'lib/amd/Underscore'],
( $ , _ ) ->
class Tooltip
defaultSettings :
hideOnMouseOut : true
css : {}
position : "above"
closeButton : true
constructor : (opts={}) ->
@_tooltip = $("<div class='tooltip-wrap'></div>");
@_tooltipContent = $("<div class='tooltip'></div>");
@_closeButton = $("<div class='tooltip-close'></div>");
@_currentPos = [0,0]
@_currentContent = ""
@_visible = false
@settings = _.extend(@defaultSettings, opts)
if @settings.hideOnMouseOut
@_tooltip.bind "mouseout", @hide
@_tooltip.addClass("tooltip-pos-" + @settings.position)
@_tooltip.css(@settings.css)
@_tooltip.append(@_tooltipContent)
if @settings.closeButton
@_tooltip.append @_closeButton
@_closeButton.bind "click", @hide
@_tooltip.appendTo "body"
$(window).resize @onWindowResized
show : (content, pos, timeout) =>
@_currentPos = pos;
@_currentContent = content;
@_tooltipContent.html(content);
pos = @getTooltipPositionFor(@getPosition(pos));
@_tooltip.css({left: pos[0], top: pos[1] }).show();
@_visible = true;
if timeout
setTimeout @hide, timeout
hide : () =>
@_tooltip.hide()
@_visible = false
remove : () =>
@_tooltip.unbind "mouseout", @hide
@_closeButton.unbind "click", @hide
@_tooltip.remove()
onWindowResized : () =>
if @_visible
updatePosition = () =>
@show(@_currentContent, @_currentPos)
setTimeout( updatePosition, 0 )
getPosition : (pos) =>
if _.isArray(pos)
pos;
else
el = $(pos);
pos = el.offset();
switch @settings.position
when "right"
[pos.left + (el.width()), pos.top + (el.height()/2)]
when "left"
[pos.left, pos.top + (el.height()/2)]
when "above"
[pos.left + (el.width()/2), pos.top]
else
[pos.left + (el.width()/2), pos.top - el.height()]
getTooltipPositionFor: (pointToPosition) =>
switch @settings.position
when "right"
[pointToPosition[0]+10, pointToPosition[1]-(@_tooltip.height()/2)]
when "left"
[pointToPosition[0]-(@_tooltip.width()+10), pointToPosition[1]-(@_tooltip.height()/2)]
when "above"
[pointToPosition[0]-@_tooltip.width()/2, pointToPosition[1]-(@_tooltip.height()+10)]
else
[pointToPosition[0]-this._tooltip.width()/2, pointToPosition[1]+(@_tooltip.height())]
)
|
[
{
"context": "sed under the MIT License\nDate: 11-08-2015\nAuthor: Julio Cesar Fausto\nSource: https://github.com/jcfausto/jcfausto-com-",
"end": 110,
"score": 0.9998652338981628,
"start": 92,
"tag": "NAME",
"value": "Julio Cesar Fausto"
},
{
"context": "or: Julio Cesar Fausto\nSource: https://github.com/jcfausto/jcfausto-com-rails\n###\n\n@AchievementItem = React.",
"end": 146,
"score": 0.9806420803070068,
"start": 138,
"tag": "USERNAME",
"value": "jcfausto"
}
] | app/assets/javascripts/components/achievement_item.js.jsx.coffee | jcfausto/jcfausto-rails-website | 1 | ###
AchievementItem React Component
Released under the MIT License
Date: 11-08-2015
Author: Julio Cesar Fausto
Source: https://github.com/jcfausto/jcfausto-com-rails
###
@AchievementItem = React.createClass
getInitialState: ->
when: this.props.when
what: this.props.what
logWhen: ->
console.log("abacaxi")
#I am using the raw html here because one could create anchors inside
#the what and in order to this work it was necessary to output
#the raw value of this property.
#using this library http://momentjs.com/, loaded through vendor assets
render: ->
`<li>
<p>{moment(this.state.when).format("MMMM Do YYYY")}</p>
<p dangerouslySetInnerHTML={{__html: this.state.what}} />
</li>`
| 82341 | ###
AchievementItem React Component
Released under the MIT License
Date: 11-08-2015
Author: <NAME>
Source: https://github.com/jcfausto/jcfausto-com-rails
###
@AchievementItem = React.createClass
getInitialState: ->
when: this.props.when
what: this.props.what
logWhen: ->
console.log("abacaxi")
#I am using the raw html here because one could create anchors inside
#the what and in order to this work it was necessary to output
#the raw value of this property.
#using this library http://momentjs.com/, loaded through vendor assets
render: ->
`<li>
<p>{moment(this.state.when).format("MMMM Do YYYY")}</p>
<p dangerouslySetInnerHTML={{__html: this.state.what}} />
</li>`
| true | ###
AchievementItem React Component
Released under the MIT License
Date: 11-08-2015
Author: PI:NAME:<NAME>END_PI
Source: https://github.com/jcfausto/jcfausto-com-rails
###
@AchievementItem = React.createClass
getInitialState: ->
when: this.props.when
what: this.props.what
logWhen: ->
console.log("abacaxi")
#I am using the raw html here because one could create anchors inside
#the what and in order to this work it was necessary to output
#the raw value of this property.
#using this library http://momentjs.com/, loaded through vendor assets
render: ->
`<li>
<p>{moment(this.state.when).format("MMMM Do YYYY")}</p>
<p dangerouslySetInnerHTML={{__html: this.state.what}} />
</li>`
|
[
{
"context": "\n collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))\n collection.add(ne",
"end": 1586,
"score": 0.9996006488800049,
"start": 1581,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))\n assert.equal(coll",
"end": 1670,
"score": 0.9989392757415771,
"start": 1664,
"tag": "NAME",
"value": "George"
},
{
"context": "\n collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5557'}))\n assert.equal(coll",
"end": 1855,
"score": 0.9995429515838623,
"start": 1851,
"tag": "NAME",
"value": "Paul"
},
{
"context": "\n collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))\n collection.add(ne",
"end": 2871,
"score": 0.9994244575500488,
"start": 2866,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))\n assert.equal(coll",
"end": 2955,
"score": 0.9991312026977539,
"start": 2949,
"tag": "NAME",
"value": "George"
},
{
"context": "\n collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5557'}))\n assert.equal(coll",
"end": 3140,
"score": 0.9994605779647827,
"start": 3136,
"tag": "NAME",
"value": "Paul"
},
{
"context": "\n collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5555'}))\n collection.add(ne",
"end": 4147,
"score": 0.9989692568778992,
"start": 4142,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5556'}))\n assert.equal(coll",
"end": 4231,
"score": 0.9991592764854431,
"start": 4225,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 4370,
"score": 0.9988712668418884,
"start": 4365,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 4379,
"score": 0.9958547949790955,
"start": 4374,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection",
"end": 4449,
"score": 0.9689589738845825,
"start": 4443,
"tag": "NAME",
"value": "George"
},
{
"context": "al(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection_observabl",
"end": 4459,
"score": 0.5141307711601257,
"start": 4455,
"tag": "NAME",
"value": "orge"
},
{
"context": "rt.equal(collection_observable()[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection_o",
"end": 4606,
"score": 0.9989644885063171,
"start": 4601,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "collection_observable()[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection_observable",
"end": 4615,
"score": 0.991382360458374,
"start": 4610,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "rt.equal(collection_observable()[1].get('name'), 'George', \"George is second\")\n\n collection.remove('b2'",
"end": 4691,
"score": 0.9567570686340332,
"start": 4685,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n model = kb.utils.wrappedMo",
"end": 4924,
"score": 0.9985663890838623,
"start": 4919,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "l(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n model = kb.utils.wrappedModel(colle",
"end": 4933,
"score": 0.5125598907470703,
"start": 4932,
"tag": "NAME",
"value": "o"
},
{
"context": "rvable()[0])\n assert.equal(model.get('name'), 'Ringo', \"Ringo is left\")\n model = collection_observa",
"end": 5048,
"score": 0.998292088508606,
"start": 5043,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "0])\n assert.equal(model.get('name'), 'Ringo', \"Ringo is left\")\n model = collection_observable()[0]\n",
"end": 5057,
"score": 0.5938268303871155,
"start": 5052,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ervable()[0]\n assert.equal(model.get('name'), 'Ringo', \"Ringo is left\")\n\n view_model = collection_o",
"end": 5149,
"score": 0.9991602897644043,
"start": 5144,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "[0]\n assert.equal(model.get('name'), 'Ringo', \"Ringo is left\")\n\n view_model = collection_observable",
"end": 5158,
"score": 0.997775673866272,
"start": 5153,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5555'}))\n collection.add(ne",
"end": 6248,
"score": 0.9990975856781006,
"start": 6243,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5556'}))\n assert.equal(coll",
"end": 6332,
"score": 0.9987043738365173,
"start": 6326,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 6471,
"score": 0.9991025924682617,
"start": 6466,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 6480,
"score": 0.9967563152313232,
"start": 6475,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection",
"end": 6550,
"score": 0.9911653399467468,
"start": 6544,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection_observabl",
"end": 6560,
"score": 0.9215126037597656,
"start": 6554,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(kb.utils.wra",
"end": 6730,
"score": 0.9983821511268616,
"start": 6725,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[0]).get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(kb.utils.wrappedModel",
"end": 6739,
"score": 0.9744758605957031,
"start": 6734,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'George', \"George is second\")\n\n collection.remove('b2'",
"end": 6838,
"score": 0.9880776405334473,
"start": 6832,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[1]).get('name'), 'George', \"George is second\")\n\n collection.remove('b2')\n asse",
"end": 6848,
"score": 0.7150306701660156,
"start": 6842,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n model = kb.utils.wrappedMo",
"end": 7069,
"score": 0.9994937181472778,
"start": 7064,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n model = kb.utils.wrappedModel(colle",
"end": 7078,
"score": 0.9964808225631714,
"start": 7073,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "rvable()[0])\n assert.equal(model.get('name'), 'Ringo', \"Ringo is left\")\n\n view_model = collection_o",
"end": 7193,
"score": 0.999529242515564,
"start": 7188,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "0])\n assert.equal(model.get('name'), 'Ringo', \"Ringo is left\")\n\n view_model = collection_observable",
"end": 7202,
"score": 0.8356430530548096,
"start": 7197,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "l(kb.utils.wrappedModel(view_model).get('name'), 'Ringo', \"Ringo is left\")\n\n view_model_count = 0\n ",
"end": 7347,
"score": 0.9991879463195801,
"start": 7342,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "appedModel(view_model).get('name'), 'Ringo', \"Ringo is left\")\n\n view_model_count = 0\n _.each(co",
"end": 7356,
"score": 0.9351378083229065,
"start": 7355,
"tag": "NAME",
"value": "o"
},
{
"context": "\n collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))\n collection.add(ne",
"end": 8287,
"score": 0.9996044635772705,
"start": 8282,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))\n assert.equal(coll",
"end": 8371,
"score": 0.9989932775497437,
"start": 8365,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 8510,
"score": 0.9995725154876709,
"start": 8505,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 8519,
"score": 0.9991174936294556,
"start": 8514,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection",
"end": 8589,
"score": 0.9993139505386353,
"start": 8583,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection_observabl",
"end": 8599,
"score": 0.9568877220153809,
"start": 8593,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert",
"end": 8770,
"score": 0.9993628263473511,
"start": 8764,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert.equal(kb.",
"end": 8780,
"score": 0.9990588426589966,
"start": 8774,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n colle",
"end": 8896,
"score": 0.9993677735328674,
"start": 8891,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[1]).get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n collection.add",
"end": 8905,
"score": 0.996988832950592,
"start": 8900,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5557'}))\n assert.equal(coll",
"end": 8990,
"score": 0.9994980692863464,
"start": 8986,
"tag": "NAME",
"value": "Paul"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 9131,
"score": 0.9989026784896851,
"start": 9126,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 9140,
"score": 0.9903509020805359,
"start": 9135,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection",
"end": 9210,
"score": 0.9992444515228271,
"start": 9204,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection.models[2]",
"end": 9220,
"score": 0.9972835779190063,
"start": 9214,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[2].get('name'), 'Paul', \"Paul is second\")\n assert.equal(collection_o",
"end": 9289,
"score": 0.9994422197341919,
"start": 9285,
"tag": "NAME",
"value": "Paul"
},
{
"context": ".equal(collection.models[2].get('name'), 'Paul', \"Paul is second\")\n assert.equal(collection_observabl",
"end": 9297,
"score": 0.9990389347076416,
"start": 9293,
"tag": "NAME",
"value": "Paul"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert",
"end": 9468,
"score": 0.999123752117157,
"start": 9462,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert.equal(kb.",
"end": 9478,
"score": 0.9990276098251343,
"start": 9472,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'Paul', \"Paul is second - sorting worked!\")\n assert.",
"end": 9593,
"score": 0.9992042779922485,
"start": 9589,
"tag": "NAME",
"value": "Paul"
},
{
"context": "collection_observable()[1]).get('name'), 'Paul', \"Paul is second - sorting worked!\")\n assert.equal(kb",
"end": 9601,
"score": 0.9991321563720703,
"start": 9597,
"tag": "NAME",
"value": "Paul"
},
{
"context": "edModel(collection_observable()[2]).get('name'), 'Ringo', \"Ringo is third - sorting worked!\")\n\n collec",
"end": 9718,
"score": 0.9991047382354736,
"start": 9713,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[2]).get('name'), 'Ringo', \"Ringo is third - sorting worked!\")\n\n collection.remo",
"end": 9727,
"score": 0.9957023859024048,
"start": 9722,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n assert.equal(kb.utils.wrap",
"end": 9990,
"score": 0.9991476535797119,
"start": 9985,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n assert.equal(kb.utils.wrappedModel(",
"end": 9999,
"score": 0.8853796720504761,
"start": 9994,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'Ringo', \"Ringo is left\")\n\n collection.reset()\n as",
"end": 10096,
"score": 0.9990402460098267,
"start": 10091,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[0]).get('name'), 'Ringo', \"Ringo is left\")\n\n collection.reset()\n assert.equa",
"end": 10105,
"score": 0.7905985116958618,
"start": 10100,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))\n collection.add(ne",
"end": 11209,
"score": 0.999387264251709,
"start": 11204,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))\n assert.equal(coll",
"end": 11293,
"score": 0.9991693496704102,
"start": 11287,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 11432,
"score": 0.9983466863632202,
"start": 11427,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 11441,
"score": 0.9890222549438477,
"start": 11436,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection",
"end": 11511,
"score": 0.9930504560470581,
"start": 11505,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection_observabl",
"end": 11521,
"score": 0.9363937377929688,
"start": 11515,
"tag": "NAME",
"value": "George"
},
{
"context": "rt.equal(collection_observable()[0].get('name'), 'George', \"George is first - sorting worked!\")\n assert",
"end": 11669,
"score": 0.9893894195556641,
"start": 11663,
"tag": "NAME",
"value": "George"
},
{
"context": "ollection_observable()[0].get('name'), 'George', \"George is first - sorting worked!\")\n assert.equal(col",
"end": 11679,
"score": 0.9148768186569214,
"start": 11673,
"tag": "NAME",
"value": "George"
},
{
"context": "rt.equal(collection_observable()[1].get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n # cle",
"end": 11772,
"score": 0.9989863634109497,
"start": 11767,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "collection_observable()[1].get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n # clean up\n ",
"end": 11781,
"score": 0.9958758354187012,
"start": 11776,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))\n collection.add(ne",
"end": 12122,
"score": 0.9993005990982056,
"start": 12117,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))\n assert.equal(coll",
"end": 12206,
"score": 0.9996615052223206,
"start": 12200,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 12345,
"score": 0.999732255935669,
"start": 12340,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 12354,
"score": 0.9995054602622986,
"start": 12349,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection",
"end": 12424,
"score": 0.999752402305603,
"start": 12418,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection_observabl",
"end": 12434,
"score": 0.9992612600326538,
"start": 12428,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert",
"end": 12605,
"score": 0.9996963739395142,
"start": 12599,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert.equal(kb.",
"end": 12615,
"score": 0.9993460774421692,
"start": 12609,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n # cle",
"end": 12731,
"score": 0.999739408493042,
"start": 12726,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[1]).get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n # clean up\n ",
"end": 12740,
"score": 0.9996210932731628,
"start": 12735,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))\n collection.add(ne",
"end": 13637,
"score": 0.9997156858444214,
"start": 13632,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))\n assert.equal(coll",
"end": 13721,
"score": 0.9996381998062134,
"start": 13715,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'George', \"George is first\")\n assert.equal(collection.",
"end": 13861,
"score": 0.9996107816696167,
"start": 13855,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[0].get('name'), 'George', \"George is first\")\n assert.equal(collection.models[1].",
"end": 13871,
"score": 0.999380350112915,
"start": 13865,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'Ringo', \"Ringo is second\")\n assert.equal(collection_",
"end": 13940,
"score": 0.9995611906051636,
"start": 13935,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[1].get('name'), 'Ringo', \"Ringo is second\")\n assert.equal(collection_observabl",
"end": 13949,
"score": 0.9988993406295776,
"start": 13944,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert",
"end": 14120,
"score": 0.9994198679924011,
"start": 14114,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert.equal(kb.",
"end": 14130,
"score": 0.999134361743927,
"start": 14124,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n colle",
"end": 14246,
"score": 0.99945068359375,
"start": 14241,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[1]).get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n collection.add",
"end": 14255,
"score": 0.9963307976722717,
"start": 14250,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5557'}))\n assert.equal(coll",
"end": 14340,
"score": 0.9996317625045776,
"start": 14336,
"tag": "NAME",
"value": "Paul"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'George', \"George is first\")\n assert.equal(collection.",
"end": 14482,
"score": 0.9992915987968445,
"start": 14476,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[0].get('name'), 'George', \"George is first\")\n assert.equal(collection.models[1].",
"end": 14492,
"score": 0.9980320930480957,
"start": 14486,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'Paul', \"Paul is second\")\n assert.equal(collection.m",
"end": 14560,
"score": 0.9995781183242798,
"start": 14556,
"tag": "NAME",
"value": "Paul"
},
{
"context": ".equal(collection.models[1].get('name'), 'Paul', \"Paul is second\")\n assert.equal(collection.models[2]",
"end": 14568,
"score": 0.999427080154419,
"start": 14564,
"tag": "NAME",
"value": "Paul"
},
{
"context": " assert.equal(collection.models[2].get('name'), 'Ringo', \"Ringo is second\")\n assert.equal(collection_",
"end": 14638,
"score": 0.9993452429771423,
"start": 14633,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[2].get('name'), 'Ringo', \"Ringo is second\")\n assert.equal(collection_observabl",
"end": 14647,
"score": 0.998184084892273,
"start": 14642,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert",
"end": 14818,
"score": 0.9991723895072937,
"start": 14812,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert.equal(kb.",
"end": 14828,
"score": 0.9989597201347351,
"start": 14822,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'Paul', \"Paul is second - sorting worked!\")\n assert.",
"end": 14943,
"score": 0.999314546585083,
"start": 14939,
"tag": "NAME",
"value": "Paul"
},
{
"context": "collection_observable()[1]).get('name'), 'Paul', \"Paul is second - sorting worked!\")\n assert.equal(kb",
"end": 14951,
"score": 0.999183177947998,
"start": 14947,
"tag": "NAME",
"value": "Paul"
},
{
"context": "edModel(collection_observable()[2]).get('name'), 'Ringo', \"Ringo is third - sorting worked!\")\n\n collec",
"end": 15068,
"score": 0.9990872144699097,
"start": 15063,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[2]).get('name'), 'Ringo', \"Ringo is third - sorting worked!\")\n\n collection.remo",
"end": 15077,
"score": 0.9972419142723083,
"start": 15072,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n assert.equal(kb.utils.wrap",
"end": 15342,
"score": 0.999268651008606,
"start": 15337,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n assert.equal(kb.utils.wrappedModel(",
"end": 15351,
"score": 0.9977028369903564,
"start": 15346,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'Ringo', \"Ringo is left\")\n\n collection.reset()\n as",
"end": 15448,
"score": 0.9991229772567749,
"start": 15443,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))\n collection.add(ne",
"end": 16267,
"score": 0.999066174030304,
"start": 16262,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))\n assert.equal(coll",
"end": 16351,
"score": 0.9985899925231934,
"start": 16345,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 16490,
"score": 0.9947067499160767,
"start": 16485,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 16499,
"score": 0.9652920961380005,
"start": 16494,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection",
"end": 16569,
"score": 0.9242401123046875,
"start": 16563,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection_observabl",
"end": 16579,
"score": 0.7780261635780334,
"start": 16573,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'Ringo', \"Ringo is first - no sorting\")\n assert.equal",
"end": 16749,
"score": 0.9938246011734009,
"start": 16744,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[0]).get('name'), 'Ringo', \"Ringo is first - no sorting\")\n assert.equal(kb.utils",
"end": 16758,
"score": 0.9691559076309204,
"start": 16753,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'George', \"George is first - no sorting\")\n\n collection",
"end": 16870,
"score": 0.9347082376480103,
"start": 16864,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[1]).get('name'), 'George', \"George is first - no sorting\")\n\n collection_obser",
"end": 16876,
"score": 0.6137537360191345,
"start": 16874,
"tag": "NAME",
"value": "Ge"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 17011,
"score": 0.9951269030570984,
"start": 17006,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 17020,
"score": 0.9257601499557495,
"start": 17015,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(kb.utils.w",
"end": 17090,
"score": 0.9206079244613647,
"start": 17084,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(kb.utils.wrappedMode",
"end": 17100,
"score": 0.7438523769378662,
"start": 17094,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert",
"end": 17200,
"score": 0.9217161536216736,
"start": 17194,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert.equal",
"end": 17206,
"score": 0.5145419239997864,
"start": 17204,
"tag": "NAME",
"value": "Ge"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n colle",
"end": 17326,
"score": 0.986566424369812,
"start": 17321,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[1]).get('name'), 'Ringo', \"Ringo is second - sorting worked!\")\n\n collection.add",
"end": 17335,
"score": 0.8106682896614075,
"start": 17330,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5554'}))\n assert.equal(coll",
"end": 17420,
"score": 0.9988116025924683,
"start": 17416,
"tag": "NAME",
"value": "Paul"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 17561,
"score": 0.9992192983627319,
"start": 17556,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 17570,
"score": 0.9988422989845276,
"start": 17565,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection",
"end": 17640,
"score": 0.999249279499054,
"start": 17634,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection.models[2]",
"end": 17650,
"score": 0.9982437491416931,
"start": 17644,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[2].get('name'), 'Paul', \"Paul is second\")\n assert.equal(collection_o",
"end": 17719,
"score": 0.999366283416748,
"start": 17715,
"tag": "NAME",
"value": "Paul"
},
{
"context": ".equal(collection.models[2].get('name'), 'Paul', \"Paul is second\")\n assert.equal(collection_observabl",
"end": 17727,
"score": 0.9987919926643372,
"start": 17723,
"tag": "NAME",
"value": "Paul"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert",
"end": 17898,
"score": 0.999343752861023,
"start": 17892,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[0]).get('name'), 'George', \"George is first - sorting worked!\")\n assert.equal(kb.",
"end": 17908,
"score": 0.9988864660263062,
"start": 17902,
"tag": "NAME",
"value": "George"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'Paul', \"Paul is second - sorting worked!\")\n assert.",
"end": 18023,
"score": 0.9993033409118652,
"start": 18019,
"tag": "NAME",
"value": "Paul"
},
{
"context": "collection_observable()[1]).get('name'), 'Paul', \"Paul is second - sorting worked!\")\n assert.equal(kb",
"end": 18031,
"score": 0.9991496801376343,
"start": 18027,
"tag": "NAME",
"value": "Paul"
},
{
"context": "edModel(collection_observable()[2]).get('name'), 'Ringo', \"Ringo is third - sorting worked!\")\n\n collec",
"end": 18148,
"score": 0.9991335272789001,
"start": 18143,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[2]).get('name'), 'Ringo', \"Ringo is third - sorting worked!\")\n\n collection_obse",
"end": 18157,
"score": 0.9980734586715698,
"start": 18152,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.m",
"end": 18295,
"score": 0.999106764793396,
"start": 18290,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is first\")\n assert.equal(collection.models[1].",
"end": 18304,
"score": 0.9985321760177612,
"start": 18299,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection",
"end": 18374,
"score": 0.998868465423584,
"start": 18368,
"tag": "NAME",
"value": "George"
},
{
"context": "qual(collection.models[1].get('name'), 'George', \"George is second\")\n assert.equal(collection.models[2]",
"end": 18384,
"score": 0.9983259439468384,
"start": 18378,
"tag": "NAME",
"value": "George"
},
{
"context": " assert.equal(collection.models[2].get('name'), 'Paul', \"Paul is second\")\n assert.equal(kb.utils.wra",
"end": 18453,
"score": 0.9990346431732178,
"start": 18449,
"tag": "NAME",
"value": "Paul"
},
{
"context": ".equal(collection.models[2].get('name'), 'Paul', \"Paul is second\")\n assert.equal(kb.utils.wrappedMode",
"end": 18461,
"score": 0.9989982843399048,
"start": 18457,
"tag": "NAME",
"value": "Paul"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'Paul', \"Paul is first - sorting worked!\")\n assert.e",
"end": 18559,
"score": 0.9989030361175537,
"start": 18555,
"tag": "NAME",
"value": "Paul"
},
{
"context": "collection_observable()[0]).get('name'), 'Paul', \"Paul is first - sorting worked!\")\n assert.equal(kb.",
"end": 18567,
"score": 0.9987624883651733,
"start": 18563,
"tag": "NAME",
"value": "Paul"
},
{
"context": "edModel(collection_observable()[1]).get('name'), 'George', \"Paul is second - sorting worked!\")\n assert.",
"end": 18684,
"score": 0.9990955591201782,
"start": 18678,
"tag": "NAME",
"value": "George"
},
{
"context": "llection_observable()[1]).get('name'), 'George', \"Paul is second - sorting worked!\")\n assert.equal(kb",
"end": 18692,
"score": 0.9987914562225342,
"start": 18688,
"tag": "NAME",
"value": "Paul"
},
{
"context": "edModel(collection_observable()[2]).get('name'), 'Ringo', \"Ringo is third - sorting worked!\")\n\n collec",
"end": 18809,
"score": 0.9987026453018188,
"start": 18804,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[2]).get('name'), 'Ringo', \"Ringo is third - sorting worked!\")\n\n collection_obse",
"end": 18818,
"score": 0.9965113997459412,
"start": 18813,
"tag": "NAME",
"value": "Ringo"
},
{
"context": " assert.equal(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n assert.equal(kb.utils.wrap",
"end": 19131,
"score": 0.9978275299072266,
"start": 19126,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "equal(collection.models[0].get('name'), 'Ringo', \"Ringo is left\")\n assert.equal(kb.utils.wrappedModel(",
"end": 19140,
"score": 0.9582017660140991,
"start": 19135,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "edModel(collection_observable()[0]).get('name'), 'Ringo', \"Ringo is left\")\n\n collection.reset()\n as",
"end": 19237,
"score": 0.9992605447769165,
"start": 19232,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ollection_observable()[0]).get('name'), 'Ringo', \"Ringo is left\")\n\n collection.reset()\n assert.equa",
"end": 19246,
"score": 0.9889404773712158,
"start": 19241,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "))\n\n john_birthdate = new Date(1940, 10, 9)\n john = new Contact({name: 'John', date: new Date(john_",
"end": 19906,
"score": 0.525766134262085,
"start": 19902,
"tag": "NAME",
"value": "john"
},
{
"context": " Date(1940, 10, 9)\n john = new Contact({name: 'John', date: new Date(john_birthdate.valueOf())})\n ",
"end": 19933,
"score": 0.9996062517166138,
"start": 19929,
"tag": "NAME",
"value": "John"
},
{
"context": " Date(1942, 6, 18)\n paul = new Contact({name: 'Paul', date: new Date(paul_birthdate.valueOf())})\n ",
"end": 20057,
"score": 0.9994443655014038,
"start": 20053,
"tag": "NAME",
"value": "Paul"
},
{
"context": "ate(1943, 2, 25)\n george = new Contact({name: 'George', date: new Date(george_birthdate.valueOf())})\n ",
"end": 20187,
"score": 0.9991762638092041,
"start": 20181,
"tag": "NAME",
"value": "George"
},
{
"context": " Date(1940, 7, 7)\n ringo = new Contact({name: 'Ringo', date: new Date(ringo_birthdate.valueOf())})\n ",
"end": 20315,
"score": 0.9996088743209839,
"start": 20310,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "odel, options) -> return if model.get('name') is 'John' then new ContactViewModelDate(model, options) el",
"end": 21035,
"score": 0.9998629093170166,
"start": 21031,
"tag": "NAME",
"value": "John"
},
{
"context": "odel, options) -> return if model.get('name') is 'George' then new ContactViewModelDate(model, options) el",
"end": 21783,
"score": 0.997556746006012,
"start": 21777,
"tag": "NAME",
"value": "George"
},
{
"context": "ericViewModel(nested_view_model.major_duo1()[0], 'John', john_birthdate)\n validateGenericViewModel(ne",
"end": 23908,
"score": 0.9995895028114319,
"start": 23904,
"tag": "NAME",
"value": "John"
},
{
"context": "ericViewModel(nested_view_model.major_duo1()[1], 'Paul', paul_birthdate)\n validateModel(nested_view_m",
"end": 23996,
"score": 0.9980341196060181,
"start": 23992,
"tag": "NAME",
"value": "Paul"
},
{
"context": "validateModel(nested_view_model.major_duo2()[0], 'John', john_birthdate)\n validateModel(nested_view_m",
"end": 24073,
"score": 0.9995957612991333,
"start": 24069,
"tag": "NAME",
"value": "John"
},
{
"context": "validateModel(nested_view_model.major_duo2()[1], 'Paul', paul_birthdate)\n validateGenericViewModel(ne",
"end": 24150,
"score": 0.996431827545166,
"start": 24146,
"tag": "NAME",
"value": "Paul"
},
{
"context": "ericViewModel(nested_view_model.major_duo3()[0], 'John', john_birthdate)\n validateGenericViewModel(ne",
"end": 24238,
"score": 0.9992164969444275,
"start": 24234,
"tag": "NAME",
"value": "John"
},
{
"context": "ericViewModel(nested_view_model.major_duo3()[1], 'Paul', paul_birthdate)\n validateContactViewModel(ne",
"end": 24326,
"score": 0.9988236427307129,
"start": 24322,
"tag": "NAME",
"value": "Paul"
},
{
"context": "tactViewModel(nested_view_model.major_duo4()[0], 'John', john_birthdate)\n validateContactViewModel(ne",
"end": 24414,
"score": 0.9992973208427429,
"start": 24410,
"tag": "NAME",
"value": "John"
},
{
"context": "tactViewModel(nested_view_model.major_duo4()[1], 'Paul', paul_birthdate)\n validateContactViewModel(ne",
"end": 24502,
"score": 0.9990867376327515,
"start": 24498,
"tag": "NAME",
"value": "Paul"
},
{
"context": "tactViewModel(nested_view_model.major_duo5()[0], 'John', john_birthdate)\n validateContactViewModel(ne",
"end": 24590,
"score": 0.9991817474365234,
"start": 24586,
"tag": "NAME",
"value": "John"
},
{
"context": "tactViewModel(nested_view_model.major_duo5()[1], 'Paul', paul_birthdate)\n validateContactViewModel(ne",
"end": 24678,
"score": 0.9990946054458618,
"start": 24674,
"tag": "NAME",
"value": "Paul"
},
{
"context": "tactViewModel(nested_view_model.major_duo6()[0], 'John', john_birthdate) # mixed\n validateGenericView",
"end": 24766,
"score": 0.9991973042488098,
"start": 24762,
"tag": "NAME",
"value": "John"
},
{
"context": "ericViewModel(nested_view_model.major_duo6()[1], 'Paul', paul_birthdate) # mixed\n\n validateGenericVie",
"end": 24862,
"score": 0.9986451268196106,
"start": 24858,
"tag": "NAME",
"value": "Paul"
},
{
"context": "ericViewModel(nested_view_model.minor_duo1()[0], 'George', george_birthdate)\n validateGenericViewModel(",
"end": 24961,
"score": 0.9672973155975342,
"start": 24955,
"tag": "NAME",
"value": "George"
},
{
"context": "ericViewModel(nested_view_model.minor_duo1()[1], 'Ringo', ringo_birthdate)\n validateModel(nested_view_",
"end": 25052,
"score": 0.9913837909698486,
"start": 25047,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "validateModel(nested_view_model.minor_duo2()[0], 'George', george_birthdate)\n validateModel(nested_view",
"end": 25132,
"score": 0.9696559906005859,
"start": 25126,
"tag": "NAME",
"value": "George"
},
{
"context": "validateModel(nested_view_model.minor_duo2()[1], 'Ringo', ringo_birthdate)\n validateGenericViewModel(n",
"end": 25212,
"score": 0.9928775429725647,
"start": 25207,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "ericViewModel(nested_view_model.minor_duo3()[0], 'George', george_birthdate)\n validateGenericViewModel(",
"end": 25303,
"score": 0.9675436615943909,
"start": 25297,
"tag": "NAME",
"value": "George"
},
{
"context": "ericViewModel(nested_view_model.minor_duo3()[1], 'Ringo', ringo_birthdate)\n validateContactViewModel(n",
"end": 25394,
"score": 0.9944412112236023,
"start": 25389,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "tactViewModel(nested_view_model.minor_duo4()[0], 'George', george_birthdate)\n validateContactViewModel(",
"end": 25485,
"score": 0.9954049587249756,
"start": 25479,
"tag": "NAME",
"value": "George"
},
{
"context": "tactViewModel(nested_view_model.minor_duo4()[1], 'Ringo', ringo_birthdate)\n validateContactViewModel(n",
"end": 25576,
"score": 0.9967378377914429,
"start": 25571,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "tactViewModel(nested_view_model.minor_duo5()[0], 'George', george_birthdate)\n validateContactViewModel(",
"end": 25667,
"score": 0.9934036731719971,
"start": 25661,
"tag": "NAME",
"value": "George"
},
{
"context": "tactViewModel(nested_view_model.minor_duo5()[1], 'Ringo', ringo_birthdate)\n validateContactViewModel(n",
"end": 25758,
"score": 0.9956598877906799,
"start": 25753,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "tactViewModel(nested_view_model.minor_duo6()[0], 'George', george_birthdate) # mixed\n validateGenericVi",
"end": 25849,
"score": 0.9748196005821228,
"start": 25843,
"tag": "NAME",
"value": "George"
},
{
"context": " collection = new kb.Collection({id: 1, name: 'Bob'})\n\n collection_observable1 = kb.collectionObs",
"end": 26348,
"score": 0.9998260140419006,
"start": 26345,
"tag": "NAME",
"value": "Bob"
},
{
"context": " collection = new kb.Collection([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}",
"end": 27140,
"score": 0.9998120665550232,
"start": 27137,
"tag": "NAME",
"value": "Bob"
},
{
"context": ".Collection([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n collection_obse",
"end": 27163,
"score": 0.9997572898864746,
"start": 27159,
"tag": "NAME",
"value": "Fred"
},
{
"context": "me: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n collection_observable1 = kb.collectionOb",
"end": 27188,
"score": 0.9995850324630737,
"start": 27182,
"tag": "NAME",
"value": "George"
},
{
"context": "ion, {filters: (model) -> model.get('name') isnt 'George'})\n collection_observable7 = kb.collectionObse",
"end": 27695,
"score": 0.999669075012207,
"start": 27689,
"tag": "NAME",
"value": "George"
},
{
"context": "n, {filters: [((model) -> model.get('name') isnt 'Bob'), ((model) -> return model.get('name') isnt 'Fre",
"end": 27814,
"score": 0.9998217225074768,
"start": 27811,
"tag": "NAME",
"value": "Bob"
},
{
"context": "Bob'), ((model) -> return model.get('name') isnt 'Fred')]})\n observable1 = ko.computed(-> _.filter(co",
"end": 27865,
"score": 0.9996845126152039,
"start": 27861,
"tag": "NAME",
"value": "Fred"
},
{
"context": "r(collection_observable6(), (vm) -> vm.name() is 'Bob'))\n\n assert.equal(_.map(_.pluck(collection_obs",
"end": 27964,
"score": 0.9987112879753113,
"start": 27961,
"tag": "NAME",
"value": "Bob"
},
{
"context": "_observable1(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, George')\n assert.equal(_.map(_.pluck(co",
"end": 28063,
"score": 0.9996792078018188,
"start": 28060,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ervable1(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, George')\n assert.equal(_.map(_.pluck(collecti",
"end": 28069,
"score": 0.9678115844726562,
"start": 28065,
"tag": "NAME",
"value": "Fred"
},
{
"context": "e1(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, George')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 28077,
"score": 0.9600355625152588,
"start": 28071,
"tag": "NAME",
"value": "George"
},
{
"context": "_observable2(), 'name'), (o) -> o()).join(', '), 'Bob')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 28174,
"score": 0.9980692267417908,
"start": 28171,
"tag": "NAME",
"value": "Bob"
},
{
"context": "_observable3(), 'name'), (o) -> o()).join(', '), 'Fred')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 28272,
"score": 0.999759316444397,
"start": 28268,
"tag": "NAME",
"value": "Fred"
},
{
"context": "_observable6(), 'name'), (o) -> o()).join(', '), 'Bob, Fred')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 28563,
"score": 0.9812154769897461,
"start": 28554,
"tag": "NAME",
"value": "Bob, Fred"
},
{
"context": "_observable7(), 'name'), (o) -> o()).join(', '), 'George')\n assert.equal(_.map(_.pluck(observable1(), '",
"end": 28663,
"score": 0.9941517114639282,
"start": 28657,
"tag": "NAME",
"value": "George"
},
{
"context": "(observable1(), 'name'), (o) -> o()).join(', '), 'Bob')\n\n collection.add([{id: 4, name: 'Bob'}, {id:",
"end": 28749,
"score": 0.9987218976020813,
"start": 28746,
"tag": "NAME",
"value": "Bob"
},
{
"context": "', '), 'Bob')\n\n collection.add([{id: 4, name: 'Bob'}, {id: 5, name: 'Fred'}, {id: 6, name: 'George'}",
"end": 28791,
"score": 0.9997075200080872,
"start": 28788,
"tag": "NAME",
"value": "Bob"
},
{
"context": "lection.add([{id: 4, name: 'Bob'}, {id: 5, name: 'Fred'}, {id: 6, name: 'George'}, {id: 7, name: 'Mary'}",
"end": 28814,
"score": 0.9997594356536865,
"start": 28810,
"tag": "NAME",
"value": "Fred"
},
{
"context": "me: 'Bob'}, {id: 5, name: 'Fred'}, {id: 6, name: 'George'}, {id: 7, name: 'Mary'}])\n\n assert.equal(_.ma",
"end": 28839,
"score": 0.9996267557144165,
"start": 28833,
"tag": "NAME",
"value": "George"
},
{
"context": " 'Fred'}, {id: 6, name: 'George'}, {id: 7, name: 'Mary'}])\n\n assert.equal(_.map(_.pluck(collection_ob",
"end": 28862,
"score": 0.9997832179069519,
"start": 28858,
"tag": "NAME",
"value": "Mary"
},
{
"context": "_observable1(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, George, Bob, Fred, George, Mary')\n asse",
"end": 28962,
"score": 0.9997090697288513,
"start": 28959,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ervable1(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, George, Bob, Fred, George, Mary')\n assert.equ",
"end": 28968,
"score": 0.9979056715965271,
"start": 28964,
"tag": "NAME",
"value": "Fred"
},
{
"context": "e1(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, George, Bob, Fred, George, Mary')\n assert.equal(_.map",
"end": 28976,
"score": 0.747208833694458,
"start": 28970,
"tag": "NAME",
"value": "George"
},
{
"context": "ame'), (o) -> o()).join(', '), 'Bob, Fred, George, Bob, Fred, George, Mary')\n assert.equal(_.map(_.pl",
"end": 28981,
"score": 0.99937903881073,
"start": 28978,
"tag": "NAME",
"value": "Bob"
},
{
"context": ", (o) -> o()).join(', '), 'Bob, Fred, George, Bob, Fred, George, Mary')\n assert.equal(_.map(_.pluck(co",
"end": 28987,
"score": 0.9912906885147095,
"start": 28983,
"tag": "NAME",
"value": "Fred"
},
{
"context": "-> o()).join(', '), 'Bob, Fred, George, Bob, Fred, George, Mary')\n assert.equal(_.map(_.pluck(collection",
"end": 28995,
"score": 0.9145404100418091,
"start": 28989,
"tag": "NAME",
"value": "George"
},
{
"context": "join(', '), 'Bob, Fred, George, Bob, Fred, George, Mary')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 29001,
"score": 0.9899170398712158,
"start": 28997,
"tag": "NAME",
"value": "Mary"
},
{
"context": "_observable2(), 'name'), (o) -> o()).join(', '), 'Bob')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 29098,
"score": 0.9977154731750488,
"start": 29095,
"tag": "NAME",
"value": "Bob"
},
{
"context": "_observable3(), 'name'), (o) -> o()).join(', '), 'Fred')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 29196,
"score": 0.9997674822807312,
"start": 29192,
"tag": "NAME",
"value": "Fred"
},
{
"context": "_observable4(), 'name'), (o) -> o()).join(', '), 'Fred')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 29294,
"score": 0.9997546672821045,
"start": 29290,
"tag": "NAME",
"value": "Fred"
},
{
"context": "_observable5(), 'name'), (o) -> o()).join(', '), 'Fred')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 29392,
"score": 0.9997283220291138,
"start": 29388,
"tag": "NAME",
"value": "Fred"
},
{
"context": "_observable6(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, Bob, Fred, Mary')\n assert.equal(_.map(_",
"end": 29489,
"score": 0.9995629787445068,
"start": 29486,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ervable6(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, Bob, Fred, Mary')\n assert.equal(_.map(_.pluck",
"end": 29495,
"score": 0.9929428100585938,
"start": 29491,
"tag": "NAME",
"value": "Fred"
},
{
"context": "e6(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, Bob, Fred, Mary')\n assert.equal(_.map(_.pluck(coll",
"end": 29500,
"score": 0.9902737736701965,
"start": 29497,
"tag": "NAME",
"value": "Bob"
},
{
"context": " 'name'), (o) -> o()).join(', '), 'Bob, Fred, Bob, Fred, Mary')\n assert.equal(_.map(_.pluck(collection",
"end": 29506,
"score": 0.9969984292984009,
"start": 29502,
"tag": "NAME",
"value": "Fred"
},
{
"context": "'), (o) -> o()).join(', '), 'Bob, Fred, Bob, Fred, Mary')\n assert.equal(_.map(_.pluck(collection_obser",
"end": 29512,
"score": 0.8799528479576111,
"start": 29508,
"tag": "NAME",
"value": "Mary"
},
{
"context": "_observable7(), 'name'), (o) -> o()).join(', '), 'George, George, Mary')\n assert.equal(_.map(_.pluck(ob",
"end": 29612,
"score": 0.9992665648460388,
"start": 29606,
"tag": "NAME",
"value": "George"
},
{
"context": "able7(), 'name'), (o) -> o()).join(', '), 'George, George, Mary')\n assert.equal(_.map(_.pluck(observable",
"end": 29620,
"score": 0.993366003036499,
"start": 29614,
"tag": "NAME",
"value": "George"
},
{
"context": " 'name'), (o) -> o()).join(', '), 'George, George, Mary')\n assert.equal(_.map(_.pluck(observable1(), '",
"end": 29626,
"score": 0.9841024875640869,
"start": 29622,
"tag": "NAME",
"value": "Mary"
},
{
"context": "(observable1(), 'name'), (o) -> o()).join(', '), 'Bob, Bob')\n\n kb.release([collection_observable1, c",
"end": 29712,
"score": 0.9995748996734619,
"start": 29709,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ervable1(), 'name'), (o) -> o()).join(', '), 'Bob, Bob')\n\n kb.release([collection_observable1, collec",
"end": 29717,
"score": 0.6786286234855652,
"start": 29714,
"tag": "NAME",
"value": "Bob"
},
{
"context": " collection = new kb.Collection([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}",
"end": 30210,
"score": 0.9995324611663818,
"start": 30207,
"tag": "NAME",
"value": "Bob"
},
{
"context": ".Collection([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n # set the viewm",
"end": 30233,
"score": 0.9994043707847595,
"start": 30229,
"tag": "NAME",
"value": "Fred"
},
{
"context": "me: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n # set the viewmodels (simulating a selec",
"end": 30258,
"score": 0.9994858503341675,
"start": 30252,
"tag": "NAME",
"value": "George"
},
{
"context": " collection = new kb.Collection([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}",
"end": 32556,
"score": 0.9998109936714172,
"start": 32553,
"tag": "NAME",
"value": "Bob"
},
{
"context": ".Collection([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n collection_obse",
"end": 32579,
"score": 0.9996225833892822,
"start": 32575,
"tag": "NAME",
"value": "Fred"
},
{
"context": "me: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n collection_observable = kb.collectionObs",
"end": 32604,
"score": 0.9996232986450195,
"start": 32598,
"tag": "NAME",
"value": "George"
},
{
"context": "collection()\n collection.reset([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}",
"end": 33447,
"score": 0.9997888207435608,
"start": 33444,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ction.reset([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n count = 0\n k",
"end": 33470,
"score": 0.9997249841690063,
"start": 33466,
"tag": "NAME",
"value": "Fred"
},
{
"context": "me: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n count = 0\n ko.computed(-> collection_",
"end": 33495,
"score": 0.9997316598892212,
"start": 33489,
"tag": "NAME",
"value": "George"
},
{
"context": "collection()\n collection.reset([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}",
"end": 34300,
"score": 0.999751627445221,
"start": 34297,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ction.reset([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n count = 0\n k",
"end": 34323,
"score": 0.9997240304946899,
"start": 34319,
"tag": "NAME",
"value": "Fred"
},
{
"context": "me: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])\n\n count = 0\n ko.computed(-> collection_",
"end": 34348,
"score": 0.9997175931930542,
"start": 34342,
"tag": "NAME",
"value": "George"
},
{
"context": " model = view_model.model()\n model.set({name: 'Bob2'})\n assert.equal(view_model.name(), 'Bob2')\n ",
"end": 36740,
"score": 0.9888571500778198,
"start": 36736,
"tag": "NAME",
"value": "Bob2"
},
{
"context": "me: 'Bob2'})\n assert.equal(view_model.name(), 'Bob2')\n view_model.test('world')\n assert.equal(v",
"end": 36785,
"score": 0.9810961484909058,
"start": 36781,
"tag": "NAME",
"value": "Bob2"
}
] | test/spec/core/collection-observable.tests.coffee | metacommunications/knockback | 0 | assert = assert or require?('chai').assert
describe 'collection-observable @quick @collection-observable', ->
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
done()
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
ContactViewModel = (model) ->
@name = kb.observable(model, 'name')
@number = kb.observable(model, 'number')
@
class ContactViewModelClass
constructor: (model) ->
@name = kb.observable(model, 'name')
@number = kb.observable(model, 'number')
class TestViewModel extends kb.ViewModel
constructor: ->
super
@test = ko.observable('hello')
value = @test()
value = @name()
it '2. Basic Usage: collection observable with ko.computed', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection)
view_model =
count: ko.computed(->return collection_observable().length )
assert.equal(collection.length, 0, "no models")
assert.equal(view_model.count(), 0, "no count")
collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))
assert.equal(collection.length, 2, "2 models")
assert.equal(view_model.count(), 2, "2 count")
collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5557'}))
assert.equal(collection.length, 3, "3 models")
assert.equal(view_model.count(), 3, "3 count")
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "1 model")
assert.equal(view_model.count(), 1, "1 count")
# clean up
kb.release(collection_observable)
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '3. Basic Usage: collection observable with ko.computed', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, factories: {models: ContactViewModel})
view_model =
count: ko.computed(-> return collection_observable().length)
assert.equal(collection.length, 0, "no models")
assert.equal(view_model.count(), 0, "no count")
collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))
assert.equal(collection.length, 2, "2 models")
assert.equal(view_model.count(), 2, "2 count")
collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5557'}))
assert.equal(collection.length, 3, "3 models")
assert.equal(view_model.count(), 3, "3 count")
assert.ok(collection_observable()[2] instanceof ContactViewModel, 'correct type from factory')
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "1 model")
assert.equal(view_model.count(), 1, "1 count")
# clean up
kb.release(collection_observable)
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '4. Basic Usage: no view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {models_only: true})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5555'}))
collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5556'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(collection_observable()[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection_observable()[1].get('name'), 'George', "George is second")
collection.remove('b2')
assert.equal(collection.length, 1, "one models")
assert.equal(collection_observable().length, 1, "one view models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is left")
model = kb.utils.wrappedModel(collection_observable()[0])
assert.equal(model.get('name'), 'Ringo', "Ringo is left")
model = collection_observable()[0]
assert.equal(model.get('name'), 'Ringo', "Ringo is left")
view_model = collection_observable.viewModelByModel(model)
assert.ok(!view_model, "no view model found since the collection observable is not wrapping models in view models")
model_count = 0
_.each(collection_observable(), (model)->model_count++)
assert.equal(model_count, 1, "one model")
assert.ok(collection_observable.collection()==collection, "collections match")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '5. Basic Usage: no sorting and no callbacks', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
factories:
models: {create: (model) -> return new ContactViewModel(model)}
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5555'}))
collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5556'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'Ringo', "Ringo is first")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'George', "George is second")
collection.remove('b2')
assert.equal(collection.length, 1, "one model")
assert.equal(collection_observable().length, 1, "one view model")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is left")
model = kb.utils.wrappedModel(collection_observable()[0])
assert.equal(model.get('name'), 'Ringo', "Ringo is left")
view_model = collection_observable.viewModelByModel(model)
assert.equal(kb.utils.wrappedModel(view_model).get('name'), 'Ringo', "Ringo is left")
view_model_count = 0
_.each(collection_observable(), (view_model)->view_model_count++)
assert.equal(view_model_count, 1, "one view model")
assert.ok(collection_observable.collection()==collection, "collections match")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '6. Collection sync sorting with sort_attribute', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModelClass
sort_attribute: 'name'
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'George', "George is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'Ringo', "Ringo is second - sorting worked!")
collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5557'}))
assert.equal(collection.length, 3, "three models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(collection.models[2].get('name'), 'Paul', "Paul is second")
assert.equal(collection_observable().length, 3, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'George', "George is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'Paul', "Paul is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), 'Ringo', "Ringo is third - sorting worked!")
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "one model")
assert.equal(collection_observable().length, 1, "one view model")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is left")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'Ringo', "Ringo is left")
collection.reset()
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '7. Collection sync sorting with comparator', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
sortNumber = (model_a, model_b) ->
parts_a = kb.utils.wrappedModel(model_a).get('number').split('-')
parts_b = kb.utils.wrappedModel(model_b).get('number').split('-')
return (parts_a.length-parts_b.length) if parts_a.length isnt parts_b.length
for index, part of parts_b
return delta unless (delta = parts_a[index] - parseInt(part, 10)) is 0
return 0
# without view models
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
models_only: true
comparator: sortNumber
})
collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(collection_observable()[0].get('name'), 'George', "George is first - sorting worked!")
assert.equal(collection_observable()[1].get('name'), 'Ringo', "Ringo is second - sorting worked!")
# clean up
kb.release(collection_observable)
# with view models
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModelClass
comparator: sortNumber
})
collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'George', "George is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'Ringo', "Ringo is second - sorting worked!")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '8. Collection sorting with callbacks', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.NameSortedContacts = kb.Collection.extend({
model: Contact
comparator: (model) -> return model.get('name')
})
collection = new kb.NameSortedContacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModel # view_model is legacy for view_model, it should be replaced with view_model or create
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'George', "George is first")
assert.equal(collection.models[1].get('name'), 'Ringo', "Ringo is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'George', "George is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'Ringo', "Ringo is second - sorting worked!")
collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5557'}))
assert.equal(collection.length, 3, "three models")
assert.equal(collection.models[0].get('name'), 'George', "George is first")
assert.equal(collection.models[1].get('name'), 'Paul', "Paul is second")
assert.equal(collection.models[2].get('name'), 'Ringo', "Ringo is second")
assert.equal(collection_observable().length, 3, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'George', "George is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'Paul', "Paul is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), 'Ringo', "Ringo is third - sorting worked!")
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "one models")
assert.equal(collection_observable().length, 1, "one view models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is left")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'Ringo', "Ringo is left")
collection.reset()
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '9. Collection sync dynamically changing the sorting function', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModel
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'Ringo', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'George', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'Ringo', "Ringo is first - no sorting")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'George', "George is first - no sorting")
collection_observable.sortAttribute('name')
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'George', "George is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'Ringo', "Ringo is second - sorting worked!")
collection.add(new Contact({id: 'b3', name: 'Paul', number: '555-555-5554'}))
assert.equal(collection.length, 3, "three models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(collection.models[2].get('name'), 'Paul', "Paul is second")
assert.equal(collection_observable().length, 3, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'George', "George is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'Paul', "Paul is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), 'Ringo', "Ringo is third - sorting worked!")
collection_observable.sortAttribute('number')
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is first")
assert.equal(collection.models[1].get('name'), 'George', "George is second")
assert.equal(collection.models[2].get('name'), 'Paul', "Paul is second")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'Paul', "Paul is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'George', "Paul is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), 'Ringo', "Ringo is third - sorting worked!")
collection_observable.sortAttribute('name')
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "one models")
assert.equal(collection_observable().length, 1, "one view models")
assert.equal(collection.models[0].get('name'), 'Ringo', "Ringo is left")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'Ringo', "Ringo is left")
collection.reset()
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '10. Nested custom view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelDate extends kb.ViewModel
constructor: (model, options) ->
super(model, _.extend({requires: ['date']}, options))
john_birthdate = new Date(1940, 10, 9)
john = new Contact({name: 'John', date: new Date(john_birthdate.valueOf())})
paul_birthdate = new Date(1942, 6, 18)
paul = new Contact({name: 'Paul', date: new Date(paul_birthdate.valueOf())})
george_birthdate = new Date(1943, 2, 25)
george = new Contact({name: 'George', date: new Date(george_birthdate.valueOf())})
ringo_birthdate = new Date(1940, 7, 7)
ringo = new Contact({name: 'Ringo', date: new Date(ringo_birthdate.valueOf())})
major_duo = new kb.Collection([john, paul])
minor_duo = new kb.Collection([george, ringo])
nested_view_model = {
major_duo1: kb.collectionObservable(major_duo)
major_duo2: kb.collectionObservable(major_duo, {models_only: true})
major_duo3: kb.collectionObservable(major_duo, {view_model: kb.ViewModel})
major_duo4: kb.collectionObservable(major_duo, {view_model: ContactViewModelDate})
major_duo5: kb.collectionObservable(major_duo, {create: (model, options) -> return new ContactViewModelDate(model, options)})
major_duo6: kb.collectionObservable(major_duo, {create: (model, options) -> return if model.get('name') is 'John' then new ContactViewModelDate(model, options) else kb.viewModel(model, options)}) # mixed
minor_duo1: kb.collectionObservable(minor_duo, {factories: {}})
minor_duo2: kb.collectionObservable(minor_duo, {factories: models: {models_only: true}})
minor_duo3: kb.collectionObservable(minor_duo, {factories: models: kb.ViewModel})
minor_duo4: kb.collectionObservable(minor_duo, {factories: models: {view_model: ContactViewModelDate}})
minor_duo5: kb.collectionObservable(minor_duo, {factories: models: {create: (model, options) -> return new ContactViewModelDate(model, options)}})
minor_duo6: kb.collectionObservable(minor_duo, {factories: models: {create: (model, options) -> return if model.get('name') is 'George' then new ContactViewModelDate(model, options) else kb.viewModel(model, options)}}) # mixed
}
validateContactViewModel = (view_model, name, birthdate) ->
model = kb.utils.wrappedModel(view_model)
assert.equal(view_model.name(), name, "#{name}: Name matches")
# set from the view model
view_model.date(new Date(1963, 11, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "#{name}: year is good")
assert.equal(current_date.getMonth(), 11, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model.date().getFullYear(), 1963, "#{name}: year is good")
assert.equal(view_model.date().getMonth(), 11, "#{name}: month is good")
assert.equal(view_model.date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
# set from the model
view_model.date(new Date(1940, 10, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "#{name}: year is good")
assert.equal(current_date.getMonth(), 10, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model.date().getFullYear(), 1940, "#{name}: year is good")
assert.equal(view_model.date().getMonth(), 10, "#{name}: month is good")
assert.equal(view_model.date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
validateGenericViewModel = (view_model, name, birthdate) ->
assert.equal(view_model.name(), name, "#{name}: Name matches")
assert.equal(view_model.date().valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
validateModel = (model, name, birthdate) ->
assert.equal(model.get('name'), name, "#{name}: Name matches")
assert.equal(model.get('date').valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
# colllections
validateGenericViewModel(nested_view_model.major_duo1()[0], 'John', john_birthdate)
validateGenericViewModel(nested_view_model.major_duo1()[1], 'Paul', paul_birthdate)
validateModel(nested_view_model.major_duo2()[0], 'John', john_birthdate)
validateModel(nested_view_model.major_duo2()[1], 'Paul', paul_birthdate)
validateGenericViewModel(nested_view_model.major_duo3()[0], 'John', john_birthdate)
validateGenericViewModel(nested_view_model.major_duo3()[1], 'Paul', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo4()[0], 'John', john_birthdate)
validateContactViewModel(nested_view_model.major_duo4()[1], 'Paul', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo5()[0], 'John', john_birthdate)
validateContactViewModel(nested_view_model.major_duo5()[1], 'Paul', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo6()[0], 'John', john_birthdate) # mixed
validateGenericViewModel(nested_view_model.major_duo6()[1], 'Paul', paul_birthdate) # mixed
validateGenericViewModel(nested_view_model.minor_duo1()[0], 'George', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo1()[1], 'Ringo', ringo_birthdate)
validateModel(nested_view_model.minor_duo2()[0], 'George', george_birthdate)
validateModel(nested_view_model.minor_duo2()[1], 'Ringo', ringo_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[0], 'George', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[1], 'Ringo', ringo_birthdate)
validateContactViewModel(nested_view_model.minor_duo4()[0], 'George', george_birthdate)
validateContactViewModel(nested_view_model.minor_duo4()[1], 'Ringo', ringo_birthdate)
validateContactViewModel(nested_view_model.minor_duo5()[0], 'George', george_birthdate)
validateContactViewModel(nested_view_model.minor_duo5()[1], 'Ringo', ringo_birthdate)
validateContactViewModel(nested_view_model.minor_duo6()[0], 'George', george_birthdate) # mixed
validateGenericViewModel(nested_view_model.minor_duo6()[1], 'Ringo', ringo_birthdate) # mixed
# and cleanup after yourself when you are done.
kb.release(nested_view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '11. Shared Options', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection({id: 1, name: 'Bob'})
collection_observable1 = kb.collectionObservable(collection)
collection_observable2 = kb.collectionObservable(collection)
collection_observable3 = kb.collectionObservable(collection, collection_observable1.shareOptions())
assert.ok(collection_observable1()[0] isnt collection_observable2()[0], 'not sharing')
assert.ok(collection_observable1()[0] is collection_observable3()[0], 'sharing')
kb.release([collection_observable1, collection_observable2, collection_observable3])
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '12. Filters option', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])
collection_observable1 = kb.collectionObservable(collection)
collection_observable2 = kb.collectionObservable(collection, {filters: 1})
collection_observable3 = kb.collectionObservable(collection, {filters: [2]})
collection_observable4 = kb.collectionObservable(collection, {filters: 5})
collection_observable5 = kb.collectionObservable(collection, {filters: [5]})
collection_observable6 = kb.collectionObservable(collection, {filters: (model) -> model.get('name') isnt 'George'})
collection_observable7 = kb.collectionObservable(collection, {filters: [((model) -> model.get('name') isnt 'Bob'), ((model) -> return model.get('name') isnt 'Fred')]})
observable1 = ko.computed(-> _.filter(collection_observable6(), (vm) -> vm.name() is 'Bob'))
assert.equal(_.map(_.pluck(collection_observable1(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, George')
assert.equal(_.map(_.pluck(collection_observable2(), 'name'), (o) -> o()).join(', '), 'Bob')
assert.equal(_.map(_.pluck(collection_observable3(), 'name'), (o) -> o()).join(', '), 'Fred')
assert.equal(_.map(_.pluck(collection_observable4(), 'name'), (o) -> o()).join(', '), '')
assert.equal(_.map(_.pluck(collection_observable5(), 'name'), (o) -> o()).join(', '), '')
assert.equal(_.map(_.pluck(collection_observable6(), 'name'), (o) -> o()).join(', '), 'Bob, Fred')
assert.equal(_.map(_.pluck(collection_observable7(), 'name'), (o) -> o()).join(', '), 'George')
assert.equal(_.map(_.pluck(observable1(), 'name'), (o) -> o()).join(', '), 'Bob')
collection.add([{id: 4, name: 'Bob'}, {id: 5, name: 'Fred'}, {id: 6, name: 'George'}, {id: 7, name: 'Mary'}])
assert.equal(_.map(_.pluck(collection_observable1(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, George, Bob, Fred, George, Mary')
assert.equal(_.map(_.pluck(collection_observable2(), 'name'), (o) -> o()).join(', '), 'Bob')
assert.equal(_.map(_.pluck(collection_observable3(), 'name'), (o) -> o()).join(', '), 'Fred')
assert.equal(_.map(_.pluck(collection_observable4(), 'name'), (o) -> o()).join(', '), 'Fred')
assert.equal(_.map(_.pluck(collection_observable5(), 'name'), (o) -> o()).join(', '), 'Fred')
assert.equal(_.map(_.pluck(collection_observable6(), 'name'), (o) -> o()).join(', '), 'Bob, Fred, Bob, Fred, Mary')
assert.equal(_.map(_.pluck(collection_observable7(), 'name'), (o) -> o()).join(', '), 'George, George, Mary')
assert.equal(_.map(_.pluck(observable1(), 'name'), (o) -> o()).join(', '), 'Bob, Bob')
kb.release([collection_observable1, collection_observable2, collection_observable3, collection_observable4, collection_observable5, collection_observable6, collection_observable7, observable1])
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '13. Setting view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])
# set the viewmodels (simulating a selectOptions)
collection_observable = kb.collectionObservable(collection)
view_models = _.map(collection.models, (model) -> kb.viewModel(model))
previous_view_model = collection_observable()[0]
collection_observable(view_models)
assert.ok(collection_observable()[0] isnt previous_view_model, 'view model updated')
assert.ok(collection_observable()[0] is view_models[0], 'view model updated from new list')
store = kb.utils.wrappedStore(collection_observable)
store.compact() # ensure compact does not throw
assert.ok(store.find(collection.models[0], kb.ViewModel) is view_models[0], 'view model was added to the store')
assert.ok(store.find(collection.models[0], kb.ViewModel) isnt previous_view_model, 'previous view model was removed from the store')
kb.release(view_models)
kb.release(collection_observable)
# set the viewmodels (simulating a selectOptions)
class SpecializedViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(collection)
view_models = _.map(collection.models, (model) -> new SpecializedViewModel(model))
previous_view_model = collection_observable()[0]
assert.throw((->collection_observable(view_models)))
# assert.throw((->collection_observable(view_models)), null, 'Store: replacing different type')
assert.ok(collection_observable()[0] isnt previous_view_model, 'view model updated')
assert.ok(collection_observable()[0] is view_models[0], 'view model updated from new list')
store = kb.utils.wrappedStore(collection_observable)
store.compact() # ensure compact does not throw
assert.ok(store.find(collection.models[0], kb.ViewModel) isnt view_models[0], 'view model was not added to the store')
assert.ok(store.find(collection.models[0], kb.ViewModel) is previous_view_model, 'previous view model was not removed from the store')
kb.release(view_models)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '14. collection change is observable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])
collection_observable = kb.collectionObservable(collection)
count = 0
ko.computed(-> collection_observable.collection(); count++)
assert.ok(collection_observable()[0] instanceof kb.ViewModel, 'is a kb.ViewModel')
collection_observable.collection(null)
collection_observable.collection(collection)
assert.equal(count, 3, "collection change was observed")
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '15. collection is generated if not passed (no options)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable()
collection = collection_observable.collection()
collection.reset([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])
count = 0
ko.computed(-> collection_observable.collection(); count++)
assert.ok(collection_observable()[0] instanceof kb.ViewModel, 'is a kb.ViewModel')
collection_observable.collection(null)
collection_observable.collection(collection)
assert.equal(count, 3, "collection change was observed")
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '16. collection is generated if not passed (options)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable({view_model: ContactViewModel})
collection = collection_observable.collection()
collection.reset([{id: 1, name: 'Bob'}, {id: 2, name: 'Fred'}, {id: 3, name: 'George'}])
count = 0
ko.computed(-> collection_observable.collection(); count++)
assert.ok(collection_observable()[0] instanceof ContactViewModel, 'is a ContactViewModel')
collection_observable.collection(null)
collection_observable.collection(collection)
assert.equal(count, 3, "collection change was observed")
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '17. collection changes do not cause dependencies inside ko.computed', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable({view_model: TestViewModel})
collection = collection_observable.collection()
count_manual = 0
ko.computed ->
collection_observable([new TestViewModel(new kb.Model({id: 10, name: 'Manual'}))]) # should not depend
count_manual++
count_reset = 0
ko.computed ->
collection.reset([{id: 20, name: 'Reset1'}, {id: 21, name: 'Reset2'}]) # should not depend
count_reset++
count_add = 0
ko.computed ->
collection.add([{id: 30, name: 'Add1'}, {id: 31, name: 'Add2'}]) # should not depend
count_add++
count_remove = 0
ko.computed ->
collection.remove(collection.at(0))
count_remove++
observable_count = 0
ko.computed ->
collection_observable() # should depend
observable_count++
assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_reset, 1, 'count_reset'); assert.equal(count_add, 1, 'count_add'); assert.equal(count_remove, 1, 'count_remove'); assert.equal(observable_count, 1, 'observable_count')
collection_observable([new TestViewModel(new kb.Model({id: 10, name: 'Manual'}))]) # should not depend
collection.reset([{id: 20, name: 'Reset1'}, {id: 21, name: 'Reset2'}]) # should not depend
collection.add([{id: 30, name: 'Add1'}, {id: 31, name: 'Add2'}]) # should not depend
collection.remove(collection.at(0))
assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_reset, 1, 'count_reset'); assert.equal(count_add, 1, 'count_add'); assert.equal(count_remove, 1, 'count_remove'); assert.equal(observable_count, 6, 'observable_count')
view_model = collection_observable()[0]
model = view_model.model()
model.set({name: 'Bob2'})
assert.equal(view_model.name(), 'Bob2')
view_model.test('world')
assert.equal(view_model.test(), 'world')
assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_reset, 1, 'count_reset'); assert.equal(count_add, 1, 'count_add'); assert.equal(count_remove, 1, 'count_remove'); assert.equal(observable_count, 6, 'observable_count')
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '18. Test auto-generate collections', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
models = (new Contact({id: id}) for id in [1..4])
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable({view_model: PersonViewModel})
collection_observable.collection().reset(models)
assert.equal(collection_observable.collection().length, 4)
for view_models in collection_observable()
assert.ok(!!view_models.date())
assert.ok(view_models.model() instanceof Contact)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '19. Test auto-generate collections with model array', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
models = (new Contact({id: id}) for id in [1..4])
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(models, {view_model: PersonViewModel})
assert.equal(collection_observable.collection().length, 4)
for view_models in collection_observable()
assert.ok(!!view_models.date())
assert.ok(view_models.model() instanceof Contact)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '20. push and unshift', (done) ->
return done() if kb.Backbone and kb.Backbone.VERSION[0] isnt '1'
kb.statistics = new kb.Statistics() # turn on stats
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(new Contacts(), {view_model: PersonViewModel})
# LEGACY
if collection_observable.collection().push
collection_observable.collection().push()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().push(null)
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().push(new Contact())
assert.equal(collection_observable.collection().length, 1)
assert.equal(collection_observable().length, 1)
collection_observable.collection().reset()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
# LEGACY
if collection_observable.collection().unshift
collection_observable.collection().unshift()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().unshift(null)
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().unshift(new Contact())
assert.equal(collection_observable.collection().length, 1)
assert.equal(collection_observable().length, 1)
collection_observable.collection().reset()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '21. Auto compact for collections', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
models = (new Contact({id: id}) for id in [1..4])
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(models, {view_model: PersonViewModel, auto_compact: true})
collection = collection_observable.collection()
assert.equal(collection_observable.collection().length, 4)
previous_view_models = collection_observable().slice()
assert.equal(previous_view_models.length, 4)
assert.equal(kb.statistics.registeredStatsString('all released'), 'ViewModel: 4\n CollectionObservable: 1', "Expected stats")
collection_observable.collection().add(new Contact({id: 5}))
new_view_models = collection_observable()
assert.equal(new_view_models.length, 5)
assert.equal(previous_view_models.length, 4)
for vm in new_view_models
if vm.model() is collection_observable.collection().models[4]
assert.ok(not(vm in previous_view_models))
else
assert.ok(vm in previous_view_models)
models = collection_observable.collection().models.slice()
collection_observable.collection().reset(models)
new_view_models = collection_observable()
assert.equal(new_view_models.length, 5)
assert.equal(previous_view_models.length, 4)
assert.ok(not(vm in previous_view_models)) for vm in new_view_models
kb.release(collection_observable)
assert.ok(kb.Statistics.eventsStats(collection).count is 0, "All collection events cleared. Expected: 0. Actual: #{JSON.stringify(kb.Statistics.eventsStats(collection))}")
for model in models
collection.remove(model)
assert.ok(kb.Statistics.eventsStats(model).count is 0, "All model events cleared. Expected: 0. Actual: #{JSON.stringify(kb.Statistics.eventsStats(model))}")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
| 108240 | assert = assert or require?('chai').assert
describe 'collection-observable @quick @collection-observable', ->
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
done()
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
ContactViewModel = (model) ->
@name = kb.observable(model, 'name')
@number = kb.observable(model, 'number')
@
class ContactViewModelClass
constructor: (model) ->
@name = kb.observable(model, 'name')
@number = kb.observable(model, 'number')
class TestViewModel extends kb.ViewModel
constructor: ->
super
@test = ko.observable('hello')
value = @test()
value = @name()
it '2. Basic Usage: collection observable with ko.computed', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection)
view_model =
count: ko.computed(->return collection_observable().length )
assert.equal(collection.length, 0, "no models")
assert.equal(view_model.count(), 0, "no count")
collection.add(new Contact({id: 'b1', name: '<NAME>', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: '<NAME>', number: '555-555-5555'}))
assert.equal(collection.length, 2, "2 models")
assert.equal(view_model.count(), 2, "2 count")
collection.add(new Contact({id: 'b3', name: '<NAME>', number: '555-555-5557'}))
assert.equal(collection.length, 3, "3 models")
assert.equal(view_model.count(), 3, "3 count")
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "1 model")
assert.equal(view_model.count(), 1, "1 count")
# clean up
kb.release(collection_observable)
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '3. Basic Usage: collection observable with ko.computed', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, factories: {models: ContactViewModel})
view_model =
count: ko.computed(-> return collection_observable().length)
assert.equal(collection.length, 0, "no models")
assert.equal(view_model.count(), 0, "no count")
collection.add(new Contact({id: 'b1', name: '<NAME>', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: '<NAME>', number: '555-555-5555'}))
assert.equal(collection.length, 2, "2 models")
assert.equal(view_model.count(), 2, "2 count")
collection.add(new Contact({id: 'b3', name: '<NAME>', number: '555-555-5557'}))
assert.equal(collection.length, 3, "3 models")
assert.equal(view_model.count(), 3, "3 count")
assert.ok(collection_observable()[2] instanceof ContactViewModel, 'correct type from factory')
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "1 model")
assert.equal(view_model.count(), 1, "1 count")
# clean up
kb.release(collection_observable)
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '4. Basic Usage: no view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {models_only: true})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: '<NAME>', number: '555-555-5555'}))
collection.add(new Contact({id: 'b2', name: '<NAME>', number: '555-555-5556'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "Ge<NAME> is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(collection_observable()[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection_observable()[1].get('name'), '<NAME>', "George is second")
collection.remove('b2')
assert.equal(collection.length, 1, "one models")
assert.equal(collection_observable().length, 1, "one view models")
assert.equal(collection.models[0].get('name'), '<NAME>', "Ring<NAME> is left")
model = kb.utils.wrappedModel(collection_observable()[0])
assert.equal(model.get('name'), '<NAME>', "<NAME> is left")
model = collection_observable()[0]
assert.equal(model.get('name'), '<NAME>', "<NAME> is left")
view_model = collection_observable.viewModelByModel(model)
assert.ok(!view_model, "no view model found since the collection observable is not wrapping models in view models")
model_count = 0
_.each(collection_observable(), (model)->model_count++)
assert.equal(model_count, 1, "one model")
assert.ok(collection_observable.collection()==collection, "collections match")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '5. Basic Usage: no sorting and no callbacks', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
factories:
models: {create: (model) -> return new ContactViewModel(model)}
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: '<NAME>', number: '555-555-5555'}))
collection.add(new Contact({id: 'b2', name: '<NAME>', number: '555-555-5556'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is first")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME> is second")
collection.remove('b2')
assert.equal(collection.length, 1, "one model")
assert.equal(collection_observable().length, 1, "one view model")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is left")
model = kb.utils.wrappedModel(collection_observable()[0])
assert.equal(model.get('name'), '<NAME>', "<NAME> is left")
view_model = collection_observable.viewModelByModel(model)
assert.equal(kb.utils.wrappedModel(view_model).get('name'), '<NAME>', "Ring<NAME> is left")
view_model_count = 0
_.each(collection_observable(), (view_model)->view_model_count++)
assert.equal(view_model_count, 1, "one view model")
assert.ok(collection_observable.collection()==collection, "collections match")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '6. Collection sync sorting with sort_attribute', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModelClass
sort_attribute: 'name'
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: '<NAME>', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: '<NAME>', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME> is second - sorting worked!")
collection.add(new Contact({id: 'b3', name: '<NAME>', number: '555-555-5557'}))
assert.equal(collection.length, 3, "three models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection.models[2].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection_observable().length, 3, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME> is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), '<NAME>', "<NAME> is third - sorting worked!")
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "one model")
assert.equal(collection_observable().length, 1, "one view model")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is left")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is left")
collection.reset()
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '7. Collection sync sorting with comparator', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
sortNumber = (model_a, model_b) ->
parts_a = kb.utils.wrappedModel(model_a).get('number').split('-')
parts_b = kb.utils.wrappedModel(model_b).get('number').split('-')
return (parts_a.length-parts_b.length) if parts_a.length isnt parts_b.length
for index, part of parts_b
return delta unless (delta = parts_a[index] - parseInt(part, 10)) is 0
return 0
# without view models
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
models_only: true
comparator: sortNumber
})
collection.add(new Contact({id: 'b1', name: '<NAME>', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: '<NAME>', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(collection_observable()[0].get('name'), '<NAME>', "<NAME> is first - sorting worked!")
assert.equal(collection_observable()[1].get('name'), '<NAME>', "<NAME> is second - sorting worked!")
# clean up
kb.release(collection_observable)
# with view models
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModelClass
comparator: sortNumber
})
collection.add(new Contact({id: 'b1', name: '<NAME>', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: '<NAME>', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME> is second - sorting worked!")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '8. Collection sorting with callbacks', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.NameSortedContacts = kb.Collection.extend({
model: Contact
comparator: (model) -> return model.get('name')
})
collection = new kb.NameSortedContacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModel # view_model is legacy for view_model, it should be replaced with view_model or create
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: '<NAME>', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: '<NAME>', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME> is second - sorting worked!")
collection.add(new Contact({id: 'b3', name: '<NAME>', number: '555-555-5557'}))
assert.equal(collection.length, 3, "three models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection.models[2].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection_observable().length, 3, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME> is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), '<NAME>', "<NAME> is third - sorting worked!")
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "one models")
assert.equal(collection_observable().length, 1, "one view models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is left")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "Ringo is left")
collection.reset()
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '9. Collection sync dynamically changing the sorting function', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModel
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: '<NAME>', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: '<NAME>', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is first - no sorting")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME>orge is first - no sorting")
collection_observable.sortAttribute('name')
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME>orge is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME> is second - sorting worked!")
collection.add(new Contact({id: 'b3', name: '<NAME>', number: '555-555-5554'}))
assert.equal(collection.length, 3, "three models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection.models[2].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection_observable().length, 3, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME> is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), '<NAME>', "<NAME> is third - sorting worked!")
collection_observable.sortAttribute('number')
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is first")
assert.equal(collection.models[1].get('name'), '<NAME>', "<NAME> is second")
assert.equal(collection.models[2].get('name'), '<NAME>', "<NAME> is second")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), '<NAME>', "<NAME> is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), '<NAME>', "<NAME> is third - sorting worked!")
collection_observable.sortAttribute('name')
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "one models")
assert.equal(collection_observable().length, 1, "one view models")
assert.equal(collection.models[0].get('name'), '<NAME>', "<NAME> is left")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), '<NAME>', "<NAME> is left")
collection.reset()
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '10. Nested custom view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelDate extends kb.ViewModel
constructor: (model, options) ->
super(model, _.extend({requires: ['date']}, options))
john_birthdate = new Date(1940, 10, 9)
<NAME> = new Contact({name: '<NAME>', date: new Date(john_birthdate.valueOf())})
paul_birthdate = new Date(1942, 6, 18)
paul = new Contact({name: '<NAME>', date: new Date(paul_birthdate.valueOf())})
george_birthdate = new Date(1943, 2, 25)
george = new Contact({name: '<NAME>', date: new Date(george_birthdate.valueOf())})
ringo_birthdate = new Date(1940, 7, 7)
ringo = new Contact({name: '<NAME>', date: new Date(ringo_birthdate.valueOf())})
major_duo = new kb.Collection([john, paul])
minor_duo = new kb.Collection([george, ringo])
nested_view_model = {
major_duo1: kb.collectionObservable(major_duo)
major_duo2: kb.collectionObservable(major_duo, {models_only: true})
major_duo3: kb.collectionObservable(major_duo, {view_model: kb.ViewModel})
major_duo4: kb.collectionObservable(major_duo, {view_model: ContactViewModelDate})
major_duo5: kb.collectionObservable(major_duo, {create: (model, options) -> return new ContactViewModelDate(model, options)})
major_duo6: kb.collectionObservable(major_duo, {create: (model, options) -> return if model.get('name') is '<NAME>' then new ContactViewModelDate(model, options) else kb.viewModel(model, options)}) # mixed
minor_duo1: kb.collectionObservable(minor_duo, {factories: {}})
minor_duo2: kb.collectionObservable(minor_duo, {factories: models: {models_only: true}})
minor_duo3: kb.collectionObservable(minor_duo, {factories: models: kb.ViewModel})
minor_duo4: kb.collectionObservable(minor_duo, {factories: models: {view_model: ContactViewModelDate}})
minor_duo5: kb.collectionObservable(minor_duo, {factories: models: {create: (model, options) -> return new ContactViewModelDate(model, options)}})
minor_duo6: kb.collectionObservable(minor_duo, {factories: models: {create: (model, options) -> return if model.get('name') is '<NAME>' then new ContactViewModelDate(model, options) else kb.viewModel(model, options)}}) # mixed
}
validateContactViewModel = (view_model, name, birthdate) ->
model = kb.utils.wrappedModel(view_model)
assert.equal(view_model.name(), name, "#{name}: Name matches")
# set from the view model
view_model.date(new Date(1963, 11, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "#{name}: year is good")
assert.equal(current_date.getMonth(), 11, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model.date().getFullYear(), 1963, "#{name}: year is good")
assert.equal(view_model.date().getMonth(), 11, "#{name}: month is good")
assert.equal(view_model.date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
# set from the model
view_model.date(new Date(1940, 10, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "#{name}: year is good")
assert.equal(current_date.getMonth(), 10, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model.date().getFullYear(), 1940, "#{name}: year is good")
assert.equal(view_model.date().getMonth(), 10, "#{name}: month is good")
assert.equal(view_model.date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
validateGenericViewModel = (view_model, name, birthdate) ->
assert.equal(view_model.name(), name, "#{name}: Name matches")
assert.equal(view_model.date().valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
validateModel = (model, name, birthdate) ->
assert.equal(model.get('name'), name, "#{name}: Name matches")
assert.equal(model.get('date').valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
# colllections
validateGenericViewModel(nested_view_model.major_duo1()[0], '<NAME>', john_birthdate)
validateGenericViewModel(nested_view_model.major_duo1()[1], '<NAME>', paul_birthdate)
validateModel(nested_view_model.major_duo2()[0], '<NAME>', john_birthdate)
validateModel(nested_view_model.major_duo2()[1], '<NAME>', paul_birthdate)
validateGenericViewModel(nested_view_model.major_duo3()[0], '<NAME>', john_birthdate)
validateGenericViewModel(nested_view_model.major_duo3()[1], '<NAME>', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo4()[0], '<NAME>', john_birthdate)
validateContactViewModel(nested_view_model.major_duo4()[1], '<NAME>', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo5()[0], '<NAME>', john_birthdate)
validateContactViewModel(nested_view_model.major_duo5()[1], '<NAME>', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo6()[0], '<NAME>', john_birthdate) # mixed
validateGenericViewModel(nested_view_model.major_duo6()[1], '<NAME>', paul_birthdate) # mixed
validateGenericViewModel(nested_view_model.minor_duo1()[0], '<NAME>', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo1()[1], '<NAME>', ringo_birthdate)
validateModel(nested_view_model.minor_duo2()[0], '<NAME>', george_birthdate)
validateModel(nested_view_model.minor_duo2()[1], '<NAME>', ringo_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[0], '<NAME>', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[1], '<NAME>', ringo_birthdate)
validateContactViewModel(nested_view_model.minor_duo4()[0], '<NAME>', george_birthdate)
validateContactViewModel(nested_view_model.minor_duo4()[1], '<NAME>', ringo_birthdate)
validateContactViewModel(nested_view_model.minor_duo5()[0], '<NAME>', george_birthdate)
validateContactViewModel(nested_view_model.minor_duo5()[1], '<NAME>', ringo_birthdate)
validateContactViewModel(nested_view_model.minor_duo6()[0], '<NAME>', george_birthdate) # mixed
validateGenericViewModel(nested_view_model.minor_duo6()[1], 'Ringo', ringo_birthdate) # mixed
# and cleanup after yourself when you are done.
kb.release(nested_view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '11. Shared Options', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection({id: 1, name: '<NAME>'})
collection_observable1 = kb.collectionObservable(collection)
collection_observable2 = kb.collectionObservable(collection)
collection_observable3 = kb.collectionObservable(collection, collection_observable1.shareOptions())
assert.ok(collection_observable1()[0] isnt collection_observable2()[0], 'not sharing')
assert.ok(collection_observable1()[0] is collection_observable3()[0], 'sharing')
kb.release([collection_observable1, collection_observable2, collection_observable3])
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '12. Filters option', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection([{id: 1, name: '<NAME>'}, {id: 2, name: '<NAME>'}, {id: 3, name: '<NAME>'}])
collection_observable1 = kb.collectionObservable(collection)
collection_observable2 = kb.collectionObservable(collection, {filters: 1})
collection_observable3 = kb.collectionObservable(collection, {filters: [2]})
collection_observable4 = kb.collectionObservable(collection, {filters: 5})
collection_observable5 = kb.collectionObservable(collection, {filters: [5]})
collection_observable6 = kb.collectionObservable(collection, {filters: (model) -> model.get('name') isnt '<NAME>'})
collection_observable7 = kb.collectionObservable(collection, {filters: [((model) -> model.get('name') isnt '<NAME>'), ((model) -> return model.get('name') isnt '<NAME>')]})
observable1 = ko.computed(-> _.filter(collection_observable6(), (vm) -> vm.name() is '<NAME>'))
assert.equal(_.map(_.pluck(collection_observable1(), 'name'), (o) -> o()).join(', '), '<NAME>, <NAME>, <NAME>')
assert.equal(_.map(_.pluck(collection_observable2(), 'name'), (o) -> o()).join(', '), '<NAME>')
assert.equal(_.map(_.pluck(collection_observable3(), 'name'), (o) -> o()).join(', '), '<NAME>')
assert.equal(_.map(_.pluck(collection_observable4(), 'name'), (o) -> o()).join(', '), '')
assert.equal(_.map(_.pluck(collection_observable5(), 'name'), (o) -> o()).join(', '), '')
assert.equal(_.map(_.pluck(collection_observable6(), 'name'), (o) -> o()).join(', '), '<NAME>')
assert.equal(_.map(_.pluck(collection_observable7(), 'name'), (o) -> o()).join(', '), '<NAME>')
assert.equal(_.map(_.pluck(observable1(), 'name'), (o) -> o()).join(', '), '<NAME>')
collection.add([{id: 4, name: '<NAME>'}, {id: 5, name: '<NAME>'}, {id: 6, name: '<NAME>'}, {id: 7, name: '<NAME>'}])
assert.equal(_.map(_.pluck(collection_observable1(), 'name'), (o) -> o()).join(', '), '<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>')
assert.equal(_.map(_.pluck(collection_observable2(), 'name'), (o) -> o()).join(', '), '<NAME>')
assert.equal(_.map(_.pluck(collection_observable3(), 'name'), (o) -> o()).join(', '), '<NAME>')
assert.equal(_.map(_.pluck(collection_observable4(), 'name'), (o) -> o()).join(', '), '<NAME>')
assert.equal(_.map(_.pluck(collection_observable5(), 'name'), (o) -> o()).join(', '), '<NAME>')
assert.equal(_.map(_.pluck(collection_observable6(), 'name'), (o) -> o()).join(', '), '<NAME>, <NAME>, <NAME>, <NAME>, <NAME>')
assert.equal(_.map(_.pluck(collection_observable7(), 'name'), (o) -> o()).join(', '), '<NAME>, <NAME>, <NAME>')
assert.equal(_.map(_.pluck(observable1(), 'name'), (o) -> o()).join(', '), '<NAME>, <NAME>')
kb.release([collection_observable1, collection_observable2, collection_observable3, collection_observable4, collection_observable5, collection_observable6, collection_observable7, observable1])
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '13. Setting view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection([{id: 1, name: '<NAME>'}, {id: 2, name: '<NAME>'}, {id: 3, name: '<NAME>'}])
# set the viewmodels (simulating a selectOptions)
collection_observable = kb.collectionObservable(collection)
view_models = _.map(collection.models, (model) -> kb.viewModel(model))
previous_view_model = collection_observable()[0]
collection_observable(view_models)
assert.ok(collection_observable()[0] isnt previous_view_model, 'view model updated')
assert.ok(collection_observable()[0] is view_models[0], 'view model updated from new list')
store = kb.utils.wrappedStore(collection_observable)
store.compact() # ensure compact does not throw
assert.ok(store.find(collection.models[0], kb.ViewModel) is view_models[0], 'view model was added to the store')
assert.ok(store.find(collection.models[0], kb.ViewModel) isnt previous_view_model, 'previous view model was removed from the store')
kb.release(view_models)
kb.release(collection_observable)
# set the viewmodels (simulating a selectOptions)
class SpecializedViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(collection)
view_models = _.map(collection.models, (model) -> new SpecializedViewModel(model))
previous_view_model = collection_observable()[0]
assert.throw((->collection_observable(view_models)))
# assert.throw((->collection_observable(view_models)), null, 'Store: replacing different type')
assert.ok(collection_observable()[0] isnt previous_view_model, 'view model updated')
assert.ok(collection_observable()[0] is view_models[0], 'view model updated from new list')
store = kb.utils.wrappedStore(collection_observable)
store.compact() # ensure compact does not throw
assert.ok(store.find(collection.models[0], kb.ViewModel) isnt view_models[0], 'view model was not added to the store')
assert.ok(store.find(collection.models[0], kb.ViewModel) is previous_view_model, 'previous view model was not removed from the store')
kb.release(view_models)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '14. collection change is observable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection([{id: 1, name: '<NAME>'}, {id: 2, name: '<NAME>'}, {id: 3, name: '<NAME>'}])
collection_observable = kb.collectionObservable(collection)
count = 0
ko.computed(-> collection_observable.collection(); count++)
assert.ok(collection_observable()[0] instanceof kb.ViewModel, 'is a kb.ViewModel')
collection_observable.collection(null)
collection_observable.collection(collection)
assert.equal(count, 3, "collection change was observed")
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '15. collection is generated if not passed (no options)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable()
collection = collection_observable.collection()
collection.reset([{id: 1, name: '<NAME>'}, {id: 2, name: '<NAME>'}, {id: 3, name: '<NAME>'}])
count = 0
ko.computed(-> collection_observable.collection(); count++)
assert.ok(collection_observable()[0] instanceof kb.ViewModel, 'is a kb.ViewModel')
collection_observable.collection(null)
collection_observable.collection(collection)
assert.equal(count, 3, "collection change was observed")
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '16. collection is generated if not passed (options)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable({view_model: ContactViewModel})
collection = collection_observable.collection()
collection.reset([{id: 1, name: '<NAME>'}, {id: 2, name: '<NAME>'}, {id: 3, name: '<NAME>'}])
count = 0
ko.computed(-> collection_observable.collection(); count++)
assert.ok(collection_observable()[0] instanceof ContactViewModel, 'is a ContactViewModel')
collection_observable.collection(null)
collection_observable.collection(collection)
assert.equal(count, 3, "collection change was observed")
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '17. collection changes do not cause dependencies inside ko.computed', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable({view_model: TestViewModel})
collection = collection_observable.collection()
count_manual = 0
ko.computed ->
collection_observable([new TestViewModel(new kb.Model({id: 10, name: 'Manual'}))]) # should not depend
count_manual++
count_reset = 0
ko.computed ->
collection.reset([{id: 20, name: 'Reset1'}, {id: 21, name: 'Reset2'}]) # should not depend
count_reset++
count_add = 0
ko.computed ->
collection.add([{id: 30, name: 'Add1'}, {id: 31, name: 'Add2'}]) # should not depend
count_add++
count_remove = 0
ko.computed ->
collection.remove(collection.at(0))
count_remove++
observable_count = 0
ko.computed ->
collection_observable() # should depend
observable_count++
assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_reset, 1, 'count_reset'); assert.equal(count_add, 1, 'count_add'); assert.equal(count_remove, 1, 'count_remove'); assert.equal(observable_count, 1, 'observable_count')
collection_observable([new TestViewModel(new kb.Model({id: 10, name: 'Manual'}))]) # should not depend
collection.reset([{id: 20, name: 'Reset1'}, {id: 21, name: 'Reset2'}]) # should not depend
collection.add([{id: 30, name: 'Add1'}, {id: 31, name: 'Add2'}]) # should not depend
collection.remove(collection.at(0))
assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_reset, 1, 'count_reset'); assert.equal(count_add, 1, 'count_add'); assert.equal(count_remove, 1, 'count_remove'); assert.equal(observable_count, 6, 'observable_count')
view_model = collection_observable()[0]
model = view_model.model()
model.set({name: '<NAME>'})
assert.equal(view_model.name(), '<NAME>')
view_model.test('world')
assert.equal(view_model.test(), 'world')
assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_reset, 1, 'count_reset'); assert.equal(count_add, 1, 'count_add'); assert.equal(count_remove, 1, 'count_remove'); assert.equal(observable_count, 6, 'observable_count')
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '18. Test auto-generate collections', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
models = (new Contact({id: id}) for id in [1..4])
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable({view_model: PersonViewModel})
collection_observable.collection().reset(models)
assert.equal(collection_observable.collection().length, 4)
for view_models in collection_observable()
assert.ok(!!view_models.date())
assert.ok(view_models.model() instanceof Contact)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '19. Test auto-generate collections with model array', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
models = (new Contact({id: id}) for id in [1..4])
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(models, {view_model: PersonViewModel})
assert.equal(collection_observable.collection().length, 4)
for view_models in collection_observable()
assert.ok(!!view_models.date())
assert.ok(view_models.model() instanceof Contact)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '20. push and unshift', (done) ->
return done() if kb.Backbone and kb.Backbone.VERSION[0] isnt '1'
kb.statistics = new kb.Statistics() # turn on stats
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(new Contacts(), {view_model: PersonViewModel})
# LEGACY
if collection_observable.collection().push
collection_observable.collection().push()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().push(null)
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().push(new Contact())
assert.equal(collection_observable.collection().length, 1)
assert.equal(collection_observable().length, 1)
collection_observable.collection().reset()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
# LEGACY
if collection_observable.collection().unshift
collection_observable.collection().unshift()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().unshift(null)
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().unshift(new Contact())
assert.equal(collection_observable.collection().length, 1)
assert.equal(collection_observable().length, 1)
collection_observable.collection().reset()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '21. Auto compact for collections', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
models = (new Contact({id: id}) for id in [1..4])
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(models, {view_model: PersonViewModel, auto_compact: true})
collection = collection_observable.collection()
assert.equal(collection_observable.collection().length, 4)
previous_view_models = collection_observable().slice()
assert.equal(previous_view_models.length, 4)
assert.equal(kb.statistics.registeredStatsString('all released'), 'ViewModel: 4\n CollectionObservable: 1', "Expected stats")
collection_observable.collection().add(new Contact({id: 5}))
new_view_models = collection_observable()
assert.equal(new_view_models.length, 5)
assert.equal(previous_view_models.length, 4)
for vm in new_view_models
if vm.model() is collection_observable.collection().models[4]
assert.ok(not(vm in previous_view_models))
else
assert.ok(vm in previous_view_models)
models = collection_observable.collection().models.slice()
collection_observable.collection().reset(models)
new_view_models = collection_observable()
assert.equal(new_view_models.length, 5)
assert.equal(previous_view_models.length, 4)
assert.ok(not(vm in previous_view_models)) for vm in new_view_models
kb.release(collection_observable)
assert.ok(kb.Statistics.eventsStats(collection).count is 0, "All collection events cleared. Expected: 0. Actual: #{JSON.stringify(kb.Statistics.eventsStats(collection))}")
for model in models
collection.remove(model)
assert.ok(kb.Statistics.eventsStats(model).count is 0, "All model events cleared. Expected: 0. Actual: #{JSON.stringify(kb.Statistics.eventsStats(model))}")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
| true | assert = assert or require?('chai').assert
describe 'collection-observable @quick @collection-observable', ->
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
done()
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
ContactViewModel = (model) ->
@name = kb.observable(model, 'name')
@number = kb.observable(model, 'number')
@
class ContactViewModelClass
constructor: (model) ->
@name = kb.observable(model, 'name')
@number = kb.observable(model, 'number')
class TestViewModel extends kb.ViewModel
constructor: ->
super
@test = ko.observable('hello')
value = @test()
value = @name()
it '2. Basic Usage: collection observable with ko.computed', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection)
view_model =
count: ko.computed(->return collection_observable().length )
assert.equal(collection.length, 0, "no models")
assert.equal(view_model.count(), 0, "no count")
collection.add(new Contact({id: 'b1', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5555'}))
assert.equal(collection.length, 2, "2 models")
assert.equal(view_model.count(), 2, "2 count")
collection.add(new Contact({id: 'b3', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5557'}))
assert.equal(collection.length, 3, "3 models")
assert.equal(view_model.count(), 3, "3 count")
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "1 model")
assert.equal(view_model.count(), 1, "1 count")
# clean up
kb.release(collection_observable)
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '3. Basic Usage: collection observable with ko.computed', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, factories: {models: ContactViewModel})
view_model =
count: ko.computed(-> return collection_observable().length)
assert.equal(collection.length, 0, "no models")
assert.equal(view_model.count(), 0, "no count")
collection.add(new Contact({id: 'b1', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5555'}))
assert.equal(collection.length, 2, "2 models")
assert.equal(view_model.count(), 2, "2 count")
collection.add(new Contact({id: 'b3', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5557'}))
assert.equal(collection.length, 3, "3 models")
assert.equal(view_model.count(), 3, "3 count")
assert.ok(collection_observable()[2] instanceof ContactViewModel, 'correct type from factory')
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "1 model")
assert.equal(view_model.count(), 1, "1 count")
# clean up
kb.release(collection_observable)
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '4. Basic Usage: no view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {models_only: true})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5555'}))
collection.add(new Contact({id: 'b2', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "GePI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(collection_observable()[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection_observable()[1].get('name'), 'PI:NAME:<NAME>END_PI', "George is second")
collection.remove('b2')
assert.equal(collection.length, 1, "one models")
assert.equal(collection_observable().length, 1, "one view models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "RingPI:NAME:<NAME>END_PI is left")
model = kb.utils.wrappedModel(collection_observable()[0])
assert.equal(model.get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is left")
model = collection_observable()[0]
assert.equal(model.get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is left")
view_model = collection_observable.viewModelByModel(model)
assert.ok(!view_model, "no view model found since the collection observable is not wrapping models in view models")
model_count = 0
_.each(collection_observable(), (model)->model_count++)
assert.equal(model_count, 1, "one model")
assert.ok(collection_observable.collection()==collection, "collections match")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '5. Basic Usage: no sorting and no callbacks', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
factories:
models: {create: (model) -> return new ContactViewModel(model)}
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5555'}))
collection.add(new Contact({id: 'b2', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
collection.remove('b2')
assert.equal(collection.length, 1, "one model")
assert.equal(collection_observable().length, 1, "one view model")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is left")
model = kb.utils.wrappedModel(collection_observable()[0])
assert.equal(model.get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is left")
view_model = collection_observable.viewModelByModel(model)
assert.equal(kb.utils.wrappedModel(view_model).get('name'), 'PI:NAME:<NAME>END_PI', "RingPI:NAME:<NAME>END_PI is left")
view_model_count = 0
_.each(collection_observable(), (view_model)->view_model_count++)
assert.equal(view_model_count, 1, "one view model")
assert.ok(collection_observable.collection()==collection, "collections match")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '6. Collection sync sorting with sort_attribute', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModelClass
sort_attribute: 'name'
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second - sorting worked!")
collection.add(new Contact({id: 'b3', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5557'}))
assert.equal(collection.length, 3, "three models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection.models[2].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 3, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is third - sorting worked!")
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "one model")
assert.equal(collection_observable().length, 1, "one view model")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is left")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is left")
collection.reset()
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '7. Collection sync sorting with comparator', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
sortNumber = (model_a, model_b) ->
parts_a = kb.utils.wrappedModel(model_a).get('number').split('-')
parts_b = kb.utils.wrappedModel(model_b).get('number').split('-')
return (parts_a.length-parts_b.length) if parts_a.length isnt parts_b.length
for index, part of parts_b
return delta unless (delta = parts_a[index] - parseInt(part, 10)) is 0
return 0
# without view models
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
models_only: true
comparator: sortNumber
})
collection.add(new Contact({id: 'b1', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(collection_observable()[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first - sorting worked!")
assert.equal(collection_observable()[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second - sorting worked!")
# clean up
kb.release(collection_observable)
# with view models
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModelClass
comparator: sortNumber
})
collection.add(new Contact({id: 'b1', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second - sorting worked!")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '8. Collection sorting with callbacks', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.NameSortedContacts = kb.Collection.extend({
model: Contact
comparator: (model) -> return model.get('name')
})
collection = new kb.NameSortedContacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModel # view_model is legacy for view_model, it should be replaced with view_model or create
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second - sorting worked!")
collection.add(new Contact({id: 'b3', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5557'}))
assert.equal(collection.length, 3, "three models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection.models[2].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 3, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is third - sorting worked!")
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "one models")
assert.equal(collection_observable().length, 1, "one view models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is left")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "Ringo is left")
collection.reset()
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '9. Collection sync dynamically changing the sorting function', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new Contacts()
collection_observable = kb.collectionObservable(collection, {
view_model: ContactViewModel
})
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
collection.add(new Contact({id: 'b1', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'}))
collection.add(new Contact({id: 'b2', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5555'}))
assert.equal(collection.length, 2, "two models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 2, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first - no sorting")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PIorge is first - no sorting")
collection_observable.sortAttribute('name')
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PIorge is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second - sorting worked!")
collection.add(new Contact({id: 'b3', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5554'}))
assert.equal(collection.length, 3, "three models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection.models[2].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection_observable().length, 3, "two view models")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is third - sorting worked!")
collection_observable.sortAttribute('number')
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first")
assert.equal(collection.models[1].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(collection.models[2].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is first - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[1]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is second - sorting worked!")
assert.equal(kb.utils.wrappedModel(collection_observable()[2]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is third - sorting worked!")
collection_observable.sortAttribute('name')
collection.remove('b2'); collection.remove('b3')
assert.equal(collection.length, 1, "one models")
assert.equal(collection_observable().length, 1, "one view models")
assert.equal(collection.models[0].get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is left")
assert.equal(kb.utils.wrappedModel(collection_observable()[0]).get('name'), 'PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI is left")
collection.reset()
assert.equal(collection.length, 0, "no models")
assert.equal(collection_observable().length, 0, "no view models")
# clean up
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '10. Nested custom view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelDate extends kb.ViewModel
constructor: (model, options) ->
super(model, _.extend({requires: ['date']}, options))
john_birthdate = new Date(1940, 10, 9)
PI:NAME:<NAME>END_PI = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(john_birthdate.valueOf())})
paul_birthdate = new Date(1942, 6, 18)
paul = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(paul_birthdate.valueOf())})
george_birthdate = new Date(1943, 2, 25)
george = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(george_birthdate.valueOf())})
ringo_birthdate = new Date(1940, 7, 7)
ringo = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(ringo_birthdate.valueOf())})
major_duo = new kb.Collection([john, paul])
minor_duo = new kb.Collection([george, ringo])
nested_view_model = {
major_duo1: kb.collectionObservable(major_duo)
major_duo2: kb.collectionObservable(major_duo, {models_only: true})
major_duo3: kb.collectionObservable(major_duo, {view_model: kb.ViewModel})
major_duo4: kb.collectionObservable(major_duo, {view_model: ContactViewModelDate})
major_duo5: kb.collectionObservable(major_duo, {create: (model, options) -> return new ContactViewModelDate(model, options)})
major_duo6: kb.collectionObservable(major_duo, {create: (model, options) -> return if model.get('name') is 'PI:NAME:<NAME>END_PI' then new ContactViewModelDate(model, options) else kb.viewModel(model, options)}) # mixed
minor_duo1: kb.collectionObservable(minor_duo, {factories: {}})
minor_duo2: kb.collectionObservable(minor_duo, {factories: models: {models_only: true}})
minor_duo3: kb.collectionObservable(minor_duo, {factories: models: kb.ViewModel})
minor_duo4: kb.collectionObservable(minor_duo, {factories: models: {view_model: ContactViewModelDate}})
minor_duo5: kb.collectionObservable(minor_duo, {factories: models: {create: (model, options) -> return new ContactViewModelDate(model, options)}})
minor_duo6: kb.collectionObservable(minor_duo, {factories: models: {create: (model, options) -> return if model.get('name') is 'PI:NAME:<NAME>END_PI' then new ContactViewModelDate(model, options) else kb.viewModel(model, options)}}) # mixed
}
validateContactViewModel = (view_model, name, birthdate) ->
model = kb.utils.wrappedModel(view_model)
assert.equal(view_model.name(), name, "#{name}: Name matches")
# set from the view model
view_model.date(new Date(1963, 11, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "#{name}: year is good")
assert.equal(current_date.getMonth(), 11, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model.date().getFullYear(), 1963, "#{name}: year is good")
assert.equal(view_model.date().getMonth(), 11, "#{name}: month is good")
assert.equal(view_model.date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
# set from the model
view_model.date(new Date(1940, 10, 10))
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "#{name}: year is good")
assert.equal(current_date.getMonth(), 10, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model.date().getFullYear(), 1940, "#{name}: year is good")
assert.equal(view_model.date().getMonth(), 10, "#{name}: month is good")
assert.equal(view_model.date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
validateGenericViewModel = (view_model, name, birthdate) ->
assert.equal(view_model.name(), name, "#{name}: Name matches")
assert.equal(view_model.date().valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
validateModel = (model, name, birthdate) ->
assert.equal(model.get('name'), name, "#{name}: Name matches")
assert.equal(model.get('date').valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
# colllections
validateGenericViewModel(nested_view_model.major_duo1()[0], 'PI:NAME:<NAME>END_PI', john_birthdate)
validateGenericViewModel(nested_view_model.major_duo1()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate)
validateModel(nested_view_model.major_duo2()[0], 'PI:NAME:<NAME>END_PI', john_birthdate)
validateModel(nested_view_model.major_duo2()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate)
validateGenericViewModel(nested_view_model.major_duo3()[0], 'PI:NAME:<NAME>END_PI', john_birthdate)
validateGenericViewModel(nested_view_model.major_duo3()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo4()[0], 'PI:NAME:<NAME>END_PI', john_birthdate)
validateContactViewModel(nested_view_model.major_duo4()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo5()[0], 'PI:NAME:<NAME>END_PI', john_birthdate)
validateContactViewModel(nested_view_model.major_duo5()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo6()[0], 'PI:NAME:<NAME>END_PI', john_birthdate) # mixed
validateGenericViewModel(nested_view_model.major_duo6()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate) # mixed
validateGenericViewModel(nested_view_model.minor_duo1()[0], 'PI:NAME:<NAME>END_PI', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo1()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate)
validateModel(nested_view_model.minor_duo2()[0], 'PI:NAME:<NAME>END_PI', george_birthdate)
validateModel(nested_view_model.minor_duo2()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[0], 'PI:NAME:<NAME>END_PI', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate)
validateContactViewModel(nested_view_model.minor_duo4()[0], 'PI:NAME:<NAME>END_PI', george_birthdate)
validateContactViewModel(nested_view_model.minor_duo4()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate)
validateContactViewModel(nested_view_model.minor_duo5()[0], 'PI:NAME:<NAME>END_PI', george_birthdate)
validateContactViewModel(nested_view_model.minor_duo5()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate)
validateContactViewModel(nested_view_model.minor_duo6()[0], 'PI:NAME:<NAME>END_PI', george_birthdate) # mixed
validateGenericViewModel(nested_view_model.minor_duo6()[1], 'Ringo', ringo_birthdate) # mixed
# and cleanup after yourself when you are done.
kb.release(nested_view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '11. Shared Options', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection({id: 1, name: 'PI:NAME:<NAME>END_PI'})
collection_observable1 = kb.collectionObservable(collection)
collection_observable2 = kb.collectionObservable(collection)
collection_observable3 = kb.collectionObservable(collection, collection_observable1.shareOptions())
assert.ok(collection_observable1()[0] isnt collection_observable2()[0], 'not sharing')
assert.ok(collection_observable1()[0] is collection_observable3()[0], 'sharing')
kb.release([collection_observable1, collection_observable2, collection_observable3])
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '12. Filters option', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection([{id: 1, name: 'PI:NAME:<NAME>END_PI'}, {id: 2, name: 'PI:NAME:<NAME>END_PI'}, {id: 3, name: 'PI:NAME:<NAME>END_PI'}])
collection_observable1 = kb.collectionObservable(collection)
collection_observable2 = kb.collectionObservable(collection, {filters: 1})
collection_observable3 = kb.collectionObservable(collection, {filters: [2]})
collection_observable4 = kb.collectionObservable(collection, {filters: 5})
collection_observable5 = kb.collectionObservable(collection, {filters: [5]})
collection_observable6 = kb.collectionObservable(collection, {filters: (model) -> model.get('name') isnt 'PI:NAME:<NAME>END_PI'})
collection_observable7 = kb.collectionObservable(collection, {filters: [((model) -> model.get('name') isnt 'PI:NAME:<NAME>END_PI'), ((model) -> return model.get('name') isnt 'PI:NAME:<NAME>END_PI')]})
observable1 = ko.computed(-> _.filter(collection_observable6(), (vm) -> vm.name() is 'PI:NAME:<NAME>END_PI'))
assert.equal(_.map(_.pluck(collection_observable1(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(collection_observable2(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(collection_observable3(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(collection_observable4(), 'name'), (o) -> o()).join(', '), '')
assert.equal(_.map(_.pluck(collection_observable5(), 'name'), (o) -> o()).join(', '), '')
assert.equal(_.map(_.pluck(collection_observable6(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(collection_observable7(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(observable1(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI')
collection.add([{id: 4, name: 'PI:NAME:<NAME>END_PI'}, {id: 5, name: 'PI:NAME:<NAME>END_PI'}, {id: 6, name: 'PI:NAME:<NAME>END_PI'}, {id: 7, name: 'PI:NAME:<NAME>END_PI'}])
assert.equal(_.map(_.pluck(collection_observable1(), 'name'), (o) -> o()).join(', '), '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')
assert.equal(_.map(_.pluck(collection_observable2(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(collection_observable3(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(collection_observable4(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(collection_observable5(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(collection_observable6(), 'name'), (o) -> o()).join(', '), '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')
assert.equal(_.map(_.pluck(collection_observable7(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI')
assert.equal(_.map(_.pluck(observable1(), 'name'), (o) -> o()).join(', '), 'PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI')
kb.release([collection_observable1, collection_observable2, collection_observable3, collection_observable4, collection_observable5, collection_observable6, collection_observable7, observable1])
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '13. Setting view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection([{id: 1, name: 'PI:NAME:<NAME>END_PI'}, {id: 2, name: 'PI:NAME:<NAME>END_PI'}, {id: 3, name: 'PI:NAME:<NAME>END_PI'}])
# set the viewmodels (simulating a selectOptions)
collection_observable = kb.collectionObservable(collection)
view_models = _.map(collection.models, (model) -> kb.viewModel(model))
previous_view_model = collection_observable()[0]
collection_observable(view_models)
assert.ok(collection_observable()[0] isnt previous_view_model, 'view model updated')
assert.ok(collection_observable()[0] is view_models[0], 'view model updated from new list')
store = kb.utils.wrappedStore(collection_observable)
store.compact() # ensure compact does not throw
assert.ok(store.find(collection.models[0], kb.ViewModel) is view_models[0], 'view model was added to the store')
assert.ok(store.find(collection.models[0], kb.ViewModel) isnt previous_view_model, 'previous view model was removed from the store')
kb.release(view_models)
kb.release(collection_observable)
# set the viewmodels (simulating a selectOptions)
class SpecializedViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(collection)
view_models = _.map(collection.models, (model) -> new SpecializedViewModel(model))
previous_view_model = collection_observable()[0]
assert.throw((->collection_observable(view_models)))
# assert.throw((->collection_observable(view_models)), null, 'Store: replacing different type')
assert.ok(collection_observable()[0] isnt previous_view_model, 'view model updated')
assert.ok(collection_observable()[0] is view_models[0], 'view model updated from new list')
store = kb.utils.wrappedStore(collection_observable)
store.compact() # ensure compact does not throw
assert.ok(store.find(collection.models[0], kb.ViewModel) isnt view_models[0], 'view model was not added to the store')
assert.ok(store.find(collection.models[0], kb.ViewModel) is previous_view_model, 'previous view model was not removed from the store')
kb.release(view_models)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '14. collection change is observable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection = new kb.Collection([{id: 1, name: 'PI:NAME:<NAME>END_PI'}, {id: 2, name: 'PI:NAME:<NAME>END_PI'}, {id: 3, name: 'PI:NAME:<NAME>END_PI'}])
collection_observable = kb.collectionObservable(collection)
count = 0
ko.computed(-> collection_observable.collection(); count++)
assert.ok(collection_observable()[0] instanceof kb.ViewModel, 'is a kb.ViewModel')
collection_observable.collection(null)
collection_observable.collection(collection)
assert.equal(count, 3, "collection change was observed")
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '15. collection is generated if not passed (no options)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable()
collection = collection_observable.collection()
collection.reset([{id: 1, name: 'PI:NAME:<NAME>END_PI'}, {id: 2, name: 'PI:NAME:<NAME>END_PI'}, {id: 3, name: 'PI:NAME:<NAME>END_PI'}])
count = 0
ko.computed(-> collection_observable.collection(); count++)
assert.ok(collection_observable()[0] instanceof kb.ViewModel, 'is a kb.ViewModel')
collection_observable.collection(null)
collection_observable.collection(collection)
assert.equal(count, 3, "collection change was observed")
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '16. collection is generated if not passed (options)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable({view_model: ContactViewModel})
collection = collection_observable.collection()
collection.reset([{id: 1, name: 'PI:NAME:<NAME>END_PI'}, {id: 2, name: 'PI:NAME:<NAME>END_PI'}, {id: 3, name: 'PI:NAME:<NAME>END_PI'}])
count = 0
ko.computed(-> collection_observable.collection(); count++)
assert.ok(collection_observable()[0] instanceof ContactViewModel, 'is a ContactViewModel')
collection_observable.collection(null)
collection_observable.collection(collection)
assert.equal(count, 3, "collection change was observed")
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '17. collection changes do not cause dependencies inside ko.computed', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
collection_observable = kb.collectionObservable({view_model: TestViewModel})
collection = collection_observable.collection()
count_manual = 0
ko.computed ->
collection_observable([new TestViewModel(new kb.Model({id: 10, name: 'Manual'}))]) # should not depend
count_manual++
count_reset = 0
ko.computed ->
collection.reset([{id: 20, name: 'Reset1'}, {id: 21, name: 'Reset2'}]) # should not depend
count_reset++
count_add = 0
ko.computed ->
collection.add([{id: 30, name: 'Add1'}, {id: 31, name: 'Add2'}]) # should not depend
count_add++
count_remove = 0
ko.computed ->
collection.remove(collection.at(0))
count_remove++
observable_count = 0
ko.computed ->
collection_observable() # should depend
observable_count++
assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_reset, 1, 'count_reset'); assert.equal(count_add, 1, 'count_add'); assert.equal(count_remove, 1, 'count_remove'); assert.equal(observable_count, 1, 'observable_count')
collection_observable([new TestViewModel(new kb.Model({id: 10, name: 'Manual'}))]) # should not depend
collection.reset([{id: 20, name: 'Reset1'}, {id: 21, name: 'Reset2'}]) # should not depend
collection.add([{id: 30, name: 'Add1'}, {id: 31, name: 'Add2'}]) # should not depend
collection.remove(collection.at(0))
assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_reset, 1, 'count_reset'); assert.equal(count_add, 1, 'count_add'); assert.equal(count_remove, 1, 'count_remove'); assert.equal(observable_count, 6, 'observable_count')
view_model = collection_observable()[0]
model = view_model.model()
model.set({name: 'PI:NAME:<NAME>END_PI'})
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI')
view_model.test('world')
assert.equal(view_model.test(), 'world')
assert.equal(count_manual, 1, 'count_manual'); assert.equal(count_reset, 1, 'count_reset'); assert.equal(count_add, 1, 'count_add'); assert.equal(count_remove, 1, 'count_remove'); assert.equal(observable_count, 6, 'observable_count')
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '18. Test auto-generate collections', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
models = (new Contact({id: id}) for id in [1..4])
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable({view_model: PersonViewModel})
collection_observable.collection().reset(models)
assert.equal(collection_observable.collection().length, 4)
for view_models in collection_observable()
assert.ok(!!view_models.date())
assert.ok(view_models.model() instanceof Contact)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '19. Test auto-generate collections with model array', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
models = (new Contact({id: id}) for id in [1..4])
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(models, {view_model: PersonViewModel})
assert.equal(collection_observable.collection().length, 4)
for view_models in collection_observable()
assert.ok(!!view_models.date())
assert.ok(view_models.model() instanceof Contact)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '20. push and unshift', (done) ->
return done() if kb.Backbone and kb.Backbone.VERSION[0] isnt '1'
kb.statistics = new kb.Statistics() # turn on stats
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(new Contacts(), {view_model: PersonViewModel})
# LEGACY
if collection_observable.collection().push
collection_observable.collection().push()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().push(null)
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().push(new Contact())
assert.equal(collection_observable.collection().length, 1)
assert.equal(collection_observable().length, 1)
collection_observable.collection().reset()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
# LEGACY
if collection_observable.collection().unshift
collection_observable.collection().unshift()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().unshift(null)
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
collection_observable.collection().unshift(new Contact())
assert.equal(collection_observable.collection().length, 1)
assert.equal(collection_observable().length, 1)
collection_observable.collection().reset()
assert.equal(collection_observable.collection().length, 0)
assert.equal(collection_observable().length, 0)
kb.release(collection_observable)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '21. Auto compact for collections', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
models = (new Contact({id: id}) for id in [1..4])
class PersonViewModel extends kb.ViewModel
collection_observable = kb.collectionObservable(models, {view_model: PersonViewModel, auto_compact: true})
collection = collection_observable.collection()
assert.equal(collection_observable.collection().length, 4)
previous_view_models = collection_observable().slice()
assert.equal(previous_view_models.length, 4)
assert.equal(kb.statistics.registeredStatsString('all released'), 'ViewModel: 4\n CollectionObservable: 1', "Expected stats")
collection_observable.collection().add(new Contact({id: 5}))
new_view_models = collection_observable()
assert.equal(new_view_models.length, 5)
assert.equal(previous_view_models.length, 4)
for vm in new_view_models
if vm.model() is collection_observable.collection().models[4]
assert.ok(not(vm in previous_view_models))
else
assert.ok(vm in previous_view_models)
models = collection_observable.collection().models.slice()
collection_observable.collection().reset(models)
new_view_models = collection_observable()
assert.equal(new_view_models.length, 5)
assert.equal(previous_view_models.length, 4)
assert.ok(not(vm in previous_view_models)) for vm in new_view_models
kb.release(collection_observable)
assert.ok(kb.Statistics.eventsStats(collection).count is 0, "All collection events cleared. Expected: 0. Actual: #{JSON.stringify(kb.Statistics.eventsStats(collection))}")
for model in models
collection.remove(model)
assert.ok(kb.Statistics.eventsStats(model).count is 0, "All model events cleared. Expected: 0. Actual: #{JSON.stringify(kb.Statistics.eventsStats(model))}")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
|
[
{
"context": "ection which user have specified\n if key is \"chalk\"\n # NOTE: With new section, the previous s",
"end": 3429,
"score": 0.9353474378585815,
"start": 3424,
"tag": "KEY",
"value": "chalk"
}
] | src/parse.coffee | adrianlee44/chalkboard | 1 | #
# @chalk function
# @function
# @name parse
# @description
# Run through code and parse out all the comments
# @param {String} code Source code to be parsed
# @param {Object} lang Language settings for the file
# @param {Object} options User settings (default {})
# @returns {Array} List of objects with all the comment block
#
definitions = require "../resources/definitions/base.json"
_ = require "lodash"
commentRegex = /^\s*@(\w+)(?:\s*(.*))?$/
NEW_LINE = /\n\r?/
module.exports = (code, lang, options = {})->
hasComment = false
multiLineKey = ""
commentBlockIndex = -1
allSections = []
currentSection = {}
argObject = {}
#
# @chalk function
# @function
# @private
# @name _setAttribute
# @description
# Helper function for setting objects
# @param {Object} object Section object with information
# @param {String} key Name of the tag
# @param {String} value Value to be set
# @param {Object} options Tag definitions (default {})
# @returns {Number|String} Return the length of the array or value
#
_setAttribute = (object, key, value, options = {}) ->
if options.hasMultiple? and options.hasMultiple
object[key] ?= []
object[key].push value
else
object[key] ?= ""
object[key] += value
#
# @chalk function
# @function
# @private
# @name _getMultiLineKey
# @description
# multiLineKey has value a.b when used in multiple line argument
# description. This function get the correct key based on the index
# @param {Integer} index Key index
#
_getMultiLineKey = (index) ->
keys = multiLineKey.split "."
index = keys.length + index if index < 0
return "" if keys.length is 0 or index < 0 or index > keys.length
keys[index]
_multiLineSetAttribute = (value) ->
object = if _.isEmpty(argObject) then currentSection else argObject
value += " \n"
_setAttribute(object,
_getMultiLineKey(-1),
value,
definitions[_getMultiLineKey(-1)]
)
_setArgObject = ->
if multiLineKey and not _.isEmpty(argObject)
_setAttribute(currentSection,
_getMultiLineKey(0),
argObject,
definitions[_getMultiLineKey(0)]
)
argObject = {}
multiLineKey = ""
#
# @chalk function
# @function
# @private
# @name _updateSection
# @description
# Check if current section or argument object are empty or not,
# push object to the correct array if necessary
#
_updateSection = ->
if hasComment and not _.isEmpty(currentSection)
# Check if there is remaining argObject to be cleared
_setArgObject()
allSections.push currentSection
currentSection = {}
hasComment = false
# Parse through each line in the file
for line in code.split(NEW_LINE)
# Check for starting and ending comment block
blockRegex = if commentBlockIndex > -1 then lang.endRegex else lang.startRegex
if match = line.match(blockRegex or lang.blockRegex)
commentBlockIndex = if commentBlockIndex > -1 then -1 else match.index
_updateSection() if commentBlockIndex is -1
continue
toMatchRegex = if commentBlockIndex > -1 then commentRegex else lang.commentRegex
if match = line.match toMatchRegex
key = match[1]
value = match[2]
# Only parse section which user have specified
if key is "chalk"
# NOTE: With new section, the previous section comments should be stored and cleaned
_updateSection()
# Starting a new section
hasComment = true
currentSection.chalk = value
continue
continue unless hasComment
# Get the definition for the key
def = definitions[key]
if key? and def?
_setArgObject()
hasArgs = def.hasArgs? and def.hasArgs
# Identifier section
# =====================
# check if the current key is an type identifier
if def.typeIdentifier and key?
type = if value then value else key
if currentSection.type?
currentSection.type.push type
else
currentSection.type = [key]
continue
# check if the current key is an access identifier
if def.accessIdentifier and key?
if currentSection.access?
console.log """
Cannot have multiple access specifier.
"""
else
currentSection.access = if key is "access" then value else key
continue
# For generic identifier
value = true if def.identifier?
# Following section is for tags with multiple arguments
if hasArgs
matchingRegex =
switch key
when "returns"
/\{([\w\|]+)}(?:\s+(.*))?/
# Type description
else
/\{([\w\|\s]+)}\s+([\w\d_-]+)(?:\s+(.*))?/
# Type name description
# Check value for arguments
# Used by param and returns tag
argsMatch = value.match matchingRegex
if argsMatch?
argObject = type: argsMatch[1] or "undefined"
switch key
when "param"
argObject.description = argsMatch[3] or ""
argObject.name = argsMatch[2]
when "returns"
argObject.description = argsMatch[2] or ""
argObject.description += " \n" if argObject.description
value = null
# when multiple lines are allowed, update the multiLineKey
if def.multipleLines
multiLineKey = if hasArgs then "#{key}.description" else key
if value?
_setAttribute currentSection, key, value, def
continue
# When key doesn't exist and multi line key is set,
# add the value to the original key
setValue = if key? and not def? then line else value
_multiLineSetAttribute setValue if multiLineKey and setValue?
# if the current line is part of multiple line tag
else if multiLineKey and ((lnMatch = line.match lang.lineRegex) or commentBlockIndex > -1)
line = line.substr commentBlockIndex
content = if commentBlockIndex > -1 then line else (lnMatch?[1] or line)
_multiLineSetAttribute content
else if commentBlockIndex is -1
_updateSection()
# Push the last section if there was no new line at the
# end of the file
_updateSection()
return allSections
| 116047 | #
# @chalk function
# @function
# @name parse
# @description
# Run through code and parse out all the comments
# @param {String} code Source code to be parsed
# @param {Object} lang Language settings for the file
# @param {Object} options User settings (default {})
# @returns {Array} List of objects with all the comment block
#
definitions = require "../resources/definitions/base.json"
_ = require "lodash"
commentRegex = /^\s*@(\w+)(?:\s*(.*))?$/
NEW_LINE = /\n\r?/
module.exports = (code, lang, options = {})->
hasComment = false
multiLineKey = ""
commentBlockIndex = -1
allSections = []
currentSection = {}
argObject = {}
#
# @chalk function
# @function
# @private
# @name _setAttribute
# @description
# Helper function for setting objects
# @param {Object} object Section object with information
# @param {String} key Name of the tag
# @param {String} value Value to be set
# @param {Object} options Tag definitions (default {})
# @returns {Number|String} Return the length of the array or value
#
_setAttribute = (object, key, value, options = {}) ->
if options.hasMultiple? and options.hasMultiple
object[key] ?= []
object[key].push value
else
object[key] ?= ""
object[key] += value
#
# @chalk function
# @function
# @private
# @name _getMultiLineKey
# @description
# multiLineKey has value a.b when used in multiple line argument
# description. This function get the correct key based on the index
# @param {Integer} index Key index
#
_getMultiLineKey = (index) ->
keys = multiLineKey.split "."
index = keys.length + index if index < 0
return "" if keys.length is 0 or index < 0 or index > keys.length
keys[index]
_multiLineSetAttribute = (value) ->
object = if _.isEmpty(argObject) then currentSection else argObject
value += " \n"
_setAttribute(object,
_getMultiLineKey(-1),
value,
definitions[_getMultiLineKey(-1)]
)
_setArgObject = ->
if multiLineKey and not _.isEmpty(argObject)
_setAttribute(currentSection,
_getMultiLineKey(0),
argObject,
definitions[_getMultiLineKey(0)]
)
argObject = {}
multiLineKey = ""
#
# @chalk function
# @function
# @private
# @name _updateSection
# @description
# Check if current section or argument object are empty or not,
# push object to the correct array if necessary
#
_updateSection = ->
if hasComment and not _.isEmpty(currentSection)
# Check if there is remaining argObject to be cleared
_setArgObject()
allSections.push currentSection
currentSection = {}
hasComment = false
# Parse through each line in the file
for line in code.split(NEW_LINE)
# Check for starting and ending comment block
blockRegex = if commentBlockIndex > -1 then lang.endRegex else lang.startRegex
if match = line.match(blockRegex or lang.blockRegex)
commentBlockIndex = if commentBlockIndex > -1 then -1 else match.index
_updateSection() if commentBlockIndex is -1
continue
toMatchRegex = if commentBlockIndex > -1 then commentRegex else lang.commentRegex
if match = line.match toMatchRegex
key = match[1]
value = match[2]
# Only parse section which user have specified
if key is "<KEY>"
# NOTE: With new section, the previous section comments should be stored and cleaned
_updateSection()
# Starting a new section
hasComment = true
currentSection.chalk = value
continue
continue unless hasComment
# Get the definition for the key
def = definitions[key]
if key? and def?
_setArgObject()
hasArgs = def.hasArgs? and def.hasArgs
# Identifier section
# =====================
# check if the current key is an type identifier
if def.typeIdentifier and key?
type = if value then value else key
if currentSection.type?
currentSection.type.push type
else
currentSection.type = [key]
continue
# check if the current key is an access identifier
if def.accessIdentifier and key?
if currentSection.access?
console.log """
Cannot have multiple access specifier.
"""
else
currentSection.access = if key is "access" then value else key
continue
# For generic identifier
value = true if def.identifier?
# Following section is for tags with multiple arguments
if hasArgs
matchingRegex =
switch key
when "returns"
/\{([\w\|]+)}(?:\s+(.*))?/
# Type description
else
/\{([\w\|\s]+)}\s+([\w\d_-]+)(?:\s+(.*))?/
# Type name description
# Check value for arguments
# Used by param and returns tag
argsMatch = value.match matchingRegex
if argsMatch?
argObject = type: argsMatch[1] or "undefined"
switch key
when "param"
argObject.description = argsMatch[3] or ""
argObject.name = argsMatch[2]
when "returns"
argObject.description = argsMatch[2] or ""
argObject.description += " \n" if argObject.description
value = null
# when multiple lines are allowed, update the multiLineKey
if def.multipleLines
multiLineKey = if hasArgs then "#{key}.description" else key
if value?
_setAttribute currentSection, key, value, def
continue
# When key doesn't exist and multi line key is set,
# add the value to the original key
setValue = if key? and not def? then line else value
_multiLineSetAttribute setValue if multiLineKey and setValue?
# if the current line is part of multiple line tag
else if multiLineKey and ((lnMatch = line.match lang.lineRegex) or commentBlockIndex > -1)
line = line.substr commentBlockIndex
content = if commentBlockIndex > -1 then line else (lnMatch?[1] or line)
_multiLineSetAttribute content
else if commentBlockIndex is -1
_updateSection()
# Push the last section if there was no new line at the
# end of the file
_updateSection()
return allSections
| true | #
# @chalk function
# @function
# @name parse
# @description
# Run through code and parse out all the comments
# @param {String} code Source code to be parsed
# @param {Object} lang Language settings for the file
# @param {Object} options User settings (default {})
# @returns {Array} List of objects with all the comment block
#
definitions = require "../resources/definitions/base.json"
_ = require "lodash"
commentRegex = /^\s*@(\w+)(?:\s*(.*))?$/
NEW_LINE = /\n\r?/
module.exports = (code, lang, options = {})->
hasComment = false
multiLineKey = ""
commentBlockIndex = -1
allSections = []
currentSection = {}
argObject = {}
#
# @chalk function
# @function
# @private
# @name _setAttribute
# @description
# Helper function for setting objects
# @param {Object} object Section object with information
# @param {String} key Name of the tag
# @param {String} value Value to be set
# @param {Object} options Tag definitions (default {})
# @returns {Number|String} Return the length of the array or value
#
_setAttribute = (object, key, value, options = {}) ->
if options.hasMultiple? and options.hasMultiple
object[key] ?= []
object[key].push value
else
object[key] ?= ""
object[key] += value
#
# @chalk function
# @function
# @private
# @name _getMultiLineKey
# @description
# multiLineKey has value a.b when used in multiple line argument
# description. This function get the correct key based on the index
# @param {Integer} index Key index
#
_getMultiLineKey = (index) ->
keys = multiLineKey.split "."
index = keys.length + index if index < 0
return "" if keys.length is 0 or index < 0 or index > keys.length
keys[index]
_multiLineSetAttribute = (value) ->
object = if _.isEmpty(argObject) then currentSection else argObject
value += " \n"
_setAttribute(object,
_getMultiLineKey(-1),
value,
definitions[_getMultiLineKey(-1)]
)
_setArgObject = ->
if multiLineKey and not _.isEmpty(argObject)
_setAttribute(currentSection,
_getMultiLineKey(0),
argObject,
definitions[_getMultiLineKey(0)]
)
argObject = {}
multiLineKey = ""
#
# @chalk function
# @function
# @private
# @name _updateSection
# @description
# Check if current section or argument object are empty or not,
# push object to the correct array if necessary
#
_updateSection = ->
if hasComment and not _.isEmpty(currentSection)
# Check if there is remaining argObject to be cleared
_setArgObject()
allSections.push currentSection
currentSection = {}
hasComment = false
# Parse through each line in the file
for line in code.split(NEW_LINE)
# Check for starting and ending comment block
blockRegex = if commentBlockIndex > -1 then lang.endRegex else lang.startRegex
if match = line.match(blockRegex or lang.blockRegex)
commentBlockIndex = if commentBlockIndex > -1 then -1 else match.index
_updateSection() if commentBlockIndex is -1
continue
toMatchRegex = if commentBlockIndex > -1 then commentRegex else lang.commentRegex
if match = line.match toMatchRegex
key = match[1]
value = match[2]
# Only parse section which user have specified
if key is "PI:KEY:<KEY>END_PI"
# NOTE: With new section, the previous section comments should be stored and cleaned
_updateSection()
# Starting a new section
hasComment = true
currentSection.chalk = value
continue
continue unless hasComment
# Get the definition for the key
def = definitions[key]
if key? and def?
_setArgObject()
hasArgs = def.hasArgs? and def.hasArgs
# Identifier section
# =====================
# check if the current key is an type identifier
if def.typeIdentifier and key?
type = if value then value else key
if currentSection.type?
currentSection.type.push type
else
currentSection.type = [key]
continue
# check if the current key is an access identifier
if def.accessIdentifier and key?
if currentSection.access?
console.log """
Cannot have multiple access specifier.
"""
else
currentSection.access = if key is "access" then value else key
continue
# For generic identifier
value = true if def.identifier?
# Following section is for tags with multiple arguments
if hasArgs
matchingRegex =
switch key
when "returns"
/\{([\w\|]+)}(?:\s+(.*))?/
# Type description
else
/\{([\w\|\s]+)}\s+([\w\d_-]+)(?:\s+(.*))?/
# Type name description
# Check value for arguments
# Used by param and returns tag
argsMatch = value.match matchingRegex
if argsMatch?
argObject = type: argsMatch[1] or "undefined"
switch key
when "param"
argObject.description = argsMatch[3] or ""
argObject.name = argsMatch[2]
when "returns"
argObject.description = argsMatch[2] or ""
argObject.description += " \n" if argObject.description
value = null
# when multiple lines are allowed, update the multiLineKey
if def.multipleLines
multiLineKey = if hasArgs then "#{key}.description" else key
if value?
_setAttribute currentSection, key, value, def
continue
# When key doesn't exist and multi line key is set,
# add the value to the original key
setValue = if key? and not def? then line else value
_multiLineSetAttribute setValue if multiLineKey and setValue?
# if the current line is part of multiple line tag
else if multiLineKey and ((lnMatch = line.match lang.lineRegex) or commentBlockIndex > -1)
line = line.substr commentBlockIndex
content = if commentBlockIndex > -1 then line else (lnMatch?[1] or line)
_multiLineSetAttribute content
else if commentBlockIndex is -1
_updateSection()
# Push the last section if there was no new line at the
# end of the file
_updateSection()
return allSections
|
[
{
"context": "s for logging messages to the console.\n#\n# @author Matthew Wagerfield @mwagerfield\n#\n#=================================",
"end": 230,
"score": 0.999879002571106,
"start": 212,
"tag": "NAME",
"value": "Matthew Wagerfield"
},
{
"context": "ges to the console.\n#\n# @author Matthew Wagerfield @mwagerfield\n#\n#==============================================",
"end": 243,
"score": 0.9994880557060242,
"start": 231,
"tag": "USERNAME",
"value": "@mwagerfield"
}
] | development/production/source/assets/scripts/coffee/core/Base.coffee | wagerfield/cinnamon | 2 | ###
#============================================================
#
# Project Base
#
# Defines the project name and namespace as well as some
# conveniece methods for logging messages to the console.
#
# @author Matthew Wagerfield @mwagerfield
#
#============================================================
###
# Debug flag.
DEBUG = true
# Project name.
DOGTAG = 'cinnamon'
# Project namespace.
@[DOGTAG] = {}
###
# Logs the provided values in the console.
# @param {object} values The values to be logged.
###
log = (values...) ->
console?.log "#{DOGTAG} »", values...
return
###
# Logs a warning in the console.
# @param {object} values The values to be logged.
###
warn = (values...) ->
console?.warn "#{DOGTAG} »", values...
return
###
# First checks for the provided namespace, and creates it if not found.
# @param {string} namespace The namespace as a string.
# @return {object} Reference to the most nested object in the namespace.
###
namespace = (namespace) ->
target = @[DOGTAG]
if typeof namespace is 'string'
target = target[space] ?= {} for space in namespace.split '.'
return target
# Create namespaces.
PROJECT = namespace()
| 197351 | ###
#============================================================
#
# Project Base
#
# Defines the project name and namespace as well as some
# conveniece methods for logging messages to the console.
#
# @author <NAME> @mwagerfield
#
#============================================================
###
# Debug flag.
DEBUG = true
# Project name.
DOGTAG = 'cinnamon'
# Project namespace.
@[DOGTAG] = {}
###
# Logs the provided values in the console.
# @param {object} values The values to be logged.
###
log = (values...) ->
console?.log "#{DOGTAG} »", values...
return
###
# Logs a warning in the console.
# @param {object} values The values to be logged.
###
warn = (values...) ->
console?.warn "#{DOGTAG} »", values...
return
###
# First checks for the provided namespace, and creates it if not found.
# @param {string} namespace The namespace as a string.
# @return {object} Reference to the most nested object in the namespace.
###
namespace = (namespace) ->
target = @[DOGTAG]
if typeof namespace is 'string'
target = target[space] ?= {} for space in namespace.split '.'
return target
# Create namespaces.
PROJECT = namespace()
| true | ###
#============================================================
#
# Project Base
#
# Defines the project name and namespace as well as some
# conveniece methods for logging messages to the console.
#
# @author PI:NAME:<NAME>END_PI @mwagerfield
#
#============================================================
###
# Debug flag.
DEBUG = true
# Project name.
DOGTAG = 'cinnamon'
# Project namespace.
@[DOGTAG] = {}
###
# Logs the provided values in the console.
# @param {object} values The values to be logged.
###
log = (values...) ->
console?.log "#{DOGTAG} »", values...
return
###
# Logs a warning in the console.
# @param {object} values The values to be logged.
###
warn = (values...) ->
console?.warn "#{DOGTAG} »", values...
return
###
# First checks for the provided namespace, and creates it if not found.
# @param {string} namespace The namespace as a string.
# @return {object} Reference to the most nested object in the namespace.
###
namespace = (namespace) ->
target = @[DOGTAG]
if typeof namespace is 'string'
target = target[space] ?= {} for space in namespace.split '.'
return target
# Create namespaces.
PROJECT = namespace()
|
[
{
"context": " #\n # ['Form', 'enterer', 'first_name', '=', 'Jim']\n #\n # will return all forms that were entered",
"end": 1265,
"score": 0.9997815489768982,
"start": 1262,
"tag": "NAME",
"value": "Jim"
},
{
"context": " that were entered by a user with the first name 'Jim'.\n #\n # The length-2 filter expressions have a ",
"end": 1350,
"score": 0.9998099207878113,
"start": 1347,
"tag": "NAME",
"value": "Jim"
},
{
"context": " # ['Form', 'enterer', 'first_name', '=', 'Jim'],\n # ['Form', 'transcription', 'regex', '",
"end": 1643,
"score": 0.9997773766517639,
"start": 1640,
"tag": "NAME",
"value": "Jim"
},
{
"context": "['Form', 'enterer', 'first_name', 'is', 'John']\n # 0 1 2 3",
"end": 9297,
"score": 0.9997142553329468,
"start": 9293,
"tag": "NAME",
"value": "John"
},
{
"context": "ue\n # ['Form', 'transcription', 'is', 'John']\n # 0 1 2 3",
"end": 9466,
"score": 0.9997164011001587,
"start": 9462,
"tag": "NAME",
"value": "John"
},
{
"context": "getRelations: (options) ->\n try\n key = \"#{@targetResourceName}_search_parameters\"\n re",
"end": 21615,
"score": 0.7635722756385803,
"start": 21612,
"tag": "KEY",
"value": "\"#{"
},
{
"context": "lations: (options) ->\n try\n key = \"#{@targetResourceName}_search_parameters\"\n relations = _.keys options[key].relation",
"end": 21653,
"score": 0.8259654641151428,
"start": 21616,
"tag": "KEY",
"value": "targetResourceName}_search_parameters"
},
{
"context": "e'\n ]\n\n userAttributes: [\n 'id'\n 'first_name'\n 'last_name'\n 'email'\n 'affi",
"end": 27755,
"score": 0.8352641463279724,
"start": 27750,
"tag": "NAME",
"value": "first"
},
{
"context": "ttributes: [\n 'id'\n 'first_name'\n 'last_name'\n 'email'\n 'affiliation'\n 'rol",
"end": 27774,
"score": 0.6884027719497681,
"start": 27769,
"tag": "NAME",
"value": "last_"
},
{
"context": " elicitation_method: 'name'\n elicitor: 'last_name'\n enterer: 'last_name'\n files: 'filenam",
"end": 30237,
"score": 0.9908736348152161,
"start": 30228,
"tag": "NAME",
"value": "last_name"
},
{
"context": "name'\n elicitor: 'last_name'\n enterer: 'last_name'\n files: 'filename'\n forms: 'transcript",
"end": 30264,
"score": 0.9950544834136963,
"start": 30255,
"tag": "NAME",
"value": "last_name"
},
{
"context": "'\n forms: 'transcription'\n memorizers: 'last_name'\n parent_file: 'filename'\n source: 'aut",
"end": 30347,
"score": 0.9591305255889893,
"start": 30338,
"tag": "NAME",
"value": "last_name"
},
{
"context": "'filename'\n source: 'author'\n speaker: 'last_name'\n syntactic_category: 'name'\n tags: 'na",
"end": 30427,
"score": 0.964048445224762,
"start": 30418,
"tag": "NAME",
"value": "last_name"
},
{
"context": " speaker: 'last_name'\n syntactic_category: 'name'\n tags: 'name'\n translations: 'transcri",
"end": 30460,
"score": 0.9930412769317627,
"start": 30456,
"tag": "NAME",
"value": "name"
},
{
"context": " translations: 'transcription'\n verifier: 'last_name'\n modifier: 'last_name'\n\n",
"end": 30543,
"score": 0.9899563789367676,
"start": 30534,
"tag": "NAME",
"value": "last_name"
},
{
"context": "ion'\n verifier: 'last_name'\n modifier: 'last_name'\n\n",
"end": 30571,
"score": 0.7861393094062805,
"start": 30562,
"tag": "NAME",
"value": "last_name"
}
] | app/scripts/views/filter-expression.coffee | OpenSourceFieldlinguistics/dative | 7 | define [
'./base'
'./../templates/filter-expression'
'autosize'
], (BaseView, filterExpressionTemplate) ->
# Filter Expression View
# ----------------------
#
# A view for a filter expression, i.e., a set of inputs for creating a filter
# expression for building the type of search (i.e., query) that the OLD
# accepts. This view spawns subviews of itself for the filter expressions
# that are contained within the filter expression that it represents. The
# idea is to help users to build complex queries using an easy-to-understand
# tree-like interface.
#
# The type of search S that the OLD accepts is a JSON array that
# matches one of the following five rewrite rules:
#
# S -> [modelName, attributeName, relationName, value]
# S -> [modelName, attributeName, subAttributeName, relationName, value]
# S -> ['not', S]
# S -> ['and', [S1, S2, ...]]
# S -> ['or', [S1, S2, ...]]
#
# For example, the filter expression
#
# ['Form', 'transcription', 'regex', '^a']
#
# will return all forms whose transcription value starts with "a".
#
# The length-5 filter expressions are for relational attributes. For example,
# the filter expression
#
# ['Form', 'enterer', 'first_name', '=', 'Jim']
#
# will return all forms that were entered by a user with the first name 'Jim'.
#
# The length-2 filter expressions have a Boolean operator as their first
# element and are used to conjoin, disjoin, or negate other filter
# expressions. For example, the filter expression
#
# ['not', [
# 'and', [
# ['Form', 'enterer', 'first_name', '=', 'Jim'],
# ['Form', 'transcription', 'regex', '^a']
# ]
# ]]
#
# will return all forms that both were not entered by a Jim and do not have a
# transcription that begins with "a".
class FilterExpressionView extends BaseView
initialize: (options) ->
# If `@consentToHideActionWidget` is set to true, then we will hide our
# action widget when the relevant Backbone-wide event is triggered.
@consentToHideActionWidget = true
@filterExpression = options.filterExpression
# The name of the resource that this filter expression targets.
@targetResourceName = options.targetResourceName or 'form'
@targetResourceNameCapitalized = @utils.capitalize @targetResourceName
# We remember the correlations between attributes and subattributes so if
# we reselect a previously selected attribute we can restore its previous
# subattribute value.
if @filterExpression.length is 5
@subattributeMemoryMap[@filterExpression[1]] = @filterExpression[2]
# `@options` is an object of options for building filter expressions,
# i.e., the attributes of the resources being searched and the attributes
# of their relational attributes and the possible relations.
@options = options.options
@initializeFilterExpressionSubviews()
# This is the primary or typical attribute of the resource being searched.
# This is simply used to create the default filter expression values.
primaryAttribute: 'transcription'
# Instantiate a new `FilterExpressionView` for each sub-filter-expression
# that we may have. These are stored in `@filterExpressionSubviews`.
initializeFilterExpressionSubviews: ->
@filterExpressionSubviews = []
if @filterExpression[0] in ['and', 'or']
for subFilterExpression in @filterExpression[1]
filterExpressionSubview =
@getNewFilterExpressionView subFilterExpression
@filterExpressionSubviews.push filterExpressionSubview
else if @filterExpression[0] is 'not'
filterExpressionSubview =
@getNewFilterExpressionView @filterExpression[1]
@filterExpressionSubviews.push filterExpressionSubview
subattributeMemoryMap: {}
listenToEvents: ->
super
@listenTo Backbone, 'filterExpressionsHideActionWidgets',
@filterExpressionsHideActionWidgets
@listenTo Backbone, 'filterExpressionDestroyed', @actionButtonsVisibility
@listenToSubviews()
listenToSubviews: ->
for filterExpressionSubview in @filterExpressionSubviews
@listenToSubview filterExpressionSubview
listenToSubview: (subview) ->
@listenTo subview, 'destroyMe', @destroyFilterExpressionSubview
@listenTo subview, 'changed', @triggerChanged
triggerChanged: -> @trigger 'changed'
# Destroy a specific filter expression subview: remove it from our "model"
# (i.e., our `@filterExpression` array) and from our array of subviews.
destroyFilterExpressionSubview: (filterExpressionSubview) ->
operator = @filterExpression[0]
if operator in ['and', 'or', 'not']
if operator is 'not' or
(operator in ['and', 'or'] and @filterExpression[1].length is 1)
Backbone.trigger 'cantDeleteFilterExpressionOnlyChild'
else
filterExpressionSubview.$el.fadeOut
complete: =>
filterExpressionSubview.close()
@closed filterExpressionSubview
index = @filterExpressionSubviews.indexOf filterExpressionSubview
@filterExpressionSubviews.splice index, 1
if @filterExpression[0] is 'not'
@filterExpression.pop 1
else
@filterExpression[1].splice index, 1
@actionButtonsVisibility()
@triggerChanged()
# Hide our action widget. `@consentToHideActionWidget` will only be false if
# this view is the one who triggered the event that causes this method to
# be called.
filterExpressionsHideActionWidgets: ->
if @consentToHideActionWidget then @hideActionWidget()
@consentToHideActionWidget = true
events:
'click button.operator': 'toggleActionWidget'
'click button.make-and': 'makeOperatorAnd'
'click button.conjoin': 'conjoin'
'click button.make-or': 'makeOperatorOr'
'click button.disjoin': 'disjoin'
'click button.negate': 'negate'
'click button.make-not-not': 'removeNotOperator'
'click button.destroy': 'destroyFilterExpression'
'click button.add-operand': 'addOperand'
'selectmenuchange .attribute': 'attributeChanged'
'selectmenuchange .sub-attribute': 'subattributeChanged'
'selectmenuchange .relation': 'relationChanged'
'input .value': 'valueChanged'
valueChanged: (event) ->
if event then @stopEvent event
value = @$('textarea.value').first().val()
if @filterExpression.length is 5
if @filterExpression[3] is 'in'
@filterExpression[4] = @jsonParse value
else
@filterExpression[4] = value
else
if @filterExpression[2] is 'in'
@filterExpression[3] = @jsonParse value
else
@filterExpression[3] = value
@triggerChanged()
jsonParse: (value) ->
try
JSON.parse value
catch
value
# The relation selectmenu of the filter expression has changed.
relationChanged: (event) ->
@stopEvent event
relation = @$('select.relation').first().val()
@syncWithRelation relation
# the "is (not) null" relations imply no sub-attribute and no pattern
# value.
if relation in ['is null', 'is not null']
if relation is 'is null'
@filterExpression.splice 2, 3, '=', null
else
@filterExpression.splice 2, 3, '!=', null
else
if @filterExpression.length is 5
@filterExpression[3] = relation
else
@filterExpression[2] = relation
@triggerChanged()
# Selecting the special relations 'is null' and 'is not null' causes the
# value <textarea> as well as any sub-attribute selectmenu to become hidden.
syncWithRelation: (value=null) ->
if not value then value = @$('select.relation').first().val()
if value in ['is null', 'is not null']
@$('textarea.value').first().hide()
@$('.ui-selectmenu-button.sub-attribute').first().hide()
else
@$('textarea.value').first().show()
@syncAttributeSubattributeSelects()
attributeChanged: (event) ->
@stopEvent event
@syncAttributeSubattributeSelects()
@syncWithRelation()
attribute = @$('select.attribute').first().val()
@filterExpression[1] = attribute
$subAttributeSelect = @$('select.sub-attribute').first()
$subAttributeSelectmenu = @$('.ui-selectmenu-button.sub-attribute').first()
if $subAttributeSelectmenu.is ':visible'
subAttribute = $subAttributeSelect.val()
if @filterExpression.length is 5
@filterExpression[2] = subAttribute
else
@filterExpression.splice 2, 0, subAttribute
else
if @filterExpression.length is 5
@filterExpression.splice 2, 1
@triggerChanged()
# Alter `@filterExpression` so that it accords with the DOM representation
# of the subattribute.
# model attribute subattribute relation value
# ['Form', 'enterer', 'first_name', 'is', 'John']
# 0 1 2 3 4
#
# model attribute relation value
# ['Form', 'transcription', 'is', 'John']
# 0 1 2 3
subattributeChanged: (event, triggerChanged=true) ->
if event then @stopEvent event
$subAttributeSelect = @$('select.sub-attribute').first()
$subAttributeSelectmenu = @$('.ui-selectmenu-button.sub-attribute').first()
if $subAttributeSelectmenu.is ':visible'
subAttribute = $subAttributeSelect.val()
@subattributeMemoryMap[@filterExpression[1]] = subAttribute
if @filterExpression.length is 5
@filterExpression[2] = subAttribute
else
@filterExpression.splice 2, 0, subAttribute
if triggerChanged then @triggerChanged()
else
if @filterExpression.length is 5
@filterExpression.splice 2, 1
# Synchronize the attribute and subattribute selectmenus.
# That is, if attribute is relational (i.e., valuated by reference to
# another object), then the sub-attribute select needs to be visible and it
# needs to be populated with the sub-attribute options relevant to its
# parent relational attribute.
# TODO: this view should remember the last selected sub-attribute of a
# given attribute.
syncAttributeSubattributeSelects: ->
attribute = @$('select.attribute').first().val()
subattributes = @subattributes()
if attribute of subattributes
# If `attribute` is relational, we rebuild its selectmenu.
$subAttributeSelect = @$('select.sub-attribute').first()
$subAttributeSelect.html ''
# Note that we remember the last attribute-subattribute correlation and
# implement that here. If there is no last correlation, we use the
# default subattribute for the given attribute, if there is one.
valueThatShouldBeSelected = null
if attribute of @subattributeMemoryMap
valueThatShouldBeSelected =
@subattributeMemoryMap[attribute]
else if attribute of @subattributeDefaults
valueThatShouldBeSelected = @subattributeDefaults[attribute]
for subattribute in subattributes[attribute].sort()
if valueThatShouldBeSelected and
valueThatShouldBeSelected is subattribute
$subAttributeSelect.append "<option value='#{subattribute}'
selected>#{@utils.snake2regular subattribute}</option>"
else
$subAttributeSelect.append "<option value='#{subattribute}'
>#{@utils.snake2regular subattribute}</option>"
# Rebuild the selectmenu machinery.
$subAttributeSelect
.selectmenu 'destroy'
.selectmenu()
.each (index, element) =>
@transferClassAndTitle @$(element) # so we can tooltipify the selectmenu
@$('.ui-selectmenu-button.sub-attribute').first()
.tooltip
content: "select a sub-attribute for the
#{@utils.snake2regular(attribute)}"
else
# If `attribute` is non-relational, we hide the sub-attribute selectmenu.
@$('select.sub-attribute').first().hide()
@$('.ui-selectmenu-button.sub-attribute').first().hide()
# If this filter expression has a boolean (and/or) as its non-terminal, add
# a new coordinand, i.e., a new filter expression under the scope of the
# boolean. If there is a "not" as the non-terminal, add an
# operand/complement under its scope. Note: this button should only be
# visible/available if the non-terminal is a boolean OR if the non-terminal
# is a stranded negation.
addOperand: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
operator = @filterExpression[0]
if operator in ['or', 'and'] or
(operator is 'not' and @filterExpression.length is 1)
newFilterExpression = @getDefaultFilterExpression()
if operator in ['or', 'and']
@filterExpression[1].push newFilterExpression
else if operator is 'not'
@filterExpression.push newFilterExpression
filterExpressionSubview =
@getNewFilterExpressionView newFilterExpression
@filterExpressionSubviews.push filterExpressionSubview
@renderFilterExpressionSubview filterExpressionSubview, true
@listenToSubview filterExpressionSubview
@triggerChanged()
getDefaultFilterExpression: ->
[@targetResourceNameCapitalized , @primaryAttribute, 'regex', '']
# Change the operator to a boolean, i.e., 'and' or 'or'.
makeOperatorBoolean: (boolean) ->
booleans = ['or', 'and']
@hideActionWidgetAnimate()
if @filterExpression[0] in booleans
@filterExpression[0] = boolean
@$('button.operator').first()
.button 'option', 'label', boolean
.button 'refresh'
@actionButtonsVisibility()
# Add a boolean ('and' or 'or') with scope over this filter expression.
coordinate: (boolean) ->
booleans = ['or', 'and']
@hideActionWidgetAnimate()
@coordinateFilterExpression boolean
@$el.fadeOut
complete: =>
for subview in @filterExpressionSubviews
subview.close()
@initializeFilterExpressionSubviews()
@$el.empty()
@render()
@$el.fadeIn
complete: =>
@$('button, .ui-selectmenu-button, .textarea').first().focus()
@triggerChanged()
# Add an "and" with scope over this filter expression.
conjoin: (event) ->
@stopEvent event
@coordinate 'and'
# Add an "or" with scope over this filter expression.
disjoin: (event) ->
@stopEvent event
@coordinate 'or'
# Change the operator of this filter expression to 'and'.
makeOperatorAnd: (event) ->
@stopEvent event
@makeOperatorBoolean 'and'
# Change the operator of this filter expression to 'or'.
makeOperatorOr: (event) ->
@stopEvent event
@makeOperatorBoolean 'or'
# Change the operator of this filter expression to 'not'.
negate: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
@negateFilterExpression()
@$el.fadeOut
complete: =>
for subview in @filterExpressionSubviews
subview.close()
@initializeFilterExpressionSubviews()
@$el.empty()
@render()
@$el.fadeIn
complete: =>
@$('button, .ui-selectmenu-button, .textarea').first().focus()
@triggerChanged()
# Remove the "not" operator from this filter expression.
removeNotOperator: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
@removeNegationFromFilterExpression()
@$el.fadeOut
complete: =>
for subview in @filterExpressionSubviews
subview.close()
@initializeFilterExpressionSubviews()
@$el.empty()
@render()
@$el.fadeIn
complete: =>
@$('button, .ui-selectmenu-button, .textarea').first().focus()
@triggerChanged()
# Change our filter expression array so that it begins with a 'not'.
negateFilterExpression: ->
@filterExpression.unshift (x for x in @filterExpression)
@filterExpression.unshift 'not'
while @filterExpression.length > 2
@filterExpression.pop()
# Change our filter expression array so that it NO LONGER begins with a
# 'not'.
removeNegationFromFilterExpression: ->
for element in @filterExpression[1]
@filterExpression.push element
@filterExpression.shift()
@filterExpression.shift()
# Change our filter expression array so that it begins with an 'and' or an
# 'or'. Here we have to shift things in the array around so that we're in a
# proper and/or configuration, i.e., go from FE to ['and/or', [FE]],
# all while not replacing any existing arrays; that is, we need to keep
# the whole filter expression array intact, no copying.
coordinateFilterExpression: (coordinator) ->
@filterExpression.unshift [(x for x in @filterExpression)]
@filterExpression.unshift coordinator
while @filterExpression.length > 2
@filterExpression.pop()
# Destroy this filter expression. Note: we trigger a `destroyMe` event and
# let the parent `FilterExpression` view handle most of the destruction.
destroyFilterExpression: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
@trigger 'destroyMe', @
# Toggle the action widget, i.e., the <div> full of buttons that pops up
# when you click on an "operator" button.
toggleActionWidget: (event) ->
if event then @stopEvent event
$actionWidgetContainer =
@$('div.filter-expression-action-widget-container').first()
if $actionWidgetContainer.is ':visible'
$actionWidgetContainer.slideUp('fast')
@$('button.operator').first()
.tooltip
content: 'click here to reveal buttons for changing this node.'
position: @tooltipPositionLeft('-20')
else
@consentToHideActionWidget = false
Backbone.trigger 'filterExpressionsHideActionWidgets'
$actionWidgetContainer
.slideDown('fast')
.find('button').first().focus()
@$('button.operator').first()
.tooltip
content: 'click here to hide the buttons for changing this node.'
position: @tooltipPositionLeft('-20')
hideActionWidget: ->
@$('div.filter-expression-action-widget-container').first().hide()
hideActionWidgetAnimate: ->
@$('div.filter-expression-action-widget-container').first()
.slideUp('fast')
# Initialize a new `FilterExpressionView` with `subFilterExpression` as its
# filter expression.
getNewFilterExpressionView: (subFilterExpression) ->
new @constructor(
model: @model
targetResourceName: @targetResourceName
filterExpression: subFilterExpression
options: @options
rootNode: false
)
template: filterExpressionTemplate
getAttributes: ->
try
key = "#{@targetResourceName}_search_parameters"
attrs = @options[key].attributes
(x for x in _.keys(attrs).sort() \
when x not in ['morpheme_break_ids', 'morpheme_gloss_ids'])
catch
[]
render: ->
context =
filterExpression: @filterExpression
options: @options
attributes: @getAttributes()
subattributes: @subattributes() # TODO: we have to do this ourselves! The OLD should provide it though...
relations: @getRelations @options
snake2regular: @utils.snake2regular
pluralize: @utils.pluralize
@$el.html @template(context)
@bordercolorify()
$filterExpressionTable = @$('.filter-expression-table').first()
$filterExpressionTable
.find('textarea').autosize().end()
.find('button').button().end()
.find('.dative-tooltip.operator')
.tooltip position: @tooltipPositionLeft('-20')
.end()
.find('.dative-tooltip').not('.operator')
.tooltip position:
my: 'left bottom'
at: 'left top-20'
collision: 'flipfit'
@renderFilterExpressionSubviews()
@hideActionWidget()
@actionButtonsVisibility()
@listenToEvents()
@selectmenuAndVisibility $filterExpressionTable
@
# Make the selects into select menus and hide the sub-attribute select if
# it's not relevant.
selectmenuAndVisibility: ($filterExpressionTable) ->
@selectmenuify $filterExpressionTable
if @filterExpression.length is 4
@$('select.sub-attribute').hide()
@$('.ui-selectmenu-button.sub-attribute').hide()
if @filterExpression[2] in ['=', '!='] and
@filterExpression[3] is null
@$('textarea.value').first().hide()
# We filter out some of the relations exposed by the OLD; this is because
# some of them are redundant and have ugly names, e.g., ugly "__ne__" is
# co-referential with "!=" and "regexp" is the same as "regex".
getRelations: (options) ->
try
key = "#{@targetResourceName}_search_parameters"
relations = _.keys options[key].relations
(r for r in relations when r isnt 'regexp' and '_' not in r)
.concat(['is null', 'is not null'])
catch
[]
selectmenuify: ($context) ->
$context.find('select')
.selectmenu width: 'auto'
.each (index, element) =>
@transferClassAndTitle @$(element) # so we can tooltipify the selectmenu
# Show/hide various action buttons for the non-terminal node of this filter
# expression, depending on its state.
actionButtonsVisibility: ->
myOperator = @filterExpression[0]
$actionWidget = @$('.filter-expression-action-widget').first()
@hideButtonForExistingState myOperator, $actionWidget
if myOperator in ['and', 'or']
if @filterExpression[1].length > 1
$actionWidget.find('button.destroy').hide()
else
$actionWidget.find('button.destroy').show()
$actionWidget.find('button.add-operand').show()
$actionWidget.find('button.make-not-not').hide()
if myOperator is 'and'
$actionWidget.find('button.make-and').hide()
$actionWidget.find('button.make-or').show()
else
$actionWidget.find('button.make-or').hide()
$actionWidget.find('button.make-and').show()
else
$actionWidget.find('button.make-or').hide()
$actionWidget.find('button.make-and').hide()
if myOperator is 'not'
$actionWidget.find('button.make-not-not').show()
if @filterExpression.length is 1
$actionWidget.find('button.add-operand').show()
else
$actionWidget.find('button.make-not-not').hide()
$actionWidget.find('button.add-operand').hide()
# Hide the button for changing to the current state. That is, if this is an
# 'and' node, we don't want to show the "make me an 'and' node" button.
hideButtonForExistingState: (myOperator, $actionWidget=null) ->
$actionWidget =
$actionWidget or @$('.filter-expression-action-widget').first()
operators = ['and', 'or', 'not', '']
for operator in operators
if myOperator is operator or myOperator not in operators
$actionWidget
.find("button.make-#{operator}").hide().end()
.find('button').not(".make-#{operator}").show()
renderFilterExpressionSubviews: ->
for filterExpressionSubview in @filterExpressionSubviews
@renderFilterExpressionSubview filterExpressionSubview
renderFilterExpressionSubview: (filterExpressionSubview, animate=false) ->
@$('.filter-expression-operand').first()
.append filterExpressionSubview.render().el
if animate
filterExpressionSubview.$el
.hide()
.fadeIn
complete: ->
filterExpressionSubview
.$('button, .ui-selectmenu-button, .textarea').first().focus()
@rendered filterExpressionSubview
# Make the border colors match the jQueryUI theme.
bordercolorify: ->
@$('.filter-expression-table').first().find('textarea, input')
.css "border-color", @constructor.jQueryUIColors().defBo
@$('.filter-expression-action-widget').first()
.css
"border-color": @constructor.jQueryUIColors().defBo
"background-color": @constructor.jQueryUIColors().defCo
# TODO: the OLD should be supplying all of this information. We should
# not have to specify it here.
subattributes: ->
switch @targetResourceName
when 'form' then @formSubattributes()
when 'file' then @fileSubattributes()
when 'collection' then @collectionSubattributes()
when 'language' then @languageSubattributes()
languageSubattributes: -> {}
collectionSubattributes: ->
elicitor: @userAttributes
enterer: @userAttributes
modifier: @userAttributes
speaker: @speakerAttributes
tags: @tagAttributes
files: @fileAttributes
source: @sourceAttributes
fileSubattributes: ->
elicitor: @userAttributes
enterer: @userAttributes
speaker: @speakerAttributes
parent_file: @fileAttributes
tags: @tagAttributes
forms: @formAttributes
collections: @collectionAttributes
formSubattributes: ->
collections: @collectionAttributes
corpora: [
'content'
'datetime_entered'
'datetime_modified'
'description'
'enterer'
'files'
'form_search'
'id'
'modifier'
'name'
'tags'
'UUID'
]
elicitation_method: [
'id'
'name'
'description'
'datetime_modified'
]
elicitor: @userAttributes
enterer: @userAttributes
modifier: @userAttributes
files: @fileAttributesNonRelational
memorizers: @userAttributes
source: @sourceAttributes
speaker: @speakerAttributes
syntactic_category: [
'datetime_modified'
'description'
'id'
'name'
'type'
]
tags: @tagAttributes
translations: [
'datetime_modified'
'form_id'
'grammaticality'
'id'
'transcription'
]
verifier: @userAttributes
sourceAttributes: [
'id'
'file_id'
'file'
'crossref_source_id'
'crossref_source'
'datetime_modified'
'type'
'key'
'address'
'annote'
'author'
'booktitle'
'chapter'
'crossref'
'edition'
'editor'
'howpublished'
'institution'
'journal'
'key_field'
'month'
'note'
'number'
'organization'
'pages'
'publisher'
'school'
'series'
'title'
'type_field'
'url'
'volume'
'year'
'affiliation'
'abstract'
'contents'
'copyright'
'ISBN'
'ISSN'
'keywords'
'language'
'location'
'LCCN'
'mrnumber'
'price'
'size'
]
userAttributes: [
'id'
'first_name'
'last_name'
'email'
'affiliation'
'role'
'markup_language'
'page_content'
'html'
'input_orthography'
'output_orthography'
'datetime_modified'
]
speakerAttributes: [
'id'
'first_name'
'last_name'
'dialect'
'markup_language'
'page_content'
'html'
'datetime_modified'
]
fileAttributesNonRelational: [
'id'
'date_elicited'
'datetime_entered'
'datetime_modified'
'filename'
'name'
'lossy_filename'
'MIME_type'
'size'
'description'
'utterance_type'
'url'
'password'
'start'
'end'
]
fileAttributes: [
'id'
'date_elicited'
'datetime_entered'
'datetime_modified'
'filename'
'name'
'lossy_filename'
'MIME_type'
'size'
'description'
'utterance_type'
'url'
'password'
'enterer'
'elicitor'
'speaker'
'tags'
'forms'
'parent_file'
'start'
'end'
]
tagAttributes: [
'id'
'name'
'description'
'datetime_modified'
]
formAttributes: [
'files',
'elicitor'
'break_gloss_category'
'tags'
'elicitation_method'
'translations'
'syntax'
'memorizers'
'syntactic_category'
'grammaticality'
'syntactic_category_string'
'datetime_modified'
'date_elicited'
'phonetic_transcription'
'morpheme_gloss'
'id'
'semantics'
'datetime_entered'
'UUID'
'narrow_phonetic_transcription'
'transcription'
'corpora'
'enterer'
'comments'
'source'
'verifier'
'speaker'
'morpheme_break'
'collections'
'speaker_comments'
]
collectionAttributes: [
'id'
'UUID'
'title'
'type'
'url'
'description'
'markup_language'
'contents'
'contents_unpacked'
'html'
'date_elicited'
'datetime_entered'
'datetime_modified'
'speaker'
'source'
'elicitor'
'enterer'
'modifier'
'tags'
'files'
]
# Maps attributes to the default subattribute that should be displayed when
# the attribute is selected.
subattributeDefaults:
collections: 'title'
corpora: 'name'
elicitation_method: 'name'
elicitor: 'last_name'
enterer: 'last_name'
files: 'filename'
forms: 'transcription'
memorizers: 'last_name'
parent_file: 'filename'
source: 'author'
speaker: 'last_name'
syntactic_category: 'name'
tags: 'name'
translations: 'transcription'
verifier: 'last_name'
modifier: 'last_name'
| 8443 | define [
'./base'
'./../templates/filter-expression'
'autosize'
], (BaseView, filterExpressionTemplate) ->
# Filter Expression View
# ----------------------
#
# A view for a filter expression, i.e., a set of inputs for creating a filter
# expression for building the type of search (i.e., query) that the OLD
# accepts. This view spawns subviews of itself for the filter expressions
# that are contained within the filter expression that it represents. The
# idea is to help users to build complex queries using an easy-to-understand
# tree-like interface.
#
# The type of search S that the OLD accepts is a JSON array that
# matches one of the following five rewrite rules:
#
# S -> [modelName, attributeName, relationName, value]
# S -> [modelName, attributeName, subAttributeName, relationName, value]
# S -> ['not', S]
# S -> ['and', [S1, S2, ...]]
# S -> ['or', [S1, S2, ...]]
#
# For example, the filter expression
#
# ['Form', 'transcription', 'regex', '^a']
#
# will return all forms whose transcription value starts with "a".
#
# The length-5 filter expressions are for relational attributes. For example,
# the filter expression
#
# ['Form', 'enterer', 'first_name', '=', '<NAME>']
#
# will return all forms that were entered by a user with the first name '<NAME>'.
#
# The length-2 filter expressions have a Boolean operator as their first
# element and are used to conjoin, disjoin, or negate other filter
# expressions. For example, the filter expression
#
# ['not', [
# 'and', [
# ['Form', 'enterer', 'first_name', '=', '<NAME>'],
# ['Form', 'transcription', 'regex', '^a']
# ]
# ]]
#
# will return all forms that both were not entered by a Jim and do not have a
# transcription that begins with "a".
class FilterExpressionView extends BaseView
initialize: (options) ->
# If `@consentToHideActionWidget` is set to true, then we will hide our
# action widget when the relevant Backbone-wide event is triggered.
@consentToHideActionWidget = true
@filterExpression = options.filterExpression
# The name of the resource that this filter expression targets.
@targetResourceName = options.targetResourceName or 'form'
@targetResourceNameCapitalized = @utils.capitalize @targetResourceName
# We remember the correlations between attributes and subattributes so if
# we reselect a previously selected attribute we can restore its previous
# subattribute value.
if @filterExpression.length is 5
@subattributeMemoryMap[@filterExpression[1]] = @filterExpression[2]
# `@options` is an object of options for building filter expressions,
# i.e., the attributes of the resources being searched and the attributes
# of their relational attributes and the possible relations.
@options = options.options
@initializeFilterExpressionSubviews()
# This is the primary or typical attribute of the resource being searched.
# This is simply used to create the default filter expression values.
primaryAttribute: 'transcription'
# Instantiate a new `FilterExpressionView` for each sub-filter-expression
# that we may have. These are stored in `@filterExpressionSubviews`.
initializeFilterExpressionSubviews: ->
@filterExpressionSubviews = []
if @filterExpression[0] in ['and', 'or']
for subFilterExpression in @filterExpression[1]
filterExpressionSubview =
@getNewFilterExpressionView subFilterExpression
@filterExpressionSubviews.push filterExpressionSubview
else if @filterExpression[0] is 'not'
filterExpressionSubview =
@getNewFilterExpressionView @filterExpression[1]
@filterExpressionSubviews.push filterExpressionSubview
subattributeMemoryMap: {}
listenToEvents: ->
super
@listenTo Backbone, 'filterExpressionsHideActionWidgets',
@filterExpressionsHideActionWidgets
@listenTo Backbone, 'filterExpressionDestroyed', @actionButtonsVisibility
@listenToSubviews()
listenToSubviews: ->
for filterExpressionSubview in @filterExpressionSubviews
@listenToSubview filterExpressionSubview
listenToSubview: (subview) ->
@listenTo subview, 'destroyMe', @destroyFilterExpressionSubview
@listenTo subview, 'changed', @triggerChanged
triggerChanged: -> @trigger 'changed'
# Destroy a specific filter expression subview: remove it from our "model"
# (i.e., our `@filterExpression` array) and from our array of subviews.
destroyFilterExpressionSubview: (filterExpressionSubview) ->
operator = @filterExpression[0]
if operator in ['and', 'or', 'not']
if operator is 'not' or
(operator in ['and', 'or'] and @filterExpression[1].length is 1)
Backbone.trigger 'cantDeleteFilterExpressionOnlyChild'
else
filterExpressionSubview.$el.fadeOut
complete: =>
filterExpressionSubview.close()
@closed filterExpressionSubview
index = @filterExpressionSubviews.indexOf filterExpressionSubview
@filterExpressionSubviews.splice index, 1
if @filterExpression[0] is 'not'
@filterExpression.pop 1
else
@filterExpression[1].splice index, 1
@actionButtonsVisibility()
@triggerChanged()
# Hide our action widget. `@consentToHideActionWidget` will only be false if
# this view is the one who triggered the event that causes this method to
# be called.
filterExpressionsHideActionWidgets: ->
if @consentToHideActionWidget then @hideActionWidget()
@consentToHideActionWidget = true
events:
'click button.operator': 'toggleActionWidget'
'click button.make-and': 'makeOperatorAnd'
'click button.conjoin': 'conjoin'
'click button.make-or': 'makeOperatorOr'
'click button.disjoin': 'disjoin'
'click button.negate': 'negate'
'click button.make-not-not': 'removeNotOperator'
'click button.destroy': 'destroyFilterExpression'
'click button.add-operand': 'addOperand'
'selectmenuchange .attribute': 'attributeChanged'
'selectmenuchange .sub-attribute': 'subattributeChanged'
'selectmenuchange .relation': 'relationChanged'
'input .value': 'valueChanged'
valueChanged: (event) ->
if event then @stopEvent event
value = @$('textarea.value').first().val()
if @filterExpression.length is 5
if @filterExpression[3] is 'in'
@filterExpression[4] = @jsonParse value
else
@filterExpression[4] = value
else
if @filterExpression[2] is 'in'
@filterExpression[3] = @jsonParse value
else
@filterExpression[3] = value
@triggerChanged()
jsonParse: (value) ->
try
JSON.parse value
catch
value
# The relation selectmenu of the filter expression has changed.
relationChanged: (event) ->
@stopEvent event
relation = @$('select.relation').first().val()
@syncWithRelation relation
# the "is (not) null" relations imply no sub-attribute and no pattern
# value.
if relation in ['is null', 'is not null']
if relation is 'is null'
@filterExpression.splice 2, 3, '=', null
else
@filterExpression.splice 2, 3, '!=', null
else
if @filterExpression.length is 5
@filterExpression[3] = relation
else
@filterExpression[2] = relation
@triggerChanged()
# Selecting the special relations 'is null' and 'is not null' causes the
# value <textarea> as well as any sub-attribute selectmenu to become hidden.
syncWithRelation: (value=null) ->
if not value then value = @$('select.relation').first().val()
if value in ['is null', 'is not null']
@$('textarea.value').first().hide()
@$('.ui-selectmenu-button.sub-attribute').first().hide()
else
@$('textarea.value').first().show()
@syncAttributeSubattributeSelects()
attributeChanged: (event) ->
@stopEvent event
@syncAttributeSubattributeSelects()
@syncWithRelation()
attribute = @$('select.attribute').first().val()
@filterExpression[1] = attribute
$subAttributeSelect = @$('select.sub-attribute').first()
$subAttributeSelectmenu = @$('.ui-selectmenu-button.sub-attribute').first()
if $subAttributeSelectmenu.is ':visible'
subAttribute = $subAttributeSelect.val()
if @filterExpression.length is 5
@filterExpression[2] = subAttribute
else
@filterExpression.splice 2, 0, subAttribute
else
if @filterExpression.length is 5
@filterExpression.splice 2, 1
@triggerChanged()
# Alter `@filterExpression` so that it accords with the DOM representation
# of the subattribute.
# model attribute subattribute relation value
# ['Form', 'enterer', 'first_name', 'is', '<NAME>']
# 0 1 2 3 4
#
# model attribute relation value
# ['Form', 'transcription', 'is', '<NAME>']
# 0 1 2 3
subattributeChanged: (event, triggerChanged=true) ->
if event then @stopEvent event
$subAttributeSelect = @$('select.sub-attribute').first()
$subAttributeSelectmenu = @$('.ui-selectmenu-button.sub-attribute').first()
if $subAttributeSelectmenu.is ':visible'
subAttribute = $subAttributeSelect.val()
@subattributeMemoryMap[@filterExpression[1]] = subAttribute
if @filterExpression.length is 5
@filterExpression[2] = subAttribute
else
@filterExpression.splice 2, 0, subAttribute
if triggerChanged then @triggerChanged()
else
if @filterExpression.length is 5
@filterExpression.splice 2, 1
# Synchronize the attribute and subattribute selectmenus.
# That is, if attribute is relational (i.e., valuated by reference to
# another object), then the sub-attribute select needs to be visible and it
# needs to be populated with the sub-attribute options relevant to its
# parent relational attribute.
# TODO: this view should remember the last selected sub-attribute of a
# given attribute.
syncAttributeSubattributeSelects: ->
attribute = @$('select.attribute').first().val()
subattributes = @subattributes()
if attribute of subattributes
# If `attribute` is relational, we rebuild its selectmenu.
$subAttributeSelect = @$('select.sub-attribute').first()
$subAttributeSelect.html ''
# Note that we remember the last attribute-subattribute correlation and
# implement that here. If there is no last correlation, we use the
# default subattribute for the given attribute, if there is one.
valueThatShouldBeSelected = null
if attribute of @subattributeMemoryMap
valueThatShouldBeSelected =
@subattributeMemoryMap[attribute]
else if attribute of @subattributeDefaults
valueThatShouldBeSelected = @subattributeDefaults[attribute]
for subattribute in subattributes[attribute].sort()
if valueThatShouldBeSelected and
valueThatShouldBeSelected is subattribute
$subAttributeSelect.append "<option value='#{subattribute}'
selected>#{@utils.snake2regular subattribute}</option>"
else
$subAttributeSelect.append "<option value='#{subattribute}'
>#{@utils.snake2regular subattribute}</option>"
# Rebuild the selectmenu machinery.
$subAttributeSelect
.selectmenu 'destroy'
.selectmenu()
.each (index, element) =>
@transferClassAndTitle @$(element) # so we can tooltipify the selectmenu
@$('.ui-selectmenu-button.sub-attribute').first()
.tooltip
content: "select a sub-attribute for the
#{@utils.snake2regular(attribute)}"
else
# If `attribute` is non-relational, we hide the sub-attribute selectmenu.
@$('select.sub-attribute').first().hide()
@$('.ui-selectmenu-button.sub-attribute').first().hide()
# If this filter expression has a boolean (and/or) as its non-terminal, add
# a new coordinand, i.e., a new filter expression under the scope of the
# boolean. If there is a "not" as the non-terminal, add an
# operand/complement under its scope. Note: this button should only be
# visible/available if the non-terminal is a boolean OR if the non-terminal
# is a stranded negation.
addOperand: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
operator = @filterExpression[0]
if operator in ['or', 'and'] or
(operator is 'not' and @filterExpression.length is 1)
newFilterExpression = @getDefaultFilterExpression()
if operator in ['or', 'and']
@filterExpression[1].push newFilterExpression
else if operator is 'not'
@filterExpression.push newFilterExpression
filterExpressionSubview =
@getNewFilterExpressionView newFilterExpression
@filterExpressionSubviews.push filterExpressionSubview
@renderFilterExpressionSubview filterExpressionSubview, true
@listenToSubview filterExpressionSubview
@triggerChanged()
getDefaultFilterExpression: ->
[@targetResourceNameCapitalized , @primaryAttribute, 'regex', '']
# Change the operator to a boolean, i.e., 'and' or 'or'.
makeOperatorBoolean: (boolean) ->
booleans = ['or', 'and']
@hideActionWidgetAnimate()
if @filterExpression[0] in booleans
@filterExpression[0] = boolean
@$('button.operator').first()
.button 'option', 'label', boolean
.button 'refresh'
@actionButtonsVisibility()
# Add a boolean ('and' or 'or') with scope over this filter expression.
coordinate: (boolean) ->
booleans = ['or', 'and']
@hideActionWidgetAnimate()
@coordinateFilterExpression boolean
@$el.fadeOut
complete: =>
for subview in @filterExpressionSubviews
subview.close()
@initializeFilterExpressionSubviews()
@$el.empty()
@render()
@$el.fadeIn
complete: =>
@$('button, .ui-selectmenu-button, .textarea').first().focus()
@triggerChanged()
# Add an "and" with scope over this filter expression.
conjoin: (event) ->
@stopEvent event
@coordinate 'and'
# Add an "or" with scope over this filter expression.
disjoin: (event) ->
@stopEvent event
@coordinate 'or'
# Change the operator of this filter expression to 'and'.
makeOperatorAnd: (event) ->
@stopEvent event
@makeOperatorBoolean 'and'
# Change the operator of this filter expression to 'or'.
makeOperatorOr: (event) ->
@stopEvent event
@makeOperatorBoolean 'or'
# Change the operator of this filter expression to 'not'.
negate: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
@negateFilterExpression()
@$el.fadeOut
complete: =>
for subview in @filterExpressionSubviews
subview.close()
@initializeFilterExpressionSubviews()
@$el.empty()
@render()
@$el.fadeIn
complete: =>
@$('button, .ui-selectmenu-button, .textarea').first().focus()
@triggerChanged()
# Remove the "not" operator from this filter expression.
removeNotOperator: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
@removeNegationFromFilterExpression()
@$el.fadeOut
complete: =>
for subview in @filterExpressionSubviews
subview.close()
@initializeFilterExpressionSubviews()
@$el.empty()
@render()
@$el.fadeIn
complete: =>
@$('button, .ui-selectmenu-button, .textarea').first().focus()
@triggerChanged()
# Change our filter expression array so that it begins with a 'not'.
negateFilterExpression: ->
@filterExpression.unshift (x for x in @filterExpression)
@filterExpression.unshift 'not'
while @filterExpression.length > 2
@filterExpression.pop()
# Change our filter expression array so that it NO LONGER begins with a
# 'not'.
removeNegationFromFilterExpression: ->
for element in @filterExpression[1]
@filterExpression.push element
@filterExpression.shift()
@filterExpression.shift()
# Change our filter expression array so that it begins with an 'and' or an
# 'or'. Here we have to shift things in the array around so that we're in a
# proper and/or configuration, i.e., go from FE to ['and/or', [FE]],
# all while not replacing any existing arrays; that is, we need to keep
# the whole filter expression array intact, no copying.
coordinateFilterExpression: (coordinator) ->
@filterExpression.unshift [(x for x in @filterExpression)]
@filterExpression.unshift coordinator
while @filterExpression.length > 2
@filterExpression.pop()
# Destroy this filter expression. Note: we trigger a `destroyMe` event and
# let the parent `FilterExpression` view handle most of the destruction.
destroyFilterExpression: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
@trigger 'destroyMe', @
# Toggle the action widget, i.e., the <div> full of buttons that pops up
# when you click on an "operator" button.
toggleActionWidget: (event) ->
if event then @stopEvent event
$actionWidgetContainer =
@$('div.filter-expression-action-widget-container').first()
if $actionWidgetContainer.is ':visible'
$actionWidgetContainer.slideUp('fast')
@$('button.operator').first()
.tooltip
content: 'click here to reveal buttons for changing this node.'
position: @tooltipPositionLeft('-20')
else
@consentToHideActionWidget = false
Backbone.trigger 'filterExpressionsHideActionWidgets'
$actionWidgetContainer
.slideDown('fast')
.find('button').first().focus()
@$('button.operator').first()
.tooltip
content: 'click here to hide the buttons for changing this node.'
position: @tooltipPositionLeft('-20')
hideActionWidget: ->
@$('div.filter-expression-action-widget-container').first().hide()
hideActionWidgetAnimate: ->
@$('div.filter-expression-action-widget-container').first()
.slideUp('fast')
# Initialize a new `FilterExpressionView` with `subFilterExpression` as its
# filter expression.
getNewFilterExpressionView: (subFilterExpression) ->
new @constructor(
model: @model
targetResourceName: @targetResourceName
filterExpression: subFilterExpression
options: @options
rootNode: false
)
template: filterExpressionTemplate
getAttributes: ->
try
key = "#{@targetResourceName}_search_parameters"
attrs = @options[key].attributes
(x for x in _.keys(attrs).sort() \
when x not in ['morpheme_break_ids', 'morpheme_gloss_ids'])
catch
[]
render: ->
context =
filterExpression: @filterExpression
options: @options
attributes: @getAttributes()
subattributes: @subattributes() # TODO: we have to do this ourselves! The OLD should provide it though...
relations: @getRelations @options
snake2regular: @utils.snake2regular
pluralize: @utils.pluralize
@$el.html @template(context)
@bordercolorify()
$filterExpressionTable = @$('.filter-expression-table').first()
$filterExpressionTable
.find('textarea').autosize().end()
.find('button').button().end()
.find('.dative-tooltip.operator')
.tooltip position: @tooltipPositionLeft('-20')
.end()
.find('.dative-tooltip').not('.operator')
.tooltip position:
my: 'left bottom'
at: 'left top-20'
collision: 'flipfit'
@renderFilterExpressionSubviews()
@hideActionWidget()
@actionButtonsVisibility()
@listenToEvents()
@selectmenuAndVisibility $filterExpressionTable
@
# Make the selects into select menus and hide the sub-attribute select if
# it's not relevant.
selectmenuAndVisibility: ($filterExpressionTable) ->
@selectmenuify $filterExpressionTable
if @filterExpression.length is 4
@$('select.sub-attribute').hide()
@$('.ui-selectmenu-button.sub-attribute').hide()
if @filterExpression[2] in ['=', '!='] and
@filterExpression[3] is null
@$('textarea.value').first().hide()
# We filter out some of the relations exposed by the OLD; this is because
# some of them are redundant and have ugly names, e.g., ugly "__ne__" is
# co-referential with "!=" and "regexp" is the same as "regex".
getRelations: (options) ->
try
key = <KEY>@<KEY>"
relations = _.keys options[key].relations
(r for r in relations when r isnt 'regexp' and '_' not in r)
.concat(['is null', 'is not null'])
catch
[]
selectmenuify: ($context) ->
$context.find('select')
.selectmenu width: 'auto'
.each (index, element) =>
@transferClassAndTitle @$(element) # so we can tooltipify the selectmenu
# Show/hide various action buttons for the non-terminal node of this filter
# expression, depending on its state.
actionButtonsVisibility: ->
myOperator = @filterExpression[0]
$actionWidget = @$('.filter-expression-action-widget').first()
@hideButtonForExistingState myOperator, $actionWidget
if myOperator in ['and', 'or']
if @filterExpression[1].length > 1
$actionWidget.find('button.destroy').hide()
else
$actionWidget.find('button.destroy').show()
$actionWidget.find('button.add-operand').show()
$actionWidget.find('button.make-not-not').hide()
if myOperator is 'and'
$actionWidget.find('button.make-and').hide()
$actionWidget.find('button.make-or').show()
else
$actionWidget.find('button.make-or').hide()
$actionWidget.find('button.make-and').show()
else
$actionWidget.find('button.make-or').hide()
$actionWidget.find('button.make-and').hide()
if myOperator is 'not'
$actionWidget.find('button.make-not-not').show()
if @filterExpression.length is 1
$actionWidget.find('button.add-operand').show()
else
$actionWidget.find('button.make-not-not').hide()
$actionWidget.find('button.add-operand').hide()
# Hide the button for changing to the current state. That is, if this is an
# 'and' node, we don't want to show the "make me an 'and' node" button.
hideButtonForExistingState: (myOperator, $actionWidget=null) ->
$actionWidget =
$actionWidget or @$('.filter-expression-action-widget').first()
operators = ['and', 'or', 'not', '']
for operator in operators
if myOperator is operator or myOperator not in operators
$actionWidget
.find("button.make-#{operator}").hide().end()
.find('button').not(".make-#{operator}").show()
renderFilterExpressionSubviews: ->
for filterExpressionSubview in @filterExpressionSubviews
@renderFilterExpressionSubview filterExpressionSubview
renderFilterExpressionSubview: (filterExpressionSubview, animate=false) ->
@$('.filter-expression-operand').first()
.append filterExpressionSubview.render().el
if animate
filterExpressionSubview.$el
.hide()
.fadeIn
complete: ->
filterExpressionSubview
.$('button, .ui-selectmenu-button, .textarea').first().focus()
@rendered filterExpressionSubview
# Make the border colors match the jQueryUI theme.
bordercolorify: ->
@$('.filter-expression-table').first().find('textarea, input')
.css "border-color", @constructor.jQueryUIColors().defBo
@$('.filter-expression-action-widget').first()
.css
"border-color": @constructor.jQueryUIColors().defBo
"background-color": @constructor.jQueryUIColors().defCo
# TODO: the OLD should be supplying all of this information. We should
# not have to specify it here.
subattributes: ->
switch @targetResourceName
when 'form' then @formSubattributes()
when 'file' then @fileSubattributes()
when 'collection' then @collectionSubattributes()
when 'language' then @languageSubattributes()
languageSubattributes: -> {}
collectionSubattributes: ->
elicitor: @userAttributes
enterer: @userAttributes
modifier: @userAttributes
speaker: @speakerAttributes
tags: @tagAttributes
files: @fileAttributes
source: @sourceAttributes
fileSubattributes: ->
elicitor: @userAttributes
enterer: @userAttributes
speaker: @speakerAttributes
parent_file: @fileAttributes
tags: @tagAttributes
forms: @formAttributes
collections: @collectionAttributes
formSubattributes: ->
collections: @collectionAttributes
corpora: [
'content'
'datetime_entered'
'datetime_modified'
'description'
'enterer'
'files'
'form_search'
'id'
'modifier'
'name'
'tags'
'UUID'
]
elicitation_method: [
'id'
'name'
'description'
'datetime_modified'
]
elicitor: @userAttributes
enterer: @userAttributes
modifier: @userAttributes
files: @fileAttributesNonRelational
memorizers: @userAttributes
source: @sourceAttributes
speaker: @speakerAttributes
syntactic_category: [
'datetime_modified'
'description'
'id'
'name'
'type'
]
tags: @tagAttributes
translations: [
'datetime_modified'
'form_id'
'grammaticality'
'id'
'transcription'
]
verifier: @userAttributes
sourceAttributes: [
'id'
'file_id'
'file'
'crossref_source_id'
'crossref_source'
'datetime_modified'
'type'
'key'
'address'
'annote'
'author'
'booktitle'
'chapter'
'crossref'
'edition'
'editor'
'howpublished'
'institution'
'journal'
'key_field'
'month'
'note'
'number'
'organization'
'pages'
'publisher'
'school'
'series'
'title'
'type_field'
'url'
'volume'
'year'
'affiliation'
'abstract'
'contents'
'copyright'
'ISBN'
'ISSN'
'keywords'
'language'
'location'
'LCCN'
'mrnumber'
'price'
'size'
]
userAttributes: [
'id'
'<NAME>_name'
'<NAME>name'
'email'
'affiliation'
'role'
'markup_language'
'page_content'
'html'
'input_orthography'
'output_orthography'
'datetime_modified'
]
speakerAttributes: [
'id'
'first_name'
'last_name'
'dialect'
'markup_language'
'page_content'
'html'
'datetime_modified'
]
fileAttributesNonRelational: [
'id'
'date_elicited'
'datetime_entered'
'datetime_modified'
'filename'
'name'
'lossy_filename'
'MIME_type'
'size'
'description'
'utterance_type'
'url'
'password'
'start'
'end'
]
fileAttributes: [
'id'
'date_elicited'
'datetime_entered'
'datetime_modified'
'filename'
'name'
'lossy_filename'
'MIME_type'
'size'
'description'
'utterance_type'
'url'
'password'
'enterer'
'elicitor'
'speaker'
'tags'
'forms'
'parent_file'
'start'
'end'
]
tagAttributes: [
'id'
'name'
'description'
'datetime_modified'
]
formAttributes: [
'files',
'elicitor'
'break_gloss_category'
'tags'
'elicitation_method'
'translations'
'syntax'
'memorizers'
'syntactic_category'
'grammaticality'
'syntactic_category_string'
'datetime_modified'
'date_elicited'
'phonetic_transcription'
'morpheme_gloss'
'id'
'semantics'
'datetime_entered'
'UUID'
'narrow_phonetic_transcription'
'transcription'
'corpora'
'enterer'
'comments'
'source'
'verifier'
'speaker'
'morpheme_break'
'collections'
'speaker_comments'
]
collectionAttributes: [
'id'
'UUID'
'title'
'type'
'url'
'description'
'markup_language'
'contents'
'contents_unpacked'
'html'
'date_elicited'
'datetime_entered'
'datetime_modified'
'speaker'
'source'
'elicitor'
'enterer'
'modifier'
'tags'
'files'
]
# Maps attributes to the default subattribute that should be displayed when
# the attribute is selected.
subattributeDefaults:
collections: 'title'
corpora: 'name'
elicitation_method: 'name'
elicitor: '<NAME>'
enterer: '<NAME>'
files: 'filename'
forms: 'transcription'
memorizers: '<NAME>'
parent_file: 'filename'
source: 'author'
speaker: '<NAME>'
syntactic_category: '<NAME>'
tags: 'name'
translations: 'transcription'
verifier: '<NAME>'
modifier: '<NAME>'
| true | define [
'./base'
'./../templates/filter-expression'
'autosize'
], (BaseView, filterExpressionTemplate) ->
# Filter Expression View
# ----------------------
#
# A view for a filter expression, i.e., a set of inputs for creating a filter
# expression for building the type of search (i.e., query) that the OLD
# accepts. This view spawns subviews of itself for the filter expressions
# that are contained within the filter expression that it represents. The
# idea is to help users to build complex queries using an easy-to-understand
# tree-like interface.
#
# The type of search S that the OLD accepts is a JSON array that
# matches one of the following five rewrite rules:
#
# S -> [modelName, attributeName, relationName, value]
# S -> [modelName, attributeName, subAttributeName, relationName, value]
# S -> ['not', S]
# S -> ['and', [S1, S2, ...]]
# S -> ['or', [S1, S2, ...]]
#
# For example, the filter expression
#
# ['Form', 'transcription', 'regex', '^a']
#
# will return all forms whose transcription value starts with "a".
#
# The length-5 filter expressions are for relational attributes. For example,
# the filter expression
#
# ['Form', 'enterer', 'first_name', '=', 'PI:NAME:<NAME>END_PI']
#
# will return all forms that were entered by a user with the first name 'PI:NAME:<NAME>END_PI'.
#
# The length-2 filter expressions have a Boolean operator as their first
# element and are used to conjoin, disjoin, or negate other filter
# expressions. For example, the filter expression
#
# ['not', [
# 'and', [
# ['Form', 'enterer', 'first_name', '=', 'PI:NAME:<NAME>END_PI'],
# ['Form', 'transcription', 'regex', '^a']
# ]
# ]]
#
# will return all forms that both were not entered by a Jim and do not have a
# transcription that begins with "a".
class FilterExpressionView extends BaseView
initialize: (options) ->
# If `@consentToHideActionWidget` is set to true, then we will hide our
# action widget when the relevant Backbone-wide event is triggered.
@consentToHideActionWidget = true
@filterExpression = options.filterExpression
# The name of the resource that this filter expression targets.
@targetResourceName = options.targetResourceName or 'form'
@targetResourceNameCapitalized = @utils.capitalize @targetResourceName
# We remember the correlations between attributes and subattributes so if
# we reselect a previously selected attribute we can restore its previous
# subattribute value.
if @filterExpression.length is 5
@subattributeMemoryMap[@filterExpression[1]] = @filterExpression[2]
# `@options` is an object of options for building filter expressions,
# i.e., the attributes of the resources being searched and the attributes
# of their relational attributes and the possible relations.
@options = options.options
@initializeFilterExpressionSubviews()
# This is the primary or typical attribute of the resource being searched.
# This is simply used to create the default filter expression values.
primaryAttribute: 'transcription'
# Instantiate a new `FilterExpressionView` for each sub-filter-expression
# that we may have. These are stored in `@filterExpressionSubviews`.
initializeFilterExpressionSubviews: ->
@filterExpressionSubviews = []
if @filterExpression[0] in ['and', 'or']
for subFilterExpression in @filterExpression[1]
filterExpressionSubview =
@getNewFilterExpressionView subFilterExpression
@filterExpressionSubviews.push filterExpressionSubview
else if @filterExpression[0] is 'not'
filterExpressionSubview =
@getNewFilterExpressionView @filterExpression[1]
@filterExpressionSubviews.push filterExpressionSubview
subattributeMemoryMap: {}
listenToEvents: ->
super
@listenTo Backbone, 'filterExpressionsHideActionWidgets',
@filterExpressionsHideActionWidgets
@listenTo Backbone, 'filterExpressionDestroyed', @actionButtonsVisibility
@listenToSubviews()
listenToSubviews: ->
for filterExpressionSubview in @filterExpressionSubviews
@listenToSubview filterExpressionSubview
listenToSubview: (subview) ->
@listenTo subview, 'destroyMe', @destroyFilterExpressionSubview
@listenTo subview, 'changed', @triggerChanged
triggerChanged: -> @trigger 'changed'
# Destroy a specific filter expression subview: remove it from our "model"
# (i.e., our `@filterExpression` array) and from our array of subviews.
destroyFilterExpressionSubview: (filterExpressionSubview) ->
operator = @filterExpression[0]
if operator in ['and', 'or', 'not']
if operator is 'not' or
(operator in ['and', 'or'] and @filterExpression[1].length is 1)
Backbone.trigger 'cantDeleteFilterExpressionOnlyChild'
else
filterExpressionSubview.$el.fadeOut
complete: =>
filterExpressionSubview.close()
@closed filterExpressionSubview
index = @filterExpressionSubviews.indexOf filterExpressionSubview
@filterExpressionSubviews.splice index, 1
if @filterExpression[0] is 'not'
@filterExpression.pop 1
else
@filterExpression[1].splice index, 1
@actionButtonsVisibility()
@triggerChanged()
# Hide our action widget. `@consentToHideActionWidget` will only be false if
# this view is the one who triggered the event that causes this method to
# be called.
filterExpressionsHideActionWidgets: ->
if @consentToHideActionWidget then @hideActionWidget()
@consentToHideActionWidget = true
events:
'click button.operator': 'toggleActionWidget'
'click button.make-and': 'makeOperatorAnd'
'click button.conjoin': 'conjoin'
'click button.make-or': 'makeOperatorOr'
'click button.disjoin': 'disjoin'
'click button.negate': 'negate'
'click button.make-not-not': 'removeNotOperator'
'click button.destroy': 'destroyFilterExpression'
'click button.add-operand': 'addOperand'
'selectmenuchange .attribute': 'attributeChanged'
'selectmenuchange .sub-attribute': 'subattributeChanged'
'selectmenuchange .relation': 'relationChanged'
'input .value': 'valueChanged'
valueChanged: (event) ->
if event then @stopEvent event
value = @$('textarea.value').first().val()
if @filterExpression.length is 5
if @filterExpression[3] is 'in'
@filterExpression[4] = @jsonParse value
else
@filterExpression[4] = value
else
if @filterExpression[2] is 'in'
@filterExpression[3] = @jsonParse value
else
@filterExpression[3] = value
@triggerChanged()
jsonParse: (value) ->
try
JSON.parse value
catch
value
# The relation selectmenu of the filter expression has changed.
relationChanged: (event) ->
@stopEvent event
relation = @$('select.relation').first().val()
@syncWithRelation relation
# the "is (not) null" relations imply no sub-attribute and no pattern
# value.
if relation in ['is null', 'is not null']
if relation is 'is null'
@filterExpression.splice 2, 3, '=', null
else
@filterExpression.splice 2, 3, '!=', null
else
if @filterExpression.length is 5
@filterExpression[3] = relation
else
@filterExpression[2] = relation
@triggerChanged()
# Selecting the special relations 'is null' and 'is not null' causes the
# value <textarea> as well as any sub-attribute selectmenu to become hidden.
syncWithRelation: (value=null) ->
if not value then value = @$('select.relation').first().val()
if value in ['is null', 'is not null']
@$('textarea.value').first().hide()
@$('.ui-selectmenu-button.sub-attribute').first().hide()
else
@$('textarea.value').first().show()
@syncAttributeSubattributeSelects()
attributeChanged: (event) ->
@stopEvent event
@syncAttributeSubattributeSelects()
@syncWithRelation()
attribute = @$('select.attribute').first().val()
@filterExpression[1] = attribute
$subAttributeSelect = @$('select.sub-attribute').first()
$subAttributeSelectmenu = @$('.ui-selectmenu-button.sub-attribute').first()
if $subAttributeSelectmenu.is ':visible'
subAttribute = $subAttributeSelect.val()
if @filterExpression.length is 5
@filterExpression[2] = subAttribute
else
@filterExpression.splice 2, 0, subAttribute
else
if @filterExpression.length is 5
@filterExpression.splice 2, 1
@triggerChanged()
# Alter `@filterExpression` so that it accords with the DOM representation
# of the subattribute.
# model attribute subattribute relation value
# ['Form', 'enterer', 'first_name', 'is', 'PI:NAME:<NAME>END_PI']
# 0 1 2 3 4
#
# model attribute relation value
# ['Form', 'transcription', 'is', 'PI:NAME:<NAME>END_PI']
# 0 1 2 3
subattributeChanged: (event, triggerChanged=true) ->
if event then @stopEvent event
$subAttributeSelect = @$('select.sub-attribute').first()
$subAttributeSelectmenu = @$('.ui-selectmenu-button.sub-attribute').first()
if $subAttributeSelectmenu.is ':visible'
subAttribute = $subAttributeSelect.val()
@subattributeMemoryMap[@filterExpression[1]] = subAttribute
if @filterExpression.length is 5
@filterExpression[2] = subAttribute
else
@filterExpression.splice 2, 0, subAttribute
if triggerChanged then @triggerChanged()
else
if @filterExpression.length is 5
@filterExpression.splice 2, 1
# Synchronize the attribute and subattribute selectmenus.
# That is, if attribute is relational (i.e., valuated by reference to
# another object), then the sub-attribute select needs to be visible and it
# needs to be populated with the sub-attribute options relevant to its
# parent relational attribute.
# TODO: this view should remember the last selected sub-attribute of a
# given attribute.
syncAttributeSubattributeSelects: ->
attribute = @$('select.attribute').first().val()
subattributes = @subattributes()
if attribute of subattributes
# If `attribute` is relational, we rebuild its selectmenu.
$subAttributeSelect = @$('select.sub-attribute').first()
$subAttributeSelect.html ''
# Note that we remember the last attribute-subattribute correlation and
# implement that here. If there is no last correlation, we use the
# default subattribute for the given attribute, if there is one.
valueThatShouldBeSelected = null
if attribute of @subattributeMemoryMap
valueThatShouldBeSelected =
@subattributeMemoryMap[attribute]
else if attribute of @subattributeDefaults
valueThatShouldBeSelected = @subattributeDefaults[attribute]
for subattribute in subattributes[attribute].sort()
if valueThatShouldBeSelected and
valueThatShouldBeSelected is subattribute
$subAttributeSelect.append "<option value='#{subattribute}'
selected>#{@utils.snake2regular subattribute}</option>"
else
$subAttributeSelect.append "<option value='#{subattribute}'
>#{@utils.snake2regular subattribute}</option>"
# Rebuild the selectmenu machinery.
$subAttributeSelect
.selectmenu 'destroy'
.selectmenu()
.each (index, element) =>
@transferClassAndTitle @$(element) # so we can tooltipify the selectmenu
@$('.ui-selectmenu-button.sub-attribute').first()
.tooltip
content: "select a sub-attribute for the
#{@utils.snake2regular(attribute)}"
else
# If `attribute` is non-relational, we hide the sub-attribute selectmenu.
@$('select.sub-attribute').first().hide()
@$('.ui-selectmenu-button.sub-attribute').first().hide()
# If this filter expression has a boolean (and/or) as its non-terminal, add
# a new coordinand, i.e., a new filter expression under the scope of the
# boolean. If there is a "not" as the non-terminal, add an
# operand/complement under its scope. Note: this button should only be
# visible/available if the non-terminal is a boolean OR if the non-terminal
# is a stranded negation.
addOperand: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
operator = @filterExpression[0]
if operator in ['or', 'and'] or
(operator is 'not' and @filterExpression.length is 1)
newFilterExpression = @getDefaultFilterExpression()
if operator in ['or', 'and']
@filterExpression[1].push newFilterExpression
else if operator is 'not'
@filterExpression.push newFilterExpression
filterExpressionSubview =
@getNewFilterExpressionView newFilterExpression
@filterExpressionSubviews.push filterExpressionSubview
@renderFilterExpressionSubview filterExpressionSubview, true
@listenToSubview filterExpressionSubview
@triggerChanged()
getDefaultFilterExpression: ->
[@targetResourceNameCapitalized , @primaryAttribute, 'regex', '']
# Change the operator to a boolean, i.e., 'and' or 'or'.
makeOperatorBoolean: (boolean) ->
booleans = ['or', 'and']
@hideActionWidgetAnimate()
if @filterExpression[0] in booleans
@filterExpression[0] = boolean
@$('button.operator').first()
.button 'option', 'label', boolean
.button 'refresh'
@actionButtonsVisibility()
# Add a boolean ('and' or 'or') with scope over this filter expression.
coordinate: (boolean) ->
booleans = ['or', 'and']
@hideActionWidgetAnimate()
@coordinateFilterExpression boolean
@$el.fadeOut
complete: =>
for subview in @filterExpressionSubviews
subview.close()
@initializeFilterExpressionSubviews()
@$el.empty()
@render()
@$el.fadeIn
complete: =>
@$('button, .ui-selectmenu-button, .textarea').first().focus()
@triggerChanged()
# Add an "and" with scope over this filter expression.
conjoin: (event) ->
@stopEvent event
@coordinate 'and'
# Add an "or" with scope over this filter expression.
disjoin: (event) ->
@stopEvent event
@coordinate 'or'
# Change the operator of this filter expression to 'and'.
makeOperatorAnd: (event) ->
@stopEvent event
@makeOperatorBoolean 'and'
# Change the operator of this filter expression to 'or'.
makeOperatorOr: (event) ->
@stopEvent event
@makeOperatorBoolean 'or'
# Change the operator of this filter expression to 'not'.
negate: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
@negateFilterExpression()
@$el.fadeOut
complete: =>
for subview in @filterExpressionSubviews
subview.close()
@initializeFilterExpressionSubviews()
@$el.empty()
@render()
@$el.fadeIn
complete: =>
@$('button, .ui-selectmenu-button, .textarea').first().focus()
@triggerChanged()
# Remove the "not" operator from this filter expression.
removeNotOperator: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
@removeNegationFromFilterExpression()
@$el.fadeOut
complete: =>
for subview in @filterExpressionSubviews
subview.close()
@initializeFilterExpressionSubviews()
@$el.empty()
@render()
@$el.fadeIn
complete: =>
@$('button, .ui-selectmenu-button, .textarea').first().focus()
@triggerChanged()
# Change our filter expression array so that it begins with a 'not'.
negateFilterExpression: ->
@filterExpression.unshift (x for x in @filterExpression)
@filterExpression.unshift 'not'
while @filterExpression.length > 2
@filterExpression.pop()
# Change our filter expression array so that it NO LONGER begins with a
# 'not'.
removeNegationFromFilterExpression: ->
for element in @filterExpression[1]
@filterExpression.push element
@filterExpression.shift()
@filterExpression.shift()
# Change our filter expression array so that it begins with an 'and' or an
# 'or'. Here we have to shift things in the array around so that we're in a
# proper and/or configuration, i.e., go from FE to ['and/or', [FE]],
# all while not replacing any existing arrays; that is, we need to keep
# the whole filter expression array intact, no copying.
coordinateFilterExpression: (coordinator) ->
@filterExpression.unshift [(x for x in @filterExpression)]
@filterExpression.unshift coordinator
while @filterExpression.length > 2
@filterExpression.pop()
# Destroy this filter expression. Note: we trigger a `destroyMe` event and
# let the parent `FilterExpression` view handle most of the destruction.
destroyFilterExpression: (event) ->
@stopEvent event
@hideActionWidgetAnimate()
@trigger 'destroyMe', @
# Toggle the action widget, i.e., the <div> full of buttons that pops up
# when you click on an "operator" button.
toggleActionWidget: (event) ->
if event then @stopEvent event
$actionWidgetContainer =
@$('div.filter-expression-action-widget-container').first()
if $actionWidgetContainer.is ':visible'
$actionWidgetContainer.slideUp('fast')
@$('button.operator').first()
.tooltip
content: 'click here to reveal buttons for changing this node.'
position: @tooltipPositionLeft('-20')
else
@consentToHideActionWidget = false
Backbone.trigger 'filterExpressionsHideActionWidgets'
$actionWidgetContainer
.slideDown('fast')
.find('button').first().focus()
@$('button.operator').first()
.tooltip
content: 'click here to hide the buttons for changing this node.'
position: @tooltipPositionLeft('-20')
hideActionWidget: ->
@$('div.filter-expression-action-widget-container').first().hide()
hideActionWidgetAnimate: ->
@$('div.filter-expression-action-widget-container').first()
.slideUp('fast')
# Initialize a new `FilterExpressionView` with `subFilterExpression` as its
# filter expression.
getNewFilterExpressionView: (subFilterExpression) ->
new @constructor(
model: @model
targetResourceName: @targetResourceName
filterExpression: subFilterExpression
options: @options
rootNode: false
)
template: filterExpressionTemplate
getAttributes: ->
try
key = "#{@targetResourceName}_search_parameters"
attrs = @options[key].attributes
(x for x in _.keys(attrs).sort() \
when x not in ['morpheme_break_ids', 'morpheme_gloss_ids'])
catch
[]
render: ->
context =
filterExpression: @filterExpression
options: @options
attributes: @getAttributes()
subattributes: @subattributes() # TODO: we have to do this ourselves! The OLD should provide it though...
relations: @getRelations @options
snake2regular: @utils.snake2regular
pluralize: @utils.pluralize
@$el.html @template(context)
@bordercolorify()
$filterExpressionTable = @$('.filter-expression-table').first()
$filterExpressionTable
.find('textarea').autosize().end()
.find('button').button().end()
.find('.dative-tooltip.operator')
.tooltip position: @tooltipPositionLeft('-20')
.end()
.find('.dative-tooltip').not('.operator')
.tooltip position:
my: 'left bottom'
at: 'left top-20'
collision: 'flipfit'
@renderFilterExpressionSubviews()
@hideActionWidget()
@actionButtonsVisibility()
@listenToEvents()
@selectmenuAndVisibility $filterExpressionTable
@
# Make the selects into select menus and hide the sub-attribute select if
# it's not relevant.
selectmenuAndVisibility: ($filterExpressionTable) ->
@selectmenuify $filterExpressionTable
if @filterExpression.length is 4
@$('select.sub-attribute').hide()
@$('.ui-selectmenu-button.sub-attribute').hide()
if @filterExpression[2] in ['=', '!='] and
@filterExpression[3] is null
@$('textarea.value').first().hide()
# We filter out some of the relations exposed by the OLD; this is because
# some of them are redundant and have ugly names, e.g., ugly "__ne__" is
# co-referential with "!=" and "regexp" is the same as "regex".
getRelations: (options) ->
try
key = PI:KEY:<KEY>END_PI@PI:KEY:<KEY>END_PI"
relations = _.keys options[key].relations
(r for r in relations when r isnt 'regexp' and '_' not in r)
.concat(['is null', 'is not null'])
catch
[]
selectmenuify: ($context) ->
$context.find('select')
.selectmenu width: 'auto'
.each (index, element) =>
@transferClassAndTitle @$(element) # so we can tooltipify the selectmenu
# Show/hide various action buttons for the non-terminal node of this filter
# expression, depending on its state.
actionButtonsVisibility: ->
myOperator = @filterExpression[0]
$actionWidget = @$('.filter-expression-action-widget').first()
@hideButtonForExistingState myOperator, $actionWidget
if myOperator in ['and', 'or']
if @filterExpression[1].length > 1
$actionWidget.find('button.destroy').hide()
else
$actionWidget.find('button.destroy').show()
$actionWidget.find('button.add-operand').show()
$actionWidget.find('button.make-not-not').hide()
if myOperator is 'and'
$actionWidget.find('button.make-and').hide()
$actionWidget.find('button.make-or').show()
else
$actionWidget.find('button.make-or').hide()
$actionWidget.find('button.make-and').show()
else
$actionWidget.find('button.make-or').hide()
$actionWidget.find('button.make-and').hide()
if myOperator is 'not'
$actionWidget.find('button.make-not-not').show()
if @filterExpression.length is 1
$actionWidget.find('button.add-operand').show()
else
$actionWidget.find('button.make-not-not').hide()
$actionWidget.find('button.add-operand').hide()
# Hide the button for changing to the current state. That is, if this is an
# 'and' node, we don't want to show the "make me an 'and' node" button.
hideButtonForExistingState: (myOperator, $actionWidget=null) ->
$actionWidget =
$actionWidget or @$('.filter-expression-action-widget').first()
operators = ['and', 'or', 'not', '']
for operator in operators
if myOperator is operator or myOperator not in operators
$actionWidget
.find("button.make-#{operator}").hide().end()
.find('button').not(".make-#{operator}").show()
renderFilterExpressionSubviews: ->
for filterExpressionSubview in @filterExpressionSubviews
@renderFilterExpressionSubview filterExpressionSubview
renderFilterExpressionSubview: (filterExpressionSubview, animate=false) ->
@$('.filter-expression-operand').first()
.append filterExpressionSubview.render().el
if animate
filterExpressionSubview.$el
.hide()
.fadeIn
complete: ->
filterExpressionSubview
.$('button, .ui-selectmenu-button, .textarea').first().focus()
@rendered filterExpressionSubview
# Make the border colors match the jQueryUI theme.
bordercolorify: ->
@$('.filter-expression-table').first().find('textarea, input')
.css "border-color", @constructor.jQueryUIColors().defBo
@$('.filter-expression-action-widget').first()
.css
"border-color": @constructor.jQueryUIColors().defBo
"background-color": @constructor.jQueryUIColors().defCo
# TODO: the OLD should be supplying all of this information. We should
# not have to specify it here.
subattributes: ->
switch @targetResourceName
when 'form' then @formSubattributes()
when 'file' then @fileSubattributes()
when 'collection' then @collectionSubattributes()
when 'language' then @languageSubattributes()
languageSubattributes: -> {}
collectionSubattributes: ->
elicitor: @userAttributes
enterer: @userAttributes
modifier: @userAttributes
speaker: @speakerAttributes
tags: @tagAttributes
files: @fileAttributes
source: @sourceAttributes
fileSubattributes: ->
elicitor: @userAttributes
enterer: @userAttributes
speaker: @speakerAttributes
parent_file: @fileAttributes
tags: @tagAttributes
forms: @formAttributes
collections: @collectionAttributes
formSubattributes: ->
collections: @collectionAttributes
corpora: [
'content'
'datetime_entered'
'datetime_modified'
'description'
'enterer'
'files'
'form_search'
'id'
'modifier'
'name'
'tags'
'UUID'
]
elicitation_method: [
'id'
'name'
'description'
'datetime_modified'
]
elicitor: @userAttributes
enterer: @userAttributes
modifier: @userAttributes
files: @fileAttributesNonRelational
memorizers: @userAttributes
source: @sourceAttributes
speaker: @speakerAttributes
syntactic_category: [
'datetime_modified'
'description'
'id'
'name'
'type'
]
tags: @tagAttributes
translations: [
'datetime_modified'
'form_id'
'grammaticality'
'id'
'transcription'
]
verifier: @userAttributes
sourceAttributes: [
'id'
'file_id'
'file'
'crossref_source_id'
'crossref_source'
'datetime_modified'
'type'
'key'
'address'
'annote'
'author'
'booktitle'
'chapter'
'crossref'
'edition'
'editor'
'howpublished'
'institution'
'journal'
'key_field'
'month'
'note'
'number'
'organization'
'pages'
'publisher'
'school'
'series'
'title'
'type_field'
'url'
'volume'
'year'
'affiliation'
'abstract'
'contents'
'copyright'
'ISBN'
'ISSN'
'keywords'
'language'
'location'
'LCCN'
'mrnumber'
'price'
'size'
]
userAttributes: [
'id'
'PI:NAME:<NAME>END_PI_name'
'PI:NAME:<NAME>END_PIname'
'email'
'affiliation'
'role'
'markup_language'
'page_content'
'html'
'input_orthography'
'output_orthography'
'datetime_modified'
]
speakerAttributes: [
'id'
'first_name'
'last_name'
'dialect'
'markup_language'
'page_content'
'html'
'datetime_modified'
]
fileAttributesNonRelational: [
'id'
'date_elicited'
'datetime_entered'
'datetime_modified'
'filename'
'name'
'lossy_filename'
'MIME_type'
'size'
'description'
'utterance_type'
'url'
'password'
'start'
'end'
]
fileAttributes: [
'id'
'date_elicited'
'datetime_entered'
'datetime_modified'
'filename'
'name'
'lossy_filename'
'MIME_type'
'size'
'description'
'utterance_type'
'url'
'password'
'enterer'
'elicitor'
'speaker'
'tags'
'forms'
'parent_file'
'start'
'end'
]
tagAttributes: [
'id'
'name'
'description'
'datetime_modified'
]
formAttributes: [
'files',
'elicitor'
'break_gloss_category'
'tags'
'elicitation_method'
'translations'
'syntax'
'memorizers'
'syntactic_category'
'grammaticality'
'syntactic_category_string'
'datetime_modified'
'date_elicited'
'phonetic_transcription'
'morpheme_gloss'
'id'
'semantics'
'datetime_entered'
'UUID'
'narrow_phonetic_transcription'
'transcription'
'corpora'
'enterer'
'comments'
'source'
'verifier'
'speaker'
'morpheme_break'
'collections'
'speaker_comments'
]
collectionAttributes: [
'id'
'UUID'
'title'
'type'
'url'
'description'
'markup_language'
'contents'
'contents_unpacked'
'html'
'date_elicited'
'datetime_entered'
'datetime_modified'
'speaker'
'source'
'elicitor'
'enterer'
'modifier'
'tags'
'files'
]
# Maps attributes to the default subattribute that should be displayed when
# the attribute is selected.
subattributeDefaults:
collections: 'title'
corpora: 'name'
elicitation_method: 'name'
elicitor: 'PI:NAME:<NAME>END_PI'
enterer: 'PI:NAME:<NAME>END_PI'
files: 'filename'
forms: 'transcription'
memorizers: 'PI:NAME:<NAME>END_PI'
parent_file: 'filename'
source: 'author'
speaker: 'PI:NAME:<NAME>END_PI'
syntactic_category: 'PI:NAME:<NAME>END_PI'
tags: 'name'
translations: 'transcription'
verifier: 'PI:NAME:<NAME>END_PI'
modifier: 'PI:NAME:<NAME>END_PI'
|
[
{
"context": "env.data.redis.last_error\n\t\t\tnext = ->\n\t\t\t\ttoken = env.data.generateUid()\n\t\t\t\t(env.data.redis.multi [\n\t\t\t\t\t['hmset', 'sessi",
"end": 2041,
"score": 0.8731780648231506,
"start": 2019,
"tag": "KEY",
"value": "env.data.generateUid()"
},
{
"context": "token\n\t\t\tdb_login name:credentials.clientId, pass:credentials.clientSecret, (err, res) ->\n\t\t\t\tif err\n\t\t\t\t\treturn cb null, fa",
"end": 2332,
"score": 0.998769998550415,
"start": 2308,
"tag": "PASSWORD",
"value": "credentials.clientSecret"
},
{
"context": "s\n\t\t\t\tdb_register name:credentials.clientId, pass:credentials.clientSecret, (err, res) ->\n\t\t\t\t\treturn cb err if err\n\t\t\t\t\tnex",
"end": 2555,
"score": 0.9987603425979614,
"start": 2531,
"tag": "PASSWORD",
"value": "credentials.clientSecret"
},
{
"context": "= ->\n\t\t\treq.user = req.clientId\n\t\t\treq.user.id = 'admin'\n\t\t\treq.body ?= {}\n\t\t\tnext()\n\t\treturn cb() if env",
"end": 3095,
"score": 0.9081029295921326,
"start": 3090,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "= ->\n\t\t\treq.user = req.clientId\n\t\t\treq.user.id = 'admin'\n\t\t\treq.body ?= {}\n\t\t\tnext()\n\t\treturn cb() if env",
"end": 3833,
"score": 0.843571126461029,
"start": 3828,
"tag": "USERNAME",
"value": "admin"
}
] | plugins/admin-auth/auth.coffee | pmstss/oauthd | 4 | # OAuth daemon
# Copyright (C) 2013 Webshell SAS
#
# 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
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public Affero License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
restify = require 'restify'
restifyOAuth2 = require 'restify-oauth2-oauthd'
module.exports = (env) ->
auth = {}
_config =
expire: 3600*5
# register the adm passphrase (first time)
db_register = env.utilities.check name:/^.{3,42}$/, pass:/^.{6,42}$/, (data, callback) ->
env.data.redis.get 'adm:pass', (e,r) ->
return callback new env.utilities.check.Error 'Unable to register' if e or r
dynsalt = Math.floor(Math.random()*9999999)
pass = env.data.generateHash data.pass + dynsalt
env.data.redis.mset 'adm:salt', dynsalt, 'adm:pass', pass, 'adm:name', data.name, (err, res) ->
return callback err if err
callback()
# checks if passphrase match
db_login = env.utilities.check name:/^.{3,42}$/, pass:/^.{6,42}$/, (data, callback) ->
env.data.redis.mget [
'adm:pass',
'adm:name',
'adm:salt'], (err, replies) ->
return callback err if err
return callback null, false if not replies[1]
calcpass = env.data.generateHash data.pass + replies[2]
return callback new env.utilities.check.Error "Invalid email or password" if replies[0] != calcpass or replies[1] != data.name
callback null, replies[1]
hooks =
grantClientToken: (credentials, req, cb) ->
if env.data.redis.last_error
return cb new env.utilities.check.Error env.data.redis.last_error
next = ->
token = env.data.generateUid()
(env.data.redis.multi [
['hmset', 'session:' + token, 'date', (new Date).getTime()]
['expire', 'session:' + token, _config.expire]
]).exec (err, r) ->
return cb err if err
return cb null, token
db_login name:credentials.clientId, pass:credentials.clientSecret, (err, res) ->
if err
return cb null, false if err.message == "Invalid email or password"
return cb err if err
return next() if res
db_register name:credentials.clientId, pass:credentials.clientSecret, (err, res) ->
return cb err if err
next()
authenticateToken: (token, req, cb) ->
return cb null, false if env.data.redis.last_error
env.data.redis.hgetall 'session:' + token, (err, res) ->
return cb err if err
return cb null, false if not res
req.clientId = res
req.token = token
return cb null, true
# Middleware setup
env.middlewares.auth = {} # inits the authentication middleware
env.middlewares.auth.needed = (req, res, next) ->
cb = ->
req.user = req.clientId
req.user.id = 'admin'
req.body ?= {}
next()
return cb() if env.data.redis.last_error
return cb() if req.clientId
# token = req.headers.cookie?.match /accessToken=%22(.*?)%22/
token = req.headers.Authorization?.replace /^Bearer /, ''
return next new restify.ResourceNotFoundError req.url + ' does not exist' if not token
env.data.redis.hget 'session:' + token, 'date', (err, res) ->
return next new restify.ResourceNotFoundError req.url + ' does not exist' if not res
req.clientId = 'admin'
cb()
# Placeholder function for multi-users plugin
env.middlewares.auth.needAccess = (right) -> env.middlewares.auth.needed
env.middlewares.auth.optional = (req, res, next) ->
cb = ->
req.user = req.clientId
req.user.id = 'admin'
req.body ?= {}
next()
return cb() if env.data.redis.last_error
return cb() if req.clientId
token = req.headers.cookie?.match /accessToken=%22(.*?)%22/
token = token?[1]
return cb() if not token
env.data.redis.hget 'session:' + token, 'date', (err, res) ->
return cb() if not res
req.clientId = 'admin'
cb()
auth.init = ->
restifyOAuth2.cc env.server,
hooks:hooks, tokenEndpoint: env.config.base + '/token',
tokenExpirationTime: _config.expire
auth.setup = (callback) ->
env.server.post env.config.base + '/signin', (req, res, next) =>
res.setHeader 'Content-Type', 'text/html'
hooks.grantClientToken {clientId:req.body.name, clientSecret:req.body.pass}, req, (e, token) =>
if not e and not token
e = new env.utilities.check.Error 'Invalid email or password'
if token
expireDate = new Date((new Date - 0) + _config.expire * 1000)
res.setHeader 'Content-Type', ''
res.json {
accessToken: token,
expires: expireDate.getTime()
}
if e
if e.status == "fail"
if e.body.name
e = new env.utilities.check.Error "Invalid email format"
if e.body.pass
e = new env.utilities.check.Error "Invalid password format (must be 6 characters min)"
res.send 400, e.message
next()
env.server.get env.config.base + '/api/apps', env.middlewares.auth.needed, (req, res, next) ->
env.data.apps.getByOwner 'admin', (err, apps) ->
res.json apps
next()
env.events.on 'app.create', (user, app) ->
if user?.id
env.data.redis.sadd 'u:' + user.id + ':apps', app.id
env.events.on 'app.remove', (user, app) ->
if user?.id
env.data.redis.srem 'u:' + user.id + ':apps', app.id
callback()
auth
| 144601 | # OAuth daemon
# Copyright (C) 2013 Webshell SAS
#
# 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
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public Affero License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
restify = require 'restify'
restifyOAuth2 = require 'restify-oauth2-oauthd'
module.exports = (env) ->
auth = {}
_config =
expire: 3600*5
# register the adm passphrase (first time)
db_register = env.utilities.check name:/^.{3,42}$/, pass:/^.{6,42}$/, (data, callback) ->
env.data.redis.get 'adm:pass', (e,r) ->
return callback new env.utilities.check.Error 'Unable to register' if e or r
dynsalt = Math.floor(Math.random()*9999999)
pass = env.data.generateHash data.pass + dynsalt
env.data.redis.mset 'adm:salt', dynsalt, 'adm:pass', pass, 'adm:name', data.name, (err, res) ->
return callback err if err
callback()
# checks if passphrase match
db_login = env.utilities.check name:/^.{3,42}$/, pass:/^.{6,42}$/, (data, callback) ->
env.data.redis.mget [
'adm:pass',
'adm:name',
'adm:salt'], (err, replies) ->
return callback err if err
return callback null, false if not replies[1]
calcpass = env.data.generateHash data.pass + replies[2]
return callback new env.utilities.check.Error "Invalid email or password" if replies[0] != calcpass or replies[1] != data.name
callback null, replies[1]
hooks =
grantClientToken: (credentials, req, cb) ->
if env.data.redis.last_error
return cb new env.utilities.check.Error env.data.redis.last_error
next = ->
token = <KEY>
(env.data.redis.multi [
['hmset', 'session:' + token, 'date', (new Date).getTime()]
['expire', 'session:' + token, _config.expire]
]).exec (err, r) ->
return cb err if err
return cb null, token
db_login name:credentials.clientId, pass:<PASSWORD>, (err, res) ->
if err
return cb null, false if err.message == "Invalid email or password"
return cb err if err
return next() if res
db_register name:credentials.clientId, pass:<PASSWORD>, (err, res) ->
return cb err if err
next()
authenticateToken: (token, req, cb) ->
return cb null, false if env.data.redis.last_error
env.data.redis.hgetall 'session:' + token, (err, res) ->
return cb err if err
return cb null, false if not res
req.clientId = res
req.token = token
return cb null, true
# Middleware setup
env.middlewares.auth = {} # inits the authentication middleware
env.middlewares.auth.needed = (req, res, next) ->
cb = ->
req.user = req.clientId
req.user.id = 'admin'
req.body ?= {}
next()
return cb() if env.data.redis.last_error
return cb() if req.clientId
# token = req.headers.cookie?.match /accessToken=%22(.*?)%22/
token = req.headers.Authorization?.replace /^Bearer /, ''
return next new restify.ResourceNotFoundError req.url + ' does not exist' if not token
env.data.redis.hget 'session:' + token, 'date', (err, res) ->
return next new restify.ResourceNotFoundError req.url + ' does not exist' if not res
req.clientId = 'admin'
cb()
# Placeholder function for multi-users plugin
env.middlewares.auth.needAccess = (right) -> env.middlewares.auth.needed
env.middlewares.auth.optional = (req, res, next) ->
cb = ->
req.user = req.clientId
req.user.id = 'admin'
req.body ?= {}
next()
return cb() if env.data.redis.last_error
return cb() if req.clientId
token = req.headers.cookie?.match /accessToken=%22(.*?)%22/
token = token?[1]
return cb() if not token
env.data.redis.hget 'session:' + token, 'date', (err, res) ->
return cb() if not res
req.clientId = 'admin'
cb()
auth.init = ->
restifyOAuth2.cc env.server,
hooks:hooks, tokenEndpoint: env.config.base + '/token',
tokenExpirationTime: _config.expire
auth.setup = (callback) ->
env.server.post env.config.base + '/signin', (req, res, next) =>
res.setHeader 'Content-Type', 'text/html'
hooks.grantClientToken {clientId:req.body.name, clientSecret:req.body.pass}, req, (e, token) =>
if not e and not token
e = new env.utilities.check.Error 'Invalid email or password'
if token
expireDate = new Date((new Date - 0) + _config.expire * 1000)
res.setHeader 'Content-Type', ''
res.json {
accessToken: token,
expires: expireDate.getTime()
}
if e
if e.status == "fail"
if e.body.name
e = new env.utilities.check.Error "Invalid email format"
if e.body.pass
e = new env.utilities.check.Error "Invalid password format (must be 6 characters min)"
res.send 400, e.message
next()
env.server.get env.config.base + '/api/apps', env.middlewares.auth.needed, (req, res, next) ->
env.data.apps.getByOwner 'admin', (err, apps) ->
res.json apps
next()
env.events.on 'app.create', (user, app) ->
if user?.id
env.data.redis.sadd 'u:' + user.id + ':apps', app.id
env.events.on 'app.remove', (user, app) ->
if user?.id
env.data.redis.srem 'u:' + user.id + ':apps', app.id
callback()
auth
| true | # OAuth daemon
# Copyright (C) 2013 Webshell SAS
#
# 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
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public Affero License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
restify = require 'restify'
restifyOAuth2 = require 'restify-oauth2-oauthd'
module.exports = (env) ->
auth = {}
_config =
expire: 3600*5
# register the adm passphrase (first time)
db_register = env.utilities.check name:/^.{3,42}$/, pass:/^.{6,42}$/, (data, callback) ->
env.data.redis.get 'adm:pass', (e,r) ->
return callback new env.utilities.check.Error 'Unable to register' if e or r
dynsalt = Math.floor(Math.random()*9999999)
pass = env.data.generateHash data.pass + dynsalt
env.data.redis.mset 'adm:salt', dynsalt, 'adm:pass', pass, 'adm:name', data.name, (err, res) ->
return callback err if err
callback()
# checks if passphrase match
db_login = env.utilities.check name:/^.{3,42}$/, pass:/^.{6,42}$/, (data, callback) ->
env.data.redis.mget [
'adm:pass',
'adm:name',
'adm:salt'], (err, replies) ->
return callback err if err
return callback null, false if not replies[1]
calcpass = env.data.generateHash data.pass + replies[2]
return callback new env.utilities.check.Error "Invalid email or password" if replies[0] != calcpass or replies[1] != data.name
callback null, replies[1]
hooks =
grantClientToken: (credentials, req, cb) ->
if env.data.redis.last_error
return cb new env.utilities.check.Error env.data.redis.last_error
next = ->
token = PI:KEY:<KEY>END_PI
(env.data.redis.multi [
['hmset', 'session:' + token, 'date', (new Date).getTime()]
['expire', 'session:' + token, _config.expire]
]).exec (err, r) ->
return cb err if err
return cb null, token
db_login name:credentials.clientId, pass:PI:PASSWORD:<PASSWORD>END_PI, (err, res) ->
if err
return cb null, false if err.message == "Invalid email or password"
return cb err if err
return next() if res
db_register name:credentials.clientId, pass:PI:PASSWORD:<PASSWORD>END_PI, (err, res) ->
return cb err if err
next()
authenticateToken: (token, req, cb) ->
return cb null, false if env.data.redis.last_error
env.data.redis.hgetall 'session:' + token, (err, res) ->
return cb err if err
return cb null, false if not res
req.clientId = res
req.token = token
return cb null, true
# Middleware setup
env.middlewares.auth = {} # inits the authentication middleware
env.middlewares.auth.needed = (req, res, next) ->
cb = ->
req.user = req.clientId
req.user.id = 'admin'
req.body ?= {}
next()
return cb() if env.data.redis.last_error
return cb() if req.clientId
# token = req.headers.cookie?.match /accessToken=%22(.*?)%22/
token = req.headers.Authorization?.replace /^Bearer /, ''
return next new restify.ResourceNotFoundError req.url + ' does not exist' if not token
env.data.redis.hget 'session:' + token, 'date', (err, res) ->
return next new restify.ResourceNotFoundError req.url + ' does not exist' if not res
req.clientId = 'admin'
cb()
# Placeholder function for multi-users plugin
env.middlewares.auth.needAccess = (right) -> env.middlewares.auth.needed
env.middlewares.auth.optional = (req, res, next) ->
cb = ->
req.user = req.clientId
req.user.id = 'admin'
req.body ?= {}
next()
return cb() if env.data.redis.last_error
return cb() if req.clientId
token = req.headers.cookie?.match /accessToken=%22(.*?)%22/
token = token?[1]
return cb() if not token
env.data.redis.hget 'session:' + token, 'date', (err, res) ->
return cb() if not res
req.clientId = 'admin'
cb()
auth.init = ->
restifyOAuth2.cc env.server,
hooks:hooks, tokenEndpoint: env.config.base + '/token',
tokenExpirationTime: _config.expire
auth.setup = (callback) ->
env.server.post env.config.base + '/signin', (req, res, next) =>
res.setHeader 'Content-Type', 'text/html'
hooks.grantClientToken {clientId:req.body.name, clientSecret:req.body.pass}, req, (e, token) =>
if not e and not token
e = new env.utilities.check.Error 'Invalid email or password'
if token
expireDate = new Date((new Date - 0) + _config.expire * 1000)
res.setHeader 'Content-Type', ''
res.json {
accessToken: token,
expires: expireDate.getTime()
}
if e
if e.status == "fail"
if e.body.name
e = new env.utilities.check.Error "Invalid email format"
if e.body.pass
e = new env.utilities.check.Error "Invalid password format (must be 6 characters min)"
res.send 400, e.message
next()
env.server.get env.config.base + '/api/apps', env.middlewares.auth.needed, (req, res, next) ->
env.data.apps.getByOwner 'admin', (err, apps) ->
res.json apps
next()
env.events.on 'app.create', (user, app) ->
if user?.id
env.data.redis.sadd 'u:' + user.id + ':apps', app.id
env.events.on 'app.remove', (user, app) ->
if user?.id
env.data.redis.srem 'u:' + user.id + ':apps', app.id
callback()
auth
|
[
{
"context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)\n# MIT Licensed\n###\n\nrequire.p",
"end": 44,
"score": 0.9998375773429871,
"start": 36,
"tag": "NAME",
"value": "Jae Kwon"
},
{
"context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)\n# MIT Licensed\n###\n\nrequire.paths.unshift 'vendo",
"end": 63,
"score": 0.9999298453330994,
"start": 46,
"tag": "EMAIL",
"value": "jae@ycatalyst.com"
},
{
"context": "v.check(req.post_data.password, 'password must be 5 to 1024 characters').len(5,1024)\n catch e\n form_erro",
"end": 15760,
"score": 0.9721235632896423,
"start": 15740,
"tag": "PASSWORD",
"value": "5 to 1024 characters"
},
{
"context": "ation here.\n if req.post_data.password != req.post_data.password2\n render_layout \"message\", {message: \"P",
"end": 18115,
"score": 0.9393680095672607,
"start": 18092,
"tag": "PASSWORD",
"value": "req.post_data.password2"
},
{
"context": "Alphanumeric()\n _v.check(data.password, 'password must be 5 to 1024 characters').len(5,1024)\n _v.ch",
"end": 23859,
"score": 0.8496078252792358,
"start": 23843,
"tag": "PASSWORD",
"value": "password must be"
},
{
"context": " _v.check(data.password, 'password must be 5 to 1024 characters').len(5,1024)\n _v.check(data.email).isEm",
"end": 23880,
"score": 0.9584094285964966,
"start": 23860,
"tag": "PASSWORD",
"value": "5 to 1024 characters"
},
{
"context": "vite specified\")\n if data.password != data.password2\n return form_error(\"passwords don't matc",
"end": 24107,
"score": 0.8675548434257507,
"start": 24098,
"tag": "PASSWORD",
"value": "password2"
}
] | server.coffee | jaekwon/YCatalyst | 3 | ###
# YCatalyst
# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)
# MIT Licensed
###
require.paths.unshift 'vendor'
require.paths.unshift 'vendor/validator'
http = require 'http'
utils = require './utils'
mongo = require './mongo'
fu = require './fu'
rec = require './static/record'
cookie = require 'cookie-node'
_ = require './static/underscore'
_v = require 'validator'
logic = require './logic/logic'
render_layout = logic.templates.render_layout
config = require './config'
cookie.secret = config.cookie_secret
DEFAULT_DEPTH = 5
if true
process.on 'uncaughtException', (err) ->
console.log "XXXXXXXXX"
console.log err.message
console.log err.stack
console.log "XXXXXXXXX FIX THIS ASAP, http://debuggable.com/posts/node-js-dealing-with-uncaught-exceptions:4c933d54-1428-443c-928d-4e1ecbdd56cb"
# a global hash from record id to [callbacks]
all_callbacks = {}
# clear old callbacks
# they can hang around for at most 30 seconds.
setInterval (->
now = new Date()
num_purged = 0
num_seen = 0
for key, callbacks of all_callbacks
num_seen += callbacks.length
while (callbacks.length > 0 && now - callbacks[0].timestamp > 30*1000)
num_purged += 1
callbacks.shift().callback([])
if callbacks.length == 0
delete all_callbacks[key]
if num_purged > 0
console.log "purged #{num_purged} of #{num_seen} in #{new Date() - now}"
), 3000
# given records, tell clients that this record had been updated
# -> if record is new
# -> if record was deleted
# -> if record got voted on
# -> if record has new number of children
#
# TODO we need to keep track of more state
# NOTE it is assumed that the records are in proximity to each other,
# specifically that the union of r.recdata.parents is small in size.
trigger_update = (records) ->
# compute the keys to notify
notify_keys = []
for record in records
if not record.is_new
notify_keys.push(record.recdata._id)
notify_keys = notify_keys.concat(record.recdata.parents or [])
notify_keys = _.uniq(notify_keys)
recdatas = (logic.records.scrubbed_recdata(record) for record in records)
for key in notify_keys
for callback in all_callbacks[key] or []
callback.callback(recdatas)
delete all_callbacks[key]
# wrapper to require current_user
require_login = (req, res, next) ->
if not req.current_user?
res.writeHead 401, status: 'login_error'
res.end 'not logged in'
return
else
next(req, res)
# wrapper generator to require current_user, but also direct them to a login page with a nice message
# message: string or optional
require_login_nice = (message) ->
return (req, res, next) ->
if not req.current_user?
render_layout "login", {message: message or 'You need to login to do that'}, req, res
else
next(req, res)
require_admin = (req, res, next) ->
if not req.current_user.is_admin
res.writeHead 401, status: 'privileges_error'
res.end 'not authorized'
return
else
next(req, res)
server = utils.Rowter([
['/static/:filepath', (req, res) ->
switch req.method
when 'GET'
filepath = req.path_data.filepath
filepath = require('path').join './static/', filepath
if filepath.indexOf('static/') != 0
res.writeHead 404, 'does not exist'
res.end()
else
fu.staticHandler(filepath)(req, res)
]
# get the most viewed sessions
# TODO cache this
['/', (req, res) ->
switch req.method
when 'GET'
#views = logic.sessions.get_viewers()
#rids = (v[0] for v in views)
#mongo.records.find {_id: {$in: rids}}, (err, cursor) ->
mongo.records.find {parent_id: null, deleted_at: {$exists: false}}, {sort: [['score', -1]]}, (err, cursor) ->
cursor.toArray (err, records) ->
if err
console.log err
return
records = (new rec.Record(r) for r in records)
render_layout "index", {records: records}, req, res
]
['/r/:id', (req, res) ->
root_id = req.path_data.id
switch req.method
when 'GET'
# requested from json, just return a single record
if req.headers['x-requested-with'] == 'XMLHttpRequest'
logic.records.get_one_record root_id, (err, record) ->
res.simpleJSON 200, record: logic.records.scrubbed_recdata(record)
return
else
logic.records.get_records root_id, DEFAULT_DEPTH, (err, all) ->
if err? or not all?
res.writeHead 404, status: 'error'
res.end()
return
render_layout "record", {root: logic.records.dangle(all, root_id)}, req, res
when 'POST'
# updating
logic.records.get_one_record root_id, (err, record) ->
if err? or not record?
res.writeHead 404, status: 'error'
res.end()
return
if record.recdata.created_by != req.current_user.username
res.simpleJSON 400, status: 'unauthorized'
return
if not record.recdata.parent_id
record.recdata.title = req.post_data.title
record.recdata.url = req.post_data.url
if req.post_data.url
try
record.recdata.host = utils.url_hostname(req.post_data.url)
catch e
record.recdata.host = 'unknown'
console.log "record with url #{req.post_data.url}: couldn't parse the hostname"
else
delete record.recdata.host
record.recdata.comment = req.post_data.comment
record.recdata.updated_at = new Date()
mongo.records.save record.recdata, (err, stuff) ->
res.simpleJSON 200, status: 'ok', updates: [logic.records.scrubbed_recdata(record)]
trigger_update [record]
]
['/r/:id/watching', (req, res) ->
switch req.method
when 'GET'
rid = req.path_data.id
watching = logic.sessions.get_watching(rid)
res.simpleJSON 200, watching
]
[wrappers: [require_login],
'/r/:id/delete', (req, res) ->
switch req.method
when 'POST'
rid = req.path_data.id
logic.records.get_one_record rid, (err, record) ->
if record
record.recdata.deleted_at = new Date()
record.recdata.deleted_by = req.current_user.username
mongo.records.save record.recdata, (err, stuff) ->
res.simpleJSON 200, status: 'ok'
trigger_update [record]
else
res.writeHead 404, status: 'error'
res.end html
]
[wrappers: [require_login],
'/r/:id/reply', (req, res) ->
switch req.method
when 'GET'
parent_id = req.path_data.id
logic.records.get_one_record parent_id, (err, parent) ->
render_layout "reply", {parent: parent}, req, res
when 'POST'
parent_id = req.path_data.id
comment = req.post_data.comment
logic.records.get_one_record parent_id, (err, parent) ->
if parent
root_id = if parent.recdata.root_id? then parent.recdata.root_id else parent.recdata._id
recdata = _id: utils.randid(), comment: comment, created_by: req.current_user.username, root_id: root_id, upvoters: [req.current_user._id]
if req.post_data.type == 'choice'
# only the parent's creator can add a poll choice
if parent.recdata.created_by != req.current_user.username
res.writeHead 401, status: 'unauthorized'
res.end "I can't let you do that"
return
recdata.type = 'choice'
record = logic.records.create_record(recdata, parent)
mongo.records.save record.recdata, (err, stuff) ->
if req.headers['x-requested-with'] == 'XMLHttpRequest'
res.simpleJSON 200, status: 'ok', updates: [logic.records.scrubbed_recdata(record)]
else
res.writeHead 302, Location: '/r/'+parent_id
res.end()
if record.recdata.type == 'choice'
# we could trigger a live update, but
# needs an update of the process.
trigger_update [record]
else
# update the parent as well, specifically num_children
parent.recdata.num_children += 1
mongo.records.save parent.recdata, (err, stuff) ->
if err
console.err "failed to update parent.num_children: #{parent_id}"
# update the root, num_discussions.
logic.records.get_one_record root_id, (err, root) ->
if err
console.err "failed ot update root.num_discussions: #{root_id}"
return
if not root.recdata.num_discussions?
root.recdata.num_discussions = 1
else
root.recdata.num_discussions += 1
mongo.records.save root.recdata, (err, stuff) ->
if err
console.err "failed to update root.num_discussions: #{root_id}"
# notify clients
trigger_update [parent, record]
else
res.writeHead 404, status: 'error'
res.end html
]
[wrappers: [require_login],
'/r/:key/recv', (req, res) ->
switch req.method
when 'GET'
key = req.path_data.key
if not all_callbacks[key]
all_callbacks[key] = []
all_callbacks[key].push
callback: (recdatas) ->
res.simpleJSON 200, recdatas
timestamp: new Date()
username: req.current_user.username if req.current_user?
if req.current_user?
logic.sessions.touch_session(key, req.current_user.username)
]
[wrappers: [require_login],
'/r/:id/upvote', (req, res) ->
switch req.method
when 'POST'
rid = req.path_data.id
logic.records.get_one_record rid, (err, record) ->
if not record.recdata.upvoters?
record.recdata.upvoters = []
if record.recdata.upvoters.indexOf(req.current_user._id) == -1
record.recdata.upvoters.push(req.current_user._id)
record.recdata.points = record.recdata.upvoters.length
# rescore the record
logic.records.score_record(record)
# save this record
mongo.records.save record.recdata, (err, stuff) ->
res.simpleJSON 200, status: 'ok', updates: [logic.records.scrubbed_recdata(record)]
# notify clients
trigger_update [record]
]
[wrappers: [require_login],
'/r/:id/follow', (req, res) ->
switch req.method
when 'POST'
rid = req.path_data.id
logic.records.follow rid, req.current_user, req.post_data.follow=='true', (err) ->
if err
res.simpleJSON 500, status: 'internal_error'
return
res.simpleJSON 200, status: 'ok'
]
[wrappers: [require_login_nice('You need to log again')],
'/inbox', (req, res) ->
switch req.method
when 'GET'
mongo.records.find {parent_followers: req.current_user._id, created_by: {$ne: req.current_user.username} }, {sort: [['created_at', -1]]}, (err, cursor) ->
cursor.toArray (err, records) ->
if err
console.log err
return
records = (new rec.Record(r) for r in records)
render_layout "inbox", {records: records}, req, res
]
['/users', (req, res) ->
# show all users
switch req.method
when 'GET'
mongo.users.find {}, {sort: [['created_at', -1]]}, (err, cursor) ->
cursor.toArray (err, users) ->
render_layout "users", {users: users}, req, res
]
['/user/:username', (req, res) ->
is_self = req.current_user and req.current_user.username == req.path_data.username
switch req.method
when 'GET'
mongo.users.findOne username: req.path_data.username, (err, user) ->
render_layout "user", {user: user, is_self: is_self}, req, res
when 'POST'
if not is_self
res.writeHead 401, status: 'unauthorized'
res.end 'unauthorized'
return
if req.post_data.bio.length > 10000
render_layout "message", {message: "Your bio is too long. Please keep it under 10K characters."}, req, res
return
mongo.users.update {username: req.path_data.username}, {$set: {bio: req.post_data.bio}}, (err, stuff) ->
if err
render_layout "message", {message: ''+err}, req, res
return
res.redirect req.url
]
['/bookmarklet', (req, res) ->
render_layout "bookmarklet", {}, req, res
]
[wrappers: [require_login_nice('You need to log in to submit')],
'/submit', (req, res) ->
switch req.method
when 'GET'
render_layout "submit", {headerbar_text: 'Submit', type: (req.query_data.type or 'link'), link_title: req.query_data.title, link_url: req.query_data.url}, req, res
when 'POST'
data = req.post_data
# validate data
try
_v.check(data.title, 'title must be 2 to 200 characters').len(2, 200)
if data.url
_v.check(data.url, 'url must be a valid http(s):// url.').isUrl()
if data.text
_v.check(data.text, 'text must be less than 10K characters for now').len(0, 10000)
if data.choices
_v.check(data.choices, 'choices must be less than 10K characters for now').len(0, 10000)
if data.type == 'poll'
choices = data.choices = (data.choices or '').split("\n\n")
if choices.length < 2
throw 'you must enter some choices separated by newlines'
else
if not data.url and not data.text and not data.choices
throw 'you must enter a URL or text'
catch e
render_layout "message", {message: ''+e}, req, res
return
# create new record
recdata = {title: data.title, comment: data.text, created_by: req.current_user.username, upvoters: [req.current_user._id]}
if data.url
recdata.url = data.url
try
recdata.host = utils.url_hostname(data.url)
catch e
recdata.host = 'unknown'
console.log "record with url #{data.url}: couldn't parse the hostname"
else if data.choices
recdata.type = 'poll'
record = logic.records.create_record(recdata)
mongo.records.save record.recdata, (err, stuff) ->
record.recdata = stuff
# if data.choices, then add the choices too
if data.choices
for choice in data.choices
choice_recdata = {comment: choice, created_by: req.current_user.username, type: 'choice'}
choice_record = logic.records.create_record(choice_recdata, record)
mongo.records.save choice_record.recdata, (err, stuff) ->
# nothing to do
# TODO assume it worked.
res.redirect "/r/#{stuff._id}"
else
res.redirect "/r/#{stuff._id}"
]
['/login', (req, res) ->
switch req.method
when 'GET'
res.setCookie 'goto', req.query_data.goto
render_layout "login", {}, req, res
when 'POST'
form_error = (error) ->
render_layout "message", {message: error}, req, res
try
_v.check(req.post_data.username, 'username must be alphanumeric, 2 to 12 characters').len(2,12).isAlphanumeric()
_v.check(req.post_data.password, 'password must be 5 to 1024 characters').len(5,1024)
catch e
form_error(''+e)
return
# get user
mongo.users.findOne username: req.post_data.username, (err, user) ->
if err or not user? or not user.password?
form_error('error, no such user?')
return
# check password
hashtimes = 10000 # runs about 80ms on my laptop
if user.password[0] == utils.passhash(req.post_data.password, user.password[1], hashtimes)
# set the user in session
res.current_user = user
res.redirect req.getCookie('goto') or '/'
else
form_error('wrong password')
return
]
['/password_reset', (req, res) ->
switch req.method
when 'GET'
if not req.query_data.key
# show the email form
render_layout "password_reset", {}, req, res
else
# ask for the password & repeat
mongo.users.findOne username: req.query_data.username, (err, user) ->
if not user
# invalid user
render_layout "message", {message: "Sorry, invalid request"}, req, res
else if user.password_reset_nonce == req.query_data.key
# reset the password
render_layout "password_reset", {user: user}, req, res
else
# wrong key/nonce
render_layout "message", {message: "Sorry, the URL is bad or expired. Check your latest email or try again"}, req, res
when 'POST'
if req.post_data.email
# we got the user's email
mongo.users.findOne email: req.post_data.email, (err, user) ->
if user
res.clearCookie 'user'
logic.mailer.send_password user: user, (err, results) ->
if err?
render_layout "message", {message: "Error sending an email, please try again."}, req, res
return
render_layout "message", {message: "check your email please."}, req, res
else
render_layout "message", {message: "Sorry, unknown email #{req.post_data.email}."}, req, res
return
else if req.post_data.password
# we got the password and all that. do all validation here.
if req.post_data.password != req.post_data.password2
render_layout "message", {message: "Password doesn't match. Go back."}, req, res
return
mongo.users.findOne username: req.post_data.username, (err, user) ->
if user
# ensure that the nonce was actually there.
if not user.password_reset_nonce or user.password_reset_nonce.length < 5 or (user.password_reset_nonce != req.post_data.password_reset_nonce)
render_layout "message", {message: "Invalid request. Check your latest email or try again"}, req, res
return
# ensure good password
if not (5 <= req.post_data.password.length <= 1024)
render_layout "message", {message: "Invalid password. Your password must be between 5 and 1024 characters in length"}, req, res
return
# save this new password and reset/delete the nonce
salt = utils.randid()
hashtimes = 10000 # runs about 80ms on my laptop
user.password = [utils.passhash(req.post_data.password, salt, hashtimes), salt, hashtimes]
delete user.password_reset_nonce
mongo.users.save user, (err, stuff) ->
# set the user in session
res.setSecureCookie 'user', JSON.stringify(user)
res.redirect '/'
else
render_layout "message", {message: "Sorry, unknown user #{req.post_data.username}."}, req, res
return
else
# dunno
res.redirect '/password_reset'
return
]
['/logout', (req, res) ->
switch req.method
when 'GET'
res.clearCookie 'user'
res.redirect '/'
]
# refer someone to the network
[wrappers: [require_login],
'/refer', (req, res) ->
switch req.method
when 'GET'
render_layout "refer", {}, req, res
when 'POST'
try
req.post_data.first_name ||= ''
req.post_data.last_name ||= ''
_v.check(req.post_data.first_name.trim(), 'Please enter the first name of the person you are referring').len(1,100)
_v.check(req.post_data.last_name.trim(), 'Please enter the last name of the person you are referring').len(1, 100)
_v.check(req.post_data.email).isEmail()
catch e
render_layout "message", {message: ''+e}, req, res
return
referral = {first_name: req.post_data.first_name.trim(), last_name: req.post_data.last_name.trim(), email: req.post_data.email, referred_by: req.current_user.username}
logic.referrals.submit referral, (err) ->
if err
render_layout "message", {message: err}, req, res
return
render_layout "message", {message: "Thanks, we'll take it from here."}, req, res
return
]
['/apply', (req, res) ->
switch req.method
when 'GET'
if req.query_data.referral
mongo.referrals.findOne {_id: req.query_data.referral}, (err, referral) ->
render_layout 'apply', {referral: referral}, req, res
else if req.getSecureCookie 'application_id'
mongo.applications.findOne {_id: req.getSecureCookie 'application_id'}, (err, application) ->
render_layout 'apply', {application: application}, req, res
else
render_layout 'apply', {referral: {}}, req, res
when 'POST'
application = {_id: req.post_data.application_id or utils.randid(), created_at: (new Date()), accepted_by: [], denied_by: []}
for key in ['first_name', 'last_name', 'email', 'referral_id', 'website', 'comment']
application[key] = req.post_data[key]
utils.compose (next) ->
if application.referral_id
mongo.referrals.findOne {_id: application.referral_id}, (err, referral) ->
application.referred_by = referral.referred_by
application.accepted_by.push referral.referred_by
next()
else
next()
, () ->
mongo.applications.save application, (err, stuff) ->
if err
render_layout 'message', {message: ''+err}, req, res
return
res.setSecureCookie 'application_id', stuff._id
render_layout 'message', {message: 'Thanks, your application has been saved. We\'ll email you shortly.'}, req, res
]
[wrappers: [require_login],
'/applicants', (req, res) ->
switch req.method
when 'GET'
mongo.applications.find {deleted_at: {$exists: false}, invited_at: {$exists: false}}, {sort: [['created_at', -1]]}, (err, cursor) ->
cursor.toArray (err, applicants) ->
render_layout 'applicants', {applicants: applicants}, req, res
]
[wrappers: [require_login],
'/applicants/:application_id/vote', (req, res) ->
switch req.method
when 'POST'
logic.applications.vote req.path_data.application_id, req.current_user, req.post_data.vote, (err) ->
if err == 'unauthorized'
res.simpleJSON 400, 'unauthorized'
return
if err
req.simpleJSON 500, ''+err
return
res.simpleJSON 200, status: 'ok'
]
['/register', (req, res) ->
switch req.method
when 'GET'
render_layout "register", {invite_code: req.query_data.invite_code, email: req.query_data.email}, req, res
when 'POST'
form_error = (error) ->
render_layout "message", {message: error}, req, res
# validate data
data = req.post_data
try
_v.check(data.username, 'username must be alphanumeric, 2 to 12 characters').len(2,12).isAlphanumeric()
_v.check(data.password, 'password must be 5 to 1024 characters').len(5,1024)
_v.check(data.email).isEmail()
catch e
return form_error(''+e)
if not data.invite?
return form_error("no invite specified")
if data.password != data.password2
return form_error("passwords don't match")
mongo.invites.findOne _id: data.invite, (err, invite) ->
if err or not invite?
form_error("invalid invite")
return
else if invite.claimed_by? and invite.claimed_by.length >= (invite.count or 1)
form_error("invite code already used #{invite.count or 1}")
return
else
# make sure the username isn't already taken
mongo.users.findOne username: data.username, (err, user) ->
if user?
form_error("username '#{data.username}' is already taken. pick another.")
return
# create the user
user = data
user._id = utils.randid()
salt = utils.randid()
hashtimes = 10000 # runs about 80ms on my laptop
user.password = [utils.passhash(user.password, salt, hashtimes), salt, hashtimes]
user.created_at = new Date()
user.application_id = invite.application_id if invite.application_id
mongo.users.save user, (err, stuff) ->
# set the user in session
res.setSecureCookie 'user', JSON.stringify(user)
res.redirect '/'
# update the invite
if invite.claimed_by?
invite.claimed_by.push(user._id)
else
invite.claimed_by = [user._id]
mongo.invites.save invite, (err, stuff) ->
#pass
]
# resets the current_user cookie. for dev and debugging as of now
[wrappers: [require_login],
'/reset_current_user', (req, res) ->
mongo.users.findOne {_id: req.current_user._id}, (err, current_user) ->
res.current_user = current_user
render_layout "message", {message: 'cookie reset!'}, req, res
]
# i'm using this to send an email, too lazy to set up an imap server...
[wrappers: [require_login, require_admin],
'/admin/messages', (req, res) ->
switch req.method
when 'GET'
render_layout 'admin/messages', {}, req, res
when 'POST'
mail = req.post_data
mail.created_at = new Date()
logic.mailer.mail_text mail, (err) ->
render_layout "message", {message: 'Your email has been sent.'}, req, res
# save the email to the db for now
mongo.messages.save mail
]
])
server.listen config.server.port, config.server.host
console.log "Server running at http://#{config.server.host}:#{config.server.port}"
| 81243 | ###
# YCatalyst
# Copyright(c) 2011 <NAME> (<EMAIL>)
# MIT Licensed
###
require.paths.unshift 'vendor'
require.paths.unshift 'vendor/validator'
http = require 'http'
utils = require './utils'
mongo = require './mongo'
fu = require './fu'
rec = require './static/record'
cookie = require 'cookie-node'
_ = require './static/underscore'
_v = require 'validator'
logic = require './logic/logic'
render_layout = logic.templates.render_layout
config = require './config'
cookie.secret = config.cookie_secret
DEFAULT_DEPTH = 5
if true
process.on 'uncaughtException', (err) ->
console.log "XXXXXXXXX"
console.log err.message
console.log err.stack
console.log "XXXXXXXXX FIX THIS ASAP, http://debuggable.com/posts/node-js-dealing-with-uncaught-exceptions:4c933d54-1428-443c-928d-4e1ecbdd56cb"
# a global hash from record id to [callbacks]
all_callbacks = {}
# clear old callbacks
# they can hang around for at most 30 seconds.
setInterval (->
now = new Date()
num_purged = 0
num_seen = 0
for key, callbacks of all_callbacks
num_seen += callbacks.length
while (callbacks.length > 0 && now - callbacks[0].timestamp > 30*1000)
num_purged += 1
callbacks.shift().callback([])
if callbacks.length == 0
delete all_callbacks[key]
if num_purged > 0
console.log "purged #{num_purged} of #{num_seen} in #{new Date() - now}"
), 3000
# given records, tell clients that this record had been updated
# -> if record is new
# -> if record was deleted
# -> if record got voted on
# -> if record has new number of children
#
# TODO we need to keep track of more state
# NOTE it is assumed that the records are in proximity to each other,
# specifically that the union of r.recdata.parents is small in size.
trigger_update = (records) ->
# compute the keys to notify
notify_keys = []
for record in records
if not record.is_new
notify_keys.push(record.recdata._id)
notify_keys = notify_keys.concat(record.recdata.parents or [])
notify_keys = _.uniq(notify_keys)
recdatas = (logic.records.scrubbed_recdata(record) for record in records)
for key in notify_keys
for callback in all_callbacks[key] or []
callback.callback(recdatas)
delete all_callbacks[key]
# wrapper to require current_user
require_login = (req, res, next) ->
if not req.current_user?
res.writeHead 401, status: 'login_error'
res.end 'not logged in'
return
else
next(req, res)
# wrapper generator to require current_user, but also direct them to a login page with a nice message
# message: string or optional
require_login_nice = (message) ->
return (req, res, next) ->
if not req.current_user?
render_layout "login", {message: message or 'You need to login to do that'}, req, res
else
next(req, res)
require_admin = (req, res, next) ->
if not req.current_user.is_admin
res.writeHead 401, status: 'privileges_error'
res.end 'not authorized'
return
else
next(req, res)
server = utils.Rowter([
['/static/:filepath', (req, res) ->
switch req.method
when 'GET'
filepath = req.path_data.filepath
filepath = require('path').join './static/', filepath
if filepath.indexOf('static/') != 0
res.writeHead 404, 'does not exist'
res.end()
else
fu.staticHandler(filepath)(req, res)
]
# get the most viewed sessions
# TODO cache this
['/', (req, res) ->
switch req.method
when 'GET'
#views = logic.sessions.get_viewers()
#rids = (v[0] for v in views)
#mongo.records.find {_id: {$in: rids}}, (err, cursor) ->
mongo.records.find {parent_id: null, deleted_at: {$exists: false}}, {sort: [['score', -1]]}, (err, cursor) ->
cursor.toArray (err, records) ->
if err
console.log err
return
records = (new rec.Record(r) for r in records)
render_layout "index", {records: records}, req, res
]
['/r/:id', (req, res) ->
root_id = req.path_data.id
switch req.method
when 'GET'
# requested from json, just return a single record
if req.headers['x-requested-with'] == 'XMLHttpRequest'
logic.records.get_one_record root_id, (err, record) ->
res.simpleJSON 200, record: logic.records.scrubbed_recdata(record)
return
else
logic.records.get_records root_id, DEFAULT_DEPTH, (err, all) ->
if err? or not all?
res.writeHead 404, status: 'error'
res.end()
return
render_layout "record", {root: logic.records.dangle(all, root_id)}, req, res
when 'POST'
# updating
logic.records.get_one_record root_id, (err, record) ->
if err? or not record?
res.writeHead 404, status: 'error'
res.end()
return
if record.recdata.created_by != req.current_user.username
res.simpleJSON 400, status: 'unauthorized'
return
if not record.recdata.parent_id
record.recdata.title = req.post_data.title
record.recdata.url = req.post_data.url
if req.post_data.url
try
record.recdata.host = utils.url_hostname(req.post_data.url)
catch e
record.recdata.host = 'unknown'
console.log "record with url #{req.post_data.url}: couldn't parse the hostname"
else
delete record.recdata.host
record.recdata.comment = req.post_data.comment
record.recdata.updated_at = new Date()
mongo.records.save record.recdata, (err, stuff) ->
res.simpleJSON 200, status: 'ok', updates: [logic.records.scrubbed_recdata(record)]
trigger_update [record]
]
['/r/:id/watching', (req, res) ->
switch req.method
when 'GET'
rid = req.path_data.id
watching = logic.sessions.get_watching(rid)
res.simpleJSON 200, watching
]
[wrappers: [require_login],
'/r/:id/delete', (req, res) ->
switch req.method
when 'POST'
rid = req.path_data.id
logic.records.get_one_record rid, (err, record) ->
if record
record.recdata.deleted_at = new Date()
record.recdata.deleted_by = req.current_user.username
mongo.records.save record.recdata, (err, stuff) ->
res.simpleJSON 200, status: 'ok'
trigger_update [record]
else
res.writeHead 404, status: 'error'
res.end html
]
[wrappers: [require_login],
'/r/:id/reply', (req, res) ->
switch req.method
when 'GET'
parent_id = req.path_data.id
logic.records.get_one_record parent_id, (err, parent) ->
render_layout "reply", {parent: parent}, req, res
when 'POST'
parent_id = req.path_data.id
comment = req.post_data.comment
logic.records.get_one_record parent_id, (err, parent) ->
if parent
root_id = if parent.recdata.root_id? then parent.recdata.root_id else parent.recdata._id
recdata = _id: utils.randid(), comment: comment, created_by: req.current_user.username, root_id: root_id, upvoters: [req.current_user._id]
if req.post_data.type == 'choice'
# only the parent's creator can add a poll choice
if parent.recdata.created_by != req.current_user.username
res.writeHead 401, status: 'unauthorized'
res.end "I can't let you do that"
return
recdata.type = 'choice'
record = logic.records.create_record(recdata, parent)
mongo.records.save record.recdata, (err, stuff) ->
if req.headers['x-requested-with'] == 'XMLHttpRequest'
res.simpleJSON 200, status: 'ok', updates: [logic.records.scrubbed_recdata(record)]
else
res.writeHead 302, Location: '/r/'+parent_id
res.end()
if record.recdata.type == 'choice'
# we could trigger a live update, but
# needs an update of the process.
trigger_update [record]
else
# update the parent as well, specifically num_children
parent.recdata.num_children += 1
mongo.records.save parent.recdata, (err, stuff) ->
if err
console.err "failed to update parent.num_children: #{parent_id}"
# update the root, num_discussions.
logic.records.get_one_record root_id, (err, root) ->
if err
console.err "failed ot update root.num_discussions: #{root_id}"
return
if not root.recdata.num_discussions?
root.recdata.num_discussions = 1
else
root.recdata.num_discussions += 1
mongo.records.save root.recdata, (err, stuff) ->
if err
console.err "failed to update root.num_discussions: #{root_id}"
# notify clients
trigger_update [parent, record]
else
res.writeHead 404, status: 'error'
res.end html
]
[wrappers: [require_login],
'/r/:key/recv', (req, res) ->
switch req.method
when 'GET'
key = req.path_data.key
if not all_callbacks[key]
all_callbacks[key] = []
all_callbacks[key].push
callback: (recdatas) ->
res.simpleJSON 200, recdatas
timestamp: new Date()
username: req.current_user.username if req.current_user?
if req.current_user?
logic.sessions.touch_session(key, req.current_user.username)
]
[wrappers: [require_login],
'/r/:id/upvote', (req, res) ->
switch req.method
when 'POST'
rid = req.path_data.id
logic.records.get_one_record rid, (err, record) ->
if not record.recdata.upvoters?
record.recdata.upvoters = []
if record.recdata.upvoters.indexOf(req.current_user._id) == -1
record.recdata.upvoters.push(req.current_user._id)
record.recdata.points = record.recdata.upvoters.length
# rescore the record
logic.records.score_record(record)
# save this record
mongo.records.save record.recdata, (err, stuff) ->
res.simpleJSON 200, status: 'ok', updates: [logic.records.scrubbed_recdata(record)]
# notify clients
trigger_update [record]
]
[wrappers: [require_login],
'/r/:id/follow', (req, res) ->
switch req.method
when 'POST'
rid = req.path_data.id
logic.records.follow rid, req.current_user, req.post_data.follow=='true', (err) ->
if err
res.simpleJSON 500, status: 'internal_error'
return
res.simpleJSON 200, status: 'ok'
]
[wrappers: [require_login_nice('You need to log again')],
'/inbox', (req, res) ->
switch req.method
when 'GET'
mongo.records.find {parent_followers: req.current_user._id, created_by: {$ne: req.current_user.username} }, {sort: [['created_at', -1]]}, (err, cursor) ->
cursor.toArray (err, records) ->
if err
console.log err
return
records = (new rec.Record(r) for r in records)
render_layout "inbox", {records: records}, req, res
]
['/users', (req, res) ->
# show all users
switch req.method
when 'GET'
mongo.users.find {}, {sort: [['created_at', -1]]}, (err, cursor) ->
cursor.toArray (err, users) ->
render_layout "users", {users: users}, req, res
]
['/user/:username', (req, res) ->
is_self = req.current_user and req.current_user.username == req.path_data.username
switch req.method
when 'GET'
mongo.users.findOne username: req.path_data.username, (err, user) ->
render_layout "user", {user: user, is_self: is_self}, req, res
when 'POST'
if not is_self
res.writeHead 401, status: 'unauthorized'
res.end 'unauthorized'
return
if req.post_data.bio.length > 10000
render_layout "message", {message: "Your bio is too long. Please keep it under 10K characters."}, req, res
return
mongo.users.update {username: req.path_data.username}, {$set: {bio: req.post_data.bio}}, (err, stuff) ->
if err
render_layout "message", {message: ''+err}, req, res
return
res.redirect req.url
]
['/bookmarklet', (req, res) ->
render_layout "bookmarklet", {}, req, res
]
[wrappers: [require_login_nice('You need to log in to submit')],
'/submit', (req, res) ->
switch req.method
when 'GET'
render_layout "submit", {headerbar_text: 'Submit', type: (req.query_data.type or 'link'), link_title: req.query_data.title, link_url: req.query_data.url}, req, res
when 'POST'
data = req.post_data
# validate data
try
_v.check(data.title, 'title must be 2 to 200 characters').len(2, 200)
if data.url
_v.check(data.url, 'url must be a valid http(s):// url.').isUrl()
if data.text
_v.check(data.text, 'text must be less than 10K characters for now').len(0, 10000)
if data.choices
_v.check(data.choices, 'choices must be less than 10K characters for now').len(0, 10000)
if data.type == 'poll'
choices = data.choices = (data.choices or '').split("\n\n")
if choices.length < 2
throw 'you must enter some choices separated by newlines'
else
if not data.url and not data.text and not data.choices
throw 'you must enter a URL or text'
catch e
render_layout "message", {message: ''+e}, req, res
return
# create new record
recdata = {title: data.title, comment: data.text, created_by: req.current_user.username, upvoters: [req.current_user._id]}
if data.url
recdata.url = data.url
try
recdata.host = utils.url_hostname(data.url)
catch e
recdata.host = 'unknown'
console.log "record with url #{data.url}: couldn't parse the hostname"
else if data.choices
recdata.type = 'poll'
record = logic.records.create_record(recdata)
mongo.records.save record.recdata, (err, stuff) ->
record.recdata = stuff
# if data.choices, then add the choices too
if data.choices
for choice in data.choices
choice_recdata = {comment: choice, created_by: req.current_user.username, type: 'choice'}
choice_record = logic.records.create_record(choice_recdata, record)
mongo.records.save choice_record.recdata, (err, stuff) ->
# nothing to do
# TODO assume it worked.
res.redirect "/r/#{stuff._id}"
else
res.redirect "/r/#{stuff._id}"
]
['/login', (req, res) ->
switch req.method
when 'GET'
res.setCookie 'goto', req.query_data.goto
render_layout "login", {}, req, res
when 'POST'
form_error = (error) ->
render_layout "message", {message: error}, req, res
try
_v.check(req.post_data.username, 'username must be alphanumeric, 2 to 12 characters').len(2,12).isAlphanumeric()
_v.check(req.post_data.password, 'password must be <PASSWORD>').len(5,1024)
catch e
form_error(''+e)
return
# get user
mongo.users.findOne username: req.post_data.username, (err, user) ->
if err or not user? or not user.password?
form_error('error, no such user?')
return
# check password
hashtimes = 10000 # runs about 80ms on my laptop
if user.password[0] == utils.passhash(req.post_data.password, user.password[1], hashtimes)
# set the user in session
res.current_user = user
res.redirect req.getCookie('goto') or '/'
else
form_error('wrong password')
return
]
['/password_reset', (req, res) ->
switch req.method
when 'GET'
if not req.query_data.key
# show the email form
render_layout "password_reset", {}, req, res
else
# ask for the password & repeat
mongo.users.findOne username: req.query_data.username, (err, user) ->
if not user
# invalid user
render_layout "message", {message: "Sorry, invalid request"}, req, res
else if user.password_reset_nonce == req.query_data.key
# reset the password
render_layout "password_reset", {user: user}, req, res
else
# wrong key/nonce
render_layout "message", {message: "Sorry, the URL is bad or expired. Check your latest email or try again"}, req, res
when 'POST'
if req.post_data.email
# we got the user's email
mongo.users.findOne email: req.post_data.email, (err, user) ->
if user
res.clearCookie 'user'
logic.mailer.send_password user: user, (err, results) ->
if err?
render_layout "message", {message: "Error sending an email, please try again."}, req, res
return
render_layout "message", {message: "check your email please."}, req, res
else
render_layout "message", {message: "Sorry, unknown email #{req.post_data.email}."}, req, res
return
else if req.post_data.password
# we got the password and all that. do all validation here.
if req.post_data.password != <PASSWORD>
render_layout "message", {message: "Password doesn't match. Go back."}, req, res
return
mongo.users.findOne username: req.post_data.username, (err, user) ->
if user
# ensure that the nonce was actually there.
if not user.password_reset_nonce or user.password_reset_nonce.length < 5 or (user.password_reset_nonce != req.post_data.password_reset_nonce)
render_layout "message", {message: "Invalid request. Check your latest email or try again"}, req, res
return
# ensure good password
if not (5 <= req.post_data.password.length <= 1024)
render_layout "message", {message: "Invalid password. Your password must be between 5 and 1024 characters in length"}, req, res
return
# save this new password and reset/delete the nonce
salt = utils.randid()
hashtimes = 10000 # runs about 80ms on my laptop
user.password = [utils.passhash(req.post_data.password, salt, hashtimes), salt, hashtimes]
delete user.password_reset_nonce
mongo.users.save user, (err, stuff) ->
# set the user in session
res.setSecureCookie 'user', JSON.stringify(user)
res.redirect '/'
else
render_layout "message", {message: "Sorry, unknown user #{req.post_data.username}."}, req, res
return
else
# dunno
res.redirect '/password_reset'
return
]
['/logout', (req, res) ->
switch req.method
when 'GET'
res.clearCookie 'user'
res.redirect '/'
]
# refer someone to the network
[wrappers: [require_login],
'/refer', (req, res) ->
switch req.method
when 'GET'
render_layout "refer", {}, req, res
when 'POST'
try
req.post_data.first_name ||= ''
req.post_data.last_name ||= ''
_v.check(req.post_data.first_name.trim(), 'Please enter the first name of the person you are referring').len(1,100)
_v.check(req.post_data.last_name.trim(), 'Please enter the last name of the person you are referring').len(1, 100)
_v.check(req.post_data.email).isEmail()
catch e
render_layout "message", {message: ''+e}, req, res
return
referral = {first_name: req.post_data.first_name.trim(), last_name: req.post_data.last_name.trim(), email: req.post_data.email, referred_by: req.current_user.username}
logic.referrals.submit referral, (err) ->
if err
render_layout "message", {message: err}, req, res
return
render_layout "message", {message: "Thanks, we'll take it from here."}, req, res
return
]
['/apply', (req, res) ->
switch req.method
when 'GET'
if req.query_data.referral
mongo.referrals.findOne {_id: req.query_data.referral}, (err, referral) ->
render_layout 'apply', {referral: referral}, req, res
else if req.getSecureCookie 'application_id'
mongo.applications.findOne {_id: req.getSecureCookie 'application_id'}, (err, application) ->
render_layout 'apply', {application: application}, req, res
else
render_layout 'apply', {referral: {}}, req, res
when 'POST'
application = {_id: req.post_data.application_id or utils.randid(), created_at: (new Date()), accepted_by: [], denied_by: []}
for key in ['first_name', 'last_name', 'email', 'referral_id', 'website', 'comment']
application[key] = req.post_data[key]
utils.compose (next) ->
if application.referral_id
mongo.referrals.findOne {_id: application.referral_id}, (err, referral) ->
application.referred_by = referral.referred_by
application.accepted_by.push referral.referred_by
next()
else
next()
, () ->
mongo.applications.save application, (err, stuff) ->
if err
render_layout 'message', {message: ''+err}, req, res
return
res.setSecureCookie 'application_id', stuff._id
render_layout 'message', {message: 'Thanks, your application has been saved. We\'ll email you shortly.'}, req, res
]
[wrappers: [require_login],
'/applicants', (req, res) ->
switch req.method
when 'GET'
mongo.applications.find {deleted_at: {$exists: false}, invited_at: {$exists: false}}, {sort: [['created_at', -1]]}, (err, cursor) ->
cursor.toArray (err, applicants) ->
render_layout 'applicants', {applicants: applicants}, req, res
]
[wrappers: [require_login],
'/applicants/:application_id/vote', (req, res) ->
switch req.method
when 'POST'
logic.applications.vote req.path_data.application_id, req.current_user, req.post_data.vote, (err) ->
if err == 'unauthorized'
res.simpleJSON 400, 'unauthorized'
return
if err
req.simpleJSON 500, ''+err
return
res.simpleJSON 200, status: 'ok'
]
['/register', (req, res) ->
switch req.method
when 'GET'
render_layout "register", {invite_code: req.query_data.invite_code, email: req.query_data.email}, req, res
when 'POST'
form_error = (error) ->
render_layout "message", {message: error}, req, res
# validate data
data = req.post_data
try
_v.check(data.username, 'username must be alphanumeric, 2 to 12 characters').len(2,12).isAlphanumeric()
_v.check(data.password, '<PASSWORD> <PASSWORD>').len(5,1024)
_v.check(data.email).isEmail()
catch e
return form_error(''+e)
if not data.invite?
return form_error("no invite specified")
if data.password != data.<PASSWORD>
return form_error("passwords don't match")
mongo.invites.findOne _id: data.invite, (err, invite) ->
if err or not invite?
form_error("invalid invite")
return
else if invite.claimed_by? and invite.claimed_by.length >= (invite.count or 1)
form_error("invite code already used #{invite.count or 1}")
return
else
# make sure the username isn't already taken
mongo.users.findOne username: data.username, (err, user) ->
if user?
form_error("username '#{data.username}' is already taken. pick another.")
return
# create the user
user = data
user._id = utils.randid()
salt = utils.randid()
hashtimes = 10000 # runs about 80ms on my laptop
user.password = [utils.passhash(user.password, salt, hashtimes), salt, hashtimes]
user.created_at = new Date()
user.application_id = invite.application_id if invite.application_id
mongo.users.save user, (err, stuff) ->
# set the user in session
res.setSecureCookie 'user', JSON.stringify(user)
res.redirect '/'
# update the invite
if invite.claimed_by?
invite.claimed_by.push(user._id)
else
invite.claimed_by = [user._id]
mongo.invites.save invite, (err, stuff) ->
#pass
]
# resets the current_user cookie. for dev and debugging as of now
[wrappers: [require_login],
'/reset_current_user', (req, res) ->
mongo.users.findOne {_id: req.current_user._id}, (err, current_user) ->
res.current_user = current_user
render_layout "message", {message: 'cookie reset!'}, req, res
]
# i'm using this to send an email, too lazy to set up an imap server...
[wrappers: [require_login, require_admin],
'/admin/messages', (req, res) ->
switch req.method
when 'GET'
render_layout 'admin/messages', {}, req, res
when 'POST'
mail = req.post_data
mail.created_at = new Date()
logic.mailer.mail_text mail, (err) ->
render_layout "message", {message: 'Your email has been sent.'}, req, res
# save the email to the db for now
mongo.messages.save mail
]
])
server.listen config.server.port, config.server.host
console.log "Server running at http://#{config.server.host}:#{config.server.port}"
| true | ###
# YCatalyst
# Copyright(c) 2011 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# MIT Licensed
###
require.paths.unshift 'vendor'
require.paths.unshift 'vendor/validator'
http = require 'http'
utils = require './utils'
mongo = require './mongo'
fu = require './fu'
rec = require './static/record'
cookie = require 'cookie-node'
_ = require './static/underscore'
_v = require 'validator'
logic = require './logic/logic'
render_layout = logic.templates.render_layout
config = require './config'
cookie.secret = config.cookie_secret
DEFAULT_DEPTH = 5
if true
process.on 'uncaughtException', (err) ->
console.log "XXXXXXXXX"
console.log err.message
console.log err.stack
console.log "XXXXXXXXX FIX THIS ASAP, http://debuggable.com/posts/node-js-dealing-with-uncaught-exceptions:4c933d54-1428-443c-928d-4e1ecbdd56cb"
# a global hash from record id to [callbacks]
all_callbacks = {}
# clear old callbacks
# they can hang around for at most 30 seconds.
setInterval (->
now = new Date()
num_purged = 0
num_seen = 0
for key, callbacks of all_callbacks
num_seen += callbacks.length
while (callbacks.length > 0 && now - callbacks[0].timestamp > 30*1000)
num_purged += 1
callbacks.shift().callback([])
if callbacks.length == 0
delete all_callbacks[key]
if num_purged > 0
console.log "purged #{num_purged} of #{num_seen} in #{new Date() - now}"
), 3000
# given records, tell clients that this record had been updated
# -> if record is new
# -> if record was deleted
# -> if record got voted on
# -> if record has new number of children
#
# TODO we need to keep track of more state
# NOTE it is assumed that the records are in proximity to each other,
# specifically that the union of r.recdata.parents is small in size.
trigger_update = (records) ->
# compute the keys to notify
notify_keys = []
for record in records
if not record.is_new
notify_keys.push(record.recdata._id)
notify_keys = notify_keys.concat(record.recdata.parents or [])
notify_keys = _.uniq(notify_keys)
recdatas = (logic.records.scrubbed_recdata(record) for record in records)
for key in notify_keys
for callback in all_callbacks[key] or []
callback.callback(recdatas)
delete all_callbacks[key]
# wrapper to require current_user
require_login = (req, res, next) ->
if not req.current_user?
res.writeHead 401, status: 'login_error'
res.end 'not logged in'
return
else
next(req, res)
# wrapper generator to require current_user, but also direct them to a login page with a nice message
# message: string or optional
require_login_nice = (message) ->
return (req, res, next) ->
if not req.current_user?
render_layout "login", {message: message or 'You need to login to do that'}, req, res
else
next(req, res)
require_admin = (req, res, next) ->
if not req.current_user.is_admin
res.writeHead 401, status: 'privileges_error'
res.end 'not authorized'
return
else
next(req, res)
server = utils.Rowter([
['/static/:filepath', (req, res) ->
switch req.method
when 'GET'
filepath = req.path_data.filepath
filepath = require('path').join './static/', filepath
if filepath.indexOf('static/') != 0
res.writeHead 404, 'does not exist'
res.end()
else
fu.staticHandler(filepath)(req, res)
]
# get the most viewed sessions
# TODO cache this
['/', (req, res) ->
switch req.method
when 'GET'
#views = logic.sessions.get_viewers()
#rids = (v[0] for v in views)
#mongo.records.find {_id: {$in: rids}}, (err, cursor) ->
mongo.records.find {parent_id: null, deleted_at: {$exists: false}}, {sort: [['score', -1]]}, (err, cursor) ->
cursor.toArray (err, records) ->
if err
console.log err
return
records = (new rec.Record(r) for r in records)
render_layout "index", {records: records}, req, res
]
['/r/:id', (req, res) ->
root_id = req.path_data.id
switch req.method
when 'GET'
# requested from json, just return a single record
if req.headers['x-requested-with'] == 'XMLHttpRequest'
logic.records.get_one_record root_id, (err, record) ->
res.simpleJSON 200, record: logic.records.scrubbed_recdata(record)
return
else
logic.records.get_records root_id, DEFAULT_DEPTH, (err, all) ->
if err? or not all?
res.writeHead 404, status: 'error'
res.end()
return
render_layout "record", {root: logic.records.dangle(all, root_id)}, req, res
when 'POST'
# updating
logic.records.get_one_record root_id, (err, record) ->
if err? or not record?
res.writeHead 404, status: 'error'
res.end()
return
if record.recdata.created_by != req.current_user.username
res.simpleJSON 400, status: 'unauthorized'
return
if not record.recdata.parent_id
record.recdata.title = req.post_data.title
record.recdata.url = req.post_data.url
if req.post_data.url
try
record.recdata.host = utils.url_hostname(req.post_data.url)
catch e
record.recdata.host = 'unknown'
console.log "record with url #{req.post_data.url}: couldn't parse the hostname"
else
delete record.recdata.host
record.recdata.comment = req.post_data.comment
record.recdata.updated_at = new Date()
mongo.records.save record.recdata, (err, stuff) ->
res.simpleJSON 200, status: 'ok', updates: [logic.records.scrubbed_recdata(record)]
trigger_update [record]
]
['/r/:id/watching', (req, res) ->
switch req.method
when 'GET'
rid = req.path_data.id
watching = logic.sessions.get_watching(rid)
res.simpleJSON 200, watching
]
[wrappers: [require_login],
'/r/:id/delete', (req, res) ->
switch req.method
when 'POST'
rid = req.path_data.id
logic.records.get_one_record rid, (err, record) ->
if record
record.recdata.deleted_at = new Date()
record.recdata.deleted_by = req.current_user.username
mongo.records.save record.recdata, (err, stuff) ->
res.simpleJSON 200, status: 'ok'
trigger_update [record]
else
res.writeHead 404, status: 'error'
res.end html
]
[wrappers: [require_login],
'/r/:id/reply', (req, res) ->
switch req.method
when 'GET'
parent_id = req.path_data.id
logic.records.get_one_record parent_id, (err, parent) ->
render_layout "reply", {parent: parent}, req, res
when 'POST'
parent_id = req.path_data.id
comment = req.post_data.comment
logic.records.get_one_record parent_id, (err, parent) ->
if parent
root_id = if parent.recdata.root_id? then parent.recdata.root_id else parent.recdata._id
recdata = _id: utils.randid(), comment: comment, created_by: req.current_user.username, root_id: root_id, upvoters: [req.current_user._id]
if req.post_data.type == 'choice'
# only the parent's creator can add a poll choice
if parent.recdata.created_by != req.current_user.username
res.writeHead 401, status: 'unauthorized'
res.end "I can't let you do that"
return
recdata.type = 'choice'
record = logic.records.create_record(recdata, parent)
mongo.records.save record.recdata, (err, stuff) ->
if req.headers['x-requested-with'] == 'XMLHttpRequest'
res.simpleJSON 200, status: 'ok', updates: [logic.records.scrubbed_recdata(record)]
else
res.writeHead 302, Location: '/r/'+parent_id
res.end()
if record.recdata.type == 'choice'
# we could trigger a live update, but
# needs an update of the process.
trigger_update [record]
else
# update the parent as well, specifically num_children
parent.recdata.num_children += 1
mongo.records.save parent.recdata, (err, stuff) ->
if err
console.err "failed to update parent.num_children: #{parent_id}"
# update the root, num_discussions.
logic.records.get_one_record root_id, (err, root) ->
if err
console.err "failed ot update root.num_discussions: #{root_id}"
return
if not root.recdata.num_discussions?
root.recdata.num_discussions = 1
else
root.recdata.num_discussions += 1
mongo.records.save root.recdata, (err, stuff) ->
if err
console.err "failed to update root.num_discussions: #{root_id}"
# notify clients
trigger_update [parent, record]
else
res.writeHead 404, status: 'error'
res.end html
]
[wrappers: [require_login],
'/r/:key/recv', (req, res) ->
switch req.method
when 'GET'
key = req.path_data.key
if not all_callbacks[key]
all_callbacks[key] = []
all_callbacks[key].push
callback: (recdatas) ->
res.simpleJSON 200, recdatas
timestamp: new Date()
username: req.current_user.username if req.current_user?
if req.current_user?
logic.sessions.touch_session(key, req.current_user.username)
]
[wrappers: [require_login],
'/r/:id/upvote', (req, res) ->
switch req.method
when 'POST'
rid = req.path_data.id
logic.records.get_one_record rid, (err, record) ->
if not record.recdata.upvoters?
record.recdata.upvoters = []
if record.recdata.upvoters.indexOf(req.current_user._id) == -1
record.recdata.upvoters.push(req.current_user._id)
record.recdata.points = record.recdata.upvoters.length
# rescore the record
logic.records.score_record(record)
# save this record
mongo.records.save record.recdata, (err, stuff) ->
res.simpleJSON 200, status: 'ok', updates: [logic.records.scrubbed_recdata(record)]
# notify clients
trigger_update [record]
]
[wrappers: [require_login],
'/r/:id/follow', (req, res) ->
switch req.method
when 'POST'
rid = req.path_data.id
logic.records.follow rid, req.current_user, req.post_data.follow=='true', (err) ->
if err
res.simpleJSON 500, status: 'internal_error'
return
res.simpleJSON 200, status: 'ok'
]
[wrappers: [require_login_nice('You need to log again')],
'/inbox', (req, res) ->
switch req.method
when 'GET'
mongo.records.find {parent_followers: req.current_user._id, created_by: {$ne: req.current_user.username} }, {sort: [['created_at', -1]]}, (err, cursor) ->
cursor.toArray (err, records) ->
if err
console.log err
return
records = (new rec.Record(r) for r in records)
render_layout "inbox", {records: records}, req, res
]
['/users', (req, res) ->
# show all users
switch req.method
when 'GET'
mongo.users.find {}, {sort: [['created_at', -1]]}, (err, cursor) ->
cursor.toArray (err, users) ->
render_layout "users", {users: users}, req, res
]
['/user/:username', (req, res) ->
is_self = req.current_user and req.current_user.username == req.path_data.username
switch req.method
when 'GET'
mongo.users.findOne username: req.path_data.username, (err, user) ->
render_layout "user", {user: user, is_self: is_self}, req, res
when 'POST'
if not is_self
res.writeHead 401, status: 'unauthorized'
res.end 'unauthorized'
return
if req.post_data.bio.length > 10000
render_layout "message", {message: "Your bio is too long. Please keep it under 10K characters."}, req, res
return
mongo.users.update {username: req.path_data.username}, {$set: {bio: req.post_data.bio}}, (err, stuff) ->
if err
render_layout "message", {message: ''+err}, req, res
return
res.redirect req.url
]
['/bookmarklet', (req, res) ->
render_layout "bookmarklet", {}, req, res
]
[wrappers: [require_login_nice('You need to log in to submit')],
'/submit', (req, res) ->
switch req.method
when 'GET'
render_layout "submit", {headerbar_text: 'Submit', type: (req.query_data.type or 'link'), link_title: req.query_data.title, link_url: req.query_data.url}, req, res
when 'POST'
data = req.post_data
# validate data
try
_v.check(data.title, 'title must be 2 to 200 characters').len(2, 200)
if data.url
_v.check(data.url, 'url must be a valid http(s):// url.').isUrl()
if data.text
_v.check(data.text, 'text must be less than 10K characters for now').len(0, 10000)
if data.choices
_v.check(data.choices, 'choices must be less than 10K characters for now').len(0, 10000)
if data.type == 'poll'
choices = data.choices = (data.choices or '').split("\n\n")
if choices.length < 2
throw 'you must enter some choices separated by newlines'
else
if not data.url and not data.text and not data.choices
throw 'you must enter a URL or text'
catch e
render_layout "message", {message: ''+e}, req, res
return
# create new record
recdata = {title: data.title, comment: data.text, created_by: req.current_user.username, upvoters: [req.current_user._id]}
if data.url
recdata.url = data.url
try
recdata.host = utils.url_hostname(data.url)
catch e
recdata.host = 'unknown'
console.log "record with url #{data.url}: couldn't parse the hostname"
else if data.choices
recdata.type = 'poll'
record = logic.records.create_record(recdata)
mongo.records.save record.recdata, (err, stuff) ->
record.recdata = stuff
# if data.choices, then add the choices too
if data.choices
for choice in data.choices
choice_recdata = {comment: choice, created_by: req.current_user.username, type: 'choice'}
choice_record = logic.records.create_record(choice_recdata, record)
mongo.records.save choice_record.recdata, (err, stuff) ->
# nothing to do
# TODO assume it worked.
res.redirect "/r/#{stuff._id}"
else
res.redirect "/r/#{stuff._id}"
]
['/login', (req, res) ->
switch req.method
when 'GET'
res.setCookie 'goto', req.query_data.goto
render_layout "login", {}, req, res
when 'POST'
form_error = (error) ->
render_layout "message", {message: error}, req, res
try
_v.check(req.post_data.username, 'username must be alphanumeric, 2 to 12 characters').len(2,12).isAlphanumeric()
_v.check(req.post_data.password, 'password must be PI:PASSWORD:<PASSWORD>END_PI').len(5,1024)
catch e
form_error(''+e)
return
# get user
mongo.users.findOne username: req.post_data.username, (err, user) ->
if err or not user? or not user.password?
form_error('error, no such user?')
return
# check password
hashtimes = 10000 # runs about 80ms on my laptop
if user.password[0] == utils.passhash(req.post_data.password, user.password[1], hashtimes)
# set the user in session
res.current_user = user
res.redirect req.getCookie('goto') or '/'
else
form_error('wrong password')
return
]
['/password_reset', (req, res) ->
switch req.method
when 'GET'
if not req.query_data.key
# show the email form
render_layout "password_reset", {}, req, res
else
# ask for the password & repeat
mongo.users.findOne username: req.query_data.username, (err, user) ->
if not user
# invalid user
render_layout "message", {message: "Sorry, invalid request"}, req, res
else if user.password_reset_nonce == req.query_data.key
# reset the password
render_layout "password_reset", {user: user}, req, res
else
# wrong key/nonce
render_layout "message", {message: "Sorry, the URL is bad or expired. Check your latest email or try again"}, req, res
when 'POST'
if req.post_data.email
# we got the user's email
mongo.users.findOne email: req.post_data.email, (err, user) ->
if user
res.clearCookie 'user'
logic.mailer.send_password user: user, (err, results) ->
if err?
render_layout "message", {message: "Error sending an email, please try again."}, req, res
return
render_layout "message", {message: "check your email please."}, req, res
else
render_layout "message", {message: "Sorry, unknown email #{req.post_data.email}."}, req, res
return
else if req.post_data.password
# we got the password and all that. do all validation here.
if req.post_data.password != PI:PASSWORD:<PASSWORD>END_PI
render_layout "message", {message: "Password doesn't match. Go back."}, req, res
return
mongo.users.findOne username: req.post_data.username, (err, user) ->
if user
# ensure that the nonce was actually there.
if not user.password_reset_nonce or user.password_reset_nonce.length < 5 or (user.password_reset_nonce != req.post_data.password_reset_nonce)
render_layout "message", {message: "Invalid request. Check your latest email or try again"}, req, res
return
# ensure good password
if not (5 <= req.post_data.password.length <= 1024)
render_layout "message", {message: "Invalid password. Your password must be between 5 and 1024 characters in length"}, req, res
return
# save this new password and reset/delete the nonce
salt = utils.randid()
hashtimes = 10000 # runs about 80ms on my laptop
user.password = [utils.passhash(req.post_data.password, salt, hashtimes), salt, hashtimes]
delete user.password_reset_nonce
mongo.users.save user, (err, stuff) ->
# set the user in session
res.setSecureCookie 'user', JSON.stringify(user)
res.redirect '/'
else
render_layout "message", {message: "Sorry, unknown user #{req.post_data.username}."}, req, res
return
else
# dunno
res.redirect '/password_reset'
return
]
['/logout', (req, res) ->
switch req.method
when 'GET'
res.clearCookie 'user'
res.redirect '/'
]
# refer someone to the network
[wrappers: [require_login],
'/refer', (req, res) ->
switch req.method
when 'GET'
render_layout "refer", {}, req, res
when 'POST'
try
req.post_data.first_name ||= ''
req.post_data.last_name ||= ''
_v.check(req.post_data.first_name.trim(), 'Please enter the first name of the person you are referring').len(1,100)
_v.check(req.post_data.last_name.trim(), 'Please enter the last name of the person you are referring').len(1, 100)
_v.check(req.post_data.email).isEmail()
catch e
render_layout "message", {message: ''+e}, req, res
return
referral = {first_name: req.post_data.first_name.trim(), last_name: req.post_data.last_name.trim(), email: req.post_data.email, referred_by: req.current_user.username}
logic.referrals.submit referral, (err) ->
if err
render_layout "message", {message: err}, req, res
return
render_layout "message", {message: "Thanks, we'll take it from here."}, req, res
return
]
['/apply', (req, res) ->
switch req.method
when 'GET'
if req.query_data.referral
mongo.referrals.findOne {_id: req.query_data.referral}, (err, referral) ->
render_layout 'apply', {referral: referral}, req, res
else if req.getSecureCookie 'application_id'
mongo.applications.findOne {_id: req.getSecureCookie 'application_id'}, (err, application) ->
render_layout 'apply', {application: application}, req, res
else
render_layout 'apply', {referral: {}}, req, res
when 'POST'
application = {_id: req.post_data.application_id or utils.randid(), created_at: (new Date()), accepted_by: [], denied_by: []}
for key in ['first_name', 'last_name', 'email', 'referral_id', 'website', 'comment']
application[key] = req.post_data[key]
utils.compose (next) ->
if application.referral_id
mongo.referrals.findOne {_id: application.referral_id}, (err, referral) ->
application.referred_by = referral.referred_by
application.accepted_by.push referral.referred_by
next()
else
next()
, () ->
mongo.applications.save application, (err, stuff) ->
if err
render_layout 'message', {message: ''+err}, req, res
return
res.setSecureCookie 'application_id', stuff._id
render_layout 'message', {message: 'Thanks, your application has been saved. We\'ll email you shortly.'}, req, res
]
[wrappers: [require_login],
'/applicants', (req, res) ->
switch req.method
when 'GET'
mongo.applications.find {deleted_at: {$exists: false}, invited_at: {$exists: false}}, {sort: [['created_at', -1]]}, (err, cursor) ->
cursor.toArray (err, applicants) ->
render_layout 'applicants', {applicants: applicants}, req, res
]
[wrappers: [require_login],
'/applicants/:application_id/vote', (req, res) ->
switch req.method
when 'POST'
logic.applications.vote req.path_data.application_id, req.current_user, req.post_data.vote, (err) ->
if err == 'unauthorized'
res.simpleJSON 400, 'unauthorized'
return
if err
req.simpleJSON 500, ''+err
return
res.simpleJSON 200, status: 'ok'
]
['/register', (req, res) ->
switch req.method
when 'GET'
render_layout "register", {invite_code: req.query_data.invite_code, email: req.query_data.email}, req, res
when 'POST'
form_error = (error) ->
render_layout "message", {message: error}, req, res
# validate data
data = req.post_data
try
_v.check(data.username, 'username must be alphanumeric, 2 to 12 characters').len(2,12).isAlphanumeric()
_v.check(data.password, 'PI:PASSWORD:<PASSWORD>END_PI PI:PASSWORD:<PASSWORD>END_PI').len(5,1024)
_v.check(data.email).isEmail()
catch e
return form_error(''+e)
if not data.invite?
return form_error("no invite specified")
if data.password != data.PI:PASSWORD:<PASSWORD>END_PI
return form_error("passwords don't match")
mongo.invites.findOne _id: data.invite, (err, invite) ->
if err or not invite?
form_error("invalid invite")
return
else if invite.claimed_by? and invite.claimed_by.length >= (invite.count or 1)
form_error("invite code already used #{invite.count or 1}")
return
else
# make sure the username isn't already taken
mongo.users.findOne username: data.username, (err, user) ->
if user?
form_error("username '#{data.username}' is already taken. pick another.")
return
# create the user
user = data
user._id = utils.randid()
salt = utils.randid()
hashtimes = 10000 # runs about 80ms on my laptop
user.password = [utils.passhash(user.password, salt, hashtimes), salt, hashtimes]
user.created_at = new Date()
user.application_id = invite.application_id if invite.application_id
mongo.users.save user, (err, stuff) ->
# set the user in session
res.setSecureCookie 'user', JSON.stringify(user)
res.redirect '/'
# update the invite
if invite.claimed_by?
invite.claimed_by.push(user._id)
else
invite.claimed_by = [user._id]
mongo.invites.save invite, (err, stuff) ->
#pass
]
# resets the current_user cookie. for dev and debugging as of now
[wrappers: [require_login],
'/reset_current_user', (req, res) ->
mongo.users.findOne {_id: req.current_user._id}, (err, current_user) ->
res.current_user = current_user
render_layout "message", {message: 'cookie reset!'}, req, res
]
# i'm using this to send an email, too lazy to set up an imap server...
[wrappers: [require_login, require_admin],
'/admin/messages', (req, res) ->
switch req.method
when 'GET'
render_layout 'admin/messages', {}, req, res
when 'POST'
mail = req.post_data
mail.created_at = new Date()
logic.mailer.mail_text mail, (err) ->
render_layout "message", {message: 'Your email has been sent.'}, req, res
# save the email to the db for now
mongo.messages.save mail
]
])
server.listen config.server.port, config.server.host
console.log "Server running at http://#{config.server.host}:#{config.server.port}"
|
[
{
"context": "###################################\n#\n# Created by Markus\n#\n###############################################",
"end": 77,
"score": 0.9990465641021729,
"start": 71,
"tag": "NAME",
"value": "Markus"
}
] | server/1_collections/_collections.coffee | agottschalk10/worklearn | 0 | #######################################################
#
# Created by Markus
#
#######################################################
#######################################################
@Secrets = new Mongo.Collection("secrets")
@Logging = new Mongo.Collection("logging")
| 53895 | #######################################################
#
# Created by <NAME>
#
#######################################################
#######################################################
@Secrets = new Mongo.Collection("secrets")
@Logging = new Mongo.Collection("logging")
| true | #######################################################
#
# Created by PI:NAME:<NAME>END_PI
#
#######################################################
#######################################################
@Secrets = new Mongo.Collection("secrets")
@Logging = new Mongo.Collection("logging")
|
[
{
"context": "essage + person\n\t\n# framerSaysHelloWorld(string, 'Laine')\n\nsayHi = (message) ->\n\tprint message\n\n# sayHi(s",
"end": 391,
"score": 0.9959349632263184,
"start": 386,
"tag": "NAME",
"value": "Laine"
}
] | prototypes/framerBasics.framer/app.coffee | davo/FramerNYCMeetup | 7 | # 1. CofeeScript Basics (spaces, vars, functions, comments)
# 2. BackgroundLayer
# 3. Layer Properties, Centering
# 4. Draggable
# 5. Constraints Layer, Frame
# 6. Set Constraints, Events
# 7. States / Animation
# This is a comment
# Variables
string = "Hello there, "
number = 42
framerSaysHelloWorld = (message, person) ->
print message + person
# framerSaysHelloWorld(string, 'Laine')
sayHi = (message) ->
print message
# sayHi(string)
# Set background
Canvas.backgroundColor = "rgba(0, 85, 255, 0.9)"
# Layers are the building blocks for pretty much everything in Framer.
# Create layer
layerA = new Layer
backgroundColor: "#fff"
borderRadius: 4
opacity: 0
scale: 0.5
# Center layer
layerA.center()
# Trigger animation with a delay
Utils.delay 0.5, ->
layerA.animate
opacity: 0.9
scale: 1
# Create a new state
layerA.states =
changeColor:
rotation: 0
scale: 0.5
backgroundColor: "red"
rotateAndChangeColor:
rotation: 180
backgroundColor: "white"
# Utils.delay 0.5, ->
# layerA.animate "changeColor"
# layerA.onAnimationEnd ->
# layerA.animate "rotateAndChangeColor"
# layerA.onTap ->
# layerA.animate "changeColor"
# layerA.onAnimationEnd ->
# layerA.animate "rotateAndChangeColor"
# Enable dragging
layerA.draggable.enabled = true
# Create constraints layer
constraints = new Layer
backgroundColor: "rgba(255,255,255,0.2)"
width: Screen.width
height: Screen.height
borderRadius: 8
constraints.center()
# print constraints.frame
# Set constraints
# Frame: x, y, width, height
layerA.draggable.constraints = constraints.frame | 167586 | # 1. CofeeScript Basics (spaces, vars, functions, comments)
# 2. BackgroundLayer
# 3. Layer Properties, Centering
# 4. Draggable
# 5. Constraints Layer, Frame
# 6. Set Constraints, Events
# 7. States / Animation
# This is a comment
# Variables
string = "Hello there, "
number = 42
framerSaysHelloWorld = (message, person) ->
print message + person
# framerSaysHelloWorld(string, '<NAME>')
sayHi = (message) ->
print message
# sayHi(string)
# Set background
Canvas.backgroundColor = "rgba(0, 85, 255, 0.9)"
# Layers are the building blocks for pretty much everything in Framer.
# Create layer
layerA = new Layer
backgroundColor: "#fff"
borderRadius: 4
opacity: 0
scale: 0.5
# Center layer
layerA.center()
# Trigger animation with a delay
Utils.delay 0.5, ->
layerA.animate
opacity: 0.9
scale: 1
# Create a new state
layerA.states =
changeColor:
rotation: 0
scale: 0.5
backgroundColor: "red"
rotateAndChangeColor:
rotation: 180
backgroundColor: "white"
# Utils.delay 0.5, ->
# layerA.animate "changeColor"
# layerA.onAnimationEnd ->
# layerA.animate "rotateAndChangeColor"
# layerA.onTap ->
# layerA.animate "changeColor"
# layerA.onAnimationEnd ->
# layerA.animate "rotateAndChangeColor"
# Enable dragging
layerA.draggable.enabled = true
# Create constraints layer
constraints = new Layer
backgroundColor: "rgba(255,255,255,0.2)"
width: Screen.width
height: Screen.height
borderRadius: 8
constraints.center()
# print constraints.frame
# Set constraints
# Frame: x, y, width, height
layerA.draggable.constraints = constraints.frame | true | # 1. CofeeScript Basics (spaces, vars, functions, comments)
# 2. BackgroundLayer
# 3. Layer Properties, Centering
# 4. Draggable
# 5. Constraints Layer, Frame
# 6. Set Constraints, Events
# 7. States / Animation
# This is a comment
# Variables
string = "Hello there, "
number = 42
framerSaysHelloWorld = (message, person) ->
print message + person
# framerSaysHelloWorld(string, 'PI:NAME:<NAME>END_PI')
sayHi = (message) ->
print message
# sayHi(string)
# Set background
Canvas.backgroundColor = "rgba(0, 85, 255, 0.9)"
# Layers are the building blocks for pretty much everything in Framer.
# Create layer
layerA = new Layer
backgroundColor: "#fff"
borderRadius: 4
opacity: 0
scale: 0.5
# Center layer
layerA.center()
# Trigger animation with a delay
Utils.delay 0.5, ->
layerA.animate
opacity: 0.9
scale: 1
# Create a new state
layerA.states =
changeColor:
rotation: 0
scale: 0.5
backgroundColor: "red"
rotateAndChangeColor:
rotation: 180
backgroundColor: "white"
# Utils.delay 0.5, ->
# layerA.animate "changeColor"
# layerA.onAnimationEnd ->
# layerA.animate "rotateAndChangeColor"
# layerA.onTap ->
# layerA.animate "changeColor"
# layerA.onAnimationEnd ->
# layerA.animate "rotateAndChangeColor"
# Enable dragging
layerA.draggable.enabled = true
# Create constraints layer
constraints = new Layer
backgroundColor: "rgba(255,255,255,0.2)"
width: Screen.width
height: Screen.height
borderRadius: 8
constraints.center()
# print constraints.frame
# Set constraints
# Frame: x, y, width, height
layerA.draggable.constraints = constraints.frame |
[
{
"context": "utils'\ncsv = require 'csv-parser'\n\nCHANNEL_KEY = 'OrderXmlFileExport'\n\nargv = utils.getDefaultOptions()\n .describe('s",
"end": 387,
"score": 0.9519387483596802,
"start": 369,
"tag": "KEY",
"value": "OrderXmlFileExport"
},
{
"context": "ials,\n host: sftpHost\n username: sftpUsername\n password: sftpPassword\n sftpTa",
"end": 6655,
"score": 0.7945821285247803,
"start": 6643,
"tag": "USERNAME",
"value": "sftpUsername"
},
{
"context": " username: sftpUsername\n password: sftpPassword\n sftpTarget: argv.sftpTarget\n\n th",
"end": 6688,
"score": 0.9959028363227844,
"start": 6676,
"tag": "PASSWORD",
"value": "sftpPassword"
},
{
"context": " new Sftp\n host: host\n username: username\n password: password\n logger: lo",
"end": 6992,
"score": 0.9965384602546692,
"start": 6984,
"tag": "USERNAME",
"value": "username"
},
{
"context": "t\n username: username\n password: password\n logger: logger\n\n sftpClient.open",
"end": 7021,
"score": 0.9980782270431519,
"start": 7013,
"tag": "PASSWORD",
"value": "password"
}
] | src/coffee/run.coffee | celeste-horgan/sphere-order-export | 3 | path = require 'path'
_ = require 'underscore'
Promise = require 'bluebird'
fs = Promise.promisifyAll require('fs')
tmp = Promise.promisifyAll require('tmp')
{ProjectCredentialsConfig, Sftp} = require 'sphere-node-utils'
package_json = require '../package.json'
OrderExport = require './orderexport'
utils = require './utils'
csv = require 'csv-parser'
CHANNEL_KEY = 'OrderXmlFileExport'
argv = utils.getDefaultOptions()
.describe('standardShippingMethod', 'Allows to define the fallback shipping method name if order has none')
.describe('exportUnsyncedOnly', 'whether only unsynced orders will be exported or not')
.describe('useExportTmpDir', 'whether to use a system tmp folder to store exported files')
.describe('csvTemplate', 'CSV template to define the structure of the export')
.describe('createSyncActions', 'upload syncInfo update actions for orders exported (only supports sftp upload')
.describe('fileWithTimestamp', 'whether exported file should contain a timestamp')
.describe('sftpCredentials', 'the path to a JSON file where to read the credentials from')
.describe('sftpHost', 'the SFTP host (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpUsername', 'the SFTP username (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpPassword', 'the SFTP password (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpTarget', 'path in the SFTP server to where to move the worked files')
.describe('sftpContinueOnProblems', 'ignore errors when processing a file and continue with the next one')
.describe('where', 'where predicate used to filter orders exported. More info here http://dev.commercetools.com/http-api.html#predicates')
.describe('fillAllRows', 'fill all rows')
.describe('exportCSVAsStream', 'Exports CSV as stream (to use for performance reasons)')
.default('standardShippingMethod', 'None')
.default('exportUnsyncedOnly', true)
.default('useExportTmpDir', false)
.default('createSyncActions', false)
.default('sftpContinueOnProblems', false)
.default('fillAllRows', false)
.default('exportCSVAsStream', false)
.argv
logger = utils.getLogger(argv)
process.on 'SIGUSR2', -> logger.reopenFileStreams()
process.on 'exit', => process.exit(@exitCode)
tmp.setGracefulCleanup()
fsExistsAsync = (path) ->
new Promise (resolve, reject) ->
fs.exists path, (exists) ->
if exists
resolve(true)
else
resolve(false)
ensureExportDir = ->
if "#{argv.useExportTmpDir}" is 'true'
# unsafeCleanup: recursively removes the created temporary directory, even when it's not empty
tmp.dirAsync {unsafeCleanup: true}
.then (tmpDir) ->
# tmp module returns an array with path to tmpDir and a cleanup function
# here we return only the path to tmpDir
tmpDir[0]
else
exportsPath = argv.targetDir
fsExistsAsync(exportsPath)
.then (exists) ->
if exists
Promise.resolve(exportsPath)
else
fs.mkdirAsync(exportsPath)
.then -> Promise.resolve(exportsPath)
readJsonFromPath = (path) ->
return Promise.resolve({}) unless path
fs.readFileAsync(path, {encoding: 'utf-8'}).then (content) ->
Promise.resolve JSON.parse(content)
exportCSVAsStream = (csvFile, orderExport) ->
new Promise (resolve, reject) ->
output = fs.createWriteStream csvFile, {encoding: 'utf-8'}
output.on 'error', (error) -> reject error
output.on 'finish', -> resolve()
orderExport.runCSVAndStreamToFile (data) =>
process.stdout.write('.')
output.write "#{data}\n"
Promise.resolve()
.then () ->
process.stdout.write('\n')
output.end()
.catch (e) -> reject(e)
createSyncOrders = (fileName) ->
logger.debug "Creating order objects with sync Information"
new Promise (resolve, reject) ->
orders = []
orderNumberMap = {}
fs.createReadStream(fileName)
.pipe(csv())
.on('data', (data) ->
if data.orderNumber and not orderNumberMap[data.orderNumber]
order =
orderNumber: data.orderNumber
syncInfo: [{
externalId: fileName
channel: CHANNEL_KEY
}]
orders.push(order)
orderNumberMap[data.orderNumber] = true
)
.on('end', () ->
logger.info "SyncInfo generated #{JSON.stringify(orders)}"
resolve(orders)
)
.on 'error', (err) ->
reject(err)
utils.ensureCredentials(argv)
.then (credentials) =>
exportType = if argv.csvTemplate then 'csv' else 'xml'
orderExport = new OrderExport
client: utils.getClientOptions(credentials, argv)
export:
perPage: argv.perPage
standardShippingMethod: argv.standardShippingMethod
exportType: exportType
exportUnsyncedOnly: argv.exportUnsyncedOnly
csvTemplate: argv.csvTemplate
fillAllRows: argv.fillAllRows
where: argv.where
ensureExportDir()
.then (outputDir) =>
logger.debug "Created output dir at #{outputDir}"
@outputDir = outputDir
fileName = utils.getFileName argv.fileWithTimestamp, 'orders'
csvFile = "#{@outputDir}/#{fileName}"
if argv.exportCSVAsStream
logger.info "Exporting orders as a stream."
exportCSVAsStream(csvFile, orderExport)
else
orderExport.run()
.then (data) =>
# TODO: xml export
# - one file for all (default)
# - one file for each order
@orderReferences = []
if exportType.toLowerCase() is 'csv'
logger.info "Storing CSV export to '#{csvFile}'."
@orderReferences.push fileName: csvFile, entry: data
fs.writeFileAsync csvFile, data
else
logger.info "Storing #{_.size data} file(s) to '#{@outputDir}'."
ts = (new Date()).getTime()
Promise.map data, (entry) =>
content = entry.xml.end(pretty: true, indent: ' ', newline: '\n')
if argv.fileWithTimestamp
fileName = "#{entry.id}_#{ts}.xml"
else
fileName = "#{entry.id}.xml"
@orderReferences.push name: fileName, entry: entry
fs.writeFileAsync "#{@outputDir}/#{fileName}", content
, {concurrency: 10}
.then =>
{sftpCredentials, sftpHost, sftpUsername, sftpPassword} = argv
if sftpCredentials or (sftpHost and sftpUsername and sftpPassword)
readJsonFromPath(sftpCredentials)
.then (credentials) =>
projectSftpCredentials = credentials[argv.projectKey] or {}
{host, username, password, sftpTarget} = _.defaults projectSftpCredentials,
host: sftpHost
username: sftpUsername
password: sftpPassword
sftpTarget: argv.sftpTarget
throw new Error 'Missing sftp host' unless host
throw new Error 'Missing sftp username' unless username
throw new Error 'Missing sftp password' unless password
sftpClient = new Sftp
host: host
username: username
password: password
logger: logger
sftpClient.openSftp()
.then (sftp) =>
fs.readdirAsync(@outputDir)
.then (files) =>
logger.info "About to upload #{_.size files} file(s) from #{@outputDir} to #{sftpTarget}"
filesSkipped = 0
Promise.map files, (filename) =>
logger.debug "Uploading #{@outputDir}/#{filename}"
if not orderExport.ordersExported
return Promise.resolve()
sftpClient.safePutFile(sftp, "#{@outputDir}/#{filename}", "#{sftpTarget}/#{filename}")
.then =>
if exportType.toLowerCase() is 'csv' and argv.createSyncActions
createSyncOrders(@orderReferences[0].fileName)
.then (orders) =>
if orders.length
if argv.fileWithTimestamp
ts = (new Date()).getTime()
ordersFileJSON = "orders_sync_#{ts}.json"
else
ordersFileJSON = 'orders_sync.json'
fs.writeFileAsync("#{@outputDir}/#{ordersFileJSON}", JSON.stringify(orders,null,2)).then =>
logger.debug "Uploading #{@outputDir}/#{ordersFileJSON}"
sftpClient.safePutFile(sftp, "#{@outputDir}/#{ordersFileJSON}", "#{sftpTarget}/#{ordersFileJSON}")
else
logger.debug "No orders: #{JSON.stringify(orders, null, 2)} exported, no orders sync action to be set."
Promise.resolve()
else
xml = _.find @orderReferences, (r) -> r.name is filename
if xml
logger.debug "About to sync order #{filename}"
orderExport.syncOrder xml.entry, filename
else
logger.warn "Not able to create syncInfo for #{filename} as xml for that file was not found"
Promise.resolve()
.catch (err) ->
if argv.sftpContinueOnProblems
filesSkipped++
logger.warn err, "There was an error processing the file #{file}, skipping and continue"
Promise.resolve()
else
Promise.reject err
, {concurrency: 1}
.then ->
totFiles = _.size(files)
if totFiles > 0
logger.info "Export to SFTP successfully finished: #{totFiles - filesSkipped} out of #{totFiles} files were processed"
else
logger.info "Export successfully finished: there were no new files to be processed"
sftpClient.close(sftp)
Promise.resolve()
.finally -> sftpClient.close(sftp)
.catch (err) =>
logger.error err, 'There was an error uploading the files to SFTP'
@exitCode = 1
.catch (err) =>
logger.error err, "Problems on getting sftp credentials from config files for project #{argv.projectKey}."
@exitCode = 1
else
Promise.resolve() # no sftp
.then =>
logger.info 'Orders export complete'
@exitCode = 0
.catch (error) =>
logger.error error, 'Oops, something went wrong!'
@exitCode = 1
.catch (err) =>
logger.error err, 'Problems on getting client credentials from config files.'
@exitCode = 1
| 191607 | path = require 'path'
_ = require 'underscore'
Promise = require 'bluebird'
fs = Promise.promisifyAll require('fs')
tmp = Promise.promisifyAll require('tmp')
{ProjectCredentialsConfig, Sftp} = require 'sphere-node-utils'
package_json = require '../package.json'
OrderExport = require './orderexport'
utils = require './utils'
csv = require 'csv-parser'
CHANNEL_KEY = '<KEY>'
argv = utils.getDefaultOptions()
.describe('standardShippingMethod', 'Allows to define the fallback shipping method name if order has none')
.describe('exportUnsyncedOnly', 'whether only unsynced orders will be exported or not')
.describe('useExportTmpDir', 'whether to use a system tmp folder to store exported files')
.describe('csvTemplate', 'CSV template to define the structure of the export')
.describe('createSyncActions', 'upload syncInfo update actions for orders exported (only supports sftp upload')
.describe('fileWithTimestamp', 'whether exported file should contain a timestamp')
.describe('sftpCredentials', 'the path to a JSON file where to read the credentials from')
.describe('sftpHost', 'the SFTP host (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpUsername', 'the SFTP username (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpPassword', 'the SFTP password (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpTarget', 'path in the SFTP server to where to move the worked files')
.describe('sftpContinueOnProblems', 'ignore errors when processing a file and continue with the next one')
.describe('where', 'where predicate used to filter orders exported. More info here http://dev.commercetools.com/http-api.html#predicates')
.describe('fillAllRows', 'fill all rows')
.describe('exportCSVAsStream', 'Exports CSV as stream (to use for performance reasons)')
.default('standardShippingMethod', 'None')
.default('exportUnsyncedOnly', true)
.default('useExportTmpDir', false)
.default('createSyncActions', false)
.default('sftpContinueOnProblems', false)
.default('fillAllRows', false)
.default('exportCSVAsStream', false)
.argv
logger = utils.getLogger(argv)
process.on 'SIGUSR2', -> logger.reopenFileStreams()
process.on 'exit', => process.exit(@exitCode)
tmp.setGracefulCleanup()
fsExistsAsync = (path) ->
new Promise (resolve, reject) ->
fs.exists path, (exists) ->
if exists
resolve(true)
else
resolve(false)
ensureExportDir = ->
if "#{argv.useExportTmpDir}" is 'true'
# unsafeCleanup: recursively removes the created temporary directory, even when it's not empty
tmp.dirAsync {unsafeCleanup: true}
.then (tmpDir) ->
# tmp module returns an array with path to tmpDir and a cleanup function
# here we return only the path to tmpDir
tmpDir[0]
else
exportsPath = argv.targetDir
fsExistsAsync(exportsPath)
.then (exists) ->
if exists
Promise.resolve(exportsPath)
else
fs.mkdirAsync(exportsPath)
.then -> Promise.resolve(exportsPath)
readJsonFromPath = (path) ->
return Promise.resolve({}) unless path
fs.readFileAsync(path, {encoding: 'utf-8'}).then (content) ->
Promise.resolve JSON.parse(content)
exportCSVAsStream = (csvFile, orderExport) ->
new Promise (resolve, reject) ->
output = fs.createWriteStream csvFile, {encoding: 'utf-8'}
output.on 'error', (error) -> reject error
output.on 'finish', -> resolve()
orderExport.runCSVAndStreamToFile (data) =>
process.stdout.write('.')
output.write "#{data}\n"
Promise.resolve()
.then () ->
process.stdout.write('\n')
output.end()
.catch (e) -> reject(e)
createSyncOrders = (fileName) ->
logger.debug "Creating order objects with sync Information"
new Promise (resolve, reject) ->
orders = []
orderNumberMap = {}
fs.createReadStream(fileName)
.pipe(csv())
.on('data', (data) ->
if data.orderNumber and not orderNumberMap[data.orderNumber]
order =
orderNumber: data.orderNumber
syncInfo: [{
externalId: fileName
channel: CHANNEL_KEY
}]
orders.push(order)
orderNumberMap[data.orderNumber] = true
)
.on('end', () ->
logger.info "SyncInfo generated #{JSON.stringify(orders)}"
resolve(orders)
)
.on 'error', (err) ->
reject(err)
utils.ensureCredentials(argv)
.then (credentials) =>
exportType = if argv.csvTemplate then 'csv' else 'xml'
orderExport = new OrderExport
client: utils.getClientOptions(credentials, argv)
export:
perPage: argv.perPage
standardShippingMethod: argv.standardShippingMethod
exportType: exportType
exportUnsyncedOnly: argv.exportUnsyncedOnly
csvTemplate: argv.csvTemplate
fillAllRows: argv.fillAllRows
where: argv.where
ensureExportDir()
.then (outputDir) =>
logger.debug "Created output dir at #{outputDir}"
@outputDir = outputDir
fileName = utils.getFileName argv.fileWithTimestamp, 'orders'
csvFile = "#{@outputDir}/#{fileName}"
if argv.exportCSVAsStream
logger.info "Exporting orders as a stream."
exportCSVAsStream(csvFile, orderExport)
else
orderExport.run()
.then (data) =>
# TODO: xml export
# - one file for all (default)
# - one file for each order
@orderReferences = []
if exportType.toLowerCase() is 'csv'
logger.info "Storing CSV export to '#{csvFile}'."
@orderReferences.push fileName: csvFile, entry: data
fs.writeFileAsync csvFile, data
else
logger.info "Storing #{_.size data} file(s) to '#{@outputDir}'."
ts = (new Date()).getTime()
Promise.map data, (entry) =>
content = entry.xml.end(pretty: true, indent: ' ', newline: '\n')
if argv.fileWithTimestamp
fileName = "#{entry.id}_#{ts}.xml"
else
fileName = "#{entry.id}.xml"
@orderReferences.push name: fileName, entry: entry
fs.writeFileAsync "#{@outputDir}/#{fileName}", content
, {concurrency: 10}
.then =>
{sftpCredentials, sftpHost, sftpUsername, sftpPassword} = argv
if sftpCredentials or (sftpHost and sftpUsername and sftpPassword)
readJsonFromPath(sftpCredentials)
.then (credentials) =>
projectSftpCredentials = credentials[argv.projectKey] or {}
{host, username, password, sftpTarget} = _.defaults projectSftpCredentials,
host: sftpHost
username: sftpUsername
password: <PASSWORD>
sftpTarget: argv.sftpTarget
throw new Error 'Missing sftp host' unless host
throw new Error 'Missing sftp username' unless username
throw new Error 'Missing sftp password' unless password
sftpClient = new Sftp
host: host
username: username
password: <PASSWORD>
logger: logger
sftpClient.openSftp()
.then (sftp) =>
fs.readdirAsync(@outputDir)
.then (files) =>
logger.info "About to upload #{_.size files} file(s) from #{@outputDir} to #{sftpTarget}"
filesSkipped = 0
Promise.map files, (filename) =>
logger.debug "Uploading #{@outputDir}/#{filename}"
if not orderExport.ordersExported
return Promise.resolve()
sftpClient.safePutFile(sftp, "#{@outputDir}/#{filename}", "#{sftpTarget}/#{filename}")
.then =>
if exportType.toLowerCase() is 'csv' and argv.createSyncActions
createSyncOrders(@orderReferences[0].fileName)
.then (orders) =>
if orders.length
if argv.fileWithTimestamp
ts = (new Date()).getTime()
ordersFileJSON = "orders_sync_#{ts}.json"
else
ordersFileJSON = 'orders_sync.json'
fs.writeFileAsync("#{@outputDir}/#{ordersFileJSON}", JSON.stringify(orders,null,2)).then =>
logger.debug "Uploading #{@outputDir}/#{ordersFileJSON}"
sftpClient.safePutFile(sftp, "#{@outputDir}/#{ordersFileJSON}", "#{sftpTarget}/#{ordersFileJSON}")
else
logger.debug "No orders: #{JSON.stringify(orders, null, 2)} exported, no orders sync action to be set."
Promise.resolve()
else
xml = _.find @orderReferences, (r) -> r.name is filename
if xml
logger.debug "About to sync order #{filename}"
orderExport.syncOrder xml.entry, filename
else
logger.warn "Not able to create syncInfo for #{filename} as xml for that file was not found"
Promise.resolve()
.catch (err) ->
if argv.sftpContinueOnProblems
filesSkipped++
logger.warn err, "There was an error processing the file #{file}, skipping and continue"
Promise.resolve()
else
Promise.reject err
, {concurrency: 1}
.then ->
totFiles = _.size(files)
if totFiles > 0
logger.info "Export to SFTP successfully finished: #{totFiles - filesSkipped} out of #{totFiles} files were processed"
else
logger.info "Export successfully finished: there were no new files to be processed"
sftpClient.close(sftp)
Promise.resolve()
.finally -> sftpClient.close(sftp)
.catch (err) =>
logger.error err, 'There was an error uploading the files to SFTP'
@exitCode = 1
.catch (err) =>
logger.error err, "Problems on getting sftp credentials from config files for project #{argv.projectKey}."
@exitCode = 1
else
Promise.resolve() # no sftp
.then =>
logger.info 'Orders export complete'
@exitCode = 0
.catch (error) =>
logger.error error, 'Oops, something went wrong!'
@exitCode = 1
.catch (err) =>
logger.error err, 'Problems on getting client credentials from config files.'
@exitCode = 1
| true | path = require 'path'
_ = require 'underscore'
Promise = require 'bluebird'
fs = Promise.promisifyAll require('fs')
tmp = Promise.promisifyAll require('tmp')
{ProjectCredentialsConfig, Sftp} = require 'sphere-node-utils'
package_json = require '../package.json'
OrderExport = require './orderexport'
utils = require './utils'
csv = require 'csv-parser'
CHANNEL_KEY = 'PI:KEY:<KEY>END_PI'
argv = utils.getDefaultOptions()
.describe('standardShippingMethod', 'Allows to define the fallback shipping method name if order has none')
.describe('exportUnsyncedOnly', 'whether only unsynced orders will be exported or not')
.describe('useExportTmpDir', 'whether to use a system tmp folder to store exported files')
.describe('csvTemplate', 'CSV template to define the structure of the export')
.describe('createSyncActions', 'upload syncInfo update actions for orders exported (only supports sftp upload')
.describe('fileWithTimestamp', 'whether exported file should contain a timestamp')
.describe('sftpCredentials', 'the path to a JSON file where to read the credentials from')
.describe('sftpHost', 'the SFTP host (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpUsername', 'the SFTP username (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpPassword', 'the SFTP password (overwrite value in sftpCredentials JSON, if given)')
.describe('sftpTarget', 'path in the SFTP server to where to move the worked files')
.describe('sftpContinueOnProblems', 'ignore errors when processing a file and continue with the next one')
.describe('where', 'where predicate used to filter orders exported. More info here http://dev.commercetools.com/http-api.html#predicates')
.describe('fillAllRows', 'fill all rows')
.describe('exportCSVAsStream', 'Exports CSV as stream (to use for performance reasons)')
.default('standardShippingMethod', 'None')
.default('exportUnsyncedOnly', true)
.default('useExportTmpDir', false)
.default('createSyncActions', false)
.default('sftpContinueOnProblems', false)
.default('fillAllRows', false)
.default('exportCSVAsStream', false)
.argv
logger = utils.getLogger(argv)
process.on 'SIGUSR2', -> logger.reopenFileStreams()
process.on 'exit', => process.exit(@exitCode)
tmp.setGracefulCleanup()
fsExistsAsync = (path) ->
new Promise (resolve, reject) ->
fs.exists path, (exists) ->
if exists
resolve(true)
else
resolve(false)
ensureExportDir = ->
if "#{argv.useExportTmpDir}" is 'true'
# unsafeCleanup: recursively removes the created temporary directory, even when it's not empty
tmp.dirAsync {unsafeCleanup: true}
.then (tmpDir) ->
# tmp module returns an array with path to tmpDir and a cleanup function
# here we return only the path to tmpDir
tmpDir[0]
else
exportsPath = argv.targetDir
fsExistsAsync(exportsPath)
.then (exists) ->
if exists
Promise.resolve(exportsPath)
else
fs.mkdirAsync(exportsPath)
.then -> Promise.resolve(exportsPath)
readJsonFromPath = (path) ->
return Promise.resolve({}) unless path
fs.readFileAsync(path, {encoding: 'utf-8'}).then (content) ->
Promise.resolve JSON.parse(content)
exportCSVAsStream = (csvFile, orderExport) ->
new Promise (resolve, reject) ->
output = fs.createWriteStream csvFile, {encoding: 'utf-8'}
output.on 'error', (error) -> reject error
output.on 'finish', -> resolve()
orderExport.runCSVAndStreamToFile (data) =>
process.stdout.write('.')
output.write "#{data}\n"
Promise.resolve()
.then () ->
process.stdout.write('\n')
output.end()
.catch (e) -> reject(e)
createSyncOrders = (fileName) ->
logger.debug "Creating order objects with sync Information"
new Promise (resolve, reject) ->
orders = []
orderNumberMap = {}
fs.createReadStream(fileName)
.pipe(csv())
.on('data', (data) ->
if data.orderNumber and not orderNumberMap[data.orderNumber]
order =
orderNumber: data.orderNumber
syncInfo: [{
externalId: fileName
channel: CHANNEL_KEY
}]
orders.push(order)
orderNumberMap[data.orderNumber] = true
)
.on('end', () ->
logger.info "SyncInfo generated #{JSON.stringify(orders)}"
resolve(orders)
)
.on 'error', (err) ->
reject(err)
utils.ensureCredentials(argv)
.then (credentials) =>
exportType = if argv.csvTemplate then 'csv' else 'xml'
orderExport = new OrderExport
client: utils.getClientOptions(credentials, argv)
export:
perPage: argv.perPage
standardShippingMethod: argv.standardShippingMethod
exportType: exportType
exportUnsyncedOnly: argv.exportUnsyncedOnly
csvTemplate: argv.csvTemplate
fillAllRows: argv.fillAllRows
where: argv.where
ensureExportDir()
.then (outputDir) =>
logger.debug "Created output dir at #{outputDir}"
@outputDir = outputDir
fileName = utils.getFileName argv.fileWithTimestamp, 'orders'
csvFile = "#{@outputDir}/#{fileName}"
if argv.exportCSVAsStream
logger.info "Exporting orders as a stream."
exportCSVAsStream(csvFile, orderExport)
else
orderExport.run()
.then (data) =>
# TODO: xml export
# - one file for all (default)
# - one file for each order
@orderReferences = []
if exportType.toLowerCase() is 'csv'
logger.info "Storing CSV export to '#{csvFile}'."
@orderReferences.push fileName: csvFile, entry: data
fs.writeFileAsync csvFile, data
else
logger.info "Storing #{_.size data} file(s) to '#{@outputDir}'."
ts = (new Date()).getTime()
Promise.map data, (entry) =>
content = entry.xml.end(pretty: true, indent: ' ', newline: '\n')
if argv.fileWithTimestamp
fileName = "#{entry.id}_#{ts}.xml"
else
fileName = "#{entry.id}.xml"
@orderReferences.push name: fileName, entry: entry
fs.writeFileAsync "#{@outputDir}/#{fileName}", content
, {concurrency: 10}
.then =>
{sftpCredentials, sftpHost, sftpUsername, sftpPassword} = argv
if sftpCredentials or (sftpHost and sftpUsername and sftpPassword)
readJsonFromPath(sftpCredentials)
.then (credentials) =>
projectSftpCredentials = credentials[argv.projectKey] or {}
{host, username, password, sftpTarget} = _.defaults projectSftpCredentials,
host: sftpHost
username: sftpUsername
password: PI:PASSWORD:<PASSWORD>END_PI
sftpTarget: argv.sftpTarget
throw new Error 'Missing sftp host' unless host
throw new Error 'Missing sftp username' unless username
throw new Error 'Missing sftp password' unless password
sftpClient = new Sftp
host: host
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
logger: logger
sftpClient.openSftp()
.then (sftp) =>
fs.readdirAsync(@outputDir)
.then (files) =>
logger.info "About to upload #{_.size files} file(s) from #{@outputDir} to #{sftpTarget}"
filesSkipped = 0
Promise.map files, (filename) =>
logger.debug "Uploading #{@outputDir}/#{filename}"
if not orderExport.ordersExported
return Promise.resolve()
sftpClient.safePutFile(sftp, "#{@outputDir}/#{filename}", "#{sftpTarget}/#{filename}")
.then =>
if exportType.toLowerCase() is 'csv' and argv.createSyncActions
createSyncOrders(@orderReferences[0].fileName)
.then (orders) =>
if orders.length
if argv.fileWithTimestamp
ts = (new Date()).getTime()
ordersFileJSON = "orders_sync_#{ts}.json"
else
ordersFileJSON = 'orders_sync.json'
fs.writeFileAsync("#{@outputDir}/#{ordersFileJSON}", JSON.stringify(orders,null,2)).then =>
logger.debug "Uploading #{@outputDir}/#{ordersFileJSON}"
sftpClient.safePutFile(sftp, "#{@outputDir}/#{ordersFileJSON}", "#{sftpTarget}/#{ordersFileJSON}")
else
logger.debug "No orders: #{JSON.stringify(orders, null, 2)} exported, no orders sync action to be set."
Promise.resolve()
else
xml = _.find @orderReferences, (r) -> r.name is filename
if xml
logger.debug "About to sync order #{filename}"
orderExport.syncOrder xml.entry, filename
else
logger.warn "Not able to create syncInfo for #{filename} as xml for that file was not found"
Promise.resolve()
.catch (err) ->
if argv.sftpContinueOnProblems
filesSkipped++
logger.warn err, "There was an error processing the file #{file}, skipping and continue"
Promise.resolve()
else
Promise.reject err
, {concurrency: 1}
.then ->
totFiles = _.size(files)
if totFiles > 0
logger.info "Export to SFTP successfully finished: #{totFiles - filesSkipped} out of #{totFiles} files were processed"
else
logger.info "Export successfully finished: there were no new files to be processed"
sftpClient.close(sftp)
Promise.resolve()
.finally -> sftpClient.close(sftp)
.catch (err) =>
logger.error err, 'There was an error uploading the files to SFTP'
@exitCode = 1
.catch (err) =>
logger.error err, "Problems on getting sftp credentials from config files for project #{argv.projectKey}."
@exitCode = 1
else
Promise.resolve() # no sftp
.then =>
logger.info 'Orders export complete'
@exitCode = 0
.catch (error) =>
logger.error error, 'Oops, something went wrong!'
@exitCode = 1
.catch (err) =>
logger.error err, 'Problems on getting client credentials from config files.'
@exitCode = 1
|
[
{
"context": "36'\n binddn: 'cn=Manager,dc=ryba'\n passwd: 'test'\n suffix_dn: 'ou=users,dc=ryba' # used by ldap",
"end": 338,
"score": 0.9994755387306213,
"start": 334,
"tag": "PASSWORD",
"value": "test"
},
{
"context": " null\n ,\n ssh: host: 'localhost', username: 'root'\n ]\n",
"end": 533,
"score": 0.522646427154541,
"start": 529,
"tag": "USERNAME",
"value": "root"
}
] | packages/core/env/systemctl/test.coffee | chibanemourad/node-nikita | 0 |
module.exports =
tags:
service_install: true
service_startup: true
service_systemctl: true # cant be activated because systemctl not compatible with Docker
conditions_is_os:
arch: '64'
name: 'centos'
version: '7.5'
ldap:
uri: 'ldaps://master3.ryba:636'
binddn: 'cn=Manager,dc=ryba'
passwd: 'test'
suffix_dn: 'ou=users,dc=ryba' # used by ldap_user
service:
name: 'cronie'
srv_name: 'crond'
chk_name: 'crond'
ssh: [
null
,
ssh: host: 'localhost', username: 'root'
]
| 31257 |
module.exports =
tags:
service_install: true
service_startup: true
service_systemctl: true # cant be activated because systemctl not compatible with Docker
conditions_is_os:
arch: '64'
name: 'centos'
version: '7.5'
ldap:
uri: 'ldaps://master3.ryba:636'
binddn: 'cn=Manager,dc=ryba'
passwd: '<PASSWORD>'
suffix_dn: 'ou=users,dc=ryba' # used by ldap_user
service:
name: 'cronie'
srv_name: 'crond'
chk_name: 'crond'
ssh: [
null
,
ssh: host: 'localhost', username: 'root'
]
| true |
module.exports =
tags:
service_install: true
service_startup: true
service_systemctl: true # cant be activated because systemctl not compatible with Docker
conditions_is_os:
arch: '64'
name: 'centos'
version: '7.5'
ldap:
uri: 'ldaps://master3.ryba:636'
binddn: 'cn=Manager,dc=ryba'
passwd: 'PI:PASSWORD:<PASSWORD>END_PI'
suffix_dn: 'ou=users,dc=ryba' # used by ldap_user
service:
name: 'cronie'
srv_name: 'crond'
chk_name: 'crond'
ssh: [
null
,
ssh: host: 'localhost', username: 'root'
]
|
[
{
"context": "ption: 'Throw dies'\n version: '0.1'\n authors: ['Álvaro Cuesta']\n",
"end": 839,
"score": 0.9998774528503418,
"start": 826,
"tag": "NAME",
"value": "Álvaro Cuesta"
}
] | plugins/dice.coffee | alvaro-cuesta/nerdobot | 2 | util = require '../lib/util'
{floor, random} = Math
DEFAULT_DIES = 1
DEFAULT_FACES = 6
MAX_DIES = 100
module.exports = ->
@addCommand 'dice',
args: "<dices, default=#{DEFAULT_DIES}, max=#{MAX_DIES}> <faces, default=#{DEFAULT_FACES}>"
description: 'Throw dies and show their sum'
({nick}, message, to) =>
to ?= nick
dies = DEFAULT_DIES
faces = DEFAULT_FACES
if message?
[a, b] = util.split message, ' '
if b? and b != ''
dies = parseInt a, 10
faces = parseInt b, 10
else if a? and a != ''
faces = parseInt a, 10
return unless 0 < dies <= MAX_DIES
sum = dies
sum += floor random() * faces for _ in [1..dies]
@say to, " = #{sum}"
name: 'Dice'
description: 'Throw dies'
version: '0.1'
authors: ['Álvaro Cuesta']
| 72546 | util = require '../lib/util'
{floor, random} = Math
DEFAULT_DIES = 1
DEFAULT_FACES = 6
MAX_DIES = 100
module.exports = ->
@addCommand 'dice',
args: "<dices, default=#{DEFAULT_DIES}, max=#{MAX_DIES}> <faces, default=#{DEFAULT_FACES}>"
description: 'Throw dies and show their sum'
({nick}, message, to) =>
to ?= nick
dies = DEFAULT_DIES
faces = DEFAULT_FACES
if message?
[a, b] = util.split message, ' '
if b? and b != ''
dies = parseInt a, 10
faces = parseInt b, 10
else if a? and a != ''
faces = parseInt a, 10
return unless 0 < dies <= MAX_DIES
sum = dies
sum += floor random() * faces for _ in [1..dies]
@say to, " = #{sum}"
name: 'Dice'
description: 'Throw dies'
version: '0.1'
authors: ['<NAME>']
| true | util = require '../lib/util'
{floor, random} = Math
DEFAULT_DIES = 1
DEFAULT_FACES = 6
MAX_DIES = 100
module.exports = ->
@addCommand 'dice',
args: "<dices, default=#{DEFAULT_DIES}, max=#{MAX_DIES}> <faces, default=#{DEFAULT_FACES}>"
description: 'Throw dies and show their sum'
({nick}, message, to) =>
to ?= nick
dies = DEFAULT_DIES
faces = DEFAULT_FACES
if message?
[a, b] = util.split message, ' '
if b? and b != ''
dies = parseInt a, 10
faces = parseInt b, 10
else if a? and a != ''
faces = parseInt a, 10
return unless 0 < dies <= MAX_DIES
sum = dies
sum += floor random() * faces for _ in [1..dies]
@say to, " = #{sum}"
name: 'Dice'
description: 'Throw dies'
version: '0.1'
authors: ['PI:NAME:<NAME>END_PI']
|
[
{
"context": "en'\n\t\t\tlocalStorage.setItem 'visitorToken', Random.id()\n\n\t\ttoken.set localStorage.getItem 'visitorToken",
"end": 302,
"score": 0.4122096002101898,
"start": 300,
"tag": "KEY",
"value": "id"
}
] | packages/rocketchat-livechat/app/client/lib/_visitor.coffee | claysaad/Rocket.Chat | 1 | msgStream = new Meteor.Streamer 'room-messages'
@visitor = new class
token = new ReactiveVar null
room = new ReactiveVar null
roomToSubscribe = new ReactiveVar null
roomSubscribed = null
register = ->
if not localStorage.getItem 'visitorToken'
localStorage.setItem 'visitorToken', Random.id()
token.set localStorage.getItem 'visitorToken'
getToken = ->
return token.get()
setRoom = (rid) ->
room.set rid
getRoom = (createOnEmpty = false) ->
roomId = room.get()
if not roomId? and createOnEmpty
roomId = Random.id()
room.set roomId
return roomId
isSubscribed = (roomId) ->
return roomSubscribed is roomId
subscribeToRoom = (roomId) ->
if roomSubscribed?
return if roomSubscribed is roomId
roomSubscribed = roomId
msgStream.on roomId, (msg) ->
if msg.t is 'command'
Commands[msg.msg]?()
else if msg.t isnt 'livechat_video_call'
ChatMessage.upsert { _id: msg._id }, msg
# notification sound
if Session.equals('sound', true)
if msg.u._id isnt Meteor.user()._id
$('#chatAudioNotification')[0].play();
register: register
getToken: getToken
setRoom: setRoom
getRoom: getRoom
subscribeToRoom: subscribeToRoom
isSubscribed: isSubscribed
| 96893 | msgStream = new Meteor.Streamer 'room-messages'
@visitor = new class
token = new ReactiveVar null
room = new ReactiveVar null
roomToSubscribe = new ReactiveVar null
roomSubscribed = null
register = ->
if not localStorage.getItem 'visitorToken'
localStorage.setItem 'visitorToken', Random.<KEY>()
token.set localStorage.getItem 'visitorToken'
getToken = ->
return token.get()
setRoom = (rid) ->
room.set rid
getRoom = (createOnEmpty = false) ->
roomId = room.get()
if not roomId? and createOnEmpty
roomId = Random.id()
room.set roomId
return roomId
isSubscribed = (roomId) ->
return roomSubscribed is roomId
subscribeToRoom = (roomId) ->
if roomSubscribed?
return if roomSubscribed is roomId
roomSubscribed = roomId
msgStream.on roomId, (msg) ->
if msg.t is 'command'
Commands[msg.msg]?()
else if msg.t isnt 'livechat_video_call'
ChatMessage.upsert { _id: msg._id }, msg
# notification sound
if Session.equals('sound', true)
if msg.u._id isnt Meteor.user()._id
$('#chatAudioNotification')[0].play();
register: register
getToken: getToken
setRoom: setRoom
getRoom: getRoom
subscribeToRoom: subscribeToRoom
isSubscribed: isSubscribed
| true | msgStream = new Meteor.Streamer 'room-messages'
@visitor = new class
token = new ReactiveVar null
room = new ReactiveVar null
roomToSubscribe = new ReactiveVar null
roomSubscribed = null
register = ->
if not localStorage.getItem 'visitorToken'
localStorage.setItem 'visitorToken', Random.PI:KEY:<KEY>END_PI()
token.set localStorage.getItem 'visitorToken'
getToken = ->
return token.get()
setRoom = (rid) ->
room.set rid
getRoom = (createOnEmpty = false) ->
roomId = room.get()
if not roomId? and createOnEmpty
roomId = Random.id()
room.set roomId
return roomId
isSubscribed = (roomId) ->
return roomSubscribed is roomId
subscribeToRoom = (roomId) ->
if roomSubscribed?
return if roomSubscribed is roomId
roomSubscribed = roomId
msgStream.on roomId, (msg) ->
if msg.t is 'command'
Commands[msg.msg]?()
else if msg.t isnt 'livechat_video_call'
ChatMessage.upsert { _id: msg._id }, msg
# notification sound
if Session.equals('sound', true)
if msg.u._id isnt Meteor.user()._id
$('#chatAudioNotification')[0].play();
register: register
getToken: getToken
setRoom: setRoom
getRoom: getRoom
subscribeToRoom: subscribeToRoom
isSubscribed: isSubscribed
|
[
{
"context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L",
"end": 35,
"score": 0.9998748898506165,
"start": 21,
"tag": "NAME",
"value": "JeongHoon Byun"
},
{
"context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# Licensed under ",
"end": 49,
"score": 0.9939646124839783,
"start": 41,
"tag": "USERNAME",
"value": "Outsider"
}
] | test/parser/php-parser.test.coffee | uppalapatisujitha/CodingConventionofCommitHistory | 421 | # Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
should = require 'should'
parser = require '../../src/parser/php-parser'
describe 'php-parser >', ->
describe 'indent >', ->
it 'check space indent #1', ->
convention = parser.indent 'function bar($baz) {', {}
convention.indent.space.should.equal 0
it 'check space indent #2', ->
convention = parser.indent ' function bar($baz) {', {}
convention.indent.space.should.equal 1
it 'check space indent #3', ->
convention = parser.indent ' function bar($baz) {', {}
convention.indent.space.should.equal 1
it 'check space indent #4', ->
convention = parser.indent ' \tfunction bar($baz) {', {}
convention.indent.space.should.equal 1
it 'check tab indent #1', ->
convention = parser.indent '\tfunction bar($baz) {', {}
convention.indent.tab.should.equal 1
it 'check tab indent #2', ->
convention = parser.indent '\t\tfunction bar($baz) {', {}
convention.indent.tab.should.equal 1
it 'check tab indent #3', ->
convention = parser.indent '\t\t function bar($baz) {', {}
convention.indent.tab.should.equal 1
it 'check tab indent #4', ->
convention = parser.indent ' \tfunction bar($baz) {', {}
convention.indent.tab.should.equal 0
it 'check tab indent #5', ->
convention = parser.indent 'function bar($baz) {', {}
convention.indent.tab.should.equal 0
describe 'class brace placement >', ->
it 'check class brace is in newline #1', ->
convention = parser.classBrace 'class Foo', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #2', ->
convention = parser.classBrace ' class Cart ', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #3', ->
convention = parser.classBrace '\tclass Cart ', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #4', ->
convention = parser.classBrace 'class Bar extends Foo ', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #5', ->
convention = parser.classBrace 'class Cart // {}', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #6', ->
convention = parser.classBrace 'class Foo {', {}
convention.classBrace.newline.should.equal 0
it 'check class brace is in same line #1', ->
convention = parser.classBrace 'class Foo {', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #2', ->
convention = parser.classBrace ' class Cart { ', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #3', ->
convention = parser.classBrace '\tclass Cart {', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #4', ->
convention = parser.classBrace 'class Bar extends Foo { } ', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #5', ->
convention = parser.classBrace 'class Cart { // {}', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #6', ->
convention = parser.classBrace 'class Cart // {}', {}
convention.classBrace.sameline.should.equal 0
describe 'control brace placement >', ->
it 'check control brace is in same line #1', ->
convention = parser.controlBrace 'if ($baz) {', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #2', ->
convention = parser.controlBrace '} else {', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #3', ->
convention = parser.controlBrace ' } elseif ($i == 1) { ', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #4', ->
convention = parser.controlBrace '\twhile ($i <= 10) {', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #5', ->
convention = parser.controlBrace ' switch ($i) { ', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #6', ->
convention = parser.controlBrace '} elseif ($i == 1) ', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in same line #7', ->
convention = parser.controlBrace 'while ($i <= 10):', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in same line #8', ->
convention = parser.controlBrace 'switch ($i):', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in same line #9', ->
convention = parser.controlBrace 'while ($i <= 10):', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in new line #1', ->
convention = parser.controlBrace ' if($baz) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #2', ->
convention = parser.controlBrace '\t\t else ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #3', ->
convention = parser.controlBrace ' elseif ($i == 1) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #4', ->
convention = parser.controlBrace '\t\twhile ($i <= 10) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #5', ->
convention = parser.controlBrace 'switch ($i) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #6', ->
convention = parser.controlBrace ' else{', {}
convention.controlBrace.newline.should.equal 0
it 'check control brace is in new line #7', ->
convention = parser.controlBrace 'while ($i <= 10) :', {}
convention.controlBrace.newline.should.equal 0
it 'check control brace is in new line #8', ->
convention = parser.controlBrace 'switch ($i):', {}
convention.controlBrace.newline.should.equal 0
it 'check control brace is in new line #9', ->
convention = parser.controlBrace '} else ', {}
convention.controlBrace.newline.should.equal 0
describe 'method brace placement >', ->
it 'check method brace is in same line #1', ->
convention = parser.methodBrace 'function bar($baz) {', {}
convention.methodBrace.sameline.should.equal 1
it 'check method brace is in same line #2', ->
convention = parser.methodBrace ' function bar($baz, $foo) { ', {}
convention.methodBrace.sameline.should.equal 1
it 'check method brace is in same line #3', ->
convention = parser.methodBrace '\t\tfunction foo() { ', {}
convention.methodBrace.sameline.should.equal 1
it 'check method brace is in same line #4', ->
convention = parser.methodBrace 'function bar($baz, $foo) // {}', {}
convention.methodBrace.sameline.should.equal 0
it 'check method brace is in new line #1', ->
convention = parser.methodBrace 'function bar($baz)', {}
convention.methodBrace.newline.should.equal 1
it 'check method brace is in new line #2', ->
convention = parser.methodBrace ' function bar($baz, $foo) ', {}
convention.methodBrace.newline.should.equal 1
it 'check method brace is in new line #3', ->
convention = parser.methodBrace '\t\tfunction foo()', {}
convention.methodBrace.newline.should.equal 1
it 'check method brace is in new line #4', ->
convention = parser.methodBrace 'function bar($baz, $foo) {', {}
convention.methodBrace.newline.should.equal 0
describe 'space around control statement >', ->
it 'check space around control statement #1', ->
convention = parser.spaceAroundControl ' if ($baz) { ', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #2', ->
convention = parser.spaceAroundControl '\t} elseif ($bar) { ', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #3', ->
convention = parser.spaceAroundControl 'if ($a > $b) :', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #4', ->
convention = parser.spaceAroundControl ' elseif ($a == $b) :', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #5', ->
convention = parser.spaceAroundControl ' while ($i <= 10) {', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #6', ->
convention = parser.spaceAroundControl ' while ($i <= 10) :', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #7', ->
convention = parser.spaceAroundControl 'do {', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #8', ->
convention = parser.spaceAroundControl '\t\tfor ($i = 1; $i <= 10; $i++) {', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #9', ->
convention = parser.spaceAroundControl ' if($baz){ ', {}
convention.spaceAroundControl.space.should.equal 0
it 'check space around control statement #10', ->
convention = parser.spaceAroundControl '\t\tfor($i = 1; $i <= 10; $i++) {', {}
convention.spaceAroundControl.space.should.equal 0
it 'check no space around control statement #1', ->
convention = parser.spaceAroundControl 'if($baz){', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #2', ->
convention = parser.spaceAroundControl '}elseif($bar){', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #3', ->
convention = parser.spaceAroundControl ' if($a > $b):', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #4', ->
convention = parser.spaceAroundControl '\t\telseif($a == $b): ', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #5', ->
convention = parser.spaceAroundControl ' while($i <= 10){ ', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #6', ->
convention = parser.spaceAroundControl ' while($i <= 10):', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #7', ->
convention = parser.spaceAroundControl 'do{', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #8', ->
convention = parser.spaceAroundControl ' for($i = 1; $i <= 10; $i++){ ', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #9', ->
convention = parser.spaceAroundControl ' if ($baz) { ', {}
convention.spaceAroundControl.nospace.should.equal 0
it 'check no space around control statement #10', ->
convention = parser.spaceAroundControl ' for($i = 1; $i <= 10; $i++) { ', {}
convention.spaceAroundControl.nospace.should.equal 0
describe 'space inside control statement >', ->
it 'check space inside control statement #1', ->
convention = parser.spaceInsideControl ' if ( $baz ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #2', ->
convention = parser.spaceInsideControl '\t\t} elseif ( $bar ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #3', ->
convention = parser.spaceInsideControl 'if ( $a > $b ) :', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #4', ->
convention = parser.spaceInsideControl ' elseif ( $a == $b ) : ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #5', ->
convention = parser.spaceInsideControl ' while ( $i <= 10 ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #6', ->
convention = parser.spaceInsideControl ' while ( $i <= 10 ) : ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #7', ->
convention = parser.spaceInsideControl ' for ( $i = 1; $i <= 10; $i++ ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #8', ->
convention = parser.spaceInsideControl ' if ($baz) { ', {}
convention.spaceInsideControl.space.should.equal 0
it 'check space inside control statement #9', ->
convention = parser.spaceInsideControl ' if ($baz ) { ', {}
convention.spaceInsideControl.space.should.equal 0
it 'check no space inside control statement #1', ->
convention = parser.spaceInsideControl ' if ($baz) { ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #2', ->
convention = parser.spaceInsideControl '} elseif ($bar) {', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #3', ->
convention = parser.spaceInsideControl 'if ($a > $b) :', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #4', ->
convention = parser.spaceInsideControl '\t\telseif ($a == $b) :', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #5', ->
convention = parser.spaceInsideControl ' while ($i <= 10) { ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #6', ->
convention = parser.spaceInsideControl ' while ($i <= 10) : ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #7', ->
convention = parser.spaceInsideControl '\t\tfor ($i = 1; $i <= 10; $i++) { ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #8', ->
convention = parser.spaceInsideControl ' } elseif ( $bar ) { ', {}
convention.spaceInsideControl.nospace.should.equal 0
it 'check no space inside control statement #9', ->
convention = parser.spaceInsideControl ' } elseif ( $bar) { ', {}
convention.spaceInsideControl.nospace.should.equal 0
describe 'space around method params >', ->
it 'check space around method params #1', ->
convention = parser.spaceAroundMethod 'function bar ($baz) {', {}
convention.spaceAroundMethod.space.should.equal 1
it 'check space around method params #2', ->
convention = parser.spaceAroundMethod ' function bar ($baz, $foo) { ', {}
convention.spaceAroundMethod.space.should.equal 1
it 'check space around method params #3', ->
convention = parser.spaceAroundMethod '\t\tfunction foo () { ', {}
convention.spaceAroundMethod.space.should.equal 1
it 'check space around method params #4', ->
convention = parser.spaceAroundMethod 'function bar ($baz, $foo) // {', {}
convention.spaceAroundMethod.space.should.equal 0
it 'check space around method params #5', ->
convention = parser.spaceAroundMethod 'function bar($baz) {', {}
convention.spaceAroundMethod.space.should.equal 0
it 'check space around method params #6', ->
convention = parser.spaceAroundMethod 'function bar($baz){', {}
convention.spaceAroundMethod.space.should.equal 0
it 'check no space around method params #1', ->
convention = parser.spaceAroundMethod 'function bar($baz){', {}
convention.spaceAroundMethod.nospace.should.equal 1
it 'check no space around method params #2', ->
convention = parser.spaceAroundMethod ' function bar($baz, $foo){ ', {}
convention.spaceAroundMethod.nospace.should.equal 1
it 'check no space around method params #3', ->
convention = parser.spaceAroundMethod '\t\tfunction foo(){ ', {}
convention.spaceAroundMethod.nospace.should.equal 1
it 'check no space around method params #4', ->
convention = parser.spaceAroundMethod ' function bar($baz, $foo)//{', {}
convention.spaceAroundMethod.nospace.should.equal 0
it 'check no space around method params #5', ->
convention = parser.spaceAroundMethod 'function bar ($baz) {', {}
convention.spaceAroundMethod.nospace.should.equal 0
it 'check no space around method params #6', ->
convention = parser.spaceAroundMethod 'function bar ($baz){', {}
convention.spaceAroundMethod.nospace.should.equal 0
describe 'space inside method params >', ->
it 'check space inside method params #1', ->
convention = parser.spaceInsideMethod 'function bar ( $baz ) {', {}
convention.spaceInsideMethod.space.should.equal 1
it 'check space inside method params #2', ->
convention = parser.spaceInsideMethod ' function bar ( $baz, $foo ) { ', {}
convention.spaceInsideMethod.space.should.equal 1
it 'check space inside method params #3', ->
convention = parser.spaceInsideMethod '\t\tfunction bar( $baz, $foo ){ ', {}
convention.spaceInsideMethod.space.should.equal 1
it 'check space inside method params #4', ->
convention = parser.spaceInsideMethod 'function foo () {', {}
convention.spaceInsideMethod.space.should.equal 0
it 'check space inside method params #5', ->
convention = parser.spaceInsideMethod 'function bar ($baz ) {', {}
convention.spaceInsideMethod.space.should.equal 0
it 'check space inside method params #6', ->
convention = parser.spaceInsideMethod 'function bar ($baz) {', {}
convention.spaceInsideMethod.space.should.equal 0
it 'check no space inside method params #1', ->
convention = parser.spaceInsideMethod 'function bar ($baz) {', {}
convention.spaceInsideMethod.nospace.should.equal 1
it 'check no space inside method params #2', ->
convention = parser.spaceInsideMethod ' function bar ($baz, $foo) { ', {}
convention.spaceInsideMethod.nospace.should.equal 1
it 'check no space inside method params #3', ->
convention = parser.spaceInsideMethod '\t\tfunction bar($baz, $foo){ ', {}
convention.spaceInsideMethod.nospace.should.equal 1
it 'check no space inside method params #4', ->
convention = parser.spaceInsideMethod ' function foo () {', {}
convention.spaceInsideMethod.nospace.should.equal 0
it 'check no space inside method params #5', ->
convention = parser.spaceInsideMethod ' function bar ($baz ) { ', {}
convention.spaceInsideMethod.nospace.should.equal 0
it 'check no space inside method params #6', ->
convention = parser.spaceInsideMethod 'function bar( $baz, $foo ){', {}
convention.spaceInsideMethod.nospace.should.equal 0
describe 'class naming >', ->
it 'check whether class name in camel case #1', ->
convention = parser.className ' class fooBarBaz { ', {}
convention.className.camel.should.equal 1
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in camel case #2', ->
convention = parser.className '\t\tclass fooBarBaz2{ ', {}
convention.className.camel.should.equal 1
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in camel case #3', ->
convention = parser.className 'class fooBar1Baz', {}
convention.className.camel.should.equal 1
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in pascal case #1', ->
convention = parser.className ' class FooBarBaz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 1
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in pascal case #2', ->
convention = parser.className '\t\tclass FooBarBaz1{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 1
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in pascal case #3', ->
convention = parser.className ' class FooBar1Baz', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 1
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in caps snake case #1', ->
convention = parser.className ' class FOO_BAR_BAZ { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 1
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in caps snake case #2', ->
convention = parser.className '\t\tclass FOO_BAR_BAZ2{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 1
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in caps snake case #3', ->
convention = parser.className ' class FOO_BAR1_BAZ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 1
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake pascal case #1', ->
convention = parser.className ' class Foo_Bar_Baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 1
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake pascal case #2', ->
convention = parser.className '\t\tclass Foo_Bar_Baz1{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 1
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake pascal case #3', ->
convention = parser.className ' class Foo_Bar2_Baz', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 1
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake case #1', ->
convention = parser.className ' class foo_bar_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 1
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake case #2', ->
convention = parser.className '\t\tclass foo_bar_baz2{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 1
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake case #3', ->
convention = parser.className ' class foo_bar1_baz', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 1
convention.className.uppersnake.should.equal 0
it 'check whether class name in uppercase snake case #1', ->
convention = parser.className ' class Foo_bar_baz {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 1
it 'check whether class name in uppercase snake case #2', ->
convention = parser.className '\t\tclass Foo_bar1_baz2{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 1
it 'check whether class name in uppercase snake case #3', ->
convention = parser.className ' class Foo_bar1_baz2', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 1
it 'all rules ingnore this #1', ->
convention = parser.className ' class _Foo_bar_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #2', ->
convention = parser.className ' class Foo_bar_baz_{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #3', ->
convention = parser.className ' class Foo_BAR_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #4', ->
convention = parser.className ' class Foo_bar_Baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #5', ->
convention = parser.className 'class foo_BAR_Baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #6', ->
convention = parser.className ' class foo_BAR_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #7', ->
convention = parser.className 'class foo_BarBaz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #8', ->
convention = parser.className 'class fooBARBaz {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #9', ->
convention = parser.className 'class foo {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #10', ->
convention = parser.className 'class FOO {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #11', ->
convention = parser.className 'class Foo {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
describe 'const naming >', ->
it 'check whether const name in camel case #1', ->
convention = parser.constName ' const fooBarBaz = 0; ', {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in camel case #2', ->
convention = parser.constName '\t\tconst fooBarBaz2=0; ', {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in camel case #3', ->
convention = parser.constName 'const fooBar1Baz = 0 ;', {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in camel case #4', ->
convention = parser.constName "define('barBaz', 0);", {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #1', ->
convention = parser.constName ' const FooBarBaz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #2', ->
convention = parser.constName '\t\tconst FooBarBaz1=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #3', ->
convention = parser.constName ' const FooBar1Baz = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #4', ->
convention = parser.constName "define('BarBaz', 0);", {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #1', ->
convention = parser.constName ' const FOO_BAR_BAZ = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #2', ->
convention = parser.constName '\t\tconst FOO_BAR_BAZ2=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #3', ->
convention = parser.constName ' const FOO_BAR1_BAZ = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #4', ->
convention = parser.constName 'define("BAR_BAZ", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #1', ->
convention = parser.constName ' const Foo_Bar_Baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #2', ->
convention = parser.constName '\t\tconst Foo_Bar_Baz1=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #3', ->
convention = parser.constName ' const Foo_Bar2_Baz=0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #4', ->
convention = parser.constName ' define("Bar_Baz", 0); ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake case #1', ->
convention = parser.constName ' const foo_bar_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'check whether const name in snake case #2', ->
convention = parser.constName '\t\tconst foo_bar_baz2=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'check whether const name in snake case #3', ->
convention = parser.constName ' const foo_bar1_baz = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'check whether const name in snake case #4', ->
convention = parser.constName "\t\tdefine('bar_baz', 0); ", {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'all rules ingnore this #1', ->
convention = parser.constName ' const _Foo_bar_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #2', ->
convention = parser.constName ' const Foo_bar_baz_=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #3', ->
convention = parser.constName ' const Foo_BAR_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #4', ->
convention = parser.constName ' const Foo_bar_Baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #5', ->
convention = parser.constName 'const foo_BAR_Baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #6', ->
convention = parser.constName ' const foo_BAR_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #7', ->
convention = parser.constName 'const foo_BarBaz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #8', ->
convention = parser.constName 'const fooBARBaz = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #9', ->
convention = parser.constName 'const foo = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #10', ->
convention = parser.constName 'const FOO = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #11', ->
convention = parser.constName 'const Foo = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #12', ->
convention = parser.constName 'define("bar", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #13', ->
convention = parser.constName 'define("barBAR", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #14', ->
convention = parser.constName 'define("barBARBaz", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
describe 'const naming >', ->
it 'check whether function name in camel case #1', ->
convention = parser.functionName 'function barBaz(){', {}
convention.functionName.camel.should.equal 1
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in camel case #2', ->
convention = parser.functionName '\t\tfunction barBaz(){', {}
convention.functionName.camel.should.equal 1
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in camel case #3', ->
convention = parser.functionName ' public function barBaz(){ ', {}
convention.functionName.camel.should.equal 1
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in pascal case #1', ->
convention = parser.functionName 'function BarBaz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 1
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in pascal case #2', ->
convention = parser.functionName '\t\tfunction BarBaz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 1
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in pascal case #3', ->
convention = parser.functionName ' public function BarBaz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 1
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in caps snake case #1', ->
convention = parser.functionName 'function BAR_BAZ(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 1
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in caps snake case #2', ->
convention = parser.functionName '\t\tfunction BAR_BAZ(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 1
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in caps snake case #3', ->
convention = parser.functionName 'public function BAR_BAZ(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 1
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in snake pascal case #1', ->
convention = parser.functionName 'function Bar_Baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 1
convention.functionName.snake.should.equal 0
it 'check whether function name in snake pascal case #2', ->
convention = parser.functionName '\t\tfunction Bar_Baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 1
convention.functionName.snake.should.equal 0
it 'check whether function name in snake pascal case #3', ->
convention = parser.functionName 'public function Bar_Baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 1
convention.functionName.snake.should.equal 0
it 'check whether function name in snake case #1', ->
convention = parser.functionName 'function bar_baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 1
it 'check whether function name in snake case #2', ->
convention = parser.functionName '\t\tfunction bar_baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 1
it 'check whether function name in snake case #3', ->
convention = parser.functionName 'public function bar_baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 1
describe 'method declare order >', ->
it 'check visibility - static case #1', ->
convention = parser.methodDeclare ' public static function bar($baz) ', {}
convention.methodDeclare.staticlate.should.equal 1
it 'check visibility - static case #2', ->
convention = parser.methodDeclare "\t\tprotected static $my_static = 'foo'; ", {}
convention.methodDeclare.staticlate.should.equal 1
it 'check visibility - static case #3', ->
convention = parser.methodDeclare "private static $my_static = 'foo'; ", {}
convention.methodDeclare.staticlate.should.equal 1
it 'check visibility - static case #4', ->
convention = parser.methodDeclare ' static public function bar($baz) ', {}
convention.methodDeclare.staticlate.should.equal 0
it 'check static - visibility case #1', ->
convention = parser.methodDeclare ' static public function bar($baz) ', {}
convention.methodDeclare.staticfirst.should.equal 1
it 'check static - visibility case #2', ->
convention = parser.methodDeclare "\t\tstatic protected $my_static = 'foo'; ", {}
convention.methodDeclare.staticfirst.should.equal 1
it 'check static - visibility case #3', ->
convention = parser.methodDeclare " static private $my_static = 'foo'; ", {}
convention.methodDeclare.staticfirst.should.equal 1
it 'check static - visibility case #4', ->
convention = parser.methodDeclare "protected static $my_static = 'foo';", {}
convention.methodDeclare.staticfirst.should.equal 0
it 'check visibility - abstract(final) case #1', ->
convention = parser.methodDeclare " public abstract function bar($baz); ", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #2', ->
convention = parser.methodDeclare "\t\tprotected abstract function getValue(); ", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #3', ->
convention = parser.methodDeclare "private abstract function getValue();", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #4', ->
convention = parser.methodDeclare " private final function getValue(); ", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #5', ->
convention = parser.methodDeclare " abstract public function bar($baz); ", {}
convention.methodDeclare.abstractlate.should.equal 0
it 'check abstract(final) - visibility case #1', ->
convention = parser.methodDeclare " abstract public function bar($baz); ", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #2', ->
convention = parser.methodDeclare "\t\tabstract protected function getValue(); ", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #3', ->
convention = parser.methodDeclare "abstract private function getValue();", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #4', ->
convention = parser.methodDeclare " final private function getValue(); ", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #5', ->
convention = parser.methodDeclare " protected abstract function getValue(); ", {}
convention.methodDeclare.abstractfirst.should.equal 0
| 202330 | # Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
should = require 'should'
parser = require '../../src/parser/php-parser'
describe 'php-parser >', ->
describe 'indent >', ->
it 'check space indent #1', ->
convention = parser.indent 'function bar($baz) {', {}
convention.indent.space.should.equal 0
it 'check space indent #2', ->
convention = parser.indent ' function bar($baz) {', {}
convention.indent.space.should.equal 1
it 'check space indent #3', ->
convention = parser.indent ' function bar($baz) {', {}
convention.indent.space.should.equal 1
it 'check space indent #4', ->
convention = parser.indent ' \tfunction bar($baz) {', {}
convention.indent.space.should.equal 1
it 'check tab indent #1', ->
convention = parser.indent '\tfunction bar($baz) {', {}
convention.indent.tab.should.equal 1
it 'check tab indent #2', ->
convention = parser.indent '\t\tfunction bar($baz) {', {}
convention.indent.tab.should.equal 1
it 'check tab indent #3', ->
convention = parser.indent '\t\t function bar($baz) {', {}
convention.indent.tab.should.equal 1
it 'check tab indent #4', ->
convention = parser.indent ' \tfunction bar($baz) {', {}
convention.indent.tab.should.equal 0
it 'check tab indent #5', ->
convention = parser.indent 'function bar($baz) {', {}
convention.indent.tab.should.equal 0
describe 'class brace placement >', ->
it 'check class brace is in newline #1', ->
convention = parser.classBrace 'class Foo', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #2', ->
convention = parser.classBrace ' class Cart ', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #3', ->
convention = parser.classBrace '\tclass Cart ', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #4', ->
convention = parser.classBrace 'class Bar extends Foo ', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #5', ->
convention = parser.classBrace 'class Cart // {}', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #6', ->
convention = parser.classBrace 'class Foo {', {}
convention.classBrace.newline.should.equal 0
it 'check class brace is in same line #1', ->
convention = parser.classBrace 'class Foo {', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #2', ->
convention = parser.classBrace ' class Cart { ', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #3', ->
convention = parser.classBrace '\tclass Cart {', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #4', ->
convention = parser.classBrace 'class Bar extends Foo { } ', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #5', ->
convention = parser.classBrace 'class Cart { // {}', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #6', ->
convention = parser.classBrace 'class Cart // {}', {}
convention.classBrace.sameline.should.equal 0
describe 'control brace placement >', ->
it 'check control brace is in same line #1', ->
convention = parser.controlBrace 'if ($baz) {', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #2', ->
convention = parser.controlBrace '} else {', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #3', ->
convention = parser.controlBrace ' } elseif ($i == 1) { ', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #4', ->
convention = parser.controlBrace '\twhile ($i <= 10) {', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #5', ->
convention = parser.controlBrace ' switch ($i) { ', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #6', ->
convention = parser.controlBrace '} elseif ($i == 1) ', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in same line #7', ->
convention = parser.controlBrace 'while ($i <= 10):', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in same line #8', ->
convention = parser.controlBrace 'switch ($i):', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in same line #9', ->
convention = parser.controlBrace 'while ($i <= 10):', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in new line #1', ->
convention = parser.controlBrace ' if($baz) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #2', ->
convention = parser.controlBrace '\t\t else ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #3', ->
convention = parser.controlBrace ' elseif ($i == 1) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #4', ->
convention = parser.controlBrace '\t\twhile ($i <= 10) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #5', ->
convention = parser.controlBrace 'switch ($i) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #6', ->
convention = parser.controlBrace ' else{', {}
convention.controlBrace.newline.should.equal 0
it 'check control brace is in new line #7', ->
convention = parser.controlBrace 'while ($i <= 10) :', {}
convention.controlBrace.newline.should.equal 0
it 'check control brace is in new line #8', ->
convention = parser.controlBrace 'switch ($i):', {}
convention.controlBrace.newline.should.equal 0
it 'check control brace is in new line #9', ->
convention = parser.controlBrace '} else ', {}
convention.controlBrace.newline.should.equal 0
describe 'method brace placement >', ->
it 'check method brace is in same line #1', ->
convention = parser.methodBrace 'function bar($baz) {', {}
convention.methodBrace.sameline.should.equal 1
it 'check method brace is in same line #2', ->
convention = parser.methodBrace ' function bar($baz, $foo) { ', {}
convention.methodBrace.sameline.should.equal 1
it 'check method brace is in same line #3', ->
convention = parser.methodBrace '\t\tfunction foo() { ', {}
convention.methodBrace.sameline.should.equal 1
it 'check method brace is in same line #4', ->
convention = parser.methodBrace 'function bar($baz, $foo) // {}', {}
convention.methodBrace.sameline.should.equal 0
it 'check method brace is in new line #1', ->
convention = parser.methodBrace 'function bar($baz)', {}
convention.methodBrace.newline.should.equal 1
it 'check method brace is in new line #2', ->
convention = parser.methodBrace ' function bar($baz, $foo) ', {}
convention.methodBrace.newline.should.equal 1
it 'check method brace is in new line #3', ->
convention = parser.methodBrace '\t\tfunction foo()', {}
convention.methodBrace.newline.should.equal 1
it 'check method brace is in new line #4', ->
convention = parser.methodBrace 'function bar($baz, $foo) {', {}
convention.methodBrace.newline.should.equal 0
describe 'space around control statement >', ->
it 'check space around control statement #1', ->
convention = parser.spaceAroundControl ' if ($baz) { ', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #2', ->
convention = parser.spaceAroundControl '\t} elseif ($bar) { ', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #3', ->
convention = parser.spaceAroundControl 'if ($a > $b) :', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #4', ->
convention = parser.spaceAroundControl ' elseif ($a == $b) :', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #5', ->
convention = parser.spaceAroundControl ' while ($i <= 10) {', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #6', ->
convention = parser.spaceAroundControl ' while ($i <= 10) :', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #7', ->
convention = parser.spaceAroundControl 'do {', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #8', ->
convention = parser.spaceAroundControl '\t\tfor ($i = 1; $i <= 10; $i++) {', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #9', ->
convention = parser.spaceAroundControl ' if($baz){ ', {}
convention.spaceAroundControl.space.should.equal 0
it 'check space around control statement #10', ->
convention = parser.spaceAroundControl '\t\tfor($i = 1; $i <= 10; $i++) {', {}
convention.spaceAroundControl.space.should.equal 0
it 'check no space around control statement #1', ->
convention = parser.spaceAroundControl 'if($baz){', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #2', ->
convention = parser.spaceAroundControl '}elseif($bar){', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #3', ->
convention = parser.spaceAroundControl ' if($a > $b):', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #4', ->
convention = parser.spaceAroundControl '\t\telseif($a == $b): ', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #5', ->
convention = parser.spaceAroundControl ' while($i <= 10){ ', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #6', ->
convention = parser.spaceAroundControl ' while($i <= 10):', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #7', ->
convention = parser.spaceAroundControl 'do{', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #8', ->
convention = parser.spaceAroundControl ' for($i = 1; $i <= 10; $i++){ ', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #9', ->
convention = parser.spaceAroundControl ' if ($baz) { ', {}
convention.spaceAroundControl.nospace.should.equal 0
it 'check no space around control statement #10', ->
convention = parser.spaceAroundControl ' for($i = 1; $i <= 10; $i++) { ', {}
convention.spaceAroundControl.nospace.should.equal 0
describe 'space inside control statement >', ->
it 'check space inside control statement #1', ->
convention = parser.spaceInsideControl ' if ( $baz ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #2', ->
convention = parser.spaceInsideControl '\t\t} elseif ( $bar ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #3', ->
convention = parser.spaceInsideControl 'if ( $a > $b ) :', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #4', ->
convention = parser.spaceInsideControl ' elseif ( $a == $b ) : ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #5', ->
convention = parser.spaceInsideControl ' while ( $i <= 10 ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #6', ->
convention = parser.spaceInsideControl ' while ( $i <= 10 ) : ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #7', ->
convention = parser.spaceInsideControl ' for ( $i = 1; $i <= 10; $i++ ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #8', ->
convention = parser.spaceInsideControl ' if ($baz) { ', {}
convention.spaceInsideControl.space.should.equal 0
it 'check space inside control statement #9', ->
convention = parser.spaceInsideControl ' if ($baz ) { ', {}
convention.spaceInsideControl.space.should.equal 0
it 'check no space inside control statement #1', ->
convention = parser.spaceInsideControl ' if ($baz) { ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #2', ->
convention = parser.spaceInsideControl '} elseif ($bar) {', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #3', ->
convention = parser.spaceInsideControl 'if ($a > $b) :', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #4', ->
convention = parser.spaceInsideControl '\t\telseif ($a == $b) :', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #5', ->
convention = parser.spaceInsideControl ' while ($i <= 10) { ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #6', ->
convention = parser.spaceInsideControl ' while ($i <= 10) : ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #7', ->
convention = parser.spaceInsideControl '\t\tfor ($i = 1; $i <= 10; $i++) { ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #8', ->
convention = parser.spaceInsideControl ' } elseif ( $bar ) { ', {}
convention.spaceInsideControl.nospace.should.equal 0
it 'check no space inside control statement #9', ->
convention = parser.spaceInsideControl ' } elseif ( $bar) { ', {}
convention.spaceInsideControl.nospace.should.equal 0
describe 'space around method params >', ->
it 'check space around method params #1', ->
convention = parser.spaceAroundMethod 'function bar ($baz) {', {}
convention.spaceAroundMethod.space.should.equal 1
it 'check space around method params #2', ->
convention = parser.spaceAroundMethod ' function bar ($baz, $foo) { ', {}
convention.spaceAroundMethod.space.should.equal 1
it 'check space around method params #3', ->
convention = parser.spaceAroundMethod '\t\tfunction foo () { ', {}
convention.spaceAroundMethod.space.should.equal 1
it 'check space around method params #4', ->
convention = parser.spaceAroundMethod 'function bar ($baz, $foo) // {', {}
convention.spaceAroundMethod.space.should.equal 0
it 'check space around method params #5', ->
convention = parser.spaceAroundMethod 'function bar($baz) {', {}
convention.spaceAroundMethod.space.should.equal 0
it 'check space around method params #6', ->
convention = parser.spaceAroundMethod 'function bar($baz){', {}
convention.spaceAroundMethod.space.should.equal 0
it 'check no space around method params #1', ->
convention = parser.spaceAroundMethod 'function bar($baz){', {}
convention.spaceAroundMethod.nospace.should.equal 1
it 'check no space around method params #2', ->
convention = parser.spaceAroundMethod ' function bar($baz, $foo){ ', {}
convention.spaceAroundMethod.nospace.should.equal 1
it 'check no space around method params #3', ->
convention = parser.spaceAroundMethod '\t\tfunction foo(){ ', {}
convention.spaceAroundMethod.nospace.should.equal 1
it 'check no space around method params #4', ->
convention = parser.spaceAroundMethod ' function bar($baz, $foo)//{', {}
convention.spaceAroundMethod.nospace.should.equal 0
it 'check no space around method params #5', ->
convention = parser.spaceAroundMethod 'function bar ($baz) {', {}
convention.spaceAroundMethod.nospace.should.equal 0
it 'check no space around method params #6', ->
convention = parser.spaceAroundMethod 'function bar ($baz){', {}
convention.spaceAroundMethod.nospace.should.equal 0
describe 'space inside method params >', ->
it 'check space inside method params #1', ->
convention = parser.spaceInsideMethod 'function bar ( $baz ) {', {}
convention.spaceInsideMethod.space.should.equal 1
it 'check space inside method params #2', ->
convention = parser.spaceInsideMethod ' function bar ( $baz, $foo ) { ', {}
convention.spaceInsideMethod.space.should.equal 1
it 'check space inside method params #3', ->
convention = parser.spaceInsideMethod '\t\tfunction bar( $baz, $foo ){ ', {}
convention.spaceInsideMethod.space.should.equal 1
it 'check space inside method params #4', ->
convention = parser.spaceInsideMethod 'function foo () {', {}
convention.spaceInsideMethod.space.should.equal 0
it 'check space inside method params #5', ->
convention = parser.spaceInsideMethod 'function bar ($baz ) {', {}
convention.spaceInsideMethod.space.should.equal 0
it 'check space inside method params #6', ->
convention = parser.spaceInsideMethod 'function bar ($baz) {', {}
convention.spaceInsideMethod.space.should.equal 0
it 'check no space inside method params #1', ->
convention = parser.spaceInsideMethod 'function bar ($baz) {', {}
convention.spaceInsideMethod.nospace.should.equal 1
it 'check no space inside method params #2', ->
convention = parser.spaceInsideMethod ' function bar ($baz, $foo) { ', {}
convention.spaceInsideMethod.nospace.should.equal 1
it 'check no space inside method params #3', ->
convention = parser.spaceInsideMethod '\t\tfunction bar($baz, $foo){ ', {}
convention.spaceInsideMethod.nospace.should.equal 1
it 'check no space inside method params #4', ->
convention = parser.spaceInsideMethod ' function foo () {', {}
convention.spaceInsideMethod.nospace.should.equal 0
it 'check no space inside method params #5', ->
convention = parser.spaceInsideMethod ' function bar ($baz ) { ', {}
convention.spaceInsideMethod.nospace.should.equal 0
it 'check no space inside method params #6', ->
convention = parser.spaceInsideMethod 'function bar( $baz, $foo ){', {}
convention.spaceInsideMethod.nospace.should.equal 0
describe 'class naming >', ->
it 'check whether class name in camel case #1', ->
convention = parser.className ' class fooBarBaz { ', {}
convention.className.camel.should.equal 1
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in camel case #2', ->
convention = parser.className '\t\tclass fooBarBaz2{ ', {}
convention.className.camel.should.equal 1
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in camel case #3', ->
convention = parser.className 'class fooBar1Baz', {}
convention.className.camel.should.equal 1
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in pascal case #1', ->
convention = parser.className ' class FooBarBaz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 1
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in pascal case #2', ->
convention = parser.className '\t\tclass FooBarBaz1{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 1
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in pascal case #3', ->
convention = parser.className ' class FooBar1Baz', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 1
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in caps snake case #1', ->
convention = parser.className ' class FOO_BAR_BAZ { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 1
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in caps snake case #2', ->
convention = parser.className '\t\tclass FOO_BAR_BAZ2{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 1
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in caps snake case #3', ->
convention = parser.className ' class FOO_BAR1_BAZ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 1
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake pascal case #1', ->
convention = parser.className ' class Foo_Bar_Baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 1
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake pascal case #2', ->
convention = parser.className '\t\tclass Foo_Bar_Baz1{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 1
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake pascal case #3', ->
convention = parser.className ' class Foo_Bar2_Baz', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 1
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake case #1', ->
convention = parser.className ' class foo_bar_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 1
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake case #2', ->
convention = parser.className '\t\tclass foo_bar_baz2{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 1
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake case #3', ->
convention = parser.className ' class foo_bar1_baz', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 1
convention.className.uppersnake.should.equal 0
it 'check whether class name in uppercase snake case #1', ->
convention = parser.className ' class Foo_bar_baz {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 1
it 'check whether class name in uppercase snake case #2', ->
convention = parser.className '\t\tclass Foo_bar1_baz2{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 1
it 'check whether class name in uppercase snake case #3', ->
convention = parser.className ' class Foo_bar1_baz2', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 1
it 'all rules ingnore this #1', ->
convention = parser.className ' class _Foo_bar_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #2', ->
convention = parser.className ' class Foo_bar_baz_{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #3', ->
convention = parser.className ' class Foo_BAR_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #4', ->
convention = parser.className ' class Foo_bar_Baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #5', ->
convention = parser.className 'class foo_BAR_Baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #6', ->
convention = parser.className ' class foo_BAR_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #7', ->
convention = parser.className 'class foo_BarBaz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #8', ->
convention = parser.className 'class fooBARBaz {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #9', ->
convention = parser.className 'class foo {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #10', ->
convention = parser.className 'class FOO {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #11', ->
convention = parser.className 'class Foo {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
describe 'const naming >', ->
it 'check whether const name in camel case #1', ->
convention = parser.constName ' const fooBarBaz = 0; ', {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in camel case #2', ->
convention = parser.constName '\t\tconst fooBarBaz2=0; ', {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in camel case #3', ->
convention = parser.constName 'const fooBar1Baz = 0 ;', {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in camel case #4', ->
convention = parser.constName "define('barBaz', 0);", {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #1', ->
convention = parser.constName ' const FooBarBaz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #2', ->
convention = parser.constName '\t\tconst FooBarBaz1=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #3', ->
convention = parser.constName ' const FooBar1Baz = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #4', ->
convention = parser.constName "define('BarBaz', 0);", {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #1', ->
convention = parser.constName ' const FOO_BAR_BAZ = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #2', ->
convention = parser.constName '\t\tconst FOO_BAR_BAZ2=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #3', ->
convention = parser.constName ' const FOO_BAR1_BAZ = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #4', ->
convention = parser.constName 'define("BAR_BAZ", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #1', ->
convention = parser.constName ' const Foo_Bar_Baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #2', ->
convention = parser.constName '\t\tconst Foo_Bar_Baz1=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #3', ->
convention = parser.constName ' const Foo_Bar2_Baz=0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #4', ->
convention = parser.constName ' define("Bar_Baz", 0); ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake case #1', ->
convention = parser.constName ' const foo_bar_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'check whether const name in snake case #2', ->
convention = parser.constName '\t\tconst foo_bar_baz2=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'check whether const name in snake case #3', ->
convention = parser.constName ' const foo_bar1_baz = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'check whether const name in snake case #4', ->
convention = parser.constName "\t\tdefine('bar_baz', 0); ", {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'all rules ingnore this #1', ->
convention = parser.constName ' const _Foo_bar_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #2', ->
convention = parser.constName ' const Foo_bar_baz_=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #3', ->
convention = parser.constName ' const Foo_BAR_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #4', ->
convention = parser.constName ' const Foo_bar_Baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #5', ->
convention = parser.constName 'const foo_BAR_Baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #6', ->
convention = parser.constName ' const foo_BAR_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #7', ->
convention = parser.constName 'const foo_BarBaz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #8', ->
convention = parser.constName 'const fooBARBaz = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #9', ->
convention = parser.constName 'const foo = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #10', ->
convention = parser.constName 'const FOO = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #11', ->
convention = parser.constName 'const Foo = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #12', ->
convention = parser.constName 'define("bar", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #13', ->
convention = parser.constName 'define("barBAR", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #14', ->
convention = parser.constName 'define("barBARBaz", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
describe 'const naming >', ->
it 'check whether function name in camel case #1', ->
convention = parser.functionName 'function barBaz(){', {}
convention.functionName.camel.should.equal 1
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in camel case #2', ->
convention = parser.functionName '\t\tfunction barBaz(){', {}
convention.functionName.camel.should.equal 1
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in camel case #3', ->
convention = parser.functionName ' public function barBaz(){ ', {}
convention.functionName.camel.should.equal 1
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in pascal case #1', ->
convention = parser.functionName 'function BarBaz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 1
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in pascal case #2', ->
convention = parser.functionName '\t\tfunction BarBaz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 1
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in pascal case #3', ->
convention = parser.functionName ' public function BarBaz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 1
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in caps snake case #1', ->
convention = parser.functionName 'function BAR_BAZ(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 1
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in caps snake case #2', ->
convention = parser.functionName '\t\tfunction BAR_BAZ(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 1
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in caps snake case #3', ->
convention = parser.functionName 'public function BAR_BAZ(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 1
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in snake pascal case #1', ->
convention = parser.functionName 'function Bar_Baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 1
convention.functionName.snake.should.equal 0
it 'check whether function name in snake pascal case #2', ->
convention = parser.functionName '\t\tfunction Bar_Baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 1
convention.functionName.snake.should.equal 0
it 'check whether function name in snake pascal case #3', ->
convention = parser.functionName 'public function Bar_Baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 1
convention.functionName.snake.should.equal 0
it 'check whether function name in snake case #1', ->
convention = parser.functionName 'function bar_baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 1
it 'check whether function name in snake case #2', ->
convention = parser.functionName '\t\tfunction bar_baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 1
it 'check whether function name in snake case #3', ->
convention = parser.functionName 'public function bar_baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 1
describe 'method declare order >', ->
it 'check visibility - static case #1', ->
convention = parser.methodDeclare ' public static function bar($baz) ', {}
convention.methodDeclare.staticlate.should.equal 1
it 'check visibility - static case #2', ->
convention = parser.methodDeclare "\t\tprotected static $my_static = 'foo'; ", {}
convention.methodDeclare.staticlate.should.equal 1
it 'check visibility - static case #3', ->
convention = parser.methodDeclare "private static $my_static = 'foo'; ", {}
convention.methodDeclare.staticlate.should.equal 1
it 'check visibility - static case #4', ->
convention = parser.methodDeclare ' static public function bar($baz) ', {}
convention.methodDeclare.staticlate.should.equal 0
it 'check static - visibility case #1', ->
convention = parser.methodDeclare ' static public function bar($baz) ', {}
convention.methodDeclare.staticfirst.should.equal 1
it 'check static - visibility case #2', ->
convention = parser.methodDeclare "\t\tstatic protected $my_static = 'foo'; ", {}
convention.methodDeclare.staticfirst.should.equal 1
it 'check static - visibility case #3', ->
convention = parser.methodDeclare " static private $my_static = 'foo'; ", {}
convention.methodDeclare.staticfirst.should.equal 1
it 'check static - visibility case #4', ->
convention = parser.methodDeclare "protected static $my_static = 'foo';", {}
convention.methodDeclare.staticfirst.should.equal 0
it 'check visibility - abstract(final) case #1', ->
convention = parser.methodDeclare " public abstract function bar($baz); ", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #2', ->
convention = parser.methodDeclare "\t\tprotected abstract function getValue(); ", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #3', ->
convention = parser.methodDeclare "private abstract function getValue();", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #4', ->
convention = parser.methodDeclare " private final function getValue(); ", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #5', ->
convention = parser.methodDeclare " abstract public function bar($baz); ", {}
convention.methodDeclare.abstractlate.should.equal 0
it 'check abstract(final) - visibility case #1', ->
convention = parser.methodDeclare " abstract public function bar($baz); ", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #2', ->
convention = parser.methodDeclare "\t\tabstract protected function getValue(); ", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #3', ->
convention = parser.methodDeclare "abstract private function getValue();", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #4', ->
convention = parser.methodDeclare " final private function getValue(); ", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #5', ->
convention = parser.methodDeclare " protected abstract function getValue(); ", {}
convention.methodDeclare.abstractfirst.should.equal 0
| true | # Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
should = require 'should'
parser = require '../../src/parser/php-parser'
describe 'php-parser >', ->
describe 'indent >', ->
it 'check space indent #1', ->
convention = parser.indent 'function bar($baz) {', {}
convention.indent.space.should.equal 0
it 'check space indent #2', ->
convention = parser.indent ' function bar($baz) {', {}
convention.indent.space.should.equal 1
it 'check space indent #3', ->
convention = parser.indent ' function bar($baz) {', {}
convention.indent.space.should.equal 1
it 'check space indent #4', ->
convention = parser.indent ' \tfunction bar($baz) {', {}
convention.indent.space.should.equal 1
it 'check tab indent #1', ->
convention = parser.indent '\tfunction bar($baz) {', {}
convention.indent.tab.should.equal 1
it 'check tab indent #2', ->
convention = parser.indent '\t\tfunction bar($baz) {', {}
convention.indent.tab.should.equal 1
it 'check tab indent #3', ->
convention = parser.indent '\t\t function bar($baz) {', {}
convention.indent.tab.should.equal 1
it 'check tab indent #4', ->
convention = parser.indent ' \tfunction bar($baz) {', {}
convention.indent.tab.should.equal 0
it 'check tab indent #5', ->
convention = parser.indent 'function bar($baz) {', {}
convention.indent.tab.should.equal 0
describe 'class brace placement >', ->
it 'check class brace is in newline #1', ->
convention = parser.classBrace 'class Foo', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #2', ->
convention = parser.classBrace ' class Cart ', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #3', ->
convention = parser.classBrace '\tclass Cart ', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #4', ->
convention = parser.classBrace 'class Bar extends Foo ', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #5', ->
convention = parser.classBrace 'class Cart // {}', {}
convention.classBrace.newline.should.equal 1
it 'check class brace is in newline #6', ->
convention = parser.classBrace 'class Foo {', {}
convention.classBrace.newline.should.equal 0
it 'check class brace is in same line #1', ->
convention = parser.classBrace 'class Foo {', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #2', ->
convention = parser.classBrace ' class Cart { ', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #3', ->
convention = parser.classBrace '\tclass Cart {', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #4', ->
convention = parser.classBrace 'class Bar extends Foo { } ', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #5', ->
convention = parser.classBrace 'class Cart { // {}', {}
convention.classBrace.sameline.should.equal 1
it 'check class brace is in same line #6', ->
convention = parser.classBrace 'class Cart // {}', {}
convention.classBrace.sameline.should.equal 0
describe 'control brace placement >', ->
it 'check control brace is in same line #1', ->
convention = parser.controlBrace 'if ($baz) {', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #2', ->
convention = parser.controlBrace '} else {', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #3', ->
convention = parser.controlBrace ' } elseif ($i == 1) { ', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #4', ->
convention = parser.controlBrace '\twhile ($i <= 10) {', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #5', ->
convention = parser.controlBrace ' switch ($i) { ', {}
convention.controlBrace.sameline.should.equal 1
it 'check control brace is in same line #6', ->
convention = parser.controlBrace '} elseif ($i == 1) ', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in same line #7', ->
convention = parser.controlBrace 'while ($i <= 10):', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in same line #8', ->
convention = parser.controlBrace 'switch ($i):', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in same line #9', ->
convention = parser.controlBrace 'while ($i <= 10):', {}
convention.controlBrace.sameline.should.equal 0
it 'check control brace is in new line #1', ->
convention = parser.controlBrace ' if($baz) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #2', ->
convention = parser.controlBrace '\t\t else ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #3', ->
convention = parser.controlBrace ' elseif ($i == 1) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #4', ->
convention = parser.controlBrace '\t\twhile ($i <= 10) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #5', ->
convention = parser.controlBrace 'switch ($i) ', {}
convention.controlBrace.newline.should.equal 1
it 'check control brace is in new line #6', ->
convention = parser.controlBrace ' else{', {}
convention.controlBrace.newline.should.equal 0
it 'check control brace is in new line #7', ->
convention = parser.controlBrace 'while ($i <= 10) :', {}
convention.controlBrace.newline.should.equal 0
it 'check control brace is in new line #8', ->
convention = parser.controlBrace 'switch ($i):', {}
convention.controlBrace.newline.should.equal 0
it 'check control brace is in new line #9', ->
convention = parser.controlBrace '} else ', {}
convention.controlBrace.newline.should.equal 0
describe 'method brace placement >', ->
it 'check method brace is in same line #1', ->
convention = parser.methodBrace 'function bar($baz) {', {}
convention.methodBrace.sameline.should.equal 1
it 'check method brace is in same line #2', ->
convention = parser.methodBrace ' function bar($baz, $foo) { ', {}
convention.methodBrace.sameline.should.equal 1
it 'check method brace is in same line #3', ->
convention = parser.methodBrace '\t\tfunction foo() { ', {}
convention.methodBrace.sameline.should.equal 1
it 'check method brace is in same line #4', ->
convention = parser.methodBrace 'function bar($baz, $foo) // {}', {}
convention.methodBrace.sameline.should.equal 0
it 'check method brace is in new line #1', ->
convention = parser.methodBrace 'function bar($baz)', {}
convention.methodBrace.newline.should.equal 1
it 'check method brace is in new line #2', ->
convention = parser.methodBrace ' function bar($baz, $foo) ', {}
convention.methodBrace.newline.should.equal 1
it 'check method brace is in new line #3', ->
convention = parser.methodBrace '\t\tfunction foo()', {}
convention.methodBrace.newline.should.equal 1
it 'check method brace is in new line #4', ->
convention = parser.methodBrace 'function bar($baz, $foo) {', {}
convention.methodBrace.newline.should.equal 0
describe 'space around control statement >', ->
it 'check space around control statement #1', ->
convention = parser.spaceAroundControl ' if ($baz) { ', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #2', ->
convention = parser.spaceAroundControl '\t} elseif ($bar) { ', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #3', ->
convention = parser.spaceAroundControl 'if ($a > $b) :', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #4', ->
convention = parser.spaceAroundControl ' elseif ($a == $b) :', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #5', ->
convention = parser.spaceAroundControl ' while ($i <= 10) {', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #6', ->
convention = parser.spaceAroundControl ' while ($i <= 10) :', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #7', ->
convention = parser.spaceAroundControl 'do {', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #8', ->
convention = parser.spaceAroundControl '\t\tfor ($i = 1; $i <= 10; $i++) {', {}
convention.spaceAroundControl.space.should.equal 1
it 'check space around control statement #9', ->
convention = parser.spaceAroundControl ' if($baz){ ', {}
convention.spaceAroundControl.space.should.equal 0
it 'check space around control statement #10', ->
convention = parser.spaceAroundControl '\t\tfor($i = 1; $i <= 10; $i++) {', {}
convention.spaceAroundControl.space.should.equal 0
it 'check no space around control statement #1', ->
convention = parser.spaceAroundControl 'if($baz){', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #2', ->
convention = parser.spaceAroundControl '}elseif($bar){', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #3', ->
convention = parser.spaceAroundControl ' if($a > $b):', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #4', ->
convention = parser.spaceAroundControl '\t\telseif($a == $b): ', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #5', ->
convention = parser.spaceAroundControl ' while($i <= 10){ ', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #6', ->
convention = parser.spaceAroundControl ' while($i <= 10):', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #7', ->
convention = parser.spaceAroundControl 'do{', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #8', ->
convention = parser.spaceAroundControl ' for($i = 1; $i <= 10; $i++){ ', {}
convention.spaceAroundControl.nospace.should.equal 1
it 'check no space around control statement #9', ->
convention = parser.spaceAroundControl ' if ($baz) { ', {}
convention.spaceAroundControl.nospace.should.equal 0
it 'check no space around control statement #10', ->
convention = parser.spaceAroundControl ' for($i = 1; $i <= 10; $i++) { ', {}
convention.spaceAroundControl.nospace.should.equal 0
describe 'space inside control statement >', ->
it 'check space inside control statement #1', ->
convention = parser.spaceInsideControl ' if ( $baz ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #2', ->
convention = parser.spaceInsideControl '\t\t} elseif ( $bar ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #3', ->
convention = parser.spaceInsideControl 'if ( $a > $b ) :', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #4', ->
convention = parser.spaceInsideControl ' elseif ( $a == $b ) : ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #5', ->
convention = parser.spaceInsideControl ' while ( $i <= 10 ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #6', ->
convention = parser.spaceInsideControl ' while ( $i <= 10 ) : ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #7', ->
convention = parser.spaceInsideControl ' for ( $i = 1; $i <= 10; $i++ ) { ', {}
convention.spaceInsideControl.space.should.equal 1
it 'check space inside control statement #8', ->
convention = parser.spaceInsideControl ' if ($baz) { ', {}
convention.spaceInsideControl.space.should.equal 0
it 'check space inside control statement #9', ->
convention = parser.spaceInsideControl ' if ($baz ) { ', {}
convention.spaceInsideControl.space.should.equal 0
it 'check no space inside control statement #1', ->
convention = parser.spaceInsideControl ' if ($baz) { ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #2', ->
convention = parser.spaceInsideControl '} elseif ($bar) {', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #3', ->
convention = parser.spaceInsideControl 'if ($a > $b) :', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #4', ->
convention = parser.spaceInsideControl '\t\telseif ($a == $b) :', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #5', ->
convention = parser.spaceInsideControl ' while ($i <= 10) { ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #6', ->
convention = parser.spaceInsideControl ' while ($i <= 10) : ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #7', ->
convention = parser.spaceInsideControl '\t\tfor ($i = 1; $i <= 10; $i++) { ', {}
convention.spaceInsideControl.nospace.should.equal 1
it 'check no space inside control statement #8', ->
convention = parser.spaceInsideControl ' } elseif ( $bar ) { ', {}
convention.spaceInsideControl.nospace.should.equal 0
it 'check no space inside control statement #9', ->
convention = parser.spaceInsideControl ' } elseif ( $bar) { ', {}
convention.spaceInsideControl.nospace.should.equal 0
describe 'space around method params >', ->
it 'check space around method params #1', ->
convention = parser.spaceAroundMethod 'function bar ($baz) {', {}
convention.spaceAroundMethod.space.should.equal 1
it 'check space around method params #2', ->
convention = parser.spaceAroundMethod ' function bar ($baz, $foo) { ', {}
convention.spaceAroundMethod.space.should.equal 1
it 'check space around method params #3', ->
convention = parser.spaceAroundMethod '\t\tfunction foo () { ', {}
convention.spaceAroundMethod.space.should.equal 1
it 'check space around method params #4', ->
convention = parser.spaceAroundMethod 'function bar ($baz, $foo) // {', {}
convention.spaceAroundMethod.space.should.equal 0
it 'check space around method params #5', ->
convention = parser.spaceAroundMethod 'function bar($baz) {', {}
convention.spaceAroundMethod.space.should.equal 0
it 'check space around method params #6', ->
convention = parser.spaceAroundMethod 'function bar($baz){', {}
convention.spaceAroundMethod.space.should.equal 0
it 'check no space around method params #1', ->
convention = parser.spaceAroundMethod 'function bar($baz){', {}
convention.spaceAroundMethod.nospace.should.equal 1
it 'check no space around method params #2', ->
convention = parser.spaceAroundMethod ' function bar($baz, $foo){ ', {}
convention.spaceAroundMethod.nospace.should.equal 1
it 'check no space around method params #3', ->
convention = parser.spaceAroundMethod '\t\tfunction foo(){ ', {}
convention.spaceAroundMethod.nospace.should.equal 1
it 'check no space around method params #4', ->
convention = parser.spaceAroundMethod ' function bar($baz, $foo)//{', {}
convention.spaceAroundMethod.nospace.should.equal 0
it 'check no space around method params #5', ->
convention = parser.spaceAroundMethod 'function bar ($baz) {', {}
convention.spaceAroundMethod.nospace.should.equal 0
it 'check no space around method params #6', ->
convention = parser.spaceAroundMethod 'function bar ($baz){', {}
convention.spaceAroundMethod.nospace.should.equal 0
describe 'space inside method params >', ->
it 'check space inside method params #1', ->
convention = parser.spaceInsideMethod 'function bar ( $baz ) {', {}
convention.spaceInsideMethod.space.should.equal 1
it 'check space inside method params #2', ->
convention = parser.spaceInsideMethod ' function bar ( $baz, $foo ) { ', {}
convention.spaceInsideMethod.space.should.equal 1
it 'check space inside method params #3', ->
convention = parser.spaceInsideMethod '\t\tfunction bar( $baz, $foo ){ ', {}
convention.spaceInsideMethod.space.should.equal 1
it 'check space inside method params #4', ->
convention = parser.spaceInsideMethod 'function foo () {', {}
convention.spaceInsideMethod.space.should.equal 0
it 'check space inside method params #5', ->
convention = parser.spaceInsideMethod 'function bar ($baz ) {', {}
convention.spaceInsideMethod.space.should.equal 0
it 'check space inside method params #6', ->
convention = parser.spaceInsideMethod 'function bar ($baz) {', {}
convention.spaceInsideMethod.space.should.equal 0
it 'check no space inside method params #1', ->
convention = parser.spaceInsideMethod 'function bar ($baz) {', {}
convention.spaceInsideMethod.nospace.should.equal 1
it 'check no space inside method params #2', ->
convention = parser.spaceInsideMethod ' function bar ($baz, $foo) { ', {}
convention.spaceInsideMethod.nospace.should.equal 1
it 'check no space inside method params #3', ->
convention = parser.spaceInsideMethod '\t\tfunction bar($baz, $foo){ ', {}
convention.spaceInsideMethod.nospace.should.equal 1
it 'check no space inside method params #4', ->
convention = parser.spaceInsideMethod ' function foo () {', {}
convention.spaceInsideMethod.nospace.should.equal 0
it 'check no space inside method params #5', ->
convention = parser.spaceInsideMethod ' function bar ($baz ) { ', {}
convention.spaceInsideMethod.nospace.should.equal 0
it 'check no space inside method params #6', ->
convention = parser.spaceInsideMethod 'function bar( $baz, $foo ){', {}
convention.spaceInsideMethod.nospace.should.equal 0
describe 'class naming >', ->
it 'check whether class name in camel case #1', ->
convention = parser.className ' class fooBarBaz { ', {}
convention.className.camel.should.equal 1
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in camel case #2', ->
convention = parser.className '\t\tclass fooBarBaz2{ ', {}
convention.className.camel.should.equal 1
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in camel case #3', ->
convention = parser.className 'class fooBar1Baz', {}
convention.className.camel.should.equal 1
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in pascal case #1', ->
convention = parser.className ' class FooBarBaz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 1
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in pascal case #2', ->
convention = parser.className '\t\tclass FooBarBaz1{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 1
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in pascal case #3', ->
convention = parser.className ' class FooBar1Baz', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 1
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in caps snake case #1', ->
convention = parser.className ' class FOO_BAR_BAZ { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 1
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in caps snake case #2', ->
convention = parser.className '\t\tclass FOO_BAR_BAZ2{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 1
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in caps snake case #3', ->
convention = parser.className ' class FOO_BAR1_BAZ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 1
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake pascal case #1', ->
convention = parser.className ' class Foo_Bar_Baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 1
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake pascal case #2', ->
convention = parser.className '\t\tclass Foo_Bar_Baz1{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 1
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake pascal case #3', ->
convention = parser.className ' class Foo_Bar2_Baz', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 1
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake case #1', ->
convention = parser.className ' class foo_bar_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 1
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake case #2', ->
convention = parser.className '\t\tclass foo_bar_baz2{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 1
convention.className.uppersnake.should.equal 0
it 'check whether class name in snake case #3', ->
convention = parser.className ' class foo_bar1_baz', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 1
convention.className.uppersnake.should.equal 0
it 'check whether class name in uppercase snake case #1', ->
convention = parser.className ' class Foo_bar_baz {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 1
it 'check whether class name in uppercase snake case #2', ->
convention = parser.className '\t\tclass Foo_bar1_baz2{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 1
it 'check whether class name in uppercase snake case #3', ->
convention = parser.className ' class Foo_bar1_baz2', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 1
it 'all rules ingnore this #1', ->
convention = parser.className ' class _Foo_bar_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #2', ->
convention = parser.className ' class Foo_bar_baz_{ ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #3', ->
convention = parser.className ' class Foo_BAR_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #4', ->
convention = parser.className ' class Foo_bar_Baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #5', ->
convention = parser.className 'class foo_BAR_Baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #6', ->
convention = parser.className ' class foo_BAR_baz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #7', ->
convention = parser.className 'class foo_BarBaz { ', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #8', ->
convention = parser.className 'class fooBARBaz {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #9', ->
convention = parser.className 'class foo {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #10', ->
convention = parser.className 'class FOO {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
it 'all rules ingnore this #11', ->
convention = parser.className 'class Foo {', {}
convention.className.camel.should.equal 0
convention.className.pascal.should.equal 0
convention.className.capssnake.should.equal 0
convention.className.snakepascal.should.equal 0
convention.className.snake.should.equal 0
convention.className.uppersnake.should.equal 0
describe 'const naming >', ->
it 'check whether const name in camel case #1', ->
convention = parser.constName ' const fooBarBaz = 0; ', {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in camel case #2', ->
convention = parser.constName '\t\tconst fooBarBaz2=0; ', {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in camel case #3', ->
convention = parser.constName 'const fooBar1Baz = 0 ;', {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in camel case #4', ->
convention = parser.constName "define('barBaz', 0);", {}
convention.constName.camel.should.equal 1
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #1', ->
convention = parser.constName ' const FooBarBaz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #2', ->
convention = parser.constName '\t\tconst FooBarBaz1=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #3', ->
convention = parser.constName ' const FooBar1Baz = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in pascal case #4', ->
convention = parser.constName "define('BarBaz', 0);", {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 1
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #1', ->
convention = parser.constName ' const FOO_BAR_BAZ = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #2', ->
convention = parser.constName '\t\tconst FOO_BAR_BAZ2=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #3', ->
convention = parser.constName ' const FOO_BAR1_BAZ = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in caps snake case #4', ->
convention = parser.constName 'define("BAR_BAZ", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 1
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #1', ->
convention = parser.constName ' const Foo_Bar_Baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #2', ->
convention = parser.constName '\t\tconst Foo_Bar_Baz1=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #3', ->
convention = parser.constName ' const Foo_Bar2_Baz=0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake pascal case #4', ->
convention = parser.constName ' define("Bar_Baz", 0); ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 1
convention.constName.snake.should.equal 0
it 'check whether const name in snake case #1', ->
convention = parser.constName ' const foo_bar_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'check whether const name in snake case #2', ->
convention = parser.constName '\t\tconst foo_bar_baz2=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'check whether const name in snake case #3', ->
convention = parser.constName ' const foo_bar1_baz = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'check whether const name in snake case #4', ->
convention = parser.constName "\t\tdefine('bar_baz', 0); ", {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 1
it 'all rules ingnore this #1', ->
convention = parser.constName ' const _Foo_bar_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #2', ->
convention = parser.constName ' const Foo_bar_baz_=0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #3', ->
convention = parser.constName ' const Foo_BAR_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #4', ->
convention = parser.constName ' const Foo_bar_Baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #5', ->
convention = parser.constName 'const foo_BAR_Baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #6', ->
convention = parser.constName ' const foo_BAR_baz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #7', ->
convention = parser.constName 'const foo_BarBaz = 0; ', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #8', ->
convention = parser.constName 'const fooBARBaz = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #9', ->
convention = parser.constName 'const foo = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #10', ->
convention = parser.constName 'const FOO = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #11', ->
convention = parser.constName 'const Foo = 0;', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #12', ->
convention = parser.constName 'define("bar", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #13', ->
convention = parser.constName 'define("barBAR", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
it 'all rules ingnore this #14', ->
convention = parser.constName 'define("barBARBaz", 0);', {}
convention.constName.camel.should.equal 0
convention.constName.pascal.should.equal 0
convention.constName.capssnake.should.equal 0
convention.constName.snakepascal.should.equal 0
convention.constName.snake.should.equal 0
describe 'const naming >', ->
it 'check whether function name in camel case #1', ->
convention = parser.functionName 'function barBaz(){', {}
convention.functionName.camel.should.equal 1
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in camel case #2', ->
convention = parser.functionName '\t\tfunction barBaz(){', {}
convention.functionName.camel.should.equal 1
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in camel case #3', ->
convention = parser.functionName ' public function barBaz(){ ', {}
convention.functionName.camel.should.equal 1
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in pascal case #1', ->
convention = parser.functionName 'function BarBaz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 1
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in pascal case #2', ->
convention = parser.functionName '\t\tfunction BarBaz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 1
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in pascal case #3', ->
convention = parser.functionName ' public function BarBaz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 1
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in caps snake case #1', ->
convention = parser.functionName 'function BAR_BAZ(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 1
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in caps snake case #2', ->
convention = parser.functionName '\t\tfunction BAR_BAZ(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 1
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in caps snake case #3', ->
convention = parser.functionName 'public function BAR_BAZ(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 1
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 0
it 'check whether function name in snake pascal case #1', ->
convention = parser.functionName 'function Bar_Baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 1
convention.functionName.snake.should.equal 0
it 'check whether function name in snake pascal case #2', ->
convention = parser.functionName '\t\tfunction Bar_Baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 1
convention.functionName.snake.should.equal 0
it 'check whether function name in snake pascal case #3', ->
convention = parser.functionName 'public function Bar_Baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 1
convention.functionName.snake.should.equal 0
it 'check whether function name in snake case #1', ->
convention = parser.functionName 'function bar_baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 1
it 'check whether function name in snake case #2', ->
convention = parser.functionName '\t\tfunction bar_baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 1
it 'check whether function name in snake case #3', ->
convention = parser.functionName 'public function bar_baz(){', {}
convention.functionName.camel.should.equal 0
convention.functionName.pascal.should.equal 0
convention.functionName.capssnake.should.equal 0
convention.functionName.snakepascal.should.equal 0
convention.functionName.snake.should.equal 1
describe 'method declare order >', ->
it 'check visibility - static case #1', ->
convention = parser.methodDeclare ' public static function bar($baz) ', {}
convention.methodDeclare.staticlate.should.equal 1
it 'check visibility - static case #2', ->
convention = parser.methodDeclare "\t\tprotected static $my_static = 'foo'; ", {}
convention.methodDeclare.staticlate.should.equal 1
it 'check visibility - static case #3', ->
convention = parser.methodDeclare "private static $my_static = 'foo'; ", {}
convention.methodDeclare.staticlate.should.equal 1
it 'check visibility - static case #4', ->
convention = parser.methodDeclare ' static public function bar($baz) ', {}
convention.methodDeclare.staticlate.should.equal 0
it 'check static - visibility case #1', ->
convention = parser.methodDeclare ' static public function bar($baz) ', {}
convention.methodDeclare.staticfirst.should.equal 1
it 'check static - visibility case #2', ->
convention = parser.methodDeclare "\t\tstatic protected $my_static = 'foo'; ", {}
convention.methodDeclare.staticfirst.should.equal 1
it 'check static - visibility case #3', ->
convention = parser.methodDeclare " static private $my_static = 'foo'; ", {}
convention.methodDeclare.staticfirst.should.equal 1
it 'check static - visibility case #4', ->
convention = parser.methodDeclare "protected static $my_static = 'foo';", {}
convention.methodDeclare.staticfirst.should.equal 0
it 'check visibility - abstract(final) case #1', ->
convention = parser.methodDeclare " public abstract function bar($baz); ", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #2', ->
convention = parser.methodDeclare "\t\tprotected abstract function getValue(); ", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #3', ->
convention = parser.methodDeclare "private abstract function getValue();", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #4', ->
convention = parser.methodDeclare " private final function getValue(); ", {}
convention.methodDeclare.abstractlate.should.equal 1
it 'check visibility - abstract(final) case #5', ->
convention = parser.methodDeclare " abstract public function bar($baz); ", {}
convention.methodDeclare.abstractlate.should.equal 0
it 'check abstract(final) - visibility case #1', ->
convention = parser.methodDeclare " abstract public function bar($baz); ", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #2', ->
convention = parser.methodDeclare "\t\tabstract protected function getValue(); ", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #3', ->
convention = parser.methodDeclare "abstract private function getValue();", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #4', ->
convention = parser.methodDeclare " final private function getValue(); ", {}
convention.methodDeclare.abstractfirst.should.equal 1
it 'check abstract(final) - visibility case #5', ->
convention = parser.methodDeclare " protected abstract function getValue(); ", {}
convention.methodDeclare.abstractfirst.should.equal 0
|
[
{
"context": " @fileoverview Prevent usage of setState\n# @author Mark Dalgleish\n###\n'use strict'\n\n# -----------------------------",
"end": 71,
"score": 0.9998747706413269,
"start": 57,
"tag": "NAME",
"value": "Mark Dalgleish"
}
] | src/tests/rules/no-render-return-value.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Prevent usage of setState
# @author Mark Dalgleish
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-render-return-value'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-render-return-value', rule,
valid: [
code: 'ReactDOM.render(<div />, document.body)'
,
code: '''
node = null
ReactDOM.render(<div ref={(ref) => node = ref}/>, document.body)
'''
,
code:
'ReactDOM.render(<div ref={(ref) => this.node = ref}/>, document.body)'
settings:
react:
version: '0.14.0'
,
code: 'React.render(<div ref={(ref) => this.node = ref}/>, document.body)'
settings:
react:
version: '0.14.0'
,
code: 'React.render(<div ref={(ref) => this.node = ref}/>, document.body)'
settings:
react:
version: '0.13.0'
]
invalid: [
code: 'Hello = ReactDOM.render(<div />, document.body)'
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: '''
o = {
inst: ReactDOM.render(<div />, document.body)
}
'''
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: '''
render = ->
return ReactDOM.render(<div />, document.body)
'''
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
,
code: '''
render = ->
ReactDOM.render(<div />, document.body)
'''
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: 'render = (a, b) => ReactDOM.render(a, b)'
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: 'inst = React.render(<div />, document.body)'
settings:
react:
version: '0.14.0'
errors: [message: 'Do not depend on the return value from React.render']
,
code: 'inst = ReactDOM.render(<div />, document.body)'
settings:
react:
version: '0.14.0'
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: 'inst = React.render(<div />, document.body)'
settings:
react:
version: '0.13.0'
errors: [message: 'Do not depend on the return value from React.render']
]
| 103542 | ###*
# @fileoverview Prevent usage of setState
# @author <NAME>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-render-return-value'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-render-return-value', rule,
valid: [
code: 'ReactDOM.render(<div />, document.body)'
,
code: '''
node = null
ReactDOM.render(<div ref={(ref) => node = ref}/>, document.body)
'''
,
code:
'ReactDOM.render(<div ref={(ref) => this.node = ref}/>, document.body)'
settings:
react:
version: '0.14.0'
,
code: 'React.render(<div ref={(ref) => this.node = ref}/>, document.body)'
settings:
react:
version: '0.14.0'
,
code: 'React.render(<div ref={(ref) => this.node = ref}/>, document.body)'
settings:
react:
version: '0.13.0'
]
invalid: [
code: 'Hello = ReactDOM.render(<div />, document.body)'
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: '''
o = {
inst: ReactDOM.render(<div />, document.body)
}
'''
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: '''
render = ->
return ReactDOM.render(<div />, document.body)
'''
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
,
code: '''
render = ->
ReactDOM.render(<div />, document.body)
'''
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: 'render = (a, b) => ReactDOM.render(a, b)'
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: 'inst = React.render(<div />, document.body)'
settings:
react:
version: '0.14.0'
errors: [message: 'Do not depend on the return value from React.render']
,
code: 'inst = ReactDOM.render(<div />, document.body)'
settings:
react:
version: '0.14.0'
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: 'inst = React.render(<div />, document.body)'
settings:
react:
version: '0.13.0'
errors: [message: 'Do not depend on the return value from React.render']
]
| true | ###*
# @fileoverview Prevent usage of setState
# @author PI:NAME:<NAME>END_PI
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-render-return-value'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-render-return-value', rule,
valid: [
code: 'ReactDOM.render(<div />, document.body)'
,
code: '''
node = null
ReactDOM.render(<div ref={(ref) => node = ref}/>, document.body)
'''
,
code:
'ReactDOM.render(<div ref={(ref) => this.node = ref}/>, document.body)'
settings:
react:
version: '0.14.0'
,
code: 'React.render(<div ref={(ref) => this.node = ref}/>, document.body)'
settings:
react:
version: '0.14.0'
,
code: 'React.render(<div ref={(ref) => this.node = ref}/>, document.body)'
settings:
react:
version: '0.13.0'
]
invalid: [
code: 'Hello = ReactDOM.render(<div />, document.body)'
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: '''
o = {
inst: ReactDOM.render(<div />, document.body)
}
'''
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: '''
render = ->
return ReactDOM.render(<div />, document.body)
'''
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
,
code: '''
render = ->
ReactDOM.render(<div />, document.body)
'''
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: 'render = (a, b) => ReactDOM.render(a, b)'
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: 'inst = React.render(<div />, document.body)'
settings:
react:
version: '0.14.0'
errors: [message: 'Do not depend on the return value from React.render']
,
code: 'inst = ReactDOM.render(<div />, document.body)'
settings:
react:
version: '0.14.0'
errors: [message: 'Do not depend on the return value from ReactDOM.render']
,
code: 'inst = React.render(<div />, document.body)'
settings:
react:
version: '0.13.0'
errors: [message: 'Do not depend on the return value from React.render']
]
|
[
{
"context": "store = secrets\n store: tmp\n password: 'mysecret'\n store.init (err) ->\n return next err if",
"end": 287,
"score": 0.9993270635604858,
"start": 279,
"tag": "PASSWORD",
"value": "mysecret"
},
{
"context": "store = secrets\n store: tmp\n password: 'mysecret'\n store.init (err) ->\n return next err if",
"end": 540,
"score": 0.9993430376052856,
"start": 532,
"tag": "PASSWORD",
"value": "mysecret"
},
{
"context": "store = secrets\n store: tmp\n password: 'mysecret'\n store.init (err) ->\n return next err if",
"end": 901,
"score": 0.9993269443511963,
"start": 893,
"tag": "PASSWORD",
"value": "mysecret"
},
{
"context": "store = secrets\n store: tmp\n password: 'mysecret'\n store.init (err) ->\n return next err if",
"end": 1426,
"score": 0.9993103742599487,
"start": 1418,
"tag": "PASSWORD",
"value": "mysecret"
},
{
"context": "store = secrets\n store: tmp\n password: 'mysecret'\n store.init (err) ->\n return next err if",
"end": 1891,
"score": 0.9993283748626709,
"start": 1883,
"tag": "PASSWORD",
"value": "mysecret"
},
{
"context": "store = secrets\n store: tmp\n password: 'mysecret'\n store.init (err) ->\n return next err if",
"end": 2406,
"score": 0.9992972612380981,
"start": 2398,
"tag": "PASSWORD",
"value": "mysecret"
},
{
"context": "store = secrets\n store: tmp\n password: 'mysecret'\n store.init (err) ->\n return next err if",
"end": 3013,
"score": 0.9993277788162231,
"start": 3005,
"tag": "PASSWORD",
"value": "mysecret"
}
] | test/secrets/index.coffee | WIN32GG/node-masson | 0 |
nikita = require 'nikita'
secrets = require '../../lib/secrets'
describe 'command configure', ->
tmp = '/tmp/masson_store'
beforeEach ->
nikita
.system.remove tmp
.promise()
it 'init', (next) ->
store = secrets
store: tmp
password: 'mysecret'
store.init (err) ->
return next err if err
store.init (err) ->
err.message.should.eql 'Store already created'
next()
it 'setget all', (next) ->
store = secrets
store: tmp
password: 'mysecret'
store.init (err) ->
return next err if err
store.set a_key: 'a value', (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.a_key.should.eql 'a value'
next()
it 'get key', (next) ->
store = secrets
store: tmp
password: 'mysecret'
store.init (err) ->
return next err if err
store.set
a_key: 'a value'
b: key: 'b value'
, (err) ->
return next err if err
store.get 'a_key', (err, value) ->
return next err if err
value.should.eql 'a value'
store.get 'b.key', (err, value) ->
return next err if err
value.should.eql 'b value'
next()
it 'get keys', (next) ->
store = secrets
store: tmp
password: 'mysecret'
store.init (err) ->
return next err if err
store.set
some: keys:
a: 'a value'
b: 'b value'
, (err) ->
return next err if err
store.get 'some.keys', (err, secrets) ->
return next err if err
secrets.should.eql
a: 'a value'
b: 'b value'
next()
it 'set key', (next) ->
store = secrets
store: tmp
password: 'mysecret'
store.init (err) ->
return next err if err
store.set
a_key: 'a value'
, (err) ->
return next err if err
store.set 'b.key', 'b value', (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.should.eql
a_key: 'a value'
b: key: 'b value'
next()
it 'set keys', (next) ->
store = secrets
store: tmp
password: 'mysecret'
store.init (err) ->
return next err if err
store.set
a_key: 'a value'
, (err) ->
return next err if err
store.set 'keys',
a: 'a value'
b: 'b value'
, (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.should.eql
a_key: 'a value'
keys:
a: 'a value'
b: 'b value'
next()
it 'unset key', (next) ->
store = secrets
store: tmp
password: 'mysecret'
store.init (err) ->
return next err if err
store.set
some: keys:
a: 'a value'
b: 'b value'
, (err) ->
return next err if err
store.unset 'some.keys.a', (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.should.eql
some: keys:
b: 'b value'
next()
| 57331 |
nikita = require 'nikita'
secrets = require '../../lib/secrets'
describe 'command configure', ->
tmp = '/tmp/masson_store'
beforeEach ->
nikita
.system.remove tmp
.promise()
it 'init', (next) ->
store = secrets
store: tmp
password: '<PASSWORD>'
store.init (err) ->
return next err if err
store.init (err) ->
err.message.should.eql 'Store already created'
next()
it 'setget all', (next) ->
store = secrets
store: tmp
password: '<PASSWORD>'
store.init (err) ->
return next err if err
store.set a_key: 'a value', (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.a_key.should.eql 'a value'
next()
it 'get key', (next) ->
store = secrets
store: tmp
password: '<PASSWORD>'
store.init (err) ->
return next err if err
store.set
a_key: 'a value'
b: key: 'b value'
, (err) ->
return next err if err
store.get 'a_key', (err, value) ->
return next err if err
value.should.eql 'a value'
store.get 'b.key', (err, value) ->
return next err if err
value.should.eql 'b value'
next()
it 'get keys', (next) ->
store = secrets
store: tmp
password: '<PASSWORD>'
store.init (err) ->
return next err if err
store.set
some: keys:
a: 'a value'
b: 'b value'
, (err) ->
return next err if err
store.get 'some.keys', (err, secrets) ->
return next err if err
secrets.should.eql
a: 'a value'
b: 'b value'
next()
it 'set key', (next) ->
store = secrets
store: tmp
password: '<PASSWORD>'
store.init (err) ->
return next err if err
store.set
a_key: 'a value'
, (err) ->
return next err if err
store.set 'b.key', 'b value', (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.should.eql
a_key: 'a value'
b: key: 'b value'
next()
it 'set keys', (next) ->
store = secrets
store: tmp
password: '<PASSWORD>'
store.init (err) ->
return next err if err
store.set
a_key: 'a value'
, (err) ->
return next err if err
store.set 'keys',
a: 'a value'
b: 'b value'
, (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.should.eql
a_key: 'a value'
keys:
a: 'a value'
b: 'b value'
next()
it 'unset key', (next) ->
store = secrets
store: tmp
password: '<PASSWORD>'
store.init (err) ->
return next err if err
store.set
some: keys:
a: 'a value'
b: 'b value'
, (err) ->
return next err if err
store.unset 'some.keys.a', (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.should.eql
some: keys:
b: 'b value'
next()
| true |
nikita = require 'nikita'
secrets = require '../../lib/secrets'
describe 'command configure', ->
tmp = '/tmp/masson_store'
beforeEach ->
nikita
.system.remove tmp
.promise()
it 'init', (next) ->
store = secrets
store: tmp
password: 'PI:PASSWORD:<PASSWORD>END_PI'
store.init (err) ->
return next err if err
store.init (err) ->
err.message.should.eql 'Store already created'
next()
it 'setget all', (next) ->
store = secrets
store: tmp
password: 'PI:PASSWORD:<PASSWORD>END_PI'
store.init (err) ->
return next err if err
store.set a_key: 'a value', (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.a_key.should.eql 'a value'
next()
it 'get key', (next) ->
store = secrets
store: tmp
password: 'PI:PASSWORD:<PASSWORD>END_PI'
store.init (err) ->
return next err if err
store.set
a_key: 'a value'
b: key: 'b value'
, (err) ->
return next err if err
store.get 'a_key', (err, value) ->
return next err if err
value.should.eql 'a value'
store.get 'b.key', (err, value) ->
return next err if err
value.should.eql 'b value'
next()
it 'get keys', (next) ->
store = secrets
store: tmp
password: 'PI:PASSWORD:<PASSWORD>END_PI'
store.init (err) ->
return next err if err
store.set
some: keys:
a: 'a value'
b: 'b value'
, (err) ->
return next err if err
store.get 'some.keys', (err, secrets) ->
return next err if err
secrets.should.eql
a: 'a value'
b: 'b value'
next()
it 'set key', (next) ->
store = secrets
store: tmp
password: 'PI:PASSWORD:<PASSWORD>END_PI'
store.init (err) ->
return next err if err
store.set
a_key: 'a value'
, (err) ->
return next err if err
store.set 'b.key', 'b value', (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.should.eql
a_key: 'a value'
b: key: 'b value'
next()
it 'set keys', (next) ->
store = secrets
store: tmp
password: 'PI:PASSWORD:<PASSWORD>END_PI'
store.init (err) ->
return next err if err
store.set
a_key: 'a value'
, (err) ->
return next err if err
store.set 'keys',
a: 'a value'
b: 'b value'
, (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.should.eql
a_key: 'a value'
keys:
a: 'a value'
b: 'b value'
next()
it 'unset key', (next) ->
store = secrets
store: tmp
password: 'PI:PASSWORD:<PASSWORD>END_PI'
store.init (err) ->
return next err if err
store.set
some: keys:
a: 'a value'
b: 'b value'
, (err) ->
return next err if err
store.unset 'some.keys.a', (err) ->
return next err if err
store.get (err, secrets) ->
return next err if err
secrets.should.eql
some: keys:
b: 'b value'
next()
|
[
{
"context": "st[] = 2\nlist[] = 3\n\n; add a group\n[person]\nname = Alexander Schilling\njob = Developer\n\n; add a subgroup\n[city.address]\n",
"end": 365,
"score": 0.9998353719711304,
"start": 346,
"tag": "NAME",
"value": "Alexander Schilling"
}
] | src/type/ini.coffee | alinex/node-formatter | 0 | ###
INI
===================================================
This is one of the oldest formats used for configurations. It is very simple but
allows also complex objects through extended groups.
Common file extension `ini`.
``` ini
; simple text
string = test
; add a simple list
list[] = 1
list[] = 2
list[] = 3
; add a group
[person]
name = Alexander Schilling
job = Developer
; add a subgroup
[city.address]
name = Stuttgart
```
Comments start with semicolon and grous/sections are marked by square brackets.
The group name defines the object to add the properties to.
__Format Options:__
- `whitespace` - `Boolean` should spaces be put arround `=` (defaults to true)
###
# Node Modules
# -------------------------------------------------
# include base modules
ini = require 'ini'
# Implementation
# -------------------------------------------------
# @param {Object} obj to be formatted
# @param {Object} [options] format options like described above
# @param {Function(Error, String)} cb callback will be called with result
exports.stringify = (obj, options, cb) ->
try
text = ini.encode obj,
whitespace: if options?.whitespace? then options.whitespace else true
catch error
return cb error
cb null, text
# @param {String} text to be parsed
# @param {Object} [options] not used in this type
# @param {Function(Error, Object)} cb callback will be called with result
exports.parse = (text, _, cb) ->
try
result = ini.decode text
catch error
return cb error
# detect failed parsing
unless result? and Object.keys(result).length
return cb new Error "could not parse any result"
if result['{']
return cb new Error "Unexpected token { at start"
for k, v of result
if v is true and k.match /:/
return cb new Error "Unexpected key name containing ':' with value true"
cb null, result
| 190884 | ###
INI
===================================================
This is one of the oldest formats used for configurations. It is very simple but
allows also complex objects through extended groups.
Common file extension `ini`.
``` ini
; simple text
string = test
; add a simple list
list[] = 1
list[] = 2
list[] = 3
; add a group
[person]
name = <NAME>
job = Developer
; add a subgroup
[city.address]
name = Stuttgart
```
Comments start with semicolon and grous/sections are marked by square brackets.
The group name defines the object to add the properties to.
__Format Options:__
- `whitespace` - `Boolean` should spaces be put arround `=` (defaults to true)
###
# Node Modules
# -------------------------------------------------
# include base modules
ini = require 'ini'
# Implementation
# -------------------------------------------------
# @param {Object} obj to be formatted
# @param {Object} [options] format options like described above
# @param {Function(Error, String)} cb callback will be called with result
exports.stringify = (obj, options, cb) ->
try
text = ini.encode obj,
whitespace: if options?.whitespace? then options.whitespace else true
catch error
return cb error
cb null, text
# @param {String} text to be parsed
# @param {Object} [options] not used in this type
# @param {Function(Error, Object)} cb callback will be called with result
exports.parse = (text, _, cb) ->
try
result = ini.decode text
catch error
return cb error
# detect failed parsing
unless result? and Object.keys(result).length
return cb new Error "could not parse any result"
if result['{']
return cb new Error "Unexpected token { at start"
for k, v of result
if v is true and k.match /:/
return cb new Error "Unexpected key name containing ':' with value true"
cb null, result
| true | ###
INI
===================================================
This is one of the oldest formats used for configurations. It is very simple but
allows also complex objects through extended groups.
Common file extension `ini`.
``` ini
; simple text
string = test
; add a simple list
list[] = 1
list[] = 2
list[] = 3
; add a group
[person]
name = PI:NAME:<NAME>END_PI
job = Developer
; add a subgroup
[city.address]
name = Stuttgart
```
Comments start with semicolon and grous/sections are marked by square brackets.
The group name defines the object to add the properties to.
__Format Options:__
- `whitespace` - `Boolean` should spaces be put arround `=` (defaults to true)
###
# Node Modules
# -------------------------------------------------
# include base modules
ini = require 'ini'
# Implementation
# -------------------------------------------------
# @param {Object} obj to be formatted
# @param {Object} [options] format options like described above
# @param {Function(Error, String)} cb callback will be called with result
exports.stringify = (obj, options, cb) ->
try
text = ini.encode obj,
whitespace: if options?.whitespace? then options.whitespace else true
catch error
return cb error
cb null, text
# @param {String} text to be parsed
# @param {Object} [options] not used in this type
# @param {Function(Error, Object)} cb callback will be called with result
exports.parse = (text, _, cb) ->
try
result = ini.decode text
catch error
return cb error
# detect failed parsing
unless result? and Object.keys(result).length
return cb new Error "could not parse any result"
if result['{']
return cb new Error "Unexpected token { at start"
for k, v of result
if v is true and k.match /:/
return cb new Error "Unexpected key name containing ':' with value true"
cb null, result
|
[
{
"context": "#\npsJS - Pub/sub implementation with test\n\nAuthor: kk- <karcsi@ekezet.com>\nLicense: UNLICENSE\n###\nclass ",
"end": 55,
"score": 0.9985396862030029,
"start": 53,
"tag": "USERNAME",
"value": "kk"
},
{
"context": " - Pub/sub implementation with test\n\nAuthor: kk- <karcsi@ekezet.com>\nLicense: UNLICENSE\n###\nclass psJS\n\n listeners",
"end": 75,
"score": 0.9999279379844666,
"start": 58,
"tag": "EMAIL",
"value": "karcsi@ekezet.com"
}
] | src/psjs.coffee | atomgomba/psjs | 0 | ###
psJS - Pub/sub implementation with test
Author: kk- <karcsi@ekezet.com>
License: UNLICENSE
###
class psJS
listeners = {}
@on: (name, fun) ->
if name of listeners
listeners[name].push fun if not listeners[name].once
else
listeners[name] = [fun]
return @
@once: (name, fun) ->
return @ if name of listeners
listeners[name] = [fun]
listeners[name].once = yes
return @
@only: (name, fun) ->
return @ if name of listeners and listeners[name].once
listeners[name] = [fun]
return @
@emit: (name, data=null) ->
return @ if not (name of listeners)
event =
name: name
data: data
for fun in listeners[name]
fun(event)
return @
@has: (name) ->
name of listeners
@hasOnce: (name) ->
name of listeners and listeners[name].once
@remove: (name) ->
if name?
return @ if not (name of listeners)
delete listeners[name]
else
listeners = {}
return @
@listeners: (newListeners) ->
listeners = newListeners if newListeners?
return listeners
if module?
module.exports = psJS
else
window.psJS = psJS
| 170395 | ###
psJS - Pub/sub implementation with test
Author: kk- <<EMAIL>>
License: UNLICENSE
###
class psJS
listeners = {}
@on: (name, fun) ->
if name of listeners
listeners[name].push fun if not listeners[name].once
else
listeners[name] = [fun]
return @
@once: (name, fun) ->
return @ if name of listeners
listeners[name] = [fun]
listeners[name].once = yes
return @
@only: (name, fun) ->
return @ if name of listeners and listeners[name].once
listeners[name] = [fun]
return @
@emit: (name, data=null) ->
return @ if not (name of listeners)
event =
name: name
data: data
for fun in listeners[name]
fun(event)
return @
@has: (name) ->
name of listeners
@hasOnce: (name) ->
name of listeners and listeners[name].once
@remove: (name) ->
if name?
return @ if not (name of listeners)
delete listeners[name]
else
listeners = {}
return @
@listeners: (newListeners) ->
listeners = newListeners if newListeners?
return listeners
if module?
module.exports = psJS
else
window.psJS = psJS
| true | ###
psJS - Pub/sub implementation with test
Author: kk- <PI:EMAIL:<EMAIL>END_PI>
License: UNLICENSE
###
class psJS
listeners = {}
@on: (name, fun) ->
if name of listeners
listeners[name].push fun if not listeners[name].once
else
listeners[name] = [fun]
return @
@once: (name, fun) ->
return @ if name of listeners
listeners[name] = [fun]
listeners[name].once = yes
return @
@only: (name, fun) ->
return @ if name of listeners and listeners[name].once
listeners[name] = [fun]
return @
@emit: (name, data=null) ->
return @ if not (name of listeners)
event =
name: name
data: data
for fun in listeners[name]
fun(event)
return @
@has: (name) ->
name of listeners
@hasOnce: (name) ->
name of listeners and listeners[name].once
@remove: (name) ->
if name?
return @ if not (name of listeners)
delete listeners[name]
else
listeners = {}
return @
@listeners: (newListeners) ->
listeners = newListeners if newListeners?
return listeners
if module?
module.exports = psJS
else
window.psJS = psJS
|
[
{
"context": "\n '(c) 2014' + bannerDate + ' L.systems SARL, Etienne Folio, Quentin Raynaud'\n 'https://bitbucket.org/ls",
"end": 584,
"score": 0.9998347163200378,
"start": 571,
"tag": "NAME",
"value": "Etienne Folio"
},
{
"context": "4' + bannerDate + ' L.systems SARL, Etienne Folio, Quentin Raynaud'\n 'https://bitbucket.org/lsystems/angular-ex",
"end": 601,
"score": 0.9998604655265808,
"start": 586,
"tag": "NAME",
"value": "Quentin Raynaud"
},
{
"context": "io, Quentin Raynaud'\n 'https://bitbucket.org/lsystems/angular-extend-promises'\n 'License: MIT'\n ",
"end": 640,
"score": 0.9985000491142273,
"start": 632,
"tag": "USERNAME",
"value": "lsystems"
}
] | Gruntfile.coffee | Intergen-NZ/angular-extend-promises | 0 | shell = require 'shelljs'
SemVer = require('semver').SemVer
webpack = require 'webpack'
module.exports = (grunt) ->
grunt.loadTasks file for file in grunt.file.expand 'node_modules/grunt-*/tasks'
pkg = grunt.file.readJSON 'package.json'
license = grunt.file.read 'LICENSE'
bannerDate = if grunt.template.today('yyyy') isnt '2014' then ('-' + grunt.template.today('yyyy')) else ''
banner = grunt.template.process(
[
'<%= pkg.name %> v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>'
'(c) 2014' + bannerDate + ' L.systems SARL, Etienne Folio, Quentin Raynaud'
'https://bitbucket.org/lsystems/angular-extend-promises'
'License: MIT'
].join('\n')
data:
pkg: pkg
license: license
)
grunt.initConfig
pkg: pkg
jshint:
options:
reporter: require('jshint-stylish')
client:
src: 'src/**/*.js'
options:
jshintrc: '.jshintrc'
verbose: true
jscs:
options:
force: true,
config: '.jscsrc'
all:
src: [
'src/**/*.js',
'tests/**/*.js'
]
clean:
options:
force: true
dist: 'dist/**/*'
mochaProtractor:
options:
browsers: ['Chrome', 'Firefox']
files: ['test/*.js']
bumpup:
files: ['package.json', 'bower.json']
options:
updateProps:
pkg: 'package.json'
webpack:
options:
entry: './src/index.js'
output:
path: 'dist'
library: '<%= pkg.name %>'
libraryTarget: 'umd'
devtool: 'source-map'
plugins: [
new webpack.BannerPlugin(banner)
]
default:
output:
filename: 'angular-extend-promises.js'
sourceMapFilename: 'angular-extend-promises.js.map'
defaultMin:
output:
filename: 'angular-extend-promises.min.js'
sourceMapFilename: 'angular-extend-promises.min.js.map'
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
withoutLodash:
output:
filename: 'angular-extend-promises-without-lodash.js'
sourceMapFilename: 'angular-extend-promises-without-lodash.js.map'
externals: [
/.*\/tmp\/lodash/
]
withoutLodashMin:
output:
filename: 'angular-extend-promises-without-lodash.min.js'
sourceMapFilename: 'angular-extend-promises-without-lodash.min.js.map'
externals: [
/.*\/tmp\/lodash/
]
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
karma:
options:
configFile: 'tests/karma.conf.coffee'
browsers: [
'PhantomJS',
'Chrome',
'Firefox'
]
singleRun: true
units1_3:
options:
files: [
'bower_components/angular1.3/angular.js',
'bower_components/angular-mocks1.3/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/units/**/*.js'
]
functionals1_3:
options:
files: [
'bower_components/angular1.3/angular.js',
'bower_components/angular-mocks1.3/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/functionals/**/*.js'
]
units1_2:
options:
files: [
'bower_components/angular1.2/angular.js',
'bower_components/angular-mocks1.2/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/units/**/*.js'
]
functionals1_2:
options:
files: [
'bower_components/angular1.2/angular.js',
'bower_components/angular-mocks1.2/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/functionals/**/*.js'
]
run = (cmd, msg) ->
cmd = cmd.join('&&') if Array.isArray cmd
res = shell.exec cmd
grunt.log.writeln[!res.code ? 'ok' : 'ko'] msg if msg
!res.code
grunt.registerTask 'lodash', () ->
grunt.file.mkdir 'tmp'
run './node_modules/.bin/lodash include=' + [
'constant'
'defaults'
'each'
'extend'
'filter'
'isArray'
'isEmpty'
'isFunction'
'isArguments'
'keys'
'map'
'methods'
'noop'
'object'
'pick'
'reduce'
'toArray'
'values'
].join(',') + ' -o tmp/lodash.js'
grunt.registerTask 'build', ['lodash', 'webpack']
grunt.registerTask 'test', ['jshint', 'jscs', 'build', 'karma']
grunt.registerTask 'default', ['clean', 'build']
grunt.registerTask 'release', (type, step) ->
type = type || 'patch'
step = step || 'start'
switch step
when 'start'
grunt.log.writeln 'Clean'
grunt.task.run ['clean', 'release:' + type + ':prepare']
when 'prepare'
grunt.log.writeln 'Build & test & bump version…'
run [
'rm -fr dist && mkdir dist'
'cd dist && git init && cd ..'
'cp .git/config dist/.git/'
'cp bower.json README.md dist/'
]
tasks = [
'test'
]
if type isnt 'prerelease'
tasks.unshift 'bumpup:' + type
tasks.push 'release:' + type + ':commit'
grunt.task.run tasks
when 'commit'
grunt.log.writeln 'Commit & push release…'
newVer = grunt.config 'pkg.version'
run [
'cd dist'
'git add -A'
'git commit -m "Release v' + newVer + '" --no-verify'
'git tag "v' + newVer + '"'
'git push origin --tags -f'
]
grunt.log.writeln 'Publish on NPM…'
run [
'rm dist/bower.json'
'cp package.json dist/'
'cd dist'
'npm publish'
]
version = new SemVer(grunt.config('pkg.version'))
if type isnt 'prerelease'
version.inc('patch')
version.prerelease = ['pre']
else
version.inc('prerelease')
grunt.log.writeln 'Bump new dev version…'
grunt.task.run ['bumpup:' + version.format(), 'release:' + type + ':end']
when 'end'
run [
'git add -A'
'git commit -m "Bump version to v' + grunt.config('pkg.version') + ' in master" --no-verify'
'git push origin master'
]
| 46200 | shell = require 'shelljs'
SemVer = require('semver').SemVer
webpack = require 'webpack'
module.exports = (grunt) ->
grunt.loadTasks file for file in grunt.file.expand 'node_modules/grunt-*/tasks'
pkg = grunt.file.readJSON 'package.json'
license = grunt.file.read 'LICENSE'
bannerDate = if grunt.template.today('yyyy') isnt '2014' then ('-' + grunt.template.today('yyyy')) else ''
banner = grunt.template.process(
[
'<%= pkg.name %> v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>'
'(c) 2014' + bannerDate + ' L.systems SARL, <NAME>, <NAME>'
'https://bitbucket.org/lsystems/angular-extend-promises'
'License: MIT'
].join('\n')
data:
pkg: pkg
license: license
)
grunt.initConfig
pkg: pkg
jshint:
options:
reporter: require('jshint-stylish')
client:
src: 'src/**/*.js'
options:
jshintrc: '.jshintrc'
verbose: true
jscs:
options:
force: true,
config: '.jscsrc'
all:
src: [
'src/**/*.js',
'tests/**/*.js'
]
clean:
options:
force: true
dist: 'dist/**/*'
mochaProtractor:
options:
browsers: ['Chrome', 'Firefox']
files: ['test/*.js']
bumpup:
files: ['package.json', 'bower.json']
options:
updateProps:
pkg: 'package.json'
webpack:
options:
entry: './src/index.js'
output:
path: 'dist'
library: '<%= pkg.name %>'
libraryTarget: 'umd'
devtool: 'source-map'
plugins: [
new webpack.BannerPlugin(banner)
]
default:
output:
filename: 'angular-extend-promises.js'
sourceMapFilename: 'angular-extend-promises.js.map'
defaultMin:
output:
filename: 'angular-extend-promises.min.js'
sourceMapFilename: 'angular-extend-promises.min.js.map'
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
withoutLodash:
output:
filename: 'angular-extend-promises-without-lodash.js'
sourceMapFilename: 'angular-extend-promises-without-lodash.js.map'
externals: [
/.*\/tmp\/lodash/
]
withoutLodashMin:
output:
filename: 'angular-extend-promises-without-lodash.min.js'
sourceMapFilename: 'angular-extend-promises-without-lodash.min.js.map'
externals: [
/.*\/tmp\/lodash/
]
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
karma:
options:
configFile: 'tests/karma.conf.coffee'
browsers: [
'PhantomJS',
'Chrome',
'Firefox'
]
singleRun: true
units1_3:
options:
files: [
'bower_components/angular1.3/angular.js',
'bower_components/angular-mocks1.3/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/units/**/*.js'
]
functionals1_3:
options:
files: [
'bower_components/angular1.3/angular.js',
'bower_components/angular-mocks1.3/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/functionals/**/*.js'
]
units1_2:
options:
files: [
'bower_components/angular1.2/angular.js',
'bower_components/angular-mocks1.2/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/units/**/*.js'
]
functionals1_2:
options:
files: [
'bower_components/angular1.2/angular.js',
'bower_components/angular-mocks1.2/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/functionals/**/*.js'
]
run = (cmd, msg) ->
cmd = cmd.join('&&') if Array.isArray cmd
res = shell.exec cmd
grunt.log.writeln[!res.code ? 'ok' : 'ko'] msg if msg
!res.code
grunt.registerTask 'lodash', () ->
grunt.file.mkdir 'tmp'
run './node_modules/.bin/lodash include=' + [
'constant'
'defaults'
'each'
'extend'
'filter'
'isArray'
'isEmpty'
'isFunction'
'isArguments'
'keys'
'map'
'methods'
'noop'
'object'
'pick'
'reduce'
'toArray'
'values'
].join(',') + ' -o tmp/lodash.js'
grunt.registerTask 'build', ['lodash', 'webpack']
grunt.registerTask 'test', ['jshint', 'jscs', 'build', 'karma']
grunt.registerTask 'default', ['clean', 'build']
grunt.registerTask 'release', (type, step) ->
type = type || 'patch'
step = step || 'start'
switch step
when 'start'
grunt.log.writeln 'Clean'
grunt.task.run ['clean', 'release:' + type + ':prepare']
when 'prepare'
grunt.log.writeln 'Build & test & bump version…'
run [
'rm -fr dist && mkdir dist'
'cd dist && git init && cd ..'
'cp .git/config dist/.git/'
'cp bower.json README.md dist/'
]
tasks = [
'test'
]
if type isnt 'prerelease'
tasks.unshift 'bumpup:' + type
tasks.push 'release:' + type + ':commit'
grunt.task.run tasks
when 'commit'
grunt.log.writeln 'Commit & push release…'
newVer = grunt.config 'pkg.version'
run [
'cd dist'
'git add -A'
'git commit -m "Release v' + newVer + '" --no-verify'
'git tag "v' + newVer + '"'
'git push origin --tags -f'
]
grunt.log.writeln 'Publish on NPM…'
run [
'rm dist/bower.json'
'cp package.json dist/'
'cd dist'
'npm publish'
]
version = new SemVer(grunt.config('pkg.version'))
if type isnt 'prerelease'
version.inc('patch')
version.prerelease = ['pre']
else
version.inc('prerelease')
grunt.log.writeln 'Bump new dev version…'
grunt.task.run ['bumpup:' + version.format(), 'release:' + type + ':end']
when 'end'
run [
'git add -A'
'git commit -m "Bump version to v' + grunt.config('pkg.version') + ' in master" --no-verify'
'git push origin master'
]
| true | shell = require 'shelljs'
SemVer = require('semver').SemVer
webpack = require 'webpack'
module.exports = (grunt) ->
grunt.loadTasks file for file in grunt.file.expand 'node_modules/grunt-*/tasks'
pkg = grunt.file.readJSON 'package.json'
license = grunt.file.read 'LICENSE'
bannerDate = if grunt.template.today('yyyy') isnt '2014' then ('-' + grunt.template.today('yyyy')) else ''
banner = grunt.template.process(
[
'<%= pkg.name %> v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>'
'(c) 2014' + bannerDate + ' L.systems SARL, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI'
'https://bitbucket.org/lsystems/angular-extend-promises'
'License: MIT'
].join('\n')
data:
pkg: pkg
license: license
)
grunt.initConfig
pkg: pkg
jshint:
options:
reporter: require('jshint-stylish')
client:
src: 'src/**/*.js'
options:
jshintrc: '.jshintrc'
verbose: true
jscs:
options:
force: true,
config: '.jscsrc'
all:
src: [
'src/**/*.js',
'tests/**/*.js'
]
clean:
options:
force: true
dist: 'dist/**/*'
mochaProtractor:
options:
browsers: ['Chrome', 'Firefox']
files: ['test/*.js']
bumpup:
files: ['package.json', 'bower.json']
options:
updateProps:
pkg: 'package.json'
webpack:
options:
entry: './src/index.js'
output:
path: 'dist'
library: '<%= pkg.name %>'
libraryTarget: 'umd'
devtool: 'source-map'
plugins: [
new webpack.BannerPlugin(banner)
]
default:
output:
filename: 'angular-extend-promises.js'
sourceMapFilename: 'angular-extend-promises.js.map'
defaultMin:
output:
filename: 'angular-extend-promises.min.js'
sourceMapFilename: 'angular-extend-promises.min.js.map'
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
withoutLodash:
output:
filename: 'angular-extend-promises-without-lodash.js'
sourceMapFilename: 'angular-extend-promises-without-lodash.js.map'
externals: [
/.*\/tmp\/lodash/
]
withoutLodashMin:
output:
filename: 'angular-extend-promises-without-lodash.min.js'
sourceMapFilename: 'angular-extend-promises-without-lodash.min.js.map'
externals: [
/.*\/tmp\/lodash/
]
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
karma:
options:
configFile: 'tests/karma.conf.coffee'
browsers: [
'PhantomJS',
'Chrome',
'Firefox'
]
singleRun: true
units1_3:
options:
files: [
'bower_components/angular1.3/angular.js',
'bower_components/angular-mocks1.3/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/units/**/*.js'
]
functionals1_3:
options:
files: [
'bower_components/angular1.3/angular.js',
'bower_components/angular-mocks1.3/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/functionals/**/*.js'
]
units1_2:
options:
files: [
'bower_components/angular1.2/angular.js',
'bower_components/angular-mocks1.2/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/units/**/*.js'
]
functionals1_2:
options:
files: [
'bower_components/angular1.2/angular.js',
'bower_components/angular-mocks1.2/angular-mocks.js'
'dist/angular-extend-promises.js'
'tests/functionals/**/*.js'
]
run = (cmd, msg) ->
cmd = cmd.join('&&') if Array.isArray cmd
res = shell.exec cmd
grunt.log.writeln[!res.code ? 'ok' : 'ko'] msg if msg
!res.code
grunt.registerTask 'lodash', () ->
grunt.file.mkdir 'tmp'
run './node_modules/.bin/lodash include=' + [
'constant'
'defaults'
'each'
'extend'
'filter'
'isArray'
'isEmpty'
'isFunction'
'isArguments'
'keys'
'map'
'methods'
'noop'
'object'
'pick'
'reduce'
'toArray'
'values'
].join(',') + ' -o tmp/lodash.js'
grunt.registerTask 'build', ['lodash', 'webpack']
grunt.registerTask 'test', ['jshint', 'jscs', 'build', 'karma']
grunt.registerTask 'default', ['clean', 'build']
grunt.registerTask 'release', (type, step) ->
type = type || 'patch'
step = step || 'start'
switch step
when 'start'
grunt.log.writeln 'Clean'
grunt.task.run ['clean', 'release:' + type + ':prepare']
when 'prepare'
grunt.log.writeln 'Build & test & bump version…'
run [
'rm -fr dist && mkdir dist'
'cd dist && git init && cd ..'
'cp .git/config dist/.git/'
'cp bower.json README.md dist/'
]
tasks = [
'test'
]
if type isnt 'prerelease'
tasks.unshift 'bumpup:' + type
tasks.push 'release:' + type + ':commit'
grunt.task.run tasks
when 'commit'
grunt.log.writeln 'Commit & push release…'
newVer = grunt.config 'pkg.version'
run [
'cd dist'
'git add -A'
'git commit -m "Release v' + newVer + '" --no-verify'
'git tag "v' + newVer + '"'
'git push origin --tags -f'
]
grunt.log.writeln 'Publish on NPM…'
run [
'rm dist/bower.json'
'cp package.json dist/'
'cd dist'
'npm publish'
]
version = new SemVer(grunt.config('pkg.version'))
if type isnt 'prerelease'
version.inc('patch')
version.prerelease = ['pre']
else
version.inc('prerelease')
grunt.log.writeln 'Bump new dev version…'
grunt.task.run ['bumpup:' + version.format(), 'release:' + type + ':end']
when 'end'
run [
'git add -A'
'git commit -m "Bump version to v' + grunt.config('pkg.version') + ' in master" --no-verify'
'git push origin master'
]
|
[
{
"context": "<SiteID>#{@userId}</SiteID>\n <Password>#{@password}</Password>\n </ServiceHeader>\n </Requ",
"end": 560,
"score": 0.6636025905609131,
"start": 551,
"tag": "PASSWORD",
"value": "@password"
}
] | src/dhl.coffee | humm64/ship_new | 0 | {Parser} = require 'xml2js'
moment = require 'moment-timezone'
{titleCase, upperCaseFirst, lowerCase} = require 'change-case'
{ShipperClient} = require './shipper'
class DhlClient extends ShipperClient
constructor: ({@userId, @password}, @options) ->
super
@parser = new Parser()
generateRequest: (trk) ->
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<req:KnownTrackingRequest xmlns:req="http://www.dhl.com">
<Request>
<ServiceHeader>
<SiteID>#{@userId}</SiteID>
<Password>#{@password}</Password>
</ServiceHeader>
</Request>
<LanguageCode>en</LanguageCode>
<AWBNumber>#{trk}</AWBNumber>
<LevelOfDetails>ALL_CHECK_POINTS</LevelOfDetails>
</req:KnownTrackingRequest>
"""
validateResponse: (response, cb) ->
handleResponse = (xmlErr, trackResult) ->
return cb(xmlErr) if xmlErr? or !trackResult?
trackingResponse = trackResult['req:TrackingResponse']
return cb(error: 'no tracking response') unless trackingResponse?
awbInfo = trackingResponse['AWBInfo']?[0]
return cb(error: 'no AWBInfo in response') unless awbInfo?
shipment = awbInfo['ShipmentInfo']?[0]
return cb(error: 'could not find shipment') unless shipment?
trackStatus = awbInfo['Status']?[0]
statusCode = trackStatus?['ActionStatus']
return cb(error: "unexpected track status code=#{statusCode}") unless statusCode.toString() is 'success'
cb null, shipment
@parser.reset()
@parser.parseString response, handleResponse
getEta: (shipment) ->
getService: (shipment) ->
getWeight: (shipment) ->
weight = shipment['Weight']?[0]
if weight? then "#{weight} LB"
presentTimestamp: (dateString, timeString) ->
return unless dateString?
timeString ?= '00:00'
inputString = "#{dateString} #{timeString} +0000"
moment(inputString).toDate()
presentAddress: (rawAddress) ->
return unless rawAddress?
firstComma = rawAddress.indexOf(',')
firstDash = rawAddress.indexOf('-', firstComma)
if firstComma > -1 and firstDash > -1
city = rawAddress.substring(0, firstComma).trim()
stateCode = rawAddress.substring(firstComma+1, firstDash).trim()
countryCode = rawAddress.substring(firstDash+1).trim()
else if firstComma < 0 and firstDash > -1
city = rawAddress.substring(0, firstDash).trim()
stateCode = null
countryCode = rawAddress.substring(firstDash+1).trim()
else
return rawAddress
city = city.replace(' HUB', '')
city = city.replace(' GATEWAY', '')
@presentLocation {city, stateCode, countryCode}
presentDetails: (rawAddress, rawDetails) ->
return unless rawDetails?
return rawDetails unless rawAddress?
rawDetails.replace(/\s\s+/, ' ').trim().replace(new RegExp("(?: at| in)? #{rawAddress.trim()}$"), '')
STATUS_MAP =
'AD': ShipperClient.STATUS_TYPES.EN_ROUTE
'AF': ShipperClient.STATUS_TYPES.EN_ROUTE
'AR': ShipperClient.STATUS_TYPES.EN_ROUTE
'BA': ShipperClient.STATUS_TYPES.DELAYED
'BN': ShipperClient.STATUS_TYPES.EN_ROUTE
'BR': ShipperClient.STATUS_TYPES.EN_ROUTE
'CA': ShipperClient.STATUS_TYPES.DELAYED
'CC': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY
'CD': ShipperClient.STATUS_TYPES.DELAYED
'CM': ShipperClient.STATUS_TYPES.DELAYED
'CR': ShipperClient.STATUS_TYPES.EN_ROUTE
'CS': ShipperClient.STATUS_TYPES.DELAYED
'DD': ShipperClient.STATUS_TYPES.DELIVERED
'DF': ShipperClient.STATUS_TYPES.EN_ROUTE
'DS': ShipperClient.STATUS_TYPES.DELAYED
'FD': ShipperClient.STATUS_TYPES.EN_ROUTE
'HP': ShipperClient.STATUS_TYPES.DELAYED
'IC': ShipperClient.STATUS_TYPES.EN_ROUTE
'MC': ShipperClient.STATUS_TYPES.DELAYED
'MD': ShipperClient.STATUS_TYPES.EN_ROUTE
'MS': ShipperClient.STATUS_TYPES.DELAYED
'ND': ShipperClient.STATUS_TYPES.DELAYED
'NH': ShipperClient.STATUS_TYPES.DELAYED
'OH': ShipperClient.STATUS_TYPES.DELAYED
'OK': ShipperClient.STATUS_TYPES.DELIVERED
'PD': ShipperClient.STATUS_TYPES.EN_ROUTE
'PL': ShipperClient.STATUS_TYPES.EN_ROUTE
'PO': ShipperClient.STATUS_TYPES.EN_ROUTE
'PU': ShipperClient.STATUS_TYPES.EN_ROUTE
'RD': ShipperClient.STATUS_TYPES.DELAYED
'RR': ShipperClient.STATUS_TYPES.DELAYED
'RT': ShipperClient.STATUS_TYPES.DELAYED
'SA': ShipperClient.STATUS_TYPES.SHIPPING
'SC': ShipperClient.STATUS_TYPES.DELAYED
'SS': ShipperClient.STATUS_TYPES.DELAYED
'TD': ShipperClient.STATUS_TYPES.DELAYED
'TP': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY
'TR': ShipperClient.STATUS_TYPES.EN_ROUTE
'UD': ShipperClient.STATUS_TYPES.DELAYED
'WC': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY
'WX': ShipperClient.STATUS_TYPES.DELAYED
presentStatus: (status) ->
STATUS_MAP[status] or ShipperClient.STATUS_TYPES.UNKNOWN
getActivitiesAndStatus: (shipment) ->
activities = []
status = null
rawActivities = shipment['ShipmentEvent']
rawActivities = [] unless rawActivities?
rawActivities.reverse()
for rawActivity in rawActivities or []
rawLocation = rawActivity['ServiceArea']?[0]?['Description']?[0]
location = @presentAddress rawLocation
timestamp = @presentTimestamp rawActivity['Date']?[0], rawActivity['Time']?[0]
details = @presentDetails rawLocation, rawActivity['ServiceEvent']?[0]?['Description']?[0]
if details? and timestamp?
details = if details.slice(-1) is '.' then details[..-2] else details
activity = {timestamp, location, details}
activities.push activity
if !status
status = @presentStatus rawActivity['ServiceEvent']?[0]?['EventCode']?[0]
{activities, status}
getDestination: (shipment) ->
destination = shipment['DestinationServiceArea']?[0]?['Description']?[0]
return unless destination?
@presentAddress destination
requestOptions: ({trackingNumber}) ->
method: 'POST'
uri: 'http://xmlpi-ea.dhl.com/XMLShippingServlet'
body: @generateRequest trackingNumber
module.exports = {DhlClient}
| 115372 | {Parser} = require 'xml2js'
moment = require 'moment-timezone'
{titleCase, upperCaseFirst, lowerCase} = require 'change-case'
{ShipperClient} = require './shipper'
class DhlClient extends ShipperClient
constructor: ({@userId, @password}, @options) ->
super
@parser = new Parser()
generateRequest: (trk) ->
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<req:KnownTrackingRequest xmlns:req="http://www.dhl.com">
<Request>
<ServiceHeader>
<SiteID>#{@userId}</SiteID>
<Password>#{<PASSWORD>}</Password>
</ServiceHeader>
</Request>
<LanguageCode>en</LanguageCode>
<AWBNumber>#{trk}</AWBNumber>
<LevelOfDetails>ALL_CHECK_POINTS</LevelOfDetails>
</req:KnownTrackingRequest>
"""
validateResponse: (response, cb) ->
handleResponse = (xmlErr, trackResult) ->
return cb(xmlErr) if xmlErr? or !trackResult?
trackingResponse = trackResult['req:TrackingResponse']
return cb(error: 'no tracking response') unless trackingResponse?
awbInfo = trackingResponse['AWBInfo']?[0]
return cb(error: 'no AWBInfo in response') unless awbInfo?
shipment = awbInfo['ShipmentInfo']?[0]
return cb(error: 'could not find shipment') unless shipment?
trackStatus = awbInfo['Status']?[0]
statusCode = trackStatus?['ActionStatus']
return cb(error: "unexpected track status code=#{statusCode}") unless statusCode.toString() is 'success'
cb null, shipment
@parser.reset()
@parser.parseString response, handleResponse
getEta: (shipment) ->
getService: (shipment) ->
getWeight: (shipment) ->
weight = shipment['Weight']?[0]
if weight? then "#{weight} LB"
presentTimestamp: (dateString, timeString) ->
return unless dateString?
timeString ?= '00:00'
inputString = "#{dateString} #{timeString} +0000"
moment(inputString).toDate()
presentAddress: (rawAddress) ->
return unless rawAddress?
firstComma = rawAddress.indexOf(',')
firstDash = rawAddress.indexOf('-', firstComma)
if firstComma > -1 and firstDash > -1
city = rawAddress.substring(0, firstComma).trim()
stateCode = rawAddress.substring(firstComma+1, firstDash).trim()
countryCode = rawAddress.substring(firstDash+1).trim()
else if firstComma < 0 and firstDash > -1
city = rawAddress.substring(0, firstDash).trim()
stateCode = null
countryCode = rawAddress.substring(firstDash+1).trim()
else
return rawAddress
city = city.replace(' HUB', '')
city = city.replace(' GATEWAY', '')
@presentLocation {city, stateCode, countryCode}
presentDetails: (rawAddress, rawDetails) ->
return unless rawDetails?
return rawDetails unless rawAddress?
rawDetails.replace(/\s\s+/, ' ').trim().replace(new RegExp("(?: at| in)? #{rawAddress.trim()}$"), '')
STATUS_MAP =
'AD': ShipperClient.STATUS_TYPES.EN_ROUTE
'AF': ShipperClient.STATUS_TYPES.EN_ROUTE
'AR': ShipperClient.STATUS_TYPES.EN_ROUTE
'BA': ShipperClient.STATUS_TYPES.DELAYED
'BN': ShipperClient.STATUS_TYPES.EN_ROUTE
'BR': ShipperClient.STATUS_TYPES.EN_ROUTE
'CA': ShipperClient.STATUS_TYPES.DELAYED
'CC': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY
'CD': ShipperClient.STATUS_TYPES.DELAYED
'CM': ShipperClient.STATUS_TYPES.DELAYED
'CR': ShipperClient.STATUS_TYPES.EN_ROUTE
'CS': ShipperClient.STATUS_TYPES.DELAYED
'DD': ShipperClient.STATUS_TYPES.DELIVERED
'DF': ShipperClient.STATUS_TYPES.EN_ROUTE
'DS': ShipperClient.STATUS_TYPES.DELAYED
'FD': ShipperClient.STATUS_TYPES.EN_ROUTE
'HP': ShipperClient.STATUS_TYPES.DELAYED
'IC': ShipperClient.STATUS_TYPES.EN_ROUTE
'MC': ShipperClient.STATUS_TYPES.DELAYED
'MD': ShipperClient.STATUS_TYPES.EN_ROUTE
'MS': ShipperClient.STATUS_TYPES.DELAYED
'ND': ShipperClient.STATUS_TYPES.DELAYED
'NH': ShipperClient.STATUS_TYPES.DELAYED
'OH': ShipperClient.STATUS_TYPES.DELAYED
'OK': ShipperClient.STATUS_TYPES.DELIVERED
'PD': ShipperClient.STATUS_TYPES.EN_ROUTE
'PL': ShipperClient.STATUS_TYPES.EN_ROUTE
'PO': ShipperClient.STATUS_TYPES.EN_ROUTE
'PU': ShipperClient.STATUS_TYPES.EN_ROUTE
'RD': ShipperClient.STATUS_TYPES.DELAYED
'RR': ShipperClient.STATUS_TYPES.DELAYED
'RT': ShipperClient.STATUS_TYPES.DELAYED
'SA': ShipperClient.STATUS_TYPES.SHIPPING
'SC': ShipperClient.STATUS_TYPES.DELAYED
'SS': ShipperClient.STATUS_TYPES.DELAYED
'TD': ShipperClient.STATUS_TYPES.DELAYED
'TP': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY
'TR': ShipperClient.STATUS_TYPES.EN_ROUTE
'UD': ShipperClient.STATUS_TYPES.DELAYED
'WC': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY
'WX': ShipperClient.STATUS_TYPES.DELAYED
presentStatus: (status) ->
STATUS_MAP[status] or ShipperClient.STATUS_TYPES.UNKNOWN
getActivitiesAndStatus: (shipment) ->
activities = []
status = null
rawActivities = shipment['ShipmentEvent']
rawActivities = [] unless rawActivities?
rawActivities.reverse()
for rawActivity in rawActivities or []
rawLocation = rawActivity['ServiceArea']?[0]?['Description']?[0]
location = @presentAddress rawLocation
timestamp = @presentTimestamp rawActivity['Date']?[0], rawActivity['Time']?[0]
details = @presentDetails rawLocation, rawActivity['ServiceEvent']?[0]?['Description']?[0]
if details? and timestamp?
details = if details.slice(-1) is '.' then details[..-2] else details
activity = {timestamp, location, details}
activities.push activity
if !status
status = @presentStatus rawActivity['ServiceEvent']?[0]?['EventCode']?[0]
{activities, status}
getDestination: (shipment) ->
destination = shipment['DestinationServiceArea']?[0]?['Description']?[0]
return unless destination?
@presentAddress destination
requestOptions: ({trackingNumber}) ->
method: 'POST'
uri: 'http://xmlpi-ea.dhl.com/XMLShippingServlet'
body: @generateRequest trackingNumber
module.exports = {DhlClient}
| true | {Parser} = require 'xml2js'
moment = require 'moment-timezone'
{titleCase, upperCaseFirst, lowerCase} = require 'change-case'
{ShipperClient} = require './shipper'
class DhlClient extends ShipperClient
constructor: ({@userId, @password}, @options) ->
super
@parser = new Parser()
generateRequest: (trk) ->
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<req:KnownTrackingRequest xmlns:req="http://www.dhl.com">
<Request>
<ServiceHeader>
<SiteID>#{@userId}</SiteID>
<Password>#{PI:PASSWORD:<PASSWORD>END_PI}</Password>
</ServiceHeader>
</Request>
<LanguageCode>en</LanguageCode>
<AWBNumber>#{trk}</AWBNumber>
<LevelOfDetails>ALL_CHECK_POINTS</LevelOfDetails>
</req:KnownTrackingRequest>
"""
validateResponse: (response, cb) ->
handleResponse = (xmlErr, trackResult) ->
return cb(xmlErr) if xmlErr? or !trackResult?
trackingResponse = trackResult['req:TrackingResponse']
return cb(error: 'no tracking response') unless trackingResponse?
awbInfo = trackingResponse['AWBInfo']?[0]
return cb(error: 'no AWBInfo in response') unless awbInfo?
shipment = awbInfo['ShipmentInfo']?[0]
return cb(error: 'could not find shipment') unless shipment?
trackStatus = awbInfo['Status']?[0]
statusCode = trackStatus?['ActionStatus']
return cb(error: "unexpected track status code=#{statusCode}") unless statusCode.toString() is 'success'
cb null, shipment
@parser.reset()
@parser.parseString response, handleResponse
getEta: (shipment) ->
getService: (shipment) ->
getWeight: (shipment) ->
weight = shipment['Weight']?[0]
if weight? then "#{weight} LB"
presentTimestamp: (dateString, timeString) ->
return unless dateString?
timeString ?= '00:00'
inputString = "#{dateString} #{timeString} +0000"
moment(inputString).toDate()
presentAddress: (rawAddress) ->
return unless rawAddress?
firstComma = rawAddress.indexOf(',')
firstDash = rawAddress.indexOf('-', firstComma)
if firstComma > -1 and firstDash > -1
city = rawAddress.substring(0, firstComma).trim()
stateCode = rawAddress.substring(firstComma+1, firstDash).trim()
countryCode = rawAddress.substring(firstDash+1).trim()
else if firstComma < 0 and firstDash > -1
city = rawAddress.substring(0, firstDash).trim()
stateCode = null
countryCode = rawAddress.substring(firstDash+1).trim()
else
return rawAddress
city = city.replace(' HUB', '')
city = city.replace(' GATEWAY', '')
@presentLocation {city, stateCode, countryCode}
presentDetails: (rawAddress, rawDetails) ->
return unless rawDetails?
return rawDetails unless rawAddress?
rawDetails.replace(/\s\s+/, ' ').trim().replace(new RegExp("(?: at| in)? #{rawAddress.trim()}$"), '')
STATUS_MAP =
'AD': ShipperClient.STATUS_TYPES.EN_ROUTE
'AF': ShipperClient.STATUS_TYPES.EN_ROUTE
'AR': ShipperClient.STATUS_TYPES.EN_ROUTE
'BA': ShipperClient.STATUS_TYPES.DELAYED
'BN': ShipperClient.STATUS_TYPES.EN_ROUTE
'BR': ShipperClient.STATUS_TYPES.EN_ROUTE
'CA': ShipperClient.STATUS_TYPES.DELAYED
'CC': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY
'CD': ShipperClient.STATUS_TYPES.DELAYED
'CM': ShipperClient.STATUS_TYPES.DELAYED
'CR': ShipperClient.STATUS_TYPES.EN_ROUTE
'CS': ShipperClient.STATUS_TYPES.DELAYED
'DD': ShipperClient.STATUS_TYPES.DELIVERED
'DF': ShipperClient.STATUS_TYPES.EN_ROUTE
'DS': ShipperClient.STATUS_TYPES.DELAYED
'FD': ShipperClient.STATUS_TYPES.EN_ROUTE
'HP': ShipperClient.STATUS_TYPES.DELAYED
'IC': ShipperClient.STATUS_TYPES.EN_ROUTE
'MC': ShipperClient.STATUS_TYPES.DELAYED
'MD': ShipperClient.STATUS_TYPES.EN_ROUTE
'MS': ShipperClient.STATUS_TYPES.DELAYED
'ND': ShipperClient.STATUS_TYPES.DELAYED
'NH': ShipperClient.STATUS_TYPES.DELAYED
'OH': ShipperClient.STATUS_TYPES.DELAYED
'OK': ShipperClient.STATUS_TYPES.DELIVERED
'PD': ShipperClient.STATUS_TYPES.EN_ROUTE
'PL': ShipperClient.STATUS_TYPES.EN_ROUTE
'PO': ShipperClient.STATUS_TYPES.EN_ROUTE
'PU': ShipperClient.STATUS_TYPES.EN_ROUTE
'RD': ShipperClient.STATUS_TYPES.DELAYED
'RR': ShipperClient.STATUS_TYPES.DELAYED
'RT': ShipperClient.STATUS_TYPES.DELAYED
'SA': ShipperClient.STATUS_TYPES.SHIPPING
'SC': ShipperClient.STATUS_TYPES.DELAYED
'SS': ShipperClient.STATUS_TYPES.DELAYED
'TD': ShipperClient.STATUS_TYPES.DELAYED
'TP': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY
'TR': ShipperClient.STATUS_TYPES.EN_ROUTE
'UD': ShipperClient.STATUS_TYPES.DELAYED
'WC': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY
'WX': ShipperClient.STATUS_TYPES.DELAYED
presentStatus: (status) ->
STATUS_MAP[status] or ShipperClient.STATUS_TYPES.UNKNOWN
getActivitiesAndStatus: (shipment) ->
activities = []
status = null
rawActivities = shipment['ShipmentEvent']
rawActivities = [] unless rawActivities?
rawActivities.reverse()
for rawActivity in rawActivities or []
rawLocation = rawActivity['ServiceArea']?[0]?['Description']?[0]
location = @presentAddress rawLocation
timestamp = @presentTimestamp rawActivity['Date']?[0], rawActivity['Time']?[0]
details = @presentDetails rawLocation, rawActivity['ServiceEvent']?[0]?['Description']?[0]
if details? and timestamp?
details = if details.slice(-1) is '.' then details[..-2] else details
activity = {timestamp, location, details}
activities.push activity
if !status
status = @presentStatus rawActivity['ServiceEvent']?[0]?['EventCode']?[0]
{activities, status}
getDestination: (shipment) ->
destination = shipment['DestinationServiceArea']?[0]?['Description']?[0]
return unless destination?
@presentAddress destination
requestOptions: ({trackingNumber}) ->
method: 'POST'
uri: 'http://xmlpi-ea.dhl.com/XMLShippingServlet'
body: @generateRequest trackingNumber
module.exports = {DhlClient}
|
[
{
"context": "do fill = (item = 'Andy') ->\n\t$('#content').append \"#{item}\"\n\tconsole.dir",
"end": 23,
"score": 0.9994560480117798,
"start": 19,
"tag": "NAME",
"value": "Andy"
}
] | components/coffee/script.coffee | IcthusSolutions/coffeeScript | 0 | do fill = (item = 'Andy') ->
$('#content').append "#{item}"
console.dir @fill
fill | 184082 | do fill = (item = '<NAME>') ->
$('#content').append "#{item}"
console.dir @fill
fill | true | do fill = (item = 'PI:NAME:<NAME>END_PI') ->
$('#content').append "#{item}"
console.dir @fill
fill |
[
{
"context": " '55f7d19c85efe377996a1231'\n accessToken: 'afasdfasdfas'\n showname: 'Teambition'\n ",
"end": 342,
"score": 0.809808611869812,
"start": 340,
"tag": "KEY",
"value": "af"
},
{
"context": "55f7d19c85efe377996a1231'\n accessToken: 'afasdfasdfas'\n showname: 'Teambition'\n avatarUrl",
"end": 352,
"score": 0.6341441869735718,
"start": 342,
"tag": "PASSWORD",
"value": "asdfasdfas"
},
{
"context": " '55f7d19c85efe377996a1233'\n accessToken: 'helloworld'\n showname: 'github'\n avatarUrl: 'w",
"end": 541,
"score": 0.9031245112419128,
"start": 531,
"tag": "KEY",
"value": "helloworld"
}
] | talk-api2x/test/servers/account.coffee | ikingye/talk-os | 3,084 | express = require 'express'
module.exports = app = express()
app.get '/v1/user/get', (req, res) ->
accountToken = req.query['accountToken']
accountToken.should.eql 'OKKKKKKK'
data =
_id: '55f7d19c85efe377996a1232'
unions:
[
refer: 'teambition'
openId: '55f7d19c85efe377996a1231'
accessToken: 'afasdfasdfas'
showname: 'Teambition'
avatarUrl: 'www.project.ci/striker/png1'
,
refer: 'github'
openId: '55f7d19c85efe377996a1233'
accessToken: 'helloworld'
showname: 'github'
avatarUrl: 'www.project.ci/striker/png2'
]
res.status(200).json data
| 52636 | express = require 'express'
module.exports = app = express()
app.get '/v1/user/get', (req, res) ->
accountToken = req.query['accountToken']
accountToken.should.eql 'OKKKKKKK'
data =
_id: '55f7d19c85efe377996a1232'
unions:
[
refer: 'teambition'
openId: '55f7d19c85efe377996a1231'
accessToken: '<KEY> <PASSWORD>'
showname: 'Teambition'
avatarUrl: 'www.project.ci/striker/png1'
,
refer: 'github'
openId: '55f7d19c85efe377996a1233'
accessToken: '<KEY>'
showname: 'github'
avatarUrl: 'www.project.ci/striker/png2'
]
res.status(200).json data
| true | express = require 'express'
module.exports = app = express()
app.get '/v1/user/get', (req, res) ->
accountToken = req.query['accountToken']
accountToken.should.eql 'OKKKKKKK'
data =
_id: '55f7d19c85efe377996a1232'
unions:
[
refer: 'teambition'
openId: '55f7d19c85efe377996a1231'
accessToken: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI'
showname: 'Teambition'
avatarUrl: 'www.project.ci/striker/png1'
,
refer: 'github'
openId: '55f7d19c85efe377996a1233'
accessToken: 'PI:KEY:<KEY>END_PI'
showname: 'github'
avatarUrl: 'www.project.ci/striker/png2'
]
res.status(200).json data
|
[
{
"context": "to run commands on, set \"hosts\", [\"example.com\", \"git@example.com\"]'\n\nensure 'keepReleases', -> 5\nensure 'env', ",
"end": 334,
"score": 0.743660569190979,
"start": 319,
"tag": "EMAIL",
"value": "git@example.com"
}
] | cockout/deploy.coffee | sergeysova/deplosha | 1 | path = require('path')
ensure 'application', ->
abort 'Please specify application name, set "application", "foo"'
ensure 'repository', ->
abort 'Please specify repository url, set "repository", "/home/git/myrepo.git"'
ensure 'hosts', ->
abort 'Specify ssh hosts to run commands on, set "hosts", ["example.com", "git@example.com"]'
ensure 'keepReleases', -> 5
ensure 'env', 'production'
ensure 'scm', 'git'
ensure 'branch', 'master'
ensure 'deployTo', -> "/var/www/apps/#{deplosha.application}/#{deplosha.env}"
ensure 'releaseName', Date.now()
ensure 'releasesDir', 'releases'
ensure 'sharedDir', 'shared'
ensure 'currentDir', 'current'
ensure 'releasesPath', -> path.resolve(deplosha.deployTo, deplosha.releasesDir)
ensure 'sharedPath', -> path.resolve(deplosha.deployTo, deplosha.sharedDir)
ensure 'currentPath', -> path.resolve(deplosha.deployTo, deplosha.currentDir)
ensure 'releasePath', -> path.resolve(deplosha.releasesPath, ''+deplosha.releaseName)
ensure 'previousReleasePath', -> path.resolve(deplosha.releasesPath, ''+deplosha.previousRelease)
ensure 'latestReleasePath', -> path.resolve(deplosha.releasesPath, ''+deplosha.latestRelease)
ensure 'env', 'production'
ensure 'nodeEntry', 'index.js'
ensure 'appPort', process.env.APP_PORT || process.env.PORT || 3003
ensure 'job', ->
if deplosha.env == 'production'
deplosha.application
else
deplosha.application + '-' + deplosha.env
namespace 'deploy', ->
task "test", ->
run 'ps aux | grep node', (data) ->
console.log data
desc """
Update code and restart server
"""
task 'default', (done) -> sequence 'update', 'restart', done
desc """
Pull latest changes from SCM and symlink latest release
as current release
"""
task 'update', (done) -> sequence 'prepare', 'updateCode', 'symlink', done
task 'prepare', (done) ->
run "ls -x #{deplosha.releasesPath}", (res) ->
rs = res[0].out.replace(/^\s+|\s+$/g, '').split(/\s+/).sort()
set 'releases', rs
set 'latestRelease', rs[rs.length - 1]
set 'previousRelease', rs[rs.length - 2]
done()
task 'updateCode', (done) ->
localRun "git ls-remote #{deplosha.repository} #{deplosha.branch}", (x) ->
head = x.split(/\s+/).shift()
run """
if [ -d #{deplosha.sharedPath}/cached-copy ];
then cd #{deplosha.sharedPath}/cached-copy &&
git fetch -q origin && git fetch --tags -q origin &&
git reset -q --hard #{head} && git clean -q -d -f;
git submodule update --init
else
git clone -q #{deplosha.repository} #{deplosha.sharedPath}/cached-copy &&
cd #{deplosha.sharedPath}/cached-copy &&
git checkout -q -b deploy #{head};
git submodule update --init
fi
""", ->
run """
cd #{deplosha.sharedPath}/cached-copy;
npm install -l;
cp -RPp #{deplosha.sharedPath}/cached-copy #{deplosha.releasePath}
""", done
task 'cleanup', (done) -> sequence 'prepare', 'removeOldReleases', done
task 'removeOldReleases', (done) ->
return console.log('Nothing to cleanup', done()) if deplosha.releases.length <= deplosha.keepReleases
console.log "Deleting #{deplosha.releases.length - deplosha.keepReleases} releases, keep latest #{deplosha.keepReleases} releases"
run "cd #{deplosha.releasesPath} && rm -rf #{deplosha.releases.slice(0, -deplosha.keepReleases).join(' ')}", done
desc """
Remove current symlink, symlink current release and log file
"""
task 'symlink', (done) ->
run """
rm -f #{deplosha.currentPath};
ln -s #{deplosha.releasePath} #{deplosha.currentPath};
ln -s #{deplosha.sharedPath}/log #{deplosha.currentPath}/log;
true
""", done
desc """
Restart upstart job, or start if job is not running
"""
task 'restart', (done) ->
run "sudo restart #{deplosha.job} || sudo start #{deplosha.job}", done
desc "Start upstart job"
task 'start', (done) ->
run "sudo start #{deplosha.job}", done
desc "Stop upstart job"
task 'stop', (done) ->
run "sudo stop #{deplosha.job}", done
desc """
Rollback current release. Removes current symlink, symlink previous,
restart process and remove code.
"""
task 'rollback', (done) ->
sequence 'prepare', 'rollback:code', 'restart', 'rollback:cleanup', done
task 'rollback:code', (done) ->
if deplosha.previousRelease
run "rm #{deplosha.currentPath}; ln -s #{deplosha.previousReleasePath} #{deplosha.currentPath}", done
task 'rollback:cleanup', (done) ->
run "if [ `readlink #{deplosha.currentPath}` != #{deplosha.latestReleasePath} ]; then rm -rf #{deplosha.latestReleasePath}; fi", done
task 'setup', (done) ->
dirs = [deplosha.deployTo, deplosha.releasesPath, deplosha.sharedPath, deplosha.sharedPath + '/log'].join(' ')
run """
NAME=`whoami`;
sudo mkdir -p #{dirs} &&
sudo chown -R $NAME:$NAME #{dirs}
""", done
task 'setup:upstart', (done) ->
sequence 'setup', 'writeUpstartScript', done
task 'writeUpstartScript', (done) ->
maybeEnv = ''
maybeEnv = "env NODE_ENV=\"#{deplosha.env}\"" if deplosha.env
maybePort = ''
maybePort = "env PORT=#{deplosha.appPort}" if deplosha.appPort
ups = """
description "#{deplosha.application}"
start on startup
stop on shutdown
#{maybePort}
#{maybeEnv}
script
export PORT
export NODE_ENV
cd #{deplosha.currentPath}
/usr/local/bin/node #{deplosha.currentPath}/#{deplosha.nodeEntry} >> #{deplosha.currentPath}/log/#{deplosha.env}.log
end script
respawn
"""
if deplosha.env == 'production'
file = deplosha.application
else
file = "#{deplosha.application}-#{deplosha.env}"
run "sudo echo '#{ups}' > /tmp/upstart.tmp && sudo mv /tmp/upstart.tmp /etc/init/#{file}.conf", done
| 42219 | path = require('path')
ensure 'application', ->
abort 'Please specify application name, set "application", "foo"'
ensure 'repository', ->
abort 'Please specify repository url, set "repository", "/home/git/myrepo.git"'
ensure 'hosts', ->
abort 'Specify ssh hosts to run commands on, set "hosts", ["example.com", "<EMAIL>"]'
ensure 'keepReleases', -> 5
ensure 'env', 'production'
ensure 'scm', 'git'
ensure 'branch', 'master'
ensure 'deployTo', -> "/var/www/apps/#{deplosha.application}/#{deplosha.env}"
ensure 'releaseName', Date.now()
ensure 'releasesDir', 'releases'
ensure 'sharedDir', 'shared'
ensure 'currentDir', 'current'
ensure 'releasesPath', -> path.resolve(deplosha.deployTo, deplosha.releasesDir)
ensure 'sharedPath', -> path.resolve(deplosha.deployTo, deplosha.sharedDir)
ensure 'currentPath', -> path.resolve(deplosha.deployTo, deplosha.currentDir)
ensure 'releasePath', -> path.resolve(deplosha.releasesPath, ''+deplosha.releaseName)
ensure 'previousReleasePath', -> path.resolve(deplosha.releasesPath, ''+deplosha.previousRelease)
ensure 'latestReleasePath', -> path.resolve(deplosha.releasesPath, ''+deplosha.latestRelease)
ensure 'env', 'production'
ensure 'nodeEntry', 'index.js'
ensure 'appPort', process.env.APP_PORT || process.env.PORT || 3003
ensure 'job', ->
if deplosha.env == 'production'
deplosha.application
else
deplosha.application + '-' + deplosha.env
namespace 'deploy', ->
task "test", ->
run 'ps aux | grep node', (data) ->
console.log data
desc """
Update code and restart server
"""
task 'default', (done) -> sequence 'update', 'restart', done
desc """
Pull latest changes from SCM and symlink latest release
as current release
"""
task 'update', (done) -> sequence 'prepare', 'updateCode', 'symlink', done
task 'prepare', (done) ->
run "ls -x #{deplosha.releasesPath}", (res) ->
rs = res[0].out.replace(/^\s+|\s+$/g, '').split(/\s+/).sort()
set 'releases', rs
set 'latestRelease', rs[rs.length - 1]
set 'previousRelease', rs[rs.length - 2]
done()
task 'updateCode', (done) ->
localRun "git ls-remote #{deplosha.repository} #{deplosha.branch}", (x) ->
head = x.split(/\s+/).shift()
run """
if [ -d #{deplosha.sharedPath}/cached-copy ];
then cd #{deplosha.sharedPath}/cached-copy &&
git fetch -q origin && git fetch --tags -q origin &&
git reset -q --hard #{head} && git clean -q -d -f;
git submodule update --init
else
git clone -q #{deplosha.repository} #{deplosha.sharedPath}/cached-copy &&
cd #{deplosha.sharedPath}/cached-copy &&
git checkout -q -b deploy #{head};
git submodule update --init
fi
""", ->
run """
cd #{deplosha.sharedPath}/cached-copy;
npm install -l;
cp -RPp #{deplosha.sharedPath}/cached-copy #{deplosha.releasePath}
""", done
task 'cleanup', (done) -> sequence 'prepare', 'removeOldReleases', done
task 'removeOldReleases', (done) ->
return console.log('Nothing to cleanup', done()) if deplosha.releases.length <= deplosha.keepReleases
console.log "Deleting #{deplosha.releases.length - deplosha.keepReleases} releases, keep latest #{deplosha.keepReleases} releases"
run "cd #{deplosha.releasesPath} && rm -rf #{deplosha.releases.slice(0, -deplosha.keepReleases).join(' ')}", done
desc """
Remove current symlink, symlink current release and log file
"""
task 'symlink', (done) ->
run """
rm -f #{deplosha.currentPath};
ln -s #{deplosha.releasePath} #{deplosha.currentPath};
ln -s #{deplosha.sharedPath}/log #{deplosha.currentPath}/log;
true
""", done
desc """
Restart upstart job, or start if job is not running
"""
task 'restart', (done) ->
run "sudo restart #{deplosha.job} || sudo start #{deplosha.job}", done
desc "Start upstart job"
task 'start', (done) ->
run "sudo start #{deplosha.job}", done
desc "Stop upstart job"
task 'stop', (done) ->
run "sudo stop #{deplosha.job}", done
desc """
Rollback current release. Removes current symlink, symlink previous,
restart process and remove code.
"""
task 'rollback', (done) ->
sequence 'prepare', 'rollback:code', 'restart', 'rollback:cleanup', done
task 'rollback:code', (done) ->
if deplosha.previousRelease
run "rm #{deplosha.currentPath}; ln -s #{deplosha.previousReleasePath} #{deplosha.currentPath}", done
task 'rollback:cleanup', (done) ->
run "if [ `readlink #{deplosha.currentPath}` != #{deplosha.latestReleasePath} ]; then rm -rf #{deplosha.latestReleasePath}; fi", done
task 'setup', (done) ->
dirs = [deplosha.deployTo, deplosha.releasesPath, deplosha.sharedPath, deplosha.sharedPath + '/log'].join(' ')
run """
NAME=`whoami`;
sudo mkdir -p #{dirs} &&
sudo chown -R $NAME:$NAME #{dirs}
""", done
task 'setup:upstart', (done) ->
sequence 'setup', 'writeUpstartScript', done
task 'writeUpstartScript', (done) ->
maybeEnv = ''
maybeEnv = "env NODE_ENV=\"#{deplosha.env}\"" if deplosha.env
maybePort = ''
maybePort = "env PORT=#{deplosha.appPort}" if deplosha.appPort
ups = """
description "#{deplosha.application}"
start on startup
stop on shutdown
#{maybePort}
#{maybeEnv}
script
export PORT
export NODE_ENV
cd #{deplosha.currentPath}
/usr/local/bin/node #{deplosha.currentPath}/#{deplosha.nodeEntry} >> #{deplosha.currentPath}/log/#{deplosha.env}.log
end script
respawn
"""
if deplosha.env == 'production'
file = deplosha.application
else
file = "#{deplosha.application}-#{deplosha.env}"
run "sudo echo '#{ups}' > /tmp/upstart.tmp && sudo mv /tmp/upstart.tmp /etc/init/#{file}.conf", done
| true | path = require('path')
ensure 'application', ->
abort 'Please specify application name, set "application", "foo"'
ensure 'repository', ->
abort 'Please specify repository url, set "repository", "/home/git/myrepo.git"'
ensure 'hosts', ->
abort 'Specify ssh hosts to run commands on, set "hosts", ["example.com", "PI:EMAIL:<EMAIL>END_PI"]'
ensure 'keepReleases', -> 5
ensure 'env', 'production'
ensure 'scm', 'git'
ensure 'branch', 'master'
ensure 'deployTo', -> "/var/www/apps/#{deplosha.application}/#{deplosha.env}"
ensure 'releaseName', Date.now()
ensure 'releasesDir', 'releases'
ensure 'sharedDir', 'shared'
ensure 'currentDir', 'current'
ensure 'releasesPath', -> path.resolve(deplosha.deployTo, deplosha.releasesDir)
ensure 'sharedPath', -> path.resolve(deplosha.deployTo, deplosha.sharedDir)
ensure 'currentPath', -> path.resolve(deplosha.deployTo, deplosha.currentDir)
ensure 'releasePath', -> path.resolve(deplosha.releasesPath, ''+deplosha.releaseName)
ensure 'previousReleasePath', -> path.resolve(deplosha.releasesPath, ''+deplosha.previousRelease)
ensure 'latestReleasePath', -> path.resolve(deplosha.releasesPath, ''+deplosha.latestRelease)
ensure 'env', 'production'
ensure 'nodeEntry', 'index.js'
ensure 'appPort', process.env.APP_PORT || process.env.PORT || 3003
ensure 'job', ->
if deplosha.env == 'production'
deplosha.application
else
deplosha.application + '-' + deplosha.env
namespace 'deploy', ->
task "test", ->
run 'ps aux | grep node', (data) ->
console.log data
desc """
Update code and restart server
"""
task 'default', (done) -> sequence 'update', 'restart', done
desc """
Pull latest changes from SCM and symlink latest release
as current release
"""
task 'update', (done) -> sequence 'prepare', 'updateCode', 'symlink', done
task 'prepare', (done) ->
run "ls -x #{deplosha.releasesPath}", (res) ->
rs = res[0].out.replace(/^\s+|\s+$/g, '').split(/\s+/).sort()
set 'releases', rs
set 'latestRelease', rs[rs.length - 1]
set 'previousRelease', rs[rs.length - 2]
done()
task 'updateCode', (done) ->
localRun "git ls-remote #{deplosha.repository} #{deplosha.branch}", (x) ->
head = x.split(/\s+/).shift()
run """
if [ -d #{deplosha.sharedPath}/cached-copy ];
then cd #{deplosha.sharedPath}/cached-copy &&
git fetch -q origin && git fetch --tags -q origin &&
git reset -q --hard #{head} && git clean -q -d -f;
git submodule update --init
else
git clone -q #{deplosha.repository} #{deplosha.sharedPath}/cached-copy &&
cd #{deplosha.sharedPath}/cached-copy &&
git checkout -q -b deploy #{head};
git submodule update --init
fi
""", ->
run """
cd #{deplosha.sharedPath}/cached-copy;
npm install -l;
cp -RPp #{deplosha.sharedPath}/cached-copy #{deplosha.releasePath}
""", done
task 'cleanup', (done) -> sequence 'prepare', 'removeOldReleases', done
task 'removeOldReleases', (done) ->
return console.log('Nothing to cleanup', done()) if deplosha.releases.length <= deplosha.keepReleases
console.log "Deleting #{deplosha.releases.length - deplosha.keepReleases} releases, keep latest #{deplosha.keepReleases} releases"
run "cd #{deplosha.releasesPath} && rm -rf #{deplosha.releases.slice(0, -deplosha.keepReleases).join(' ')}", done
desc """
Remove current symlink, symlink current release and log file
"""
task 'symlink', (done) ->
run """
rm -f #{deplosha.currentPath};
ln -s #{deplosha.releasePath} #{deplosha.currentPath};
ln -s #{deplosha.sharedPath}/log #{deplosha.currentPath}/log;
true
""", done
desc """
Restart upstart job, or start if job is not running
"""
task 'restart', (done) ->
run "sudo restart #{deplosha.job} || sudo start #{deplosha.job}", done
desc "Start upstart job"
task 'start', (done) ->
run "sudo start #{deplosha.job}", done
desc "Stop upstart job"
task 'stop', (done) ->
run "sudo stop #{deplosha.job}", done
desc """
Rollback current release. Removes current symlink, symlink previous,
restart process and remove code.
"""
task 'rollback', (done) ->
sequence 'prepare', 'rollback:code', 'restart', 'rollback:cleanup', done
task 'rollback:code', (done) ->
if deplosha.previousRelease
run "rm #{deplosha.currentPath}; ln -s #{deplosha.previousReleasePath} #{deplosha.currentPath}", done
task 'rollback:cleanup', (done) ->
run "if [ `readlink #{deplosha.currentPath}` != #{deplosha.latestReleasePath} ]; then rm -rf #{deplosha.latestReleasePath}; fi", done
task 'setup', (done) ->
dirs = [deplosha.deployTo, deplosha.releasesPath, deplosha.sharedPath, deplosha.sharedPath + '/log'].join(' ')
run """
NAME=`whoami`;
sudo mkdir -p #{dirs} &&
sudo chown -R $NAME:$NAME #{dirs}
""", done
task 'setup:upstart', (done) ->
sequence 'setup', 'writeUpstartScript', done
task 'writeUpstartScript', (done) ->
maybeEnv = ''
maybeEnv = "env NODE_ENV=\"#{deplosha.env}\"" if deplosha.env
maybePort = ''
maybePort = "env PORT=#{deplosha.appPort}" if deplosha.appPort
ups = """
description "#{deplosha.application}"
start on startup
stop on shutdown
#{maybePort}
#{maybeEnv}
script
export PORT
export NODE_ENV
cd #{deplosha.currentPath}
/usr/local/bin/node #{deplosha.currentPath}/#{deplosha.nodeEntry} >> #{deplosha.currentPath}/log/#{deplosha.env}.log
end script
respawn
"""
if deplosha.env == 'production'
file = deplosha.application
else
file = "#{deplosha.application}-#{deplosha.env}"
run "sudo echo '#{ups}' > /tmp/upstart.tmp && sudo mv /tmp/upstart.tmp /etc/init/#{file}.conf", done
|
[
{
"context": " Under MIT license, see LICENSE file for details\n Andrey Popp (c) 2013\n\n###\n\npath ",
"end": 96,
"score": 0.9998130798339844,
"start": 85,
"tag": "NAME",
"value": "Andrey Popp"
}
] | index.coffee | andreypopp/wall | 2 | ###
Application entry point.
Under MIT license, see LICENSE file for details
Andrey Popp (c) 2013
###
path = require 'path'
{extend} = require 'underscore'
express = require 'express'
page = require 'connect-page'
stylus = require 'connect-stylus'
browserify = require 'connect-browserify'
passport = require 'passport'
reactApp = require 'react-app'
{Item} = require './models'
auth = require './auth'
api = require './api'
rel = path.join.bind(null, __dirname)
assets = (options = {}) ->
app = express()
app.get '/css/index.css', stylus
entry: rel 'ui/index.styl'
use: ['normalize', 'nib']
includeCSS: true
app.get '/js/index.js', browserify
entry: rel 'ui/index.coffee'
extensions: ['.coffee']
transforms: ['coffeeify', 'reactify/undoubted']
debug: true
app.use '/font', express.static rel('node_modules/font-awesome/font')
app
module.exports = (options = {}) ->
app = express()
app.use express.logger('dev')
app.use express.favicon()
app.use express.cookieParser()
app.use express.cookieSession(secret: options?.secret)
app.use passport.initialize()
app.use passport.session()
app.use '/auth', auth(options?.auth)
app.use '/api', api(options)
app.use '/a', assets(options)
app.use page
title: options.title or 'wall'
scripts: ['/a/js/index.js']
stylesheets: ['/a/css/index.css']
meta:
viewport: 'width=device-width, user-scalable=no'
data:
title: options.title or 'wall'
authProviders: Object.keys(options.auth)
app.use express.errorHandler()
app
extend module.exports, {api, assets, auth}
| 4521 | ###
Application entry point.
Under MIT license, see LICENSE file for details
<NAME> (c) 2013
###
path = require 'path'
{extend} = require 'underscore'
express = require 'express'
page = require 'connect-page'
stylus = require 'connect-stylus'
browserify = require 'connect-browserify'
passport = require 'passport'
reactApp = require 'react-app'
{Item} = require './models'
auth = require './auth'
api = require './api'
rel = path.join.bind(null, __dirname)
assets = (options = {}) ->
app = express()
app.get '/css/index.css', stylus
entry: rel 'ui/index.styl'
use: ['normalize', 'nib']
includeCSS: true
app.get '/js/index.js', browserify
entry: rel 'ui/index.coffee'
extensions: ['.coffee']
transforms: ['coffeeify', 'reactify/undoubted']
debug: true
app.use '/font', express.static rel('node_modules/font-awesome/font')
app
module.exports = (options = {}) ->
app = express()
app.use express.logger('dev')
app.use express.favicon()
app.use express.cookieParser()
app.use express.cookieSession(secret: options?.secret)
app.use passport.initialize()
app.use passport.session()
app.use '/auth', auth(options?.auth)
app.use '/api', api(options)
app.use '/a', assets(options)
app.use page
title: options.title or 'wall'
scripts: ['/a/js/index.js']
stylesheets: ['/a/css/index.css']
meta:
viewport: 'width=device-width, user-scalable=no'
data:
title: options.title or 'wall'
authProviders: Object.keys(options.auth)
app.use express.errorHandler()
app
extend module.exports, {api, assets, auth}
| true | ###
Application entry point.
Under MIT license, see LICENSE file for details
PI:NAME:<NAME>END_PI (c) 2013
###
path = require 'path'
{extend} = require 'underscore'
express = require 'express'
page = require 'connect-page'
stylus = require 'connect-stylus'
browserify = require 'connect-browserify'
passport = require 'passport'
reactApp = require 'react-app'
{Item} = require './models'
auth = require './auth'
api = require './api'
rel = path.join.bind(null, __dirname)
assets = (options = {}) ->
app = express()
app.get '/css/index.css', stylus
entry: rel 'ui/index.styl'
use: ['normalize', 'nib']
includeCSS: true
app.get '/js/index.js', browserify
entry: rel 'ui/index.coffee'
extensions: ['.coffee']
transforms: ['coffeeify', 'reactify/undoubted']
debug: true
app.use '/font', express.static rel('node_modules/font-awesome/font')
app
module.exports = (options = {}) ->
app = express()
app.use express.logger('dev')
app.use express.favicon()
app.use express.cookieParser()
app.use express.cookieSession(secret: options?.secret)
app.use passport.initialize()
app.use passport.session()
app.use '/auth', auth(options?.auth)
app.use '/api', api(options)
app.use '/a', assets(options)
app.use page
title: options.title or 'wall'
scripts: ['/a/js/index.js']
stylesheets: ['/a/css/index.css']
meta:
viewport: 'width=device-width, user-scalable=no'
data:
title: options.title or 'wall'
authProviders: Object.keys(options.auth)
app.use express.errorHandler()
app
extend module.exports, {api, assets, auth}
|
[
{
"context": "et Chamber\": {\n cards: -3\n coins: +2\n }\n \"Shanty Town\": {\n actions: +1\n cards: 0\n }\n Silver: {\n",
"end": 7212,
"score": 0.9681650400161743,
"start": 7201,
"tag": "NAME",
"value": "Shanty Town"
}
] | heuristics.coffee | rspeer/dominiate | 65 | # These heuristics are intended to estimate the average effect on your hand
# state when you play the card, not to define what the card actually does.
#
# NOTE: This is not used anywhere yet. I thought it would be useful as a base
# case for code that analyzes a game tree.
#
# The values are all constants, even when the card's effect isn't, so that in
# the base case a hand can be quickly evaluated. The more sophisticated way to
# evaluate a hand, of course, is to consider the actual effect of playing the
# card, and evaluate the resulting hand, recursively. As such, it doesn't even
# matter when these values are wrong for complex actions, as long as they're
# not incredibly wrong.
#
# The +'s have no effect on the values, they just make some of them sound more
# natural.
#
# Victory cards are modeled as cards that replace their action and do nothing
# (this isn't accurate, but the things that would care about the difference --
# like Libraries -- aren't accurate either.)
#
# If they appeared as the default -1 action, it would imply that there was some
# benefit to having +actions with victory cards.
#
# "Churn" is how many more cards you get to see than you get to keep. (Think of
# what Cellar and Warehouse do, even though they're different.) This doesn't
# model the effect of cycling through your deck or stacking it; that's too hard
# to describe without describing what the card actually does in a situation.
heuristics = {
default: {
actions: -1 # _difference_ in number of actions
attack: 0 # how much it hurts your opponents (negative means it helps)
nextTurn: 0 # estimated benefit of a duration or top-decker
buys: 0 # number of +buys
cards: -1 # _difference_ in cards in hand
coins: 0 # number of coins you get
gain: 0 # number of (good) cards you gain
trash: 0 # number of cards you can trash
chips: 0 # number of VP chips
}
Adventurer: {
actions: -1
cards: +1
}
Alchemist: {
actions: 0
cards: +1
nextTurn: +1
}
Ambassador: {
trash: 1.5
cards: -2.5
attack: 1
}
Apothecary: {
actions: 0
cards: +0.5
}
Apprentice: {
actions: 0
cards: +2
trash: 1
}
"Bag of Gold": {
actions: 0
nextTurn: +2
gain: 1
}
Bank: {
actions: 0
coins: 4
}
Baron: {
coins: +3
buys: +1
gain: 0.1
}
Bazaar: {
actions: +1
cards: 0
coins: +1
}
Bishop: {
trash: 1
cards: -2
coins: +1
chips: +2
}
"Black Market": {
coins: +2
buys: 0.5 # you might use it as a buy
gain: 0.3 # you might benefit from it
}
Bridge: {
coins: +3
buys: +1
}
Bureaucrat: {
attack: 0.5
gain: 0.5
}
Caravan: {
actions: 0
cards: 0
nextTurn: +1
}
Cellar: {
actions: 0
churn: 3
}
Chancellor: {
coins: +2
}
Chapel: {
trash: 4
cards: -4
}
City: {
actions: +1
cards: +0.2
coins: +0.1
buys: +0.1
}
Colony: {actions: 0}
Conspirator: {
coins: +1
actions: -0.6
cards: -0.6
}
Contraband: {
actions: 0
coins: +3
buys: +1
attack: -1
}
Copper: {
actions: 0
coins: +1
}
Coppersmith: {
coins: +2
}
"Council Room": {
cards: +3
buys: +1
attack: -1
}
"Counting House": {
cards: +3
}
Courtyard: {
cards: +1
churn: 1
}
Curse: {actions: 0}
Cutpurse: {
attack: 1
coins: +2
}
Diadem: {
actions: 0
coins: +3
}
Duchy: {actions: 0}
Duke: {actions: 0}
Embargo: {
coins: +2
}
Envoy: {
cards: +3
}
Estate: {actions: 0}
Expand: {
trash: 1
cards: -2
gain: 1
}
Explorer: {
gain: 1
cards: 0
}
Fairgrounds: {actions: 0}
Familiar: {
attack: 2
cards: 0
actions: 0
}
"Farming Village": {
actions: +1
cards: 0
}
Feast: {
gain: 1
}
Festival: {
actions: +1
coins: +2
buys: +1
}
"Fishing Village": {
actions: +1
coins: +1
nextTurn: +2
}
Followers: {
attack: 4
cards: +1
}
Forge: {
trash: 3
cards: -4
gain: 1
}
"Fortune Teller": {
attack: 0.5
coins: +2
}
Goons: {
attack: 2.5
coins: +2
chips: +2
}
"Grand Market": {
actions: 0
cards: 0
coins: +2
buys: +1
}
"Great Hall": {
actions: 0
cards: 0
}
Hamlet: {
actions: +0.5
buys: +0.5
cards: -1
}
Harem: {
actions: 0
coins: +2
}
Herbalist: {
buys: +1
coins: +1
nextTurn: +0.5
}
Hoard: {
actions: 0
gain: 0.5
coins: +2
}
"Horn of Plenty": {
actions: 0
gain: 1
}
"Horse Traders": {
cards: -3
coins: +3
buys: +1
}
"Hunting Party": {
cards: +1
actions: 0
}
Ironworks: {
gain: 1
actions: +0.4
coins: +0.4
cards: +0.2
}
Island: {
trash: 1
cards: -2
}
Jester: {
attack: 1
coins: +2
gain: 0.5
}
"King's Court": {
actions: +2
}
Laboratory: {
actions: 0
cards: +1
}
Library: {
cards: +2
}
Lighthouse: {
nextTurn: +1.5
coins: +1
actions: 0
}
Loan: {
actions: 0
cards: -1
trash: 1
}
Lookout: {
cards: -1
trash: 1
}
Market: {
actions: 0
cards: 0
coins: +1
buys: +1
}
Masquerade: {
cards: +1
trash: 1
}
Menagerie: {
actions: 0
cards: +1
}
"Merchant Ship": {
nextTurn: +2
coins: +2
}
Militia: {
attack: 2
coins: +2
}
Mine: {
trash: 1
cards: -1
gain: 1
coins: +1
}
"Mining Village": {
actions: +1
cards: 0
}
Minion: {
attack: 0.5
cards: +1.5
churn: 1.5
coins: 1
}
Mint: {
gain: 1
}
Moat: {
cards: +1
}
Moneylender: {
trash: 1
cards: -2
coins: +2
}
Monument: {
coins: +2
}
Mountebank: {
attack: 2
coins: +2
}
"Native Village": {
actions: +1
cards: +0.5
}
Navigator: {
coins: +2
nextTurn: +0.5
}
Nobles: {
actions: 0
cards: +0.5
}
Outpost: {
nextTurn: +0.5
}
Pawn: {
actions: -0.5
cards: -0.5
coins: +0.5
buys: +0.5
}
"Pearl Diver": {
actions: 0
cards: 0
}
Peddler: {
actions: 0
cards: 0
coins: +1
}
"Philosopher's Stone": {
actions: 0
coins: +4
}
"Pirate Ship": {
attack: 0.5
coins: +3
}
Platinum: {
actions: 0
coins: +5
}
Possession: {
nextTurn: +5
}
Potion: {
actions: 0
potions: +1
}
Princess: {
coins: +4
buys: +1
}
Province: {actions: 0}
Quarry: {
actions: 0
coins: +3
}
Rabble: {
attack: 1
cards: +2
}
Remake: {
trash: 2
cards: -3
gain: 2
}
Remodel: {
trash: 1
cards: -2
gain: 1
}
"Royal Seal": {
actions: 0
coins: 2
nextTurn: +0.5
}
Saboteur: {
attack: 2.5
}
Salvager: {
trash: 1
cards: -2
coins: +2
buys: +1
}
Scout: {
actions: 0
cards: +0.5
}
"Scrying Pool": {
actions: 0
cards: +1
attack: 1
}
"Sea Hag": {
attack: 3
}
"Secret Chamber": {
cards: -3
coins: +2
}
"Shanty Town": {
actions: +1
cards: 0
}
Silver: {
actions: 0
coins: +2
}
Smithy: {
cards: +2
}
Smugglers: {
gain: 1
}
Spy: {
attack: 1
actions: 0
cards: 0
nextTurn: +0.2
}
Stash: {
actions: 0
coins: +2
}
Steward: {
trash: 1
cards: -0.5
coins: +0.5
cards: -2
}
Swindler: {
attack: 1.5
coins: +2
}
Tactician: {
cards: -5
nextTurn: +6
}
Talisman: {
actions: 0
coins: 1
}
Thief: {
gain: 0.5
}
"Throne Room": {
actions: +1
}
Torturer: {
attack: 2
cards: +2
}
Tournament: {
}
"Trade Route": {
cards: -2
trash: 1
coins: +1
buys: +1
}
"Trading Post": {
trash: 2
cards: -2
}
Transmute: {
trash: 1
gain: 1
cards: -2
}
"Treasure Map": {}
Treasury: {
actions: 0
cards: 0
coins: +1
nextTurn: +1
}
Tribute: {
actions: 0
cards: 0
coins: +1
}
"Trusty Steed": {
actions: +0.7
cards: +0.7
coins: +0.6
}
University: {
actions: +1
gain: 1
}
Upgrade: {
actions: 0
cards: -1
trash: 1
gain: 1
}
Vault: {
cards: -1
coins: +2
churn: 2
}
Venture: {
coins: +2.5
}
Village: {
actions: +1
}
Vineyard: {actions: 0}
"Walled Village": {
actions: +1
nextTurn: +0.3
}
Warehouse: {
actions: 0
churn: 3
}
Watchtower: {
cards: +1.5
}
Wharf: {
cards: +1
buys: +1
nextTurn: +3
}
"Wishing Well": {
cards: +0.3
actions: 0
}
Witch: {
attack: 3
cards: +1
}
Woodcutter: {
coins: +2
buys: +1
}
"Worker's Village": {
actions: +1
}
Workshop: {
gain: 1
}
"Young Witch": {
attack: 2
churn: 2
}
}
| 37050 | # These heuristics are intended to estimate the average effect on your hand
# state when you play the card, not to define what the card actually does.
#
# NOTE: This is not used anywhere yet. I thought it would be useful as a base
# case for code that analyzes a game tree.
#
# The values are all constants, even when the card's effect isn't, so that in
# the base case a hand can be quickly evaluated. The more sophisticated way to
# evaluate a hand, of course, is to consider the actual effect of playing the
# card, and evaluate the resulting hand, recursively. As such, it doesn't even
# matter when these values are wrong for complex actions, as long as they're
# not incredibly wrong.
#
# The +'s have no effect on the values, they just make some of them sound more
# natural.
#
# Victory cards are modeled as cards that replace their action and do nothing
# (this isn't accurate, but the things that would care about the difference --
# like Libraries -- aren't accurate either.)
#
# If they appeared as the default -1 action, it would imply that there was some
# benefit to having +actions with victory cards.
#
# "Churn" is how many more cards you get to see than you get to keep. (Think of
# what Cellar and Warehouse do, even though they're different.) This doesn't
# model the effect of cycling through your deck or stacking it; that's too hard
# to describe without describing what the card actually does in a situation.
heuristics = {
default: {
actions: -1 # _difference_ in number of actions
attack: 0 # how much it hurts your opponents (negative means it helps)
nextTurn: 0 # estimated benefit of a duration or top-decker
buys: 0 # number of +buys
cards: -1 # _difference_ in cards in hand
coins: 0 # number of coins you get
gain: 0 # number of (good) cards you gain
trash: 0 # number of cards you can trash
chips: 0 # number of VP chips
}
Adventurer: {
actions: -1
cards: +1
}
Alchemist: {
actions: 0
cards: +1
nextTurn: +1
}
Ambassador: {
trash: 1.5
cards: -2.5
attack: 1
}
Apothecary: {
actions: 0
cards: +0.5
}
Apprentice: {
actions: 0
cards: +2
trash: 1
}
"Bag of Gold": {
actions: 0
nextTurn: +2
gain: 1
}
Bank: {
actions: 0
coins: 4
}
Baron: {
coins: +3
buys: +1
gain: 0.1
}
Bazaar: {
actions: +1
cards: 0
coins: +1
}
Bishop: {
trash: 1
cards: -2
coins: +1
chips: +2
}
"Black Market": {
coins: +2
buys: 0.5 # you might use it as a buy
gain: 0.3 # you might benefit from it
}
Bridge: {
coins: +3
buys: +1
}
Bureaucrat: {
attack: 0.5
gain: 0.5
}
Caravan: {
actions: 0
cards: 0
nextTurn: +1
}
Cellar: {
actions: 0
churn: 3
}
Chancellor: {
coins: +2
}
Chapel: {
trash: 4
cards: -4
}
City: {
actions: +1
cards: +0.2
coins: +0.1
buys: +0.1
}
Colony: {actions: 0}
Conspirator: {
coins: +1
actions: -0.6
cards: -0.6
}
Contraband: {
actions: 0
coins: +3
buys: +1
attack: -1
}
Copper: {
actions: 0
coins: +1
}
Coppersmith: {
coins: +2
}
"Council Room": {
cards: +3
buys: +1
attack: -1
}
"Counting House": {
cards: +3
}
Courtyard: {
cards: +1
churn: 1
}
Curse: {actions: 0}
Cutpurse: {
attack: 1
coins: +2
}
Diadem: {
actions: 0
coins: +3
}
Duchy: {actions: 0}
Duke: {actions: 0}
Embargo: {
coins: +2
}
Envoy: {
cards: +3
}
Estate: {actions: 0}
Expand: {
trash: 1
cards: -2
gain: 1
}
Explorer: {
gain: 1
cards: 0
}
Fairgrounds: {actions: 0}
Familiar: {
attack: 2
cards: 0
actions: 0
}
"Farming Village": {
actions: +1
cards: 0
}
Feast: {
gain: 1
}
Festival: {
actions: +1
coins: +2
buys: +1
}
"Fishing Village": {
actions: +1
coins: +1
nextTurn: +2
}
Followers: {
attack: 4
cards: +1
}
Forge: {
trash: 3
cards: -4
gain: 1
}
"Fortune Teller": {
attack: 0.5
coins: +2
}
Goons: {
attack: 2.5
coins: +2
chips: +2
}
"Grand Market": {
actions: 0
cards: 0
coins: +2
buys: +1
}
"Great Hall": {
actions: 0
cards: 0
}
Hamlet: {
actions: +0.5
buys: +0.5
cards: -1
}
Harem: {
actions: 0
coins: +2
}
Herbalist: {
buys: +1
coins: +1
nextTurn: +0.5
}
Hoard: {
actions: 0
gain: 0.5
coins: +2
}
"Horn of Plenty": {
actions: 0
gain: 1
}
"Horse Traders": {
cards: -3
coins: +3
buys: +1
}
"Hunting Party": {
cards: +1
actions: 0
}
Ironworks: {
gain: 1
actions: +0.4
coins: +0.4
cards: +0.2
}
Island: {
trash: 1
cards: -2
}
Jester: {
attack: 1
coins: +2
gain: 0.5
}
"King's Court": {
actions: +2
}
Laboratory: {
actions: 0
cards: +1
}
Library: {
cards: +2
}
Lighthouse: {
nextTurn: +1.5
coins: +1
actions: 0
}
Loan: {
actions: 0
cards: -1
trash: 1
}
Lookout: {
cards: -1
trash: 1
}
Market: {
actions: 0
cards: 0
coins: +1
buys: +1
}
Masquerade: {
cards: +1
trash: 1
}
Menagerie: {
actions: 0
cards: +1
}
"Merchant Ship": {
nextTurn: +2
coins: +2
}
Militia: {
attack: 2
coins: +2
}
Mine: {
trash: 1
cards: -1
gain: 1
coins: +1
}
"Mining Village": {
actions: +1
cards: 0
}
Minion: {
attack: 0.5
cards: +1.5
churn: 1.5
coins: 1
}
Mint: {
gain: 1
}
Moat: {
cards: +1
}
Moneylender: {
trash: 1
cards: -2
coins: +2
}
Monument: {
coins: +2
}
Mountebank: {
attack: 2
coins: +2
}
"Native Village": {
actions: +1
cards: +0.5
}
Navigator: {
coins: +2
nextTurn: +0.5
}
Nobles: {
actions: 0
cards: +0.5
}
Outpost: {
nextTurn: +0.5
}
Pawn: {
actions: -0.5
cards: -0.5
coins: +0.5
buys: +0.5
}
"Pearl Diver": {
actions: 0
cards: 0
}
Peddler: {
actions: 0
cards: 0
coins: +1
}
"Philosopher's Stone": {
actions: 0
coins: +4
}
"Pirate Ship": {
attack: 0.5
coins: +3
}
Platinum: {
actions: 0
coins: +5
}
Possession: {
nextTurn: +5
}
Potion: {
actions: 0
potions: +1
}
Princess: {
coins: +4
buys: +1
}
Province: {actions: 0}
Quarry: {
actions: 0
coins: +3
}
Rabble: {
attack: 1
cards: +2
}
Remake: {
trash: 2
cards: -3
gain: 2
}
Remodel: {
trash: 1
cards: -2
gain: 1
}
"Royal Seal": {
actions: 0
coins: 2
nextTurn: +0.5
}
Saboteur: {
attack: 2.5
}
Salvager: {
trash: 1
cards: -2
coins: +2
buys: +1
}
Scout: {
actions: 0
cards: +0.5
}
"Scrying Pool": {
actions: 0
cards: +1
attack: 1
}
"Sea Hag": {
attack: 3
}
"Secret Chamber": {
cards: -3
coins: +2
}
"<NAME>": {
actions: +1
cards: 0
}
Silver: {
actions: 0
coins: +2
}
Smithy: {
cards: +2
}
Smugglers: {
gain: 1
}
Spy: {
attack: 1
actions: 0
cards: 0
nextTurn: +0.2
}
Stash: {
actions: 0
coins: +2
}
Steward: {
trash: 1
cards: -0.5
coins: +0.5
cards: -2
}
Swindler: {
attack: 1.5
coins: +2
}
Tactician: {
cards: -5
nextTurn: +6
}
Talisman: {
actions: 0
coins: 1
}
Thief: {
gain: 0.5
}
"Throne Room": {
actions: +1
}
Torturer: {
attack: 2
cards: +2
}
Tournament: {
}
"Trade Route": {
cards: -2
trash: 1
coins: +1
buys: +1
}
"Trading Post": {
trash: 2
cards: -2
}
Transmute: {
trash: 1
gain: 1
cards: -2
}
"Treasure Map": {}
Treasury: {
actions: 0
cards: 0
coins: +1
nextTurn: +1
}
Tribute: {
actions: 0
cards: 0
coins: +1
}
"Trusty Steed": {
actions: +0.7
cards: +0.7
coins: +0.6
}
University: {
actions: +1
gain: 1
}
Upgrade: {
actions: 0
cards: -1
trash: 1
gain: 1
}
Vault: {
cards: -1
coins: +2
churn: 2
}
Venture: {
coins: +2.5
}
Village: {
actions: +1
}
Vineyard: {actions: 0}
"Walled Village": {
actions: +1
nextTurn: +0.3
}
Warehouse: {
actions: 0
churn: 3
}
Watchtower: {
cards: +1.5
}
Wharf: {
cards: +1
buys: +1
nextTurn: +3
}
"Wishing Well": {
cards: +0.3
actions: 0
}
Witch: {
attack: 3
cards: +1
}
Woodcutter: {
coins: +2
buys: +1
}
"Worker's Village": {
actions: +1
}
Workshop: {
gain: 1
}
"Young Witch": {
attack: 2
churn: 2
}
}
| true | # These heuristics are intended to estimate the average effect on your hand
# state when you play the card, not to define what the card actually does.
#
# NOTE: This is not used anywhere yet. I thought it would be useful as a base
# case for code that analyzes a game tree.
#
# The values are all constants, even when the card's effect isn't, so that in
# the base case a hand can be quickly evaluated. The more sophisticated way to
# evaluate a hand, of course, is to consider the actual effect of playing the
# card, and evaluate the resulting hand, recursively. As such, it doesn't even
# matter when these values are wrong for complex actions, as long as they're
# not incredibly wrong.
#
# The +'s have no effect on the values, they just make some of them sound more
# natural.
#
# Victory cards are modeled as cards that replace their action and do nothing
# (this isn't accurate, but the things that would care about the difference --
# like Libraries -- aren't accurate either.)
#
# If they appeared as the default -1 action, it would imply that there was some
# benefit to having +actions with victory cards.
#
# "Churn" is how many more cards you get to see than you get to keep. (Think of
# what Cellar and Warehouse do, even though they're different.) This doesn't
# model the effect of cycling through your deck or stacking it; that's too hard
# to describe without describing what the card actually does in a situation.
heuristics = {
default: {
actions: -1 # _difference_ in number of actions
attack: 0 # how much it hurts your opponents (negative means it helps)
nextTurn: 0 # estimated benefit of a duration or top-decker
buys: 0 # number of +buys
cards: -1 # _difference_ in cards in hand
coins: 0 # number of coins you get
gain: 0 # number of (good) cards you gain
trash: 0 # number of cards you can trash
chips: 0 # number of VP chips
}
Adventurer: {
actions: -1
cards: +1
}
Alchemist: {
actions: 0
cards: +1
nextTurn: +1
}
Ambassador: {
trash: 1.5
cards: -2.5
attack: 1
}
Apothecary: {
actions: 0
cards: +0.5
}
Apprentice: {
actions: 0
cards: +2
trash: 1
}
"Bag of Gold": {
actions: 0
nextTurn: +2
gain: 1
}
Bank: {
actions: 0
coins: 4
}
Baron: {
coins: +3
buys: +1
gain: 0.1
}
Bazaar: {
actions: +1
cards: 0
coins: +1
}
Bishop: {
trash: 1
cards: -2
coins: +1
chips: +2
}
"Black Market": {
coins: +2
buys: 0.5 # you might use it as a buy
gain: 0.3 # you might benefit from it
}
Bridge: {
coins: +3
buys: +1
}
Bureaucrat: {
attack: 0.5
gain: 0.5
}
Caravan: {
actions: 0
cards: 0
nextTurn: +1
}
Cellar: {
actions: 0
churn: 3
}
Chancellor: {
coins: +2
}
Chapel: {
trash: 4
cards: -4
}
City: {
actions: +1
cards: +0.2
coins: +0.1
buys: +0.1
}
Colony: {actions: 0}
Conspirator: {
coins: +1
actions: -0.6
cards: -0.6
}
Contraband: {
actions: 0
coins: +3
buys: +1
attack: -1
}
Copper: {
actions: 0
coins: +1
}
Coppersmith: {
coins: +2
}
"Council Room": {
cards: +3
buys: +1
attack: -1
}
"Counting House": {
cards: +3
}
Courtyard: {
cards: +1
churn: 1
}
Curse: {actions: 0}
Cutpurse: {
attack: 1
coins: +2
}
Diadem: {
actions: 0
coins: +3
}
Duchy: {actions: 0}
Duke: {actions: 0}
Embargo: {
coins: +2
}
Envoy: {
cards: +3
}
Estate: {actions: 0}
Expand: {
trash: 1
cards: -2
gain: 1
}
Explorer: {
gain: 1
cards: 0
}
Fairgrounds: {actions: 0}
Familiar: {
attack: 2
cards: 0
actions: 0
}
"Farming Village": {
actions: +1
cards: 0
}
Feast: {
gain: 1
}
Festival: {
actions: +1
coins: +2
buys: +1
}
"Fishing Village": {
actions: +1
coins: +1
nextTurn: +2
}
Followers: {
attack: 4
cards: +1
}
Forge: {
trash: 3
cards: -4
gain: 1
}
"Fortune Teller": {
attack: 0.5
coins: +2
}
Goons: {
attack: 2.5
coins: +2
chips: +2
}
"Grand Market": {
actions: 0
cards: 0
coins: +2
buys: +1
}
"Great Hall": {
actions: 0
cards: 0
}
Hamlet: {
actions: +0.5
buys: +0.5
cards: -1
}
Harem: {
actions: 0
coins: +2
}
Herbalist: {
buys: +1
coins: +1
nextTurn: +0.5
}
Hoard: {
actions: 0
gain: 0.5
coins: +2
}
"Horn of Plenty": {
actions: 0
gain: 1
}
"Horse Traders": {
cards: -3
coins: +3
buys: +1
}
"Hunting Party": {
cards: +1
actions: 0
}
Ironworks: {
gain: 1
actions: +0.4
coins: +0.4
cards: +0.2
}
Island: {
trash: 1
cards: -2
}
Jester: {
attack: 1
coins: +2
gain: 0.5
}
"King's Court": {
actions: +2
}
Laboratory: {
actions: 0
cards: +1
}
Library: {
cards: +2
}
Lighthouse: {
nextTurn: +1.5
coins: +1
actions: 0
}
Loan: {
actions: 0
cards: -1
trash: 1
}
Lookout: {
cards: -1
trash: 1
}
Market: {
actions: 0
cards: 0
coins: +1
buys: +1
}
Masquerade: {
cards: +1
trash: 1
}
Menagerie: {
actions: 0
cards: +1
}
"Merchant Ship": {
nextTurn: +2
coins: +2
}
Militia: {
attack: 2
coins: +2
}
Mine: {
trash: 1
cards: -1
gain: 1
coins: +1
}
"Mining Village": {
actions: +1
cards: 0
}
Minion: {
attack: 0.5
cards: +1.5
churn: 1.5
coins: 1
}
Mint: {
gain: 1
}
Moat: {
cards: +1
}
Moneylender: {
trash: 1
cards: -2
coins: +2
}
Monument: {
coins: +2
}
Mountebank: {
attack: 2
coins: +2
}
"Native Village": {
actions: +1
cards: +0.5
}
Navigator: {
coins: +2
nextTurn: +0.5
}
Nobles: {
actions: 0
cards: +0.5
}
Outpost: {
nextTurn: +0.5
}
Pawn: {
actions: -0.5
cards: -0.5
coins: +0.5
buys: +0.5
}
"Pearl Diver": {
actions: 0
cards: 0
}
Peddler: {
actions: 0
cards: 0
coins: +1
}
"Philosopher's Stone": {
actions: 0
coins: +4
}
"Pirate Ship": {
attack: 0.5
coins: +3
}
Platinum: {
actions: 0
coins: +5
}
Possession: {
nextTurn: +5
}
Potion: {
actions: 0
potions: +1
}
Princess: {
coins: +4
buys: +1
}
Province: {actions: 0}
Quarry: {
actions: 0
coins: +3
}
Rabble: {
attack: 1
cards: +2
}
Remake: {
trash: 2
cards: -3
gain: 2
}
Remodel: {
trash: 1
cards: -2
gain: 1
}
"Royal Seal": {
actions: 0
coins: 2
nextTurn: +0.5
}
Saboteur: {
attack: 2.5
}
Salvager: {
trash: 1
cards: -2
coins: +2
buys: +1
}
Scout: {
actions: 0
cards: +0.5
}
"Scrying Pool": {
actions: 0
cards: +1
attack: 1
}
"Sea Hag": {
attack: 3
}
"Secret Chamber": {
cards: -3
coins: +2
}
"PI:NAME:<NAME>END_PI": {
actions: +1
cards: 0
}
Silver: {
actions: 0
coins: +2
}
Smithy: {
cards: +2
}
Smugglers: {
gain: 1
}
Spy: {
attack: 1
actions: 0
cards: 0
nextTurn: +0.2
}
Stash: {
actions: 0
coins: +2
}
Steward: {
trash: 1
cards: -0.5
coins: +0.5
cards: -2
}
Swindler: {
attack: 1.5
coins: +2
}
Tactician: {
cards: -5
nextTurn: +6
}
Talisman: {
actions: 0
coins: 1
}
Thief: {
gain: 0.5
}
"Throne Room": {
actions: +1
}
Torturer: {
attack: 2
cards: +2
}
Tournament: {
}
"Trade Route": {
cards: -2
trash: 1
coins: +1
buys: +1
}
"Trading Post": {
trash: 2
cards: -2
}
Transmute: {
trash: 1
gain: 1
cards: -2
}
"Treasure Map": {}
Treasury: {
actions: 0
cards: 0
coins: +1
nextTurn: +1
}
Tribute: {
actions: 0
cards: 0
coins: +1
}
"Trusty Steed": {
actions: +0.7
cards: +0.7
coins: +0.6
}
University: {
actions: +1
gain: 1
}
Upgrade: {
actions: 0
cards: -1
trash: 1
gain: 1
}
Vault: {
cards: -1
coins: +2
churn: 2
}
Venture: {
coins: +2.5
}
Village: {
actions: +1
}
Vineyard: {actions: 0}
"Walled Village": {
actions: +1
nextTurn: +0.3
}
Warehouse: {
actions: 0
churn: 3
}
Watchtower: {
cards: +1.5
}
Wharf: {
cards: +1
buys: +1
nextTurn: +3
}
"Wishing Well": {
cards: +0.3
actions: 0
}
Witch: {
attack: 3
cards: +1
}
Woodcutter: {
coins: +2
buys: +1
}
"Worker's Village": {
actions: +1
}
Workshop: {
gain: 1
}
"Young Witch": {
attack: 2
churn: 2
}
}
|
[
{
"context": "s = ->\n res = {}\n for key in [\n 'social.twitter.message'\n 'social.youtube.url'\n ]\n orionDict",
"end": 332,
"score": 0.844690203666687,
"start": 317,
"tag": "KEY",
"value": "twitter.message"
}
] | app/013_socials/socials.coffee | PEM--/asv-la-soiree | 1 | # Social messages
orion.dictionary.addDefinition 'twitter.message', 'social',
type: String, label: 'Message par défaut pour Twitter'
orion.dictionary.addDefinition 'youtube.url', 'social',
type: String, label: 'Adresse YouTube'
if Meteor.isServer
@socialValues = ->
res = {}
for key in [
'social.twitter.message'
'social.youtube.url'
]
orionDictKey = orion.dictionary.get key
res[key] = if orionDictKey is ''
eval "Meteor.settings.dictionary.#{key}"
else
orionDictKey
res
if Meteor.isClient
Template.socials.viewmodel
facebookURL: ->
FB_URL = 'https://www.facebook.com/sharer/sharer.php'
siteUrl = Meteor.settings.public.proxy.url
FB_URL + '?u=' + encodeURIComponent siteUrl
twitterURL: ->
TWITTER_URL = 'https://twitter.com/intent/tweet'
siteUrl = Meteor.settings.public.proxy.url
msg = orion.dictionary.get 'social.twitter.message'
TWITTER_URL + '?source=' + (encodeURIComponent siteUrl) +
'&text=' + (encodeURIComponent msg) +
'&via=' + orion.dictionary.get('social.twitter.site')?.substr(1)
gplusURL: ->
GPLUS_URL = 'https://plus.google.com/share'
siteUrl = Meteor.settings.public.proxy.url
GPLUS_URL + '?url=' + encodeURIComponent siteUrl
youtubeURL: -> orion.dictionary.get 'social.youtube.url'
| 134832 | # Social messages
orion.dictionary.addDefinition 'twitter.message', 'social',
type: String, label: 'Message par défaut pour Twitter'
orion.dictionary.addDefinition 'youtube.url', 'social',
type: String, label: 'Adresse YouTube'
if Meteor.isServer
@socialValues = ->
res = {}
for key in [
'social.<KEY>'
'social.youtube.url'
]
orionDictKey = orion.dictionary.get key
res[key] = if orionDictKey is ''
eval "Meteor.settings.dictionary.#{key}"
else
orionDictKey
res
if Meteor.isClient
Template.socials.viewmodel
facebookURL: ->
FB_URL = 'https://www.facebook.com/sharer/sharer.php'
siteUrl = Meteor.settings.public.proxy.url
FB_URL + '?u=' + encodeURIComponent siteUrl
twitterURL: ->
TWITTER_URL = 'https://twitter.com/intent/tweet'
siteUrl = Meteor.settings.public.proxy.url
msg = orion.dictionary.get 'social.twitter.message'
TWITTER_URL + '?source=' + (encodeURIComponent siteUrl) +
'&text=' + (encodeURIComponent msg) +
'&via=' + orion.dictionary.get('social.twitter.site')?.substr(1)
gplusURL: ->
GPLUS_URL = 'https://plus.google.com/share'
siteUrl = Meteor.settings.public.proxy.url
GPLUS_URL + '?url=' + encodeURIComponent siteUrl
youtubeURL: -> orion.dictionary.get 'social.youtube.url'
| true | # Social messages
orion.dictionary.addDefinition 'twitter.message', 'social',
type: String, label: 'Message par défaut pour Twitter'
orion.dictionary.addDefinition 'youtube.url', 'social',
type: String, label: 'Adresse YouTube'
if Meteor.isServer
@socialValues = ->
res = {}
for key in [
'social.PI:KEY:<KEY>END_PI'
'social.youtube.url'
]
orionDictKey = orion.dictionary.get key
res[key] = if orionDictKey is ''
eval "Meteor.settings.dictionary.#{key}"
else
orionDictKey
res
if Meteor.isClient
Template.socials.viewmodel
facebookURL: ->
FB_URL = 'https://www.facebook.com/sharer/sharer.php'
siteUrl = Meteor.settings.public.proxy.url
FB_URL + '?u=' + encodeURIComponent siteUrl
twitterURL: ->
TWITTER_URL = 'https://twitter.com/intent/tweet'
siteUrl = Meteor.settings.public.proxy.url
msg = orion.dictionary.get 'social.twitter.message'
TWITTER_URL + '?source=' + (encodeURIComponent siteUrl) +
'&text=' + (encodeURIComponent msg) +
'&via=' + orion.dictionary.get('social.twitter.site')?.substr(1)
gplusURL: ->
GPLUS_URL = 'https://plus.google.com/share'
siteUrl = Meteor.settings.public.proxy.url
GPLUS_URL + '?url=' + encodeURIComponent siteUrl
youtubeURL: -> orion.dictionary.get 'social.youtube.url'
|
[
{
"context": "ut {\n userid: String!\n password: String!\n }\",\n },\n type: UserAuthTC,\n ",
"end": 777,
"score": 0.6925026178359985,
"start": 771,
"tag": "PASSWORD",
"value": "String"
}
] | controller/schema/userauth_schema.coffee | rirufa/roomchat-server | 0 | LoginService = require('../../service/login_service')
GrahqlBaseSchema = require('../grahql_base_schema')
class UserAuthSchema extends GrahqlBaseSchema
OnDefineSchema: (schemaComposer)->
UserAuthTC = schemaComposer.createObjectTC("
type UserAuth{
sucess: Boolean,
token: String,
user: String,
}")
UserAuthTC.addRelation(
'user',
{
resolver: () => schemaComposer.getAnyTC("User").getResolver("findByID"),
prepareArgs: {
filter: (source) => {id:source.user},
},
projection: { user: 1 },
}
)
UserAuthTC.addResolver({
kind: 'query',
name: 'getToken',
args: {
filter: "input UserAuthInput {
userid: String!
password: String!
}",
},
type: UserAuthTC,
resolve: ({ args, context }) =>
result = await LoginService.auth(args.filter.userid, args.filter.password)
if result != null
return {
sucess: true,
token: result.token,
user: result.id
}
else
return {
sucess: false,
token: null,
user: null
}
,
})
query = {
userGetToken: UserAuthTC.getResolver('getToken'),
}
return [query]
module.exports = UserAuthSchema
| 189967 | LoginService = require('../../service/login_service')
GrahqlBaseSchema = require('../grahql_base_schema')
class UserAuthSchema extends GrahqlBaseSchema
OnDefineSchema: (schemaComposer)->
UserAuthTC = schemaComposer.createObjectTC("
type UserAuth{
sucess: Boolean,
token: String,
user: String,
}")
UserAuthTC.addRelation(
'user',
{
resolver: () => schemaComposer.getAnyTC("User").getResolver("findByID"),
prepareArgs: {
filter: (source) => {id:source.user},
},
projection: { user: 1 },
}
)
UserAuthTC.addResolver({
kind: 'query',
name: 'getToken',
args: {
filter: "input UserAuthInput {
userid: String!
password: <PASSWORD>!
}",
},
type: UserAuthTC,
resolve: ({ args, context }) =>
result = await LoginService.auth(args.filter.userid, args.filter.password)
if result != null
return {
sucess: true,
token: result.token,
user: result.id
}
else
return {
sucess: false,
token: null,
user: null
}
,
})
query = {
userGetToken: UserAuthTC.getResolver('getToken'),
}
return [query]
module.exports = UserAuthSchema
| true | LoginService = require('../../service/login_service')
GrahqlBaseSchema = require('../grahql_base_schema')
class UserAuthSchema extends GrahqlBaseSchema
OnDefineSchema: (schemaComposer)->
UserAuthTC = schemaComposer.createObjectTC("
type UserAuth{
sucess: Boolean,
token: String,
user: String,
}")
UserAuthTC.addRelation(
'user',
{
resolver: () => schemaComposer.getAnyTC("User").getResolver("findByID"),
prepareArgs: {
filter: (source) => {id:source.user},
},
projection: { user: 1 },
}
)
UserAuthTC.addResolver({
kind: 'query',
name: 'getToken',
args: {
filter: "input UserAuthInput {
userid: String!
password: PI:PASSWORD:<PASSWORD>END_PI!
}",
},
type: UserAuthTC,
resolve: ({ args, context }) =>
result = await LoginService.auth(args.filter.userid, args.filter.password)
if result != null
return {
sucess: true,
token: result.token,
user: result.id
}
else
return {
sucess: false,
token: null,
user: null
}
,
})
query = {
userGetToken: UserAuthTC.getResolver('getToken'),
}
return [query]
module.exports = UserAuthSchema
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9989554286003113,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-repl-.save.load.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.
# A stream to push an array into a REPL
ArrayStream = ->
@run = (data) ->
self = this
data.forEach (line) ->
self.emit "data", line + "\n"
return
return
return
assert = require("assert")
util = require("util")
join = require("path").join
fs = require("fs")
common = require("../common")
repl = require("repl")
util.inherits ArrayStream, require("stream").Stream
ArrayStream::readable = true
ArrayStream::writable = true
ArrayStream::resume = ->
ArrayStream::write = ->
works = [
["inner.one"]
"inner.o"
]
putIn = new ArrayStream()
testMe = repl.start("", putIn)
testFile = [
"var top = function () {"
"var inner = {one:1};"
]
saveFileName = join(common.tmpDir, "test.save.js")
# input some data
putIn.run testFile
# save it to a file
putIn.run [".save " + saveFileName]
# the file should have what I wrote
assert.equal fs.readFileSync(saveFileName, "utf8"), testFile.join("\n") + "\n"
# make sure that the REPL data is "correct"
# so when I load it back I know I'm good
testMe.complete "inner.o", (error, data) ->
assert.deepEqual data, works
return
# clear the REPL
putIn.run [".clear"]
# Load the file back in
putIn.run [".load " + saveFileName]
# make sure that the REPL data is "correct"
testMe.complete "inner.o", (error, data) ->
assert.deepEqual data, works
return
# clear the REPL
putIn.run [".clear"]
loadFile = join(common.tmpDir, "file.does.not.exist")
# should not break
putIn.write = (data) ->
# make sure I get a failed to load message and not some crazy error
assert.equal data, "Failed to load:" + loadFile + "\n"
# eat me to avoid work
putIn.write = ->
return
putIn.run [".load " + loadFile]
#TODO how do I do a failed .save test?
| 211376 | # 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.
# A stream to push an array into a REPL
ArrayStream = ->
@run = (data) ->
self = this
data.forEach (line) ->
self.emit "data", line + "\n"
return
return
return
assert = require("assert")
util = require("util")
join = require("path").join
fs = require("fs")
common = require("../common")
repl = require("repl")
util.inherits ArrayStream, require("stream").Stream
ArrayStream::readable = true
ArrayStream::writable = true
ArrayStream::resume = ->
ArrayStream::write = ->
works = [
["inner.one"]
"inner.o"
]
putIn = new ArrayStream()
testMe = repl.start("", putIn)
testFile = [
"var top = function () {"
"var inner = {one:1};"
]
saveFileName = join(common.tmpDir, "test.save.js")
# input some data
putIn.run testFile
# save it to a file
putIn.run [".save " + saveFileName]
# the file should have what I wrote
assert.equal fs.readFileSync(saveFileName, "utf8"), testFile.join("\n") + "\n"
# make sure that the REPL data is "correct"
# so when I load it back I know I'm good
testMe.complete "inner.o", (error, data) ->
assert.deepEqual data, works
return
# clear the REPL
putIn.run [".clear"]
# Load the file back in
putIn.run [".load " + saveFileName]
# make sure that the REPL data is "correct"
testMe.complete "inner.o", (error, data) ->
assert.deepEqual data, works
return
# clear the REPL
putIn.run [".clear"]
loadFile = join(common.tmpDir, "file.does.not.exist")
# should not break
putIn.write = (data) ->
# make sure I get a failed to load message and not some crazy error
assert.equal data, "Failed to load:" + loadFile + "\n"
# eat me to avoid work
putIn.write = ->
return
putIn.run [".load " + loadFile]
#TODO how do I do a failed .save test?
| 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.
# A stream to push an array into a REPL
ArrayStream = ->
@run = (data) ->
self = this
data.forEach (line) ->
self.emit "data", line + "\n"
return
return
return
assert = require("assert")
util = require("util")
join = require("path").join
fs = require("fs")
common = require("../common")
repl = require("repl")
util.inherits ArrayStream, require("stream").Stream
ArrayStream::readable = true
ArrayStream::writable = true
ArrayStream::resume = ->
ArrayStream::write = ->
works = [
["inner.one"]
"inner.o"
]
putIn = new ArrayStream()
testMe = repl.start("", putIn)
testFile = [
"var top = function () {"
"var inner = {one:1};"
]
saveFileName = join(common.tmpDir, "test.save.js")
# input some data
putIn.run testFile
# save it to a file
putIn.run [".save " + saveFileName]
# the file should have what I wrote
assert.equal fs.readFileSync(saveFileName, "utf8"), testFile.join("\n") + "\n"
# make sure that the REPL data is "correct"
# so when I load it back I know I'm good
testMe.complete "inner.o", (error, data) ->
assert.deepEqual data, works
return
# clear the REPL
putIn.run [".clear"]
# Load the file back in
putIn.run [".load " + saveFileName]
# make sure that the REPL data is "correct"
testMe.complete "inner.o", (error, data) ->
assert.deepEqual data, works
return
# clear the REPL
putIn.run [".clear"]
loadFile = join(common.tmpDir, "file.does.not.exist")
# should not break
putIn.write = (data) ->
# make sure I get a failed to load message and not some crazy error
assert.equal data, "Failed to load:" + loadFile + "\n"
# eat me to avoid work
putIn.write = ->
return
putIn.run [".load " + loadFile]
#TODO how do I do a failed .save test?
|
[
{
"context": "P, RESTR, CHNGE\n\n# Notes:\n# None\n#\n# Author:\n# KeShiXiong <sxke@Ctrip.com>\n\nclass Ticket\n construc",
"end": 193,
"score": 0.6492208242416382,
"start": 191,
"tag": "NAME",
"value": "Ke"
},
{
"context": "RESTR, CHNGE\n\n# Notes:\n# None\n#\n# Author:\n# KeShiXiong <sxke@Ctrip.com>\n\nclass Ticket\n constructo",
"end": 195,
"score": 0.5143230557441711,
"start": 193,
"tag": "USERNAME",
"value": "Sh"
},
{
"context": "STR, CHNGE\n\n# Notes:\n# None\n#\n# Author:\n# KeShiXiong <sxke@Ctrip.com>\n\nclass Ticket\n constructor:(@t",
"end": 200,
"score": 0.5522047877311707,
"start": 195,
"tag": "NAME",
"value": "iXion"
},
{
"context": "CHNGE\n\n# Notes:\n# None\n#\n# Author:\n# KeShiXiong <sxke@Ctrip.com>\n\nclass Ticket\n constructor:(@ti",
"end": 201,
"score": 0.5455642342567444,
"start": 200,
"tag": "USERNAME",
"value": "g"
},
{
"context": "GE\n\n# Notes:\n# None\n#\n# Author:\n# KeShiXiong <sxke@Ctrip.com>\n\nclass Ticket\n constructor:(@tid) ->\n @reque",
"end": 217,
"score": 0.999926745891571,
"start": 203,
"tag": "EMAIL",
"value": "sxke@Ctrip.com"
},
{
"context": "00').post(JSON.stringify({\n \"access_token\": \"a22335403b2e5bb676efe821a9474993\",\n \"request_body\": @requestBody\n })) (err",
"end": 523,
"score": 0.936331033706665,
"start": 491,
"tag": "KEY",
"value": "a22335403b2e5bb676efe821a9474993"
}
] | hubot-scripts/remedyTicket.coffee | leoxhj/haojiexu | 0 | # Description
# Remedy Ticket Info
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# <TICKET ID> - INC, CRQ, TAS, OP, RESTR, CHNGE
# Notes:
# None
#
# Author:
# KeShiXiong <sxke@Ctrip.com>
class Ticket
constructor:(@tid) ->
@requestBody = ""
@data = undefined
fetchInfo:(robot, callback) ->
self = @
robot.logger.info('start fetchInfo')
robot.http('http://osg.ops.ctripcorp.com/api/11100').post(JSON.stringify({
"access_token": "a22335403b2e5bb676efe821a9474993",
"request_body": @requestBody
})) (err, res, body) ->
robot.logger.debug('fetchInfo body', body)
try
jsonBody = JSON.parse(body)
catch
jsonBody = {}
if jsonBody?.status == 'success'
self.data = jsonBody.data[0] if jsonBody.data?.length > 0
else
robot.logger.error('fetchInfo fail', jsonBody)
callback err, body
getInfoStr: ->
'http://r.ctripcorp.com/remedy/'+@tid
class IncidentTicket extends Ticket
statusMap: {
0: "已记录",
1: "已分派",
2: "处理中",
3: "暂停中",
4: "已解决",
5: "已关闭",
6: "已取消",
7: "已重开"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "HPD:Help Desk",
"query": {
"Incident_Number": @tid
},
"fieldNames": [
"Assigned_Group",
"Assignee",
"Description",
"Status"
],
"order": "Entry_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 处理人: #{@data.Assignee} 主题: #{@data.Description} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class InfrastructureChangeTicket extends Ticket
statusMap: {
0: "起草中",
1: "已提交",
2: "已设计",
3: "已接受",
4: "已批准",
5: "进行中",
6: "已实施",
7: "已复核",
8: "暂停中",
9: "已延期",
10: "已否决",
11: "已完成",
12: "已失败"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CHG:Infrastructure Change",
"query": {
"Infrastructure_Change_ID": @tid
},
"fieldNames": [
"ASGRP",
"ASCHG",
"Description",
"Change_Request_Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 负责人: #{@data.ASCHG} 主题: #{@data.Description} [color=#0000FF]#{@statusMap[@data.Change_Request_Status]}[/color]"
str
class TaskTicket extends Ticket
statusMap: {
0: "等待中",
1: "已分派",
2: "已接受",
3: "进行中",
4: "已完成",
5: "已失败",
6: "已取消",
7: "已拒绝"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "TMS:Task",
"query": {
"Task_ID": @tid
},
"fieldNames": [
"Assignee_Group",
"Assignee",
"TaskName",
"TMS_Status"
],
"order": "Task_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 工单负责人: #{@data.Assignee} 主题: #{@data.TaskName} [color=#0000FF]#{@statusMap[@data.TMS_Status]}[/color]"
str
class OPTTicket extends Ticket
statusMap: {
0: "新操作任务",
1: "任务实施中",
2: "任务完成"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:OperationWorkOrder",
"query": {
"Request_ID": @tid
},
"fieldNames": [
"OPT_Assigned_Group",
"OPT_Assigned",
"Short_Description",
"Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 负责人: #{@data.OPT_Assigned} 主题: #{@data.Short_Description} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class RestorationTicket extends Ticket
statusMap: {
8000: "处理中",
25000: "已恢复",
32000: "已关闭",
33000: "已取消"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:RestorationTicket",
"query": {
"Ticket_ID": @tid
},
"fieldNames": [
"Chr_AssignedGroup",
"Chr_Assignee",
"Summary",
"Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 负责人: #{@data.Chr_Assignee} 主题: #{@data.Summary} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class ChangeRequestTicket extends Ticket
statusMap: {
0: "准备中",
1: "待审批",
2: "已批准",
3: "待执行",
4: "执行中",
5: "已过期",
6: "已拒绝",
7: "已完成",
8: "已取消",
9: "已关闭",
10: "已失败",
11: "已接受"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:ChangeRequest",
"query": {
"TicketID": @tid
},
"fieldNames": [
"Assigned_Group_",
"Assignee",
"Summary",
"Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 处理人: #{@data.Assignee} 主题: #{@data.Summary} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class ServiceRequestTicket extends Ticket
statusMap: {
0: "Pending",
1: "Success",
2: "Failure",
3: "Processing",
4: "Hold"
}
statusMap2: {
0: "ENP",
1: "WOLF"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:APIStagingForm",
"query": {
"ApplicationID": @tid
},
"fieldNames": [
"Chr_LastENPEventID",
"Chr_CallbackURL",
"Status",
"MQ_Type",
"OParameter1",
"Remedy_Event"
],
"order": "Transaction_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += "\nRemedy_Event: #{@data.Remedy_Event}\nMQ类型: #{@statusMap2[@data.MQ_Type]}\nENP事件ID: #{@data.Chr_LastENPEventID}\n回调地址: #{@data.Chr_CallbackURL}\nStatus: [color=#0000FF]#{@statusMap[@data.Status]}[/color]\n数据: #{@data.OParameter1}"
str
module.exports = (robot) ->
robot.hear /^ *(?:INC|CRQ|TAS)\d{12} *$|^ *(?:RESTR|CHNGE|APPSV|SASRV|SECUR|MONTR|DBSRV)\d{10} *$|^ *OP\d{13} *$/i, (res) ->
robot.logger.info('matched ticket bot', res.match)
match = res.match[0].trim()
if match.indexOf('INC') == 0
tickObj = new IncidentTicket(match)
else if match.indexOf('CRQ') == 0
tickObj = new InfrastructureChangeTicket(match)
else if match.indexOf('TAS') == 0
tickObj = new TaskTicket(match)
else if match.indexOf('OP') == 0
tickObj = new OPTTicket(match)
else if match.indexOf('RESTR') == 0
tickObj = new RestorationTicket(match)
else if match.indexOf('CHNGE') == 0
tickObj = new ChangeRequestTicket(match)
else
tickObj = new ServiceRequestTicket(match)
tickObj?.fetchInfo robot, (err, data) ->
robot.logger.error err if err
res.send tickObj.getInfoStr()
| 205488 | # Description
# Remedy Ticket Info
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# <TICKET ID> - INC, CRQ, TAS, OP, RESTR, CHNGE
# Notes:
# None
#
# Author:
# <NAME>Sh<NAME>g <<EMAIL>>
class Ticket
constructor:(@tid) ->
@requestBody = ""
@data = undefined
fetchInfo:(robot, callback) ->
self = @
robot.logger.info('start fetchInfo')
robot.http('http://osg.ops.ctripcorp.com/api/11100').post(JSON.stringify({
"access_token": "<KEY>",
"request_body": @requestBody
})) (err, res, body) ->
robot.logger.debug('fetchInfo body', body)
try
jsonBody = JSON.parse(body)
catch
jsonBody = {}
if jsonBody?.status == 'success'
self.data = jsonBody.data[0] if jsonBody.data?.length > 0
else
robot.logger.error('fetchInfo fail', jsonBody)
callback err, body
getInfoStr: ->
'http://r.ctripcorp.com/remedy/'+@tid
class IncidentTicket extends Ticket
statusMap: {
0: "已记录",
1: "已分派",
2: "处理中",
3: "暂停中",
4: "已解决",
5: "已关闭",
6: "已取消",
7: "已重开"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "HPD:Help Desk",
"query": {
"Incident_Number": @tid
},
"fieldNames": [
"Assigned_Group",
"Assignee",
"Description",
"Status"
],
"order": "Entry_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 处理人: #{@data.Assignee} 主题: #{@data.Description} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class InfrastructureChangeTicket extends Ticket
statusMap: {
0: "起草中",
1: "已提交",
2: "已设计",
3: "已接受",
4: "已批准",
5: "进行中",
6: "已实施",
7: "已复核",
8: "暂停中",
9: "已延期",
10: "已否决",
11: "已完成",
12: "已失败"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CHG:Infrastructure Change",
"query": {
"Infrastructure_Change_ID": @tid
},
"fieldNames": [
"ASGRP",
"ASCHG",
"Description",
"Change_Request_Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 负责人: #{@data.ASCHG} 主题: #{@data.Description} [color=#0000FF]#{@statusMap[@data.Change_Request_Status]}[/color]"
str
class TaskTicket extends Ticket
statusMap: {
0: "等待中",
1: "已分派",
2: "已接受",
3: "进行中",
4: "已完成",
5: "已失败",
6: "已取消",
7: "已拒绝"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "TMS:Task",
"query": {
"Task_ID": @tid
},
"fieldNames": [
"Assignee_Group",
"Assignee",
"TaskName",
"TMS_Status"
],
"order": "Task_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 工单负责人: #{@data.Assignee} 主题: #{@data.TaskName} [color=#0000FF]#{@statusMap[@data.TMS_Status]}[/color]"
str
class OPTTicket extends Ticket
statusMap: {
0: "新操作任务",
1: "任务实施中",
2: "任务完成"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:OperationWorkOrder",
"query": {
"Request_ID": @tid
},
"fieldNames": [
"OPT_Assigned_Group",
"OPT_Assigned",
"Short_Description",
"Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 负责人: #{@data.OPT_Assigned} 主题: #{@data.Short_Description} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class RestorationTicket extends Ticket
statusMap: {
8000: "处理中",
25000: "已恢复",
32000: "已关闭",
33000: "已取消"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:RestorationTicket",
"query": {
"Ticket_ID": @tid
},
"fieldNames": [
"Chr_AssignedGroup",
"Chr_Assignee",
"Summary",
"Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 负责人: #{@data.Chr_Assignee} 主题: #{@data.Summary} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class ChangeRequestTicket extends Ticket
statusMap: {
0: "准备中",
1: "待审批",
2: "已批准",
3: "待执行",
4: "执行中",
5: "已过期",
6: "已拒绝",
7: "已完成",
8: "已取消",
9: "已关闭",
10: "已失败",
11: "已接受"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:ChangeRequest",
"query": {
"TicketID": @tid
},
"fieldNames": [
"Assigned_Group_",
"Assignee",
"Summary",
"Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 处理人: #{@data.Assignee} 主题: #{@data.Summary} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class ServiceRequestTicket extends Ticket
statusMap: {
0: "Pending",
1: "Success",
2: "Failure",
3: "Processing",
4: "Hold"
}
statusMap2: {
0: "ENP",
1: "WOLF"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:APIStagingForm",
"query": {
"ApplicationID": @tid
},
"fieldNames": [
"Chr_LastENPEventID",
"Chr_CallbackURL",
"Status",
"MQ_Type",
"OParameter1",
"Remedy_Event"
],
"order": "Transaction_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += "\nRemedy_Event: #{@data.Remedy_Event}\nMQ类型: #{@statusMap2[@data.MQ_Type]}\nENP事件ID: #{@data.Chr_LastENPEventID}\n回调地址: #{@data.Chr_CallbackURL}\nStatus: [color=#0000FF]#{@statusMap[@data.Status]}[/color]\n数据: #{@data.OParameter1}"
str
module.exports = (robot) ->
robot.hear /^ *(?:INC|CRQ|TAS)\d{12} *$|^ *(?:RESTR|CHNGE|APPSV|SASRV|SECUR|MONTR|DBSRV)\d{10} *$|^ *OP\d{13} *$/i, (res) ->
robot.logger.info('matched ticket bot', res.match)
match = res.match[0].trim()
if match.indexOf('INC') == 0
tickObj = new IncidentTicket(match)
else if match.indexOf('CRQ') == 0
tickObj = new InfrastructureChangeTicket(match)
else if match.indexOf('TAS') == 0
tickObj = new TaskTicket(match)
else if match.indexOf('OP') == 0
tickObj = new OPTTicket(match)
else if match.indexOf('RESTR') == 0
tickObj = new RestorationTicket(match)
else if match.indexOf('CHNGE') == 0
tickObj = new ChangeRequestTicket(match)
else
tickObj = new ServiceRequestTicket(match)
tickObj?.fetchInfo robot, (err, data) ->
robot.logger.error err if err
res.send tickObj.getInfoStr()
| true | # Description
# Remedy Ticket Info
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# <TICKET ID> - INC, CRQ, TAS, OP, RESTR, CHNGE
# Notes:
# None
#
# Author:
# PI:NAME:<NAME>END_PIShPI:NAME:<NAME>END_PIg <PI:EMAIL:<EMAIL>END_PI>
class Ticket
constructor:(@tid) ->
@requestBody = ""
@data = undefined
fetchInfo:(robot, callback) ->
self = @
robot.logger.info('start fetchInfo')
robot.http('http://osg.ops.ctripcorp.com/api/11100').post(JSON.stringify({
"access_token": "PI:KEY:<KEY>END_PI",
"request_body": @requestBody
})) (err, res, body) ->
robot.logger.debug('fetchInfo body', body)
try
jsonBody = JSON.parse(body)
catch
jsonBody = {}
if jsonBody?.status == 'success'
self.data = jsonBody.data[0] if jsonBody.data?.length > 0
else
robot.logger.error('fetchInfo fail', jsonBody)
callback err, body
getInfoStr: ->
'http://r.ctripcorp.com/remedy/'+@tid
class IncidentTicket extends Ticket
statusMap: {
0: "已记录",
1: "已分派",
2: "处理中",
3: "暂停中",
4: "已解决",
5: "已关闭",
6: "已取消",
7: "已重开"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "HPD:Help Desk",
"query": {
"Incident_Number": @tid
},
"fieldNames": [
"Assigned_Group",
"Assignee",
"Description",
"Status"
],
"order": "Entry_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 处理人: #{@data.Assignee} 主题: #{@data.Description} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class InfrastructureChangeTicket extends Ticket
statusMap: {
0: "起草中",
1: "已提交",
2: "已设计",
3: "已接受",
4: "已批准",
5: "进行中",
6: "已实施",
7: "已复核",
8: "暂停中",
9: "已延期",
10: "已否决",
11: "已完成",
12: "已失败"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CHG:Infrastructure Change",
"query": {
"Infrastructure_Change_ID": @tid
},
"fieldNames": [
"ASGRP",
"ASCHG",
"Description",
"Change_Request_Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 负责人: #{@data.ASCHG} 主题: #{@data.Description} [color=#0000FF]#{@statusMap[@data.Change_Request_Status]}[/color]"
str
class TaskTicket extends Ticket
statusMap: {
0: "等待中",
1: "已分派",
2: "已接受",
3: "进行中",
4: "已完成",
5: "已失败",
6: "已取消",
7: "已拒绝"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "TMS:Task",
"query": {
"Task_ID": @tid
},
"fieldNames": [
"Assignee_Group",
"Assignee",
"TaskName",
"TMS_Status"
],
"order": "Task_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 工单负责人: #{@data.Assignee} 主题: #{@data.TaskName} [color=#0000FF]#{@statusMap[@data.TMS_Status]}[/color]"
str
class OPTTicket extends Ticket
statusMap: {
0: "新操作任务",
1: "任务实施中",
2: "任务完成"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:OperationWorkOrder",
"query": {
"Request_ID": @tid
},
"fieldNames": [
"OPT_Assigned_Group",
"OPT_Assigned",
"Short_Description",
"Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 负责人: #{@data.OPT_Assigned} 主题: #{@data.Short_Description} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class RestorationTicket extends Ticket
statusMap: {
8000: "处理中",
25000: "已恢复",
32000: "已关闭",
33000: "已取消"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:RestorationTicket",
"query": {
"Ticket_ID": @tid
},
"fieldNames": [
"Chr_AssignedGroup",
"Chr_Assignee",
"Summary",
"Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 负责人: #{@data.Chr_Assignee} 主题: #{@data.Summary} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class ChangeRequestTicket extends Ticket
statusMap: {
0: "准备中",
1: "待审批",
2: "已批准",
3: "待执行",
4: "执行中",
5: "已过期",
6: "已拒绝",
7: "已完成",
8: "已取消",
9: "已关闭",
10: "已失败",
11: "已接受"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:ChangeRequest",
"query": {
"TicketID": @tid
},
"fieldNames": [
"Assigned_Group_",
"Assignee",
"Summary",
"Status"
],
"order": "Request_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += " 处理人: #{@data.Assignee} 主题: #{@data.Summary} [color=#0000FF]#{@statusMap[@data.Status]}[/color]"
str
class ServiceRequestTicket extends Ticket
statusMap: {
0: "Pending",
1: "Success",
2: "Failure",
3: "Processing",
4: "Hold"
}
statusMap2: {
0: "ENP",
1: "WOLF"
}
constructor:(@tid) ->
super @tid
@requestBody = {
"action": "CTRIP:APIStagingForm",
"query": {
"ApplicationID": @tid
},
"fieldNames": [
"Chr_LastENPEventID",
"Chr_CallbackURL",
"Status",
"MQ_Type",
"OParameter1",
"Remedy_Event"
],
"order": "Transaction_ID",
"start": 0,
"limit": 1
}
getInfoStr: ->
str = super
if @data
str += "\nRemedy_Event: #{@data.Remedy_Event}\nMQ类型: #{@statusMap2[@data.MQ_Type]}\nENP事件ID: #{@data.Chr_LastENPEventID}\n回调地址: #{@data.Chr_CallbackURL}\nStatus: [color=#0000FF]#{@statusMap[@data.Status]}[/color]\n数据: #{@data.OParameter1}"
str
module.exports = (robot) ->
robot.hear /^ *(?:INC|CRQ|TAS)\d{12} *$|^ *(?:RESTR|CHNGE|APPSV|SASRV|SECUR|MONTR|DBSRV)\d{10} *$|^ *OP\d{13} *$/i, (res) ->
robot.logger.info('matched ticket bot', res.match)
match = res.match[0].trim()
if match.indexOf('INC') == 0
tickObj = new IncidentTicket(match)
else if match.indexOf('CRQ') == 0
tickObj = new InfrastructureChangeTicket(match)
else if match.indexOf('TAS') == 0
tickObj = new TaskTicket(match)
else if match.indexOf('OP') == 0
tickObj = new OPTTicket(match)
else if match.indexOf('RESTR') == 0
tickObj = new RestorationTicket(match)
else if match.indexOf('CHNGE') == 0
tickObj = new ChangeRequestTicket(match)
else
tickObj = new ServiceRequestTicket(match)
tickObj?.fetchInfo robot, (err, data) ->
robot.logger.error err if err
res.send tickObj.getInfoStr()
|
[
{
"context": "random\n# with a 100% deterministic alternative.\n\n# Robert Jenkins' 32 bit integer hash function.\nGenerateKey = ->\n ",
"end": 2356,
"score": 0.9997140169143677,
"start": 2342,
"tag": "NAME",
"value": "Robert Jenkins"
},
{
"context": " 30\n i = 0\n\n while i < kNModifications\n key = CreateNewPoint()\n greatest = splayTree.findGreatestLessThan(k",
"end": 3114,
"score": 0.9602945446968079,
"start": 3100,
"tag": "KEY",
"value": "CreateNewPoint"
}
] | deps/v8/benchmarks/spinning-balls/v.coffee | lxe/io.coffee | 0 | # Copyright 2011 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# 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.
###*
This function provides requestAnimationFrame in a cross browser way.
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
###
Point = (x, y, z, payload) ->
@x = x
@y = y
@z = z
@next = null
@prev = null
@payload = payload
@lifeForce = kInitialLifeForce
return
PointsList = ->
@head = null
@count = 0
return
GeneratePayloadTree = (depth, tag) ->
if depth is 0
array: [
0
1
2
3
4
5
6
7
8
9
]
string: "String for key " + tag + " in leaf node"
else
left: GeneratePayloadTree(depth - 1, tag)
right: GeneratePayloadTree(depth - 1, tag)
# To make the benchmark results predictable, we replace Math.random
# with a 100% deterministic alternative.
# Robert Jenkins' 32 bit integer hash function.
GenerateKey = ->
# The benchmark framework guarantees that Math.random is
# deterministic; see base.js.
Math.random()
CreateNewPoint = ->
# Insert new node with a unique key.
key = undefined
loop
key = GenerateKey()
break unless splayTree.find(key)?
point = new Point(Math.random() * 40 - 20, Math.random() * 40 - 20, Math.random() * 40 - 20, GeneratePayloadTree(5, "" + key))
livePoints.add point
splayTree.insert key, point
key
ModifyPointsSet = ->
if livePoints.count < kNPoints
i = 0
while i < kNModifications
CreateNewPoint()
i++
else if kNModifications is 20
kNModifications = 80
kDecay = 30
i = 0
while i < kNModifications
key = CreateNewPoint()
greatest = splayTree.findGreatestLessThan(key)
unless greatest?
point = splayTree.remove(key).value
else
point = splayTree.remove(greatest.key).value
livePoints.remove point
point.payload = null
dyingPoints.add point
i++
return
PausePlot = (width, height, size, scale) ->
canvas = document.createElement("canvas")
canvas.width = @width = width
canvas.height = @height = height
document.body.appendChild canvas
@ctx = canvas.getContext("2d")
if typeof scale isnt "number"
@autoScale = true
@maxPause = 0
else
@autoScale = false
@maxPause = scale
@size = size
# Initialize cyclic buffer for pauses.
@pauses = new Array(@size)
@start = @size
@idx = 0
return
Scene = (width, height) ->
canvas = document.createElement("canvas")
canvas.width = width
canvas.height = height
document.body.appendChild canvas
@ctx = canvas.getContext("2d")
@width = canvas.width
@height = canvas.height
# Projection configuration.
@x0 = canvas.width / 2
@y0 = canvas.height / 2
@z0 = 100
@f = 1000 # Focal length.
# Camera is rotating around y-axis.
@angle = 0
return
# Rotate the camera around y-axis.
# Perform perspective projection.
# Rotate the scene around y-axis.
# Decay the current point and remove it from the list
# if it's life-force ran out.
updateStats = (pause) ->
numberOfFrames++
sumOfSquaredPauses += (pause - 20) * (pause - 20) if pause > 20
pauseDistribution[Math.floor(pause / 10)] |= 0
pauseDistribution[Math.floor(pause / 10)]++
return
renderStats = ->
msg = document.createElement("p")
msg.innerHTML = "Score " + Math.round(numberOfFrames * 1000 / sumOfSquaredPauses)
table = document.createElement("table")
table.align = "center"
i = 0
while i < pauseDistribution.length
if pauseDistribution[i] > 0
row = document.createElement("tr")
time = document.createElement("td")
count = document.createElement("td")
time.innerHTML = i * 10 + "-" + (i + 1) * 10 + "ms"
count.innerHTML = " => " + pauseDistribution[i]
row.appendChild time
row.appendChild count
table.appendChild row
i++
div.appendChild msg
div.appendChild table
return
render = ->
if typeof renderingStartTime is "undefined"
renderingStartTime = Date.now()
benchmarkStartTime = renderingStartTime
ModifyPointsSet()
scene.draw()
renderingEndTime = Date.now()
pause = renderingEndTime - renderingStartTime
pausePlot.addPause pause
renderingStartTime = renderingEndTime
pausePlot.draw()
updateStats pause
div.innerHTML = livePoints.count + "/" + dyingPoints.count + " " + pause + "(max = " + pausePlot.maxPause + ") ms " + numberOfFrames + " frames"
if renderingEndTime < benchmarkStartTime + benchmarkTimeLimit
# Schedule next frame.
requestAnimationFrame render
else
renderStats()
return
Form = ->
create = (tag) ->
document.createElement tag
text = (value) ->
document.createTextNode value
col = (a) ->
td = create("td")
td.appendChild a
td
row = (a, b) ->
tr = create("tr")
tr.appendChild col(a)
tr.appendChild col(b)
tr
@form = create("form")
@form.setAttribute "action", "javascript:start()"
table = create("table")
table.setAttribute "style", "margin-left: auto; margin-right: auto;"
@timelimit = create("input")
@timelimit.setAttribute "value", "60"
table.appendChild row(text("Time limit in seconds"), @timelimit)
@autoscale = create("input")
@autoscale.setAttribute "type", "checkbox"
@autoscale.setAttribute "checked", "true"
table.appendChild row(text("Autoscale pauses plot"), @autoscale)
button = create("input")
button.setAttribute "type", "submit"
button.setAttribute "value", "Start"
@form.appendChild table
@form.appendChild button
document.body.appendChild @form
return
init = ->
livePoints = new PointsList
dyingPoints = new PointsList
splayTree = new SplayTree()
scene = new Scene(640, 480)
div = document.createElement("div")
document.body.appendChild div
pausePlot = new PausePlot(480, (if autoScale then 240 else 500), 160, (if autoScale then undefined else 500))
return
start = ->
benchmarkTimeLimit = form.timelimit.value * 1000
autoScale = form.autoscale.checked
form.remove()
init()
render()
return
unless window.requestAnimationFrame
window.requestAnimationFrame = (->
window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or window.msRequestAnimationFrame or (callback, element) ->
window.setTimeout callback, 1000 / 60
return
)()
kNPoints = 8000
kNModifications = 20
kNVisiblePoints = 200
kDecaySpeed = 20
kPointRadius = 4
kInitialLifeForce = 100
livePoints = undefined
dyingPoints = undefined
scene = undefined
renderingStartTime = undefined
scene = undefined
pausePlot = undefined
splayTree = undefined
numberOfFrames = 0
sumOfSquaredPauses = 0
benchmarkStartTime = undefined
benchmarkTimeLimit = undefined
autoScale = undefined
pauseDistribution = []
Point::color = ->
"rgba(0, 0, 0, " + (@lifeForce / kInitialLifeForce) + ")"
Point::decay = ->
@lifeForce -= kDecaySpeed
@lifeForce <= 0
PointsList::add = (point) ->
@head.prev = point if @head isnt null
point.next = @head
@head = point
@count++
return
PointsList::remove = (point) ->
point.next.prev = point.prev if point.next isnt null
if point.prev isnt null
point.prev.next = point.next
else
@head = point.next
@count--
return
Math.random = (->
seed = 49734321
->
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff
(seed & 0xfffffff) / 0x10000000
)()
PausePlot::addPause = (p) ->
@idx = 0 if @idx is @size
@start++ if @idx is @start
@start = 0 if @start is @size
@pauses[@idx++] = p
return
PausePlot::iteratePauses = (f) ->
if @start < @idx
i = @start
while i < @idx
f.call this, i - @start, @pauses[i]
i++
else
i = @start
while i < @size
f.call this, i - @start, @pauses[i]
i++
offs = @size - @start
i = 0
while i < @idx
f.call this, i + offs, @pauses[i]
i++
return
PausePlot::draw = ->
first = null
if @autoScale
@iteratePauses (i, v) ->
first = v if first is null
@maxPause = Math.max(v, @maxPause)
return
dx = @width / @size
dy = @height / @maxPause
@ctx.save()
@ctx.clearRect 0, 0, @width, @height
@ctx.beginPath()
@ctx.moveTo 1, dy * @pauses[@start]
p = first
@iteratePauses (i, v) ->
delta = v - p
x = 1 + dx * i
y = dy * v
@ctx.lineTo x, y
if delta > 2 * (p / 3)
@ctx.font = "bold 12px sans-serif"
@ctx.textBaseline = "bottom"
@ctx.fillText v + "ms", x + 2, y
p = v
return
@ctx.strokeStyle = "black"
@ctx.stroke()
@ctx.restore()
return
Scene::drawPoint = (x, y, z, color) ->
rx = x * Math.cos(@angle) - z * Math.sin(@angle)
ry = y
rz = x * Math.sin(@angle) + z * Math.cos(@angle)
px = (@f * rx) / (rz - @z0) + @x0
py = (@f * ry) / (rz - @z0) + @y0
@ctx.save()
@ctx.fillStyle = color
@ctx.beginPath()
@ctx.arc px, py, kPointRadius, 0, 2 * Math.PI, true
@ctx.fill()
@ctx.restore()
return
Scene::drawDyingPoints = ->
point_next = null
point = dyingPoints.head
while point isnt null
scene.drawPoint point.x, point.y, point.z, point.color()
point_next = point.next
dyingPoints.remove point if point.decay()
point = point_next
return
Scene::draw = ->
@ctx.save()
@ctx.clearRect 0, 0, @width, @height
@drawDyingPoints()
@ctx.restore()
@angle += Math.PI / 90.0
return
Form::remove = ->
document.body.removeChild @form
return
form = new Form()
| 80829 | # Copyright 2011 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# 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.
###*
This function provides requestAnimationFrame in a cross browser way.
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
###
Point = (x, y, z, payload) ->
@x = x
@y = y
@z = z
@next = null
@prev = null
@payload = payload
@lifeForce = kInitialLifeForce
return
PointsList = ->
@head = null
@count = 0
return
GeneratePayloadTree = (depth, tag) ->
if depth is 0
array: [
0
1
2
3
4
5
6
7
8
9
]
string: "String for key " + tag + " in leaf node"
else
left: GeneratePayloadTree(depth - 1, tag)
right: GeneratePayloadTree(depth - 1, tag)
# To make the benchmark results predictable, we replace Math.random
# with a 100% deterministic alternative.
# <NAME>' 32 bit integer hash function.
GenerateKey = ->
# The benchmark framework guarantees that Math.random is
# deterministic; see base.js.
Math.random()
CreateNewPoint = ->
# Insert new node with a unique key.
key = undefined
loop
key = GenerateKey()
break unless splayTree.find(key)?
point = new Point(Math.random() * 40 - 20, Math.random() * 40 - 20, Math.random() * 40 - 20, GeneratePayloadTree(5, "" + key))
livePoints.add point
splayTree.insert key, point
key
ModifyPointsSet = ->
if livePoints.count < kNPoints
i = 0
while i < kNModifications
CreateNewPoint()
i++
else if kNModifications is 20
kNModifications = 80
kDecay = 30
i = 0
while i < kNModifications
key = <KEY>()
greatest = splayTree.findGreatestLessThan(key)
unless greatest?
point = splayTree.remove(key).value
else
point = splayTree.remove(greatest.key).value
livePoints.remove point
point.payload = null
dyingPoints.add point
i++
return
PausePlot = (width, height, size, scale) ->
canvas = document.createElement("canvas")
canvas.width = @width = width
canvas.height = @height = height
document.body.appendChild canvas
@ctx = canvas.getContext("2d")
if typeof scale isnt "number"
@autoScale = true
@maxPause = 0
else
@autoScale = false
@maxPause = scale
@size = size
# Initialize cyclic buffer for pauses.
@pauses = new Array(@size)
@start = @size
@idx = 0
return
Scene = (width, height) ->
canvas = document.createElement("canvas")
canvas.width = width
canvas.height = height
document.body.appendChild canvas
@ctx = canvas.getContext("2d")
@width = canvas.width
@height = canvas.height
# Projection configuration.
@x0 = canvas.width / 2
@y0 = canvas.height / 2
@z0 = 100
@f = 1000 # Focal length.
# Camera is rotating around y-axis.
@angle = 0
return
# Rotate the camera around y-axis.
# Perform perspective projection.
# Rotate the scene around y-axis.
# Decay the current point and remove it from the list
# if it's life-force ran out.
updateStats = (pause) ->
numberOfFrames++
sumOfSquaredPauses += (pause - 20) * (pause - 20) if pause > 20
pauseDistribution[Math.floor(pause / 10)] |= 0
pauseDistribution[Math.floor(pause / 10)]++
return
renderStats = ->
msg = document.createElement("p")
msg.innerHTML = "Score " + Math.round(numberOfFrames * 1000 / sumOfSquaredPauses)
table = document.createElement("table")
table.align = "center"
i = 0
while i < pauseDistribution.length
if pauseDistribution[i] > 0
row = document.createElement("tr")
time = document.createElement("td")
count = document.createElement("td")
time.innerHTML = i * 10 + "-" + (i + 1) * 10 + "ms"
count.innerHTML = " => " + pauseDistribution[i]
row.appendChild time
row.appendChild count
table.appendChild row
i++
div.appendChild msg
div.appendChild table
return
render = ->
if typeof renderingStartTime is "undefined"
renderingStartTime = Date.now()
benchmarkStartTime = renderingStartTime
ModifyPointsSet()
scene.draw()
renderingEndTime = Date.now()
pause = renderingEndTime - renderingStartTime
pausePlot.addPause pause
renderingStartTime = renderingEndTime
pausePlot.draw()
updateStats pause
div.innerHTML = livePoints.count + "/" + dyingPoints.count + " " + pause + "(max = " + pausePlot.maxPause + ") ms " + numberOfFrames + " frames"
if renderingEndTime < benchmarkStartTime + benchmarkTimeLimit
# Schedule next frame.
requestAnimationFrame render
else
renderStats()
return
Form = ->
create = (tag) ->
document.createElement tag
text = (value) ->
document.createTextNode value
col = (a) ->
td = create("td")
td.appendChild a
td
row = (a, b) ->
tr = create("tr")
tr.appendChild col(a)
tr.appendChild col(b)
tr
@form = create("form")
@form.setAttribute "action", "javascript:start()"
table = create("table")
table.setAttribute "style", "margin-left: auto; margin-right: auto;"
@timelimit = create("input")
@timelimit.setAttribute "value", "60"
table.appendChild row(text("Time limit in seconds"), @timelimit)
@autoscale = create("input")
@autoscale.setAttribute "type", "checkbox"
@autoscale.setAttribute "checked", "true"
table.appendChild row(text("Autoscale pauses plot"), @autoscale)
button = create("input")
button.setAttribute "type", "submit"
button.setAttribute "value", "Start"
@form.appendChild table
@form.appendChild button
document.body.appendChild @form
return
init = ->
livePoints = new PointsList
dyingPoints = new PointsList
splayTree = new SplayTree()
scene = new Scene(640, 480)
div = document.createElement("div")
document.body.appendChild div
pausePlot = new PausePlot(480, (if autoScale then 240 else 500), 160, (if autoScale then undefined else 500))
return
start = ->
benchmarkTimeLimit = form.timelimit.value * 1000
autoScale = form.autoscale.checked
form.remove()
init()
render()
return
unless window.requestAnimationFrame
window.requestAnimationFrame = (->
window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or window.msRequestAnimationFrame or (callback, element) ->
window.setTimeout callback, 1000 / 60
return
)()
kNPoints = 8000
kNModifications = 20
kNVisiblePoints = 200
kDecaySpeed = 20
kPointRadius = 4
kInitialLifeForce = 100
livePoints = undefined
dyingPoints = undefined
scene = undefined
renderingStartTime = undefined
scene = undefined
pausePlot = undefined
splayTree = undefined
numberOfFrames = 0
sumOfSquaredPauses = 0
benchmarkStartTime = undefined
benchmarkTimeLimit = undefined
autoScale = undefined
pauseDistribution = []
Point::color = ->
"rgba(0, 0, 0, " + (@lifeForce / kInitialLifeForce) + ")"
Point::decay = ->
@lifeForce -= kDecaySpeed
@lifeForce <= 0
PointsList::add = (point) ->
@head.prev = point if @head isnt null
point.next = @head
@head = point
@count++
return
PointsList::remove = (point) ->
point.next.prev = point.prev if point.next isnt null
if point.prev isnt null
point.prev.next = point.next
else
@head = point.next
@count--
return
Math.random = (->
seed = 49734321
->
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff
(seed & 0xfffffff) / 0x10000000
)()
PausePlot::addPause = (p) ->
@idx = 0 if @idx is @size
@start++ if @idx is @start
@start = 0 if @start is @size
@pauses[@idx++] = p
return
PausePlot::iteratePauses = (f) ->
if @start < @idx
i = @start
while i < @idx
f.call this, i - @start, @pauses[i]
i++
else
i = @start
while i < @size
f.call this, i - @start, @pauses[i]
i++
offs = @size - @start
i = 0
while i < @idx
f.call this, i + offs, @pauses[i]
i++
return
PausePlot::draw = ->
first = null
if @autoScale
@iteratePauses (i, v) ->
first = v if first is null
@maxPause = Math.max(v, @maxPause)
return
dx = @width / @size
dy = @height / @maxPause
@ctx.save()
@ctx.clearRect 0, 0, @width, @height
@ctx.beginPath()
@ctx.moveTo 1, dy * @pauses[@start]
p = first
@iteratePauses (i, v) ->
delta = v - p
x = 1 + dx * i
y = dy * v
@ctx.lineTo x, y
if delta > 2 * (p / 3)
@ctx.font = "bold 12px sans-serif"
@ctx.textBaseline = "bottom"
@ctx.fillText v + "ms", x + 2, y
p = v
return
@ctx.strokeStyle = "black"
@ctx.stroke()
@ctx.restore()
return
Scene::drawPoint = (x, y, z, color) ->
rx = x * Math.cos(@angle) - z * Math.sin(@angle)
ry = y
rz = x * Math.sin(@angle) + z * Math.cos(@angle)
px = (@f * rx) / (rz - @z0) + @x0
py = (@f * ry) / (rz - @z0) + @y0
@ctx.save()
@ctx.fillStyle = color
@ctx.beginPath()
@ctx.arc px, py, kPointRadius, 0, 2 * Math.PI, true
@ctx.fill()
@ctx.restore()
return
Scene::drawDyingPoints = ->
point_next = null
point = dyingPoints.head
while point isnt null
scene.drawPoint point.x, point.y, point.z, point.color()
point_next = point.next
dyingPoints.remove point if point.decay()
point = point_next
return
Scene::draw = ->
@ctx.save()
@ctx.clearRect 0, 0, @width, @height
@drawDyingPoints()
@ctx.restore()
@angle += Math.PI / 90.0
return
Form::remove = ->
document.body.removeChild @form
return
form = new Form()
| true | # Copyright 2011 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# 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.
###*
This function provides requestAnimationFrame in a cross browser way.
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
###
Point = (x, y, z, payload) ->
@x = x
@y = y
@z = z
@next = null
@prev = null
@payload = payload
@lifeForce = kInitialLifeForce
return
PointsList = ->
@head = null
@count = 0
return
GeneratePayloadTree = (depth, tag) ->
if depth is 0
array: [
0
1
2
3
4
5
6
7
8
9
]
string: "String for key " + tag + " in leaf node"
else
left: GeneratePayloadTree(depth - 1, tag)
right: GeneratePayloadTree(depth - 1, tag)
# To make the benchmark results predictable, we replace Math.random
# with a 100% deterministic alternative.
# PI:NAME:<NAME>END_PI' 32 bit integer hash function.
GenerateKey = ->
# The benchmark framework guarantees that Math.random is
# deterministic; see base.js.
Math.random()
CreateNewPoint = ->
# Insert new node with a unique key.
key = undefined
loop
key = GenerateKey()
break unless splayTree.find(key)?
point = new Point(Math.random() * 40 - 20, Math.random() * 40 - 20, Math.random() * 40 - 20, GeneratePayloadTree(5, "" + key))
livePoints.add point
splayTree.insert key, point
key
ModifyPointsSet = ->
if livePoints.count < kNPoints
i = 0
while i < kNModifications
CreateNewPoint()
i++
else if kNModifications is 20
kNModifications = 80
kDecay = 30
i = 0
while i < kNModifications
key = PI:KEY:<KEY>END_PI()
greatest = splayTree.findGreatestLessThan(key)
unless greatest?
point = splayTree.remove(key).value
else
point = splayTree.remove(greatest.key).value
livePoints.remove point
point.payload = null
dyingPoints.add point
i++
return
PausePlot = (width, height, size, scale) ->
canvas = document.createElement("canvas")
canvas.width = @width = width
canvas.height = @height = height
document.body.appendChild canvas
@ctx = canvas.getContext("2d")
if typeof scale isnt "number"
@autoScale = true
@maxPause = 0
else
@autoScale = false
@maxPause = scale
@size = size
# Initialize cyclic buffer for pauses.
@pauses = new Array(@size)
@start = @size
@idx = 0
return
Scene = (width, height) ->
canvas = document.createElement("canvas")
canvas.width = width
canvas.height = height
document.body.appendChild canvas
@ctx = canvas.getContext("2d")
@width = canvas.width
@height = canvas.height
# Projection configuration.
@x0 = canvas.width / 2
@y0 = canvas.height / 2
@z0 = 100
@f = 1000 # Focal length.
# Camera is rotating around y-axis.
@angle = 0
return
# Rotate the camera around y-axis.
# Perform perspective projection.
# Rotate the scene around y-axis.
# Decay the current point and remove it from the list
# if it's life-force ran out.
updateStats = (pause) ->
numberOfFrames++
sumOfSquaredPauses += (pause - 20) * (pause - 20) if pause > 20
pauseDistribution[Math.floor(pause / 10)] |= 0
pauseDistribution[Math.floor(pause / 10)]++
return
renderStats = ->
msg = document.createElement("p")
msg.innerHTML = "Score " + Math.round(numberOfFrames * 1000 / sumOfSquaredPauses)
table = document.createElement("table")
table.align = "center"
i = 0
while i < pauseDistribution.length
if pauseDistribution[i] > 0
row = document.createElement("tr")
time = document.createElement("td")
count = document.createElement("td")
time.innerHTML = i * 10 + "-" + (i + 1) * 10 + "ms"
count.innerHTML = " => " + pauseDistribution[i]
row.appendChild time
row.appendChild count
table.appendChild row
i++
div.appendChild msg
div.appendChild table
return
render = ->
if typeof renderingStartTime is "undefined"
renderingStartTime = Date.now()
benchmarkStartTime = renderingStartTime
ModifyPointsSet()
scene.draw()
renderingEndTime = Date.now()
pause = renderingEndTime - renderingStartTime
pausePlot.addPause pause
renderingStartTime = renderingEndTime
pausePlot.draw()
updateStats pause
div.innerHTML = livePoints.count + "/" + dyingPoints.count + " " + pause + "(max = " + pausePlot.maxPause + ") ms " + numberOfFrames + " frames"
if renderingEndTime < benchmarkStartTime + benchmarkTimeLimit
# Schedule next frame.
requestAnimationFrame render
else
renderStats()
return
Form = ->
create = (tag) ->
document.createElement tag
text = (value) ->
document.createTextNode value
col = (a) ->
td = create("td")
td.appendChild a
td
row = (a, b) ->
tr = create("tr")
tr.appendChild col(a)
tr.appendChild col(b)
tr
@form = create("form")
@form.setAttribute "action", "javascript:start()"
table = create("table")
table.setAttribute "style", "margin-left: auto; margin-right: auto;"
@timelimit = create("input")
@timelimit.setAttribute "value", "60"
table.appendChild row(text("Time limit in seconds"), @timelimit)
@autoscale = create("input")
@autoscale.setAttribute "type", "checkbox"
@autoscale.setAttribute "checked", "true"
table.appendChild row(text("Autoscale pauses plot"), @autoscale)
button = create("input")
button.setAttribute "type", "submit"
button.setAttribute "value", "Start"
@form.appendChild table
@form.appendChild button
document.body.appendChild @form
return
init = ->
livePoints = new PointsList
dyingPoints = new PointsList
splayTree = new SplayTree()
scene = new Scene(640, 480)
div = document.createElement("div")
document.body.appendChild div
pausePlot = new PausePlot(480, (if autoScale then 240 else 500), 160, (if autoScale then undefined else 500))
return
start = ->
benchmarkTimeLimit = form.timelimit.value * 1000
autoScale = form.autoscale.checked
form.remove()
init()
render()
return
unless window.requestAnimationFrame
window.requestAnimationFrame = (->
window.webkitRequestAnimationFrame or window.mozRequestAnimationFrame or window.oRequestAnimationFrame or window.msRequestAnimationFrame or (callback, element) ->
window.setTimeout callback, 1000 / 60
return
)()
kNPoints = 8000
kNModifications = 20
kNVisiblePoints = 200
kDecaySpeed = 20
kPointRadius = 4
kInitialLifeForce = 100
livePoints = undefined
dyingPoints = undefined
scene = undefined
renderingStartTime = undefined
scene = undefined
pausePlot = undefined
splayTree = undefined
numberOfFrames = 0
sumOfSquaredPauses = 0
benchmarkStartTime = undefined
benchmarkTimeLimit = undefined
autoScale = undefined
pauseDistribution = []
Point::color = ->
"rgba(0, 0, 0, " + (@lifeForce / kInitialLifeForce) + ")"
Point::decay = ->
@lifeForce -= kDecaySpeed
@lifeForce <= 0
PointsList::add = (point) ->
@head.prev = point if @head isnt null
point.next = @head
@head = point
@count++
return
PointsList::remove = (point) ->
point.next.prev = point.prev if point.next isnt null
if point.prev isnt null
point.prev.next = point.next
else
@head = point.next
@count--
return
Math.random = (->
seed = 49734321
->
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff
(seed & 0xfffffff) / 0x10000000
)()
PausePlot::addPause = (p) ->
@idx = 0 if @idx is @size
@start++ if @idx is @start
@start = 0 if @start is @size
@pauses[@idx++] = p
return
PausePlot::iteratePauses = (f) ->
if @start < @idx
i = @start
while i < @idx
f.call this, i - @start, @pauses[i]
i++
else
i = @start
while i < @size
f.call this, i - @start, @pauses[i]
i++
offs = @size - @start
i = 0
while i < @idx
f.call this, i + offs, @pauses[i]
i++
return
PausePlot::draw = ->
first = null
if @autoScale
@iteratePauses (i, v) ->
first = v if first is null
@maxPause = Math.max(v, @maxPause)
return
dx = @width / @size
dy = @height / @maxPause
@ctx.save()
@ctx.clearRect 0, 0, @width, @height
@ctx.beginPath()
@ctx.moveTo 1, dy * @pauses[@start]
p = first
@iteratePauses (i, v) ->
delta = v - p
x = 1 + dx * i
y = dy * v
@ctx.lineTo x, y
if delta > 2 * (p / 3)
@ctx.font = "bold 12px sans-serif"
@ctx.textBaseline = "bottom"
@ctx.fillText v + "ms", x + 2, y
p = v
return
@ctx.strokeStyle = "black"
@ctx.stroke()
@ctx.restore()
return
Scene::drawPoint = (x, y, z, color) ->
rx = x * Math.cos(@angle) - z * Math.sin(@angle)
ry = y
rz = x * Math.sin(@angle) + z * Math.cos(@angle)
px = (@f * rx) / (rz - @z0) + @x0
py = (@f * ry) / (rz - @z0) + @y0
@ctx.save()
@ctx.fillStyle = color
@ctx.beginPath()
@ctx.arc px, py, kPointRadius, 0, 2 * Math.PI, true
@ctx.fill()
@ctx.restore()
return
Scene::drawDyingPoints = ->
point_next = null
point = dyingPoints.head
while point isnt null
scene.drawPoint point.x, point.y, point.z, point.color()
point_next = point.next
dyingPoints.remove point if point.decay()
point = point_next
return
Scene::draw = ->
@ctx.save()
@ctx.clearRect 0, 0, @width, @height
@drawDyingPoints()
@ctx.restore()
@angle += Math.PI / 90.0
return
Form::remove = ->
document.body.removeChild @form
return
form = new Form()
|
[
{
"context": "', 'required' => 'required', 'placeholder' => 'eg: hellolaravel@gmail.com']) }}\n \"\"\"\n \"file->collective\":\n \"prefix\":",
"end": 1612,
"score": 0.9999151825904846,
"start": 1590,
"tag": "EMAIL",
"value": "hellolaravel@gmail.com"
}
] | snippets/laravel-collective.cson | code4mk/atom-lara | 0 | ########################################################
# Atom Laravel Snippet #
# Laravel collective #
#####################################################
'.text.html.php.blade':
"open->collective":
"prefix": "lc-open"
"body": """
{!! Form::open(['method' => 'POST', 'route' => 'routeName', 'class' => 'test']) !!}
"""
"submit->collective":
"prefix": "lc-sub"
"body": """
{{ Form::submit('button', ['class' => 'test test2']) }}
"""
"checkbox->collective":
"prefix": "lc-check"
"body": """
{{ Form::checkbox('checkbox_id', null, null, ['id' => 'checkbox_id']) }}
"""
"close->collective":
"prefix": "lc-close"
"body": """
{!! Form::close() !!}
"""
"label->collective":
"prefix": "lc-label"
"body": """
{{ Form::label('meLabel', 'labelName', ['class' => 'test test2']) }}
"""
"text->collective":
"prefix": "lc-text"
"body": """
{{ Form::text('meLabel', null, ['class' => 'test', 'required' => 'required']) }}
"""
"textarea->collective":
"prefix": "lc-textarea"
"body": """
{{ Form::textarea('meLabel', null, ['class' => 'test', 'required' => 'required']) }}
"""
"date->collective":
"prefix": "lc-date"
"body": """
{{ Form::date('meLabel', null, ['class' => 'test', 'required' => 'required']) }}
"""
"email->collective":
"prefix": "lc-email"
"body": """
{{ Form::email('email', null, ['class' => 'test', 'required' => 'required', 'placeholder' => 'eg: hellolaravel@gmail.com']) }}
"""
"file->collective":
"prefix": "lc-file"
"body": """
{{ Form::file('meLabel', ['required' => 'required']) }}
"""
"model->collective":
"prefix": "lc-model"
"body": """
{{ Form::model($model, ['route' => ['models.update', models->id}], 'method' => 'PUT']) }}
"""
"reset->collective":
"prefix": "lc-reset"
"body": """
{{ Form::reset("Reset", ['class' => 'test'] ) }}
"""
"hidden->collective":
"prefix": "lc-hidden"
"body": """
{{ Form::hidden('meLabel', 'value') }}
"""
"number->collective":
"prefix": "lc-number"
"body": """
{{ Form::number('meLabel', null, ['class' => 'test']) }}
"""
"password->collective":
"prefix": "lc-password"
"body": """
{{ Form::password('meLabel', ['class' => 'test']) }}
"""
"radio->collective":
"prefix": "lc-radio"
"body": """
{{ Form::radio('meLabel', null, null ['class' => 'test']) }}
"""
"select->collective":
"prefix": "lc-select"
"body": """
{{ Form::select('meLabel', $options, $selected_value, ['class' => 'test', 'multiple']) }}
"""
"month->collective":
"prefix": "lc-month"
"body": """
{{ Form::selectRange('meLabel', ['class' => 'test']) }}
"""
"action->collective":
"prefix": "lc-action"
"body": """
'action' => ['Controller@method', $user->id]
"""
"files true->collective":
"prefix": "lc-f"
"body": """
'files' => true
"""
| 135242 | ########################################################
# Atom Laravel Snippet #
# Laravel collective #
#####################################################
'.text.html.php.blade':
"open->collective":
"prefix": "lc-open"
"body": """
{!! Form::open(['method' => 'POST', 'route' => 'routeName', 'class' => 'test']) !!}
"""
"submit->collective":
"prefix": "lc-sub"
"body": """
{{ Form::submit('button', ['class' => 'test test2']) }}
"""
"checkbox->collective":
"prefix": "lc-check"
"body": """
{{ Form::checkbox('checkbox_id', null, null, ['id' => 'checkbox_id']) }}
"""
"close->collective":
"prefix": "lc-close"
"body": """
{!! Form::close() !!}
"""
"label->collective":
"prefix": "lc-label"
"body": """
{{ Form::label('meLabel', 'labelName', ['class' => 'test test2']) }}
"""
"text->collective":
"prefix": "lc-text"
"body": """
{{ Form::text('meLabel', null, ['class' => 'test', 'required' => 'required']) }}
"""
"textarea->collective":
"prefix": "lc-textarea"
"body": """
{{ Form::textarea('meLabel', null, ['class' => 'test', 'required' => 'required']) }}
"""
"date->collective":
"prefix": "lc-date"
"body": """
{{ Form::date('meLabel', null, ['class' => 'test', 'required' => 'required']) }}
"""
"email->collective":
"prefix": "lc-email"
"body": """
{{ Form::email('email', null, ['class' => 'test', 'required' => 'required', 'placeholder' => 'eg: <EMAIL>']) }}
"""
"file->collective":
"prefix": "lc-file"
"body": """
{{ Form::file('meLabel', ['required' => 'required']) }}
"""
"model->collective":
"prefix": "lc-model"
"body": """
{{ Form::model($model, ['route' => ['models.update', models->id}], 'method' => 'PUT']) }}
"""
"reset->collective":
"prefix": "lc-reset"
"body": """
{{ Form::reset("Reset", ['class' => 'test'] ) }}
"""
"hidden->collective":
"prefix": "lc-hidden"
"body": """
{{ Form::hidden('meLabel', 'value') }}
"""
"number->collective":
"prefix": "lc-number"
"body": """
{{ Form::number('meLabel', null, ['class' => 'test']) }}
"""
"password->collective":
"prefix": "lc-password"
"body": """
{{ Form::password('meLabel', ['class' => 'test']) }}
"""
"radio->collective":
"prefix": "lc-radio"
"body": """
{{ Form::radio('meLabel', null, null ['class' => 'test']) }}
"""
"select->collective":
"prefix": "lc-select"
"body": """
{{ Form::select('meLabel', $options, $selected_value, ['class' => 'test', 'multiple']) }}
"""
"month->collective":
"prefix": "lc-month"
"body": """
{{ Form::selectRange('meLabel', ['class' => 'test']) }}
"""
"action->collective":
"prefix": "lc-action"
"body": """
'action' => ['Controller@method', $user->id]
"""
"files true->collective":
"prefix": "lc-f"
"body": """
'files' => true
"""
| true | ########################################################
# Atom Laravel Snippet #
# Laravel collective #
#####################################################
'.text.html.php.blade':
"open->collective":
"prefix": "lc-open"
"body": """
{!! Form::open(['method' => 'POST', 'route' => 'routeName', 'class' => 'test']) !!}
"""
"submit->collective":
"prefix": "lc-sub"
"body": """
{{ Form::submit('button', ['class' => 'test test2']) }}
"""
"checkbox->collective":
"prefix": "lc-check"
"body": """
{{ Form::checkbox('checkbox_id', null, null, ['id' => 'checkbox_id']) }}
"""
"close->collective":
"prefix": "lc-close"
"body": """
{!! Form::close() !!}
"""
"label->collective":
"prefix": "lc-label"
"body": """
{{ Form::label('meLabel', 'labelName', ['class' => 'test test2']) }}
"""
"text->collective":
"prefix": "lc-text"
"body": """
{{ Form::text('meLabel', null, ['class' => 'test', 'required' => 'required']) }}
"""
"textarea->collective":
"prefix": "lc-textarea"
"body": """
{{ Form::textarea('meLabel', null, ['class' => 'test', 'required' => 'required']) }}
"""
"date->collective":
"prefix": "lc-date"
"body": """
{{ Form::date('meLabel', null, ['class' => 'test', 'required' => 'required']) }}
"""
"email->collective":
"prefix": "lc-email"
"body": """
{{ Form::email('email', null, ['class' => 'test', 'required' => 'required', 'placeholder' => 'eg: PI:EMAIL:<EMAIL>END_PI']) }}
"""
"file->collective":
"prefix": "lc-file"
"body": """
{{ Form::file('meLabel', ['required' => 'required']) }}
"""
"model->collective":
"prefix": "lc-model"
"body": """
{{ Form::model($model, ['route' => ['models.update', models->id}], 'method' => 'PUT']) }}
"""
"reset->collective":
"prefix": "lc-reset"
"body": """
{{ Form::reset("Reset", ['class' => 'test'] ) }}
"""
"hidden->collective":
"prefix": "lc-hidden"
"body": """
{{ Form::hidden('meLabel', 'value') }}
"""
"number->collective":
"prefix": "lc-number"
"body": """
{{ Form::number('meLabel', null, ['class' => 'test']) }}
"""
"password->collective":
"prefix": "lc-password"
"body": """
{{ Form::password('meLabel', ['class' => 'test']) }}
"""
"radio->collective":
"prefix": "lc-radio"
"body": """
{{ Form::radio('meLabel', null, null ['class' => 'test']) }}
"""
"select->collective":
"prefix": "lc-select"
"body": """
{{ Form::select('meLabel', $options, $selected_value, ['class' => 'test', 'multiple']) }}
"""
"month->collective":
"prefix": "lc-month"
"body": """
{{ Form::selectRange('meLabel', ['class' => 'test']) }}
"""
"action->collective":
"prefix": "lc-action"
"body": """
'action' => ['Controller@method', $user->id]
"""
"files true->collective":
"prefix": "lc-f"
"body": """
'files' => true
"""
|
[
{
"context": "before ->\n @skip() if __globalTest.offline\n\n [Alice, Bob] = [null, null]\n it 'create mailboxes', ->\n",
"end": 504,
"score": 0.5225240588188171,
"start": 499,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ull]\n it 'create mailboxes', ->\n MailBox.new('Alice').then (ret)->\n Alice = ret\n MailBox.ne",
"end": 576,
"score": 0.990593433380127,
"start": 571,
"tag": "NAME",
"value": "Alice"
},
{
"context": "s', ->\n MailBox.new('Alice').then (ret)->\n Alice = ret\n MailBox.new('Bob').then (ret)->\n ",
"end": 603,
"score": 0.8163347840309143,
"start": 598,
"tag": "NAME",
"value": "Alice"
},
{
"context": "then (ret)->\n Alice = ret\n MailBox.new('Bob').then (ret)->\n Bob = ret\n Alice.ke",
"end": 632,
"score": 0.9922529458999634,
"start": 629,
"tag": "NAME",
"value": "Bob"
},
{
"context": " ret\n MailBox.new('Bob').then (ret)->\n Bob = ret\n Alice.keyRing.addGuest('Bob', Bob.g",
"end": 659,
"score": 0.5066850185394287,
"start": 656,
"tag": "NAME",
"value": "Bob"
},
{
"context": " Bob = ret\n Alice.keyRing.addGuest('Bob', Bob.getPubCommKey()).then ->\n Bob.keyR",
"end": 701,
"score": 0.8931401968002319,
"start": 698,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ommKey()).then ->\n Bob.keyRing.addGuest('Alice', Alice.getPubCommKey())\n\n it 'upload message to",
"end": 770,
"score": 0.996282160282135,
"start": 765,
"tag": "NAME",
"value": "Alice"
},
{
"context": ")).then ->\n Bob.keyRing.addGuest('Alice', Alice.getPubCommKey())\n\n it 'upload message to mailbox",
"end": 778,
"score": 0.9155716300010681,
"start": 773,
"tag": "NAME",
"value": "Alice"
},
{
"context": "new Relay(__globalTest.host)\n Alice.sendToVia('Bob', r, 'Hi Bob from Alice 202').then (msg) ->\n ",
"end": 900,
"score": 0.9698861241340637,
"start": 897,
"tag": "NAME",
"value": "Bob"
},
{
"context": "globalTest.host)\n Alice.sendToVia('Bob', r, 'Hi Bob from Alice 202').then (msg) ->\n window.__glo",
"end": 913,
"score": 0.9465746283531189,
"start": 910,
"tag": "NAME",
"value": "Bob"
},
{
"context": "t.host)\n Alice.sendToVia('Bob', r, 'Hi Bob from Alice 202').then (msg) ->\n window.__globalTest.bob",
"end": 924,
"score": 0.9820727705955505,
"start": 919,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ta']).then (msg)->\n expect(msg).equal 'Hi Bob from Alice 202'\n\n it 'delete from Bob mailbox', ",
"end": 1743,
"score": 0.9960988759994507,
"start": 1740,
"tag": "NAME",
"value": "Bob"
},
{
"context": "n (msg)->\n expect(msg).equal 'Hi Bob from Alice 202'\n\n it 'delete from Bob mailbox', ->\n r = ",
"end": 1754,
"score": 0.9948311448097229,
"start": 1749,
"tag": "NAME",
"value": "Alice"
},
{
"context": "en ->\n # not deleted anything\n r.delete(Bob, []).then ->\n r.count(Bob).then (count)->\n",
"end": 1914,
"score": 0.9781212210655212,
"start": 1911,
"tag": "NAME",
"value": "Bob"
},
{
"context": "g\n r.delete(Bob, []).then ->\n r.count(Bob).then (count)->\n # so it is the same cou",
"end": 1947,
"score": 0.962733805179596,
"start": 1944,
"tag": "NAME",
"value": "Bob"
},
{
"context": " # now lets delete for real\n r.delete(Bob, [__globalTest.bob_nonce2]).then (result)->\n ",
"end": 2091,
"score": 0.9271404147148132,
"start": 2088,
"tag": "NAME",
"value": "Bob"
},
{
"context": " expect(result).equal 0\n r.count(Bob).then (count)->\n expect(count).equal",
"end": 2194,
"score": 0.8464697003364563,
"start": 2191,
"tag": "NAME",
"value": "Bob"
},
{
"context": " st = window.__globalTest.alice_storage_token\n Alice.connectToRelay(r).then ->\n r.messageStatus(A",
"end": 2383,
"score": 0.6914510130882263,
"start": 2378,
"tag": "NAME",
"value": "Alice"
},
{
"context": "e.connectToRelay(r).then ->\n r.messageStatus(Alice,st).then (ttl)->\n expect(ttl).equal -2 # ",
"end": 2437,
"score": 0.5226203799247742,
"start": 2432,
"tag": "NAME",
"value": "Alice"
},
{
"context": "age is now deleted\n\n it 'clear mailboxes', ->\n Alice.selfDestruct(true).then ->\n Bob.selfDestruct",
"end": 2547,
"score": 0.8162298202514648,
"start": 2542,
"tag": "NAME",
"value": "Alice"
},
{
"context": "es', ->\n Alice.selfDestruct(true).then ->\n Bob.selfDestruct(true)\n",
"end": 2584,
"score": 0.6063424944877625,
"start": 2581,
"tag": "NAME",
"value": "Bob"
}
] | tests/specs/06a.relay.coffee | vault12/glow | 14 | # Copyright (c) 2015 Vault12, Inc.
# MIT License https://opensource.org/licenses/MIT
__CRYPTO_DEBUG = true # Expose #theglow objects as window globals
expect = require('chai').expect
MailBox = require 'mailbox'
Nacl = require 'nacl'
Relay = require 'relay'
describe 'Relay Ops, wrapper API', ->
return unless window.__globalTest.runTests['relay wrapper']
@slow(window.__globalTest.slow)
@timeout(window.__globalTest.timeouts.tiny)
before ->
@skip() if __globalTest.offline
[Alice, Bob] = [null, null]
it 'create mailboxes', ->
MailBox.new('Alice').then (ret)->
Alice = ret
MailBox.new('Bob').then (ret)->
Bob = ret
Alice.keyRing.addGuest('Bob', Bob.getPubCommKey()).then ->
Bob.keyRing.addGuest('Alice', Alice.getPubCommKey())
it 'upload message to mailbox :hpk', ->
r = new Relay(__globalTest.host)
Alice.sendToVia('Bob', r, 'Hi Bob from Alice 202').then (msg) ->
window.__globalTest.bob_nonce2 = msg.payload.nonce
window.__globalTest.alice_storage_token = msg.storage_token
it 'check uploaded message status', ->
r = new Relay(__globalTest.host)
st = window.__globalTest.alice_storage_token
Alice.connectToRelay(r).then ->
Alice.relay_msg_status(r,st).then (ttl)->
expect(ttl).above 0
it 'count Bob mailbox', ->
r = new Relay(__globalTest.host)
Bob.connectToRelay(r).then ->
r.count(Bob).then (count)->
expect(count).equal 1
it 'download Bob mailbox', ->
r = new Relay(__globalTest.host)
Bob.connectToRelay(r).then ->
r.download(Bob).then (result)->
d = result[0]
Bob.decodeMessage('Alice', d['nonce'], d['data']).then (msg)->
expect(msg).equal 'Hi Bob from Alice 202'
it 'delete from Bob mailbox', ->
r = new Relay(__globalTest.host)
Bob.connectToRelay(r).then ->
# not deleted anything
r.delete(Bob, []).then ->
r.count(Bob).then (count)->
# so it is the same count
expect(count).equal 1
# now lets delete for real
r.delete(Bob, [__globalTest.bob_nonce2]).then (result)->
expect(result).equal 0
r.count(Bob).then (count)->
expect(count).equal 0
it 'check deleted message status', ->
r = new Relay(__globalTest.host)
st = window.__globalTest.alice_storage_token
Alice.connectToRelay(r).then ->
r.messageStatus(Alice,st).then (ttl)->
expect(ttl).equal -2 # message is now deleted
it 'clear mailboxes', ->
Alice.selfDestruct(true).then ->
Bob.selfDestruct(true)
| 217589 | # Copyright (c) 2015 Vault12, Inc.
# MIT License https://opensource.org/licenses/MIT
__CRYPTO_DEBUG = true # Expose #theglow objects as window globals
expect = require('chai').expect
MailBox = require 'mailbox'
Nacl = require 'nacl'
Relay = require 'relay'
describe 'Relay Ops, wrapper API', ->
return unless window.__globalTest.runTests['relay wrapper']
@slow(window.__globalTest.slow)
@timeout(window.__globalTest.timeouts.tiny)
before ->
@skip() if __globalTest.offline
[<NAME>, Bob] = [null, null]
it 'create mailboxes', ->
MailBox.new('<NAME>').then (ret)->
<NAME> = ret
MailBox.new('<NAME>').then (ret)->
<NAME> = ret
Alice.keyRing.addGuest('<NAME>', Bob.getPubCommKey()).then ->
Bob.keyRing.addGuest('<NAME>', <NAME>.getPubCommKey())
it 'upload message to mailbox :hpk', ->
r = new Relay(__globalTest.host)
Alice.sendToVia('<NAME>', r, 'Hi <NAME> from <NAME> 202').then (msg) ->
window.__globalTest.bob_nonce2 = msg.payload.nonce
window.__globalTest.alice_storage_token = msg.storage_token
it 'check uploaded message status', ->
r = new Relay(__globalTest.host)
st = window.__globalTest.alice_storage_token
Alice.connectToRelay(r).then ->
Alice.relay_msg_status(r,st).then (ttl)->
expect(ttl).above 0
it 'count Bob mailbox', ->
r = new Relay(__globalTest.host)
Bob.connectToRelay(r).then ->
r.count(Bob).then (count)->
expect(count).equal 1
it 'download Bob mailbox', ->
r = new Relay(__globalTest.host)
Bob.connectToRelay(r).then ->
r.download(Bob).then (result)->
d = result[0]
Bob.decodeMessage('Alice', d['nonce'], d['data']).then (msg)->
expect(msg).equal 'Hi <NAME> from <NAME> 202'
it 'delete from Bob mailbox', ->
r = new Relay(__globalTest.host)
Bob.connectToRelay(r).then ->
# not deleted anything
r.delete(<NAME>, []).then ->
r.count(<NAME>).then (count)->
# so it is the same count
expect(count).equal 1
# now lets delete for real
r.delete(<NAME>, [__globalTest.bob_nonce2]).then (result)->
expect(result).equal 0
r.count(<NAME>).then (count)->
expect(count).equal 0
it 'check deleted message status', ->
r = new Relay(__globalTest.host)
st = window.__globalTest.alice_storage_token
<NAME>.connectToRelay(r).then ->
r.messageStatus(<NAME>,st).then (ttl)->
expect(ttl).equal -2 # message is now deleted
it 'clear mailboxes', ->
<NAME>.selfDestruct(true).then ->
<NAME>.selfDestruct(true)
| true | # Copyright (c) 2015 Vault12, Inc.
# MIT License https://opensource.org/licenses/MIT
__CRYPTO_DEBUG = true # Expose #theglow objects as window globals
expect = require('chai').expect
MailBox = require 'mailbox'
Nacl = require 'nacl'
Relay = require 'relay'
describe 'Relay Ops, wrapper API', ->
return unless window.__globalTest.runTests['relay wrapper']
@slow(window.__globalTest.slow)
@timeout(window.__globalTest.timeouts.tiny)
before ->
@skip() if __globalTest.offline
[PI:NAME:<NAME>END_PI, Bob] = [null, null]
it 'create mailboxes', ->
MailBox.new('PI:NAME:<NAME>END_PI').then (ret)->
PI:NAME:<NAME>END_PI = ret
MailBox.new('PI:NAME:<NAME>END_PI').then (ret)->
PI:NAME:<NAME>END_PI = ret
Alice.keyRing.addGuest('PI:NAME:<NAME>END_PI', Bob.getPubCommKey()).then ->
Bob.keyRing.addGuest('PI:NAME:<NAME>END_PI', PI:NAME:<NAME>END_PI.getPubCommKey())
it 'upload message to mailbox :hpk', ->
r = new Relay(__globalTest.host)
Alice.sendToVia('PI:NAME:<NAME>END_PI', r, 'Hi PI:NAME:<NAME>END_PI from PI:NAME:<NAME>END_PI 202').then (msg) ->
window.__globalTest.bob_nonce2 = msg.payload.nonce
window.__globalTest.alice_storage_token = msg.storage_token
it 'check uploaded message status', ->
r = new Relay(__globalTest.host)
st = window.__globalTest.alice_storage_token
Alice.connectToRelay(r).then ->
Alice.relay_msg_status(r,st).then (ttl)->
expect(ttl).above 0
it 'count Bob mailbox', ->
r = new Relay(__globalTest.host)
Bob.connectToRelay(r).then ->
r.count(Bob).then (count)->
expect(count).equal 1
it 'download Bob mailbox', ->
r = new Relay(__globalTest.host)
Bob.connectToRelay(r).then ->
r.download(Bob).then (result)->
d = result[0]
Bob.decodeMessage('Alice', d['nonce'], d['data']).then (msg)->
expect(msg).equal 'Hi PI:NAME:<NAME>END_PI from PI:NAME:<NAME>END_PI 202'
it 'delete from Bob mailbox', ->
r = new Relay(__globalTest.host)
Bob.connectToRelay(r).then ->
# not deleted anything
r.delete(PI:NAME:<NAME>END_PI, []).then ->
r.count(PI:NAME:<NAME>END_PI).then (count)->
# so it is the same count
expect(count).equal 1
# now lets delete for real
r.delete(PI:NAME:<NAME>END_PI, [__globalTest.bob_nonce2]).then (result)->
expect(result).equal 0
r.count(PI:NAME:<NAME>END_PI).then (count)->
expect(count).equal 0
it 'check deleted message status', ->
r = new Relay(__globalTest.host)
st = window.__globalTest.alice_storage_token
PI:NAME:<NAME>END_PI.connectToRelay(r).then ->
r.messageStatus(PI:NAME:<NAME>END_PI,st).then (ttl)->
expect(ttl).equal -2 # message is now deleted
it 'clear mailboxes', ->
PI:NAME:<NAME>END_PI.selfDestruct(true).then ->
PI:NAME:<NAME>END_PI.selfDestruct(true)
|
[
{
"context": "(robot) ->\n\n client = new LuaClient {\n host: '127.0.0.1',\n port: 27064,\n name: 'hubot',\n pass: '",
"end": 698,
"score": 0.9997137784957886,
"start": 689,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " host: '127.0.0.1',\n port: 27064,\n name: 'hubot',\n pass: 'redacted'\n }\n\n client.on 'log', (m",
"end": 734,
"score": 0.9991219639778137,
"start": 729,
"tag": "USERNAME",
"value": "hubot"
},
{
"context": "',\n port: 27064,\n name: 'hubot',\n pass: 'redacted'\n }\n\n client.on 'log', (msg...) ->\n sendToRo",
"end": 756,
"score": 0.998913049697876,
"start": 748,
"tag": "PASSWORD",
"value": "redacted"
}
] | garrysmod/lua-socket-server/hubot/lua-server.coffee | samuelmaddock/recycling-bin | 3 | # Description:
# Manages communication to and from the GMT lua server.
#
LuaClient = require './luaserver/LuaClient.coffee'
LOG_ROOM = 'status'
roomMap = {
default: 'status',
ballrace1: 'chat_ballrace1',
ballrace2: 'chat_ballrace2',
lobby1: 'chat_lobby1',
lobby2: 'chat_lobby2',
minigolf1: 'chat_minigolf1',
minigolf2: 'chat_minigolf2',
pvp1: 'chat_pvp1',
pvp2: 'chat_pvp2',
sourcekarts1: 'chat_sourcekarts1',
sourcekarts2: 'chat_sourcekarts2',
uch1: 'chat_uch1',
uch2: 'chat_uch2',
virus1: 'chat_virus1',
virus2: 'chat_virus2',
zm1: 'chat_zm1',
zm2: 'chat_zm2',
test: 'status'
}
module.exports = (robot) ->
client = new LuaClient {
host: '127.0.0.1',
port: 27064,
name: 'hubot',
pass: 'redacted'
}
client.on 'log', (msg...) ->
sendToRoom LOG_ROOM, msg...
client.hook 'servermsg', (buf) ->
serverName = buf.ReadString()
msg = buf.ReadString()
room = roomMap[serverName] or roomMap.default
sendToRoom room, msg
client.hook 'output', (buf) ->
text = buf.ReadString()
hasUid = (buf.ReadByte() == 1)
if hasUid
room = buf.ReadString()
else
room = LOG_ROOM
text = "```#{text}```"
sendToRoom room, text
sendToRoom = (room, msg...) ->
envelope = {
room: room
}
text = msg.join()
robot.send envelope, text
client.connect()
robot.hear /^!((\w+.*\s*)+)/i, (msg) ->
cmd = msg.match[1]
client.sendHook 'hubotcmd', cmd, msg.envelope
robot.respond /serverinfo(.*)/i, (msg) ->
target = if msg.match.length then msg.match[1] else null
if target and target.length
cmd = 'serverinfo ' + target.trim()
else
cmd = 'serverinfo'
client.sendHook 'hubotcmd', cmd, msg.envelope
| 211775 | # Description:
# Manages communication to and from the GMT lua server.
#
LuaClient = require './luaserver/LuaClient.coffee'
LOG_ROOM = 'status'
roomMap = {
default: 'status',
ballrace1: 'chat_ballrace1',
ballrace2: 'chat_ballrace2',
lobby1: 'chat_lobby1',
lobby2: 'chat_lobby2',
minigolf1: 'chat_minigolf1',
minigolf2: 'chat_minigolf2',
pvp1: 'chat_pvp1',
pvp2: 'chat_pvp2',
sourcekarts1: 'chat_sourcekarts1',
sourcekarts2: 'chat_sourcekarts2',
uch1: 'chat_uch1',
uch2: 'chat_uch2',
virus1: 'chat_virus1',
virus2: 'chat_virus2',
zm1: 'chat_zm1',
zm2: 'chat_zm2',
test: 'status'
}
module.exports = (robot) ->
client = new LuaClient {
host: '127.0.0.1',
port: 27064,
name: 'hubot',
pass: '<PASSWORD>'
}
client.on 'log', (msg...) ->
sendToRoom LOG_ROOM, msg...
client.hook 'servermsg', (buf) ->
serverName = buf.ReadString()
msg = buf.ReadString()
room = roomMap[serverName] or roomMap.default
sendToRoom room, msg
client.hook 'output', (buf) ->
text = buf.ReadString()
hasUid = (buf.ReadByte() == 1)
if hasUid
room = buf.ReadString()
else
room = LOG_ROOM
text = "```#{text}```"
sendToRoom room, text
sendToRoom = (room, msg...) ->
envelope = {
room: room
}
text = msg.join()
robot.send envelope, text
client.connect()
robot.hear /^!((\w+.*\s*)+)/i, (msg) ->
cmd = msg.match[1]
client.sendHook 'hubotcmd', cmd, msg.envelope
robot.respond /serverinfo(.*)/i, (msg) ->
target = if msg.match.length then msg.match[1] else null
if target and target.length
cmd = 'serverinfo ' + target.trim()
else
cmd = 'serverinfo'
client.sendHook 'hubotcmd', cmd, msg.envelope
| true | # Description:
# Manages communication to and from the GMT lua server.
#
LuaClient = require './luaserver/LuaClient.coffee'
LOG_ROOM = 'status'
roomMap = {
default: 'status',
ballrace1: 'chat_ballrace1',
ballrace2: 'chat_ballrace2',
lobby1: 'chat_lobby1',
lobby2: 'chat_lobby2',
minigolf1: 'chat_minigolf1',
minigolf2: 'chat_minigolf2',
pvp1: 'chat_pvp1',
pvp2: 'chat_pvp2',
sourcekarts1: 'chat_sourcekarts1',
sourcekarts2: 'chat_sourcekarts2',
uch1: 'chat_uch1',
uch2: 'chat_uch2',
virus1: 'chat_virus1',
virus2: 'chat_virus2',
zm1: 'chat_zm1',
zm2: 'chat_zm2',
test: 'status'
}
module.exports = (robot) ->
client = new LuaClient {
host: '127.0.0.1',
port: 27064,
name: 'hubot',
pass: 'PI:PASSWORD:<PASSWORD>END_PI'
}
client.on 'log', (msg...) ->
sendToRoom LOG_ROOM, msg...
client.hook 'servermsg', (buf) ->
serverName = buf.ReadString()
msg = buf.ReadString()
room = roomMap[serverName] or roomMap.default
sendToRoom room, msg
client.hook 'output', (buf) ->
text = buf.ReadString()
hasUid = (buf.ReadByte() == 1)
if hasUid
room = buf.ReadString()
else
room = LOG_ROOM
text = "```#{text}```"
sendToRoom room, text
sendToRoom = (room, msg...) ->
envelope = {
room: room
}
text = msg.join()
robot.send envelope, text
client.connect()
robot.hear /^!((\w+.*\s*)+)/i, (msg) ->
cmd = msg.match[1]
client.sendHook 'hubotcmd', cmd, msg.envelope
robot.respond /serverinfo(.*)/i, (msg) ->
target = if msg.match.length then msg.match[1] else null
if target and target.length
cmd = 'serverinfo ' + target.trim()
else
cmd = 'serverinfo'
client.sendHook 'hubotcmd', cmd, msg.envelope
|
[
{
"context": "# Panel.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Base abstra",
"end": 23,
"score": 0.9975488185882568,
"start": 17,
"tag": "NAME",
"value": "Tomasz"
},
{
"context": "# Panel.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Base abstract class for",
"end": 37,
"score": 0.9905672073364258,
"start": 25,
"tag": "NAME",
"value": "Tomek) Zemla"
},
{
"context": "# Panel.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Base abstract class for all UI panels. There a",
"end": 60,
"score": 0.9999303221702576,
"start": 40,
"tag": "EMAIL",
"value": "tomek@datacratic.com"
}
] | src/Panel.coffee | SachithDassanayaka/sachithdassanayaka.github.io | 0 | # Panel.coffee
# Tomasz (Tomek) Zemla
# tomek@datacratic.com
# Base abstract class for all UI panels. There are four classes derived from Panel:
# Menu - main application menu (left)
# Console - main output/info area (right)
# ToolBar - top window control
# StatusBar - bottom window helper
Subject = require('./Subject.coffee')
class Panel extends Subject
# E V E N T S
@EVENT_PANEL_SHOWN : "EVENT_PANEL_SHOWN"
@EVENT_PANEL_HIDDEN : "EVENT_PANEL_HIDDEN"
visible: true # default
# C O N S T R U C T O R
# Create panel. The id parameter is the id of the element in HTML (example: "#Menu")
constructor: (@id) ->
super()
# Show this panel.
show: ->
$(@id).show()
@visible = true
@notify(Panel.EVENT_PANEL_SHOWN)
# Hide this panel.
hide: ->
$(@id).hide()
@visible = false
@notify(Panel.EVENT_PANEL_HIDDEN)
# Toggle visibility.
toggle: ->
if @visible then @hide() else @show()
return @visible
module.exports = Panel | 181525 | # Panel.coffee
# <NAME> (<NAME>
# <EMAIL>
# Base abstract class for all UI panels. There are four classes derived from Panel:
# Menu - main application menu (left)
# Console - main output/info area (right)
# ToolBar - top window control
# StatusBar - bottom window helper
Subject = require('./Subject.coffee')
class Panel extends Subject
# E V E N T S
@EVENT_PANEL_SHOWN : "EVENT_PANEL_SHOWN"
@EVENT_PANEL_HIDDEN : "EVENT_PANEL_HIDDEN"
visible: true # default
# C O N S T R U C T O R
# Create panel. The id parameter is the id of the element in HTML (example: "#Menu")
constructor: (@id) ->
super()
# Show this panel.
show: ->
$(@id).show()
@visible = true
@notify(Panel.EVENT_PANEL_SHOWN)
# Hide this panel.
hide: ->
$(@id).hide()
@visible = false
@notify(Panel.EVENT_PANEL_HIDDEN)
# Toggle visibility.
toggle: ->
if @visible then @hide() else @show()
return @visible
module.exports = Panel | true | # Panel.coffee
# PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI
# PI:EMAIL:<EMAIL>END_PI
# Base abstract class for all UI panels. There are four classes derived from Panel:
# Menu - main application menu (left)
# Console - main output/info area (right)
# ToolBar - top window control
# StatusBar - bottom window helper
Subject = require('./Subject.coffee')
class Panel extends Subject
# E V E N T S
@EVENT_PANEL_SHOWN : "EVENT_PANEL_SHOWN"
@EVENT_PANEL_HIDDEN : "EVENT_PANEL_HIDDEN"
visible: true # default
# C O N S T R U C T O R
# Create panel. The id parameter is the id of the element in HTML (example: "#Menu")
constructor: (@id) ->
super()
# Show this panel.
show: ->
$(@id).show()
@visible = true
@notify(Panel.EVENT_PANEL_SHOWN)
# Hide this panel.
hide: ->
$(@id).hide()
@visible = false
@notify(Panel.EVENT_PANEL_HIDDEN)
# Toggle visibility.
toggle: ->
if @visible then @hide() else @show()
return @visible
module.exports = Panel |
[
{
"context": "r based on description from http://artis.imag.fr/~Xavier.Decoret/resources/xdkbibtex/bibtex_summary.html#comment\n ",
"end": 85,
"score": 0.9887773394584656,
"start": 71,
"tag": "NAME",
"value": "Xavier.Decoret"
},
{
"context": "t @preamble\n \t\n'''\nfileTypes: [\n \"bib\"\n]\nname: \"BibTeX\"\npatterns: [\n {\n begin: \"@Comment\"\n beginC",
"end": 218,
"score": 0.7740433812141418,
"start": 212,
"tag": "NAME",
"value": "BibTeX"
}
] | grammars/bibtex.cson | aviatesk/Atom-LaTeX | 69 | comment: '''
Grammar based on description from http://artis.imag.fr/~Xavier.Decoret/resources/xdkbibtex/bibtex_summary.html#comment
TODO: Does not support @preamble
'''
fileTypes: [
"bib"
]
name: "BibTeX"
patterns: [
{
begin: "@Comment"
beginCaptures:
"0":
name: "punctuation.definition.comment.bibtex"
end: "$\\n?"
name: "comment.line.at-sign.bibtex"
}
{
begin: "((@)String)\\s*(\\{)\\s*([a-zA-Z]*)"
beginCaptures:
"1":
name: "keyword.other.string-constant.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.string-constant.begin.bibtex"
"4":
name: "variable.other.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.section.string-constant.end.bibtex"
name: "meta.string-constant.braces.bibtex"
patterns: [
{
include: "#string_content"
}
]
}
{
begin: "((@)String)\\s*(\\()\\s*([a-zA-Z]*)"
beginCaptures:
"1":
name: "keyword.other.string-constant.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.string-constant.begin.bibtex"
"4":
name: "variable.other.bibtex"
end: "\\)"
endCaptures:
"0":
name: "punctuation.section.string-constant.end.bibtex"
name: "meta.string-constant.parenthesis.bibtex"
patterns: [
{
include: "#string_content"
}
]
}
{
begin: "((@)[a-zA-Z]+)\\s*(\\{)\\s*([^\\s,]*)"
beginCaptures:
"1":
name: "keyword.other.entry-type.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.entry.begin.bibtex"
"4":
name: "entity.name.type.entry-key.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.section.entry.end.bibtex"
name: "meta.entry.braces.bibtex"
patterns: [
{
begin: "([a-zA-Z0-9\\!\\$\\&\\*\\+\\-\\.\\/\\:\\;\\<\\>\\?\\[\\]\\^\\_\\`\\|]+)\\s*(\\=)"
beginCaptures:
"1":
name: "string.unquoted.key.bibtex"
"2":
name: "punctuation.separator.key-value.bibtex"
end: "(?=[,}])"
name: "meta.key-assignment.bibtex"
patterns: [
{
include: "#string_content"
}
{
include: "#integer"
}
]
}
]
}
{
begin: "((@)[a-zA-Z]+)\\s*(\\()\\s*([^\\s,]*)"
beginCaptures:
"1":
name: "keyword.other.entry-type.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.entry.begin.bibtex"
"4":
name: "entity.name.type.entry-key.bibtex"
end: "\\)"
endCaptures:
"0":
name: "punctuation.section.entry.end.bibtex"
name: "meta.entry.parenthesis.bibtex"
patterns: [
{
begin: "([a-zA-Z0-9\\!\\$\\&\\*\\+\\-\\.\\/\\:\\;\\<\\>\\?\\[\\]\\^\\_\\`\\|]+)\\s*(\\=)"
beginCaptures:
"1":
name: "string.unquoted.key.bibtex"
"2":
name: "punctuation.separator.key-value.bibtex"
end: "(?=[,)])"
name: "meta.key-assignment.bibtex"
patterns: [
{
include: "#string_content"
}
{
include: "#integer"
}
]
}
]
}
{
begin: "[^@\\n]"
end: "(?=@)"
name: "comment.block.bibtex"
}
]
repository:
integer:
match: "\\d+"
name: "constant.numeric.bibtex"
nested_braces:
begin: "\\{"
beginCaptures:
"0":
name: "punctuation.definition.group.begin.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.definition.group.end.bibtex"
patterns: [
{
include: "#nested_braces"
}
]
string_content:
patterns: [
{
begin: "\""
beginCaptures:
"0":
name: "punctuation.definition.string.begin.bibtex"
end: "\""
endCaptures:
"0":
name: "punctuation.definition.string.end.bibtex"
name: "string.quoted.double.bibtex"
patterns: [
{
include: "#nested_braces"
}
]
}
{
begin: "\\{"
beginCaptures:
"0":
name: "punctuation.definition.string.begin.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.definition.string.end.bibtex"
name: "string.quoted.other.braces.bibtex"
patterns: [
{
match: "@"
name: "invalid.illegal.at-sign.bibtex"
}
{
include: "#nested_braces"
}
]
}
]
scopeName: "text.bibtex"
| 77005 | comment: '''
Grammar based on description from http://artis.imag.fr/~<NAME>/resources/xdkbibtex/bibtex_summary.html#comment
TODO: Does not support @preamble
'''
fileTypes: [
"bib"
]
name: "<NAME>"
patterns: [
{
begin: "@Comment"
beginCaptures:
"0":
name: "punctuation.definition.comment.bibtex"
end: "$\\n?"
name: "comment.line.at-sign.bibtex"
}
{
begin: "((@)String)\\s*(\\{)\\s*([a-zA-Z]*)"
beginCaptures:
"1":
name: "keyword.other.string-constant.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.string-constant.begin.bibtex"
"4":
name: "variable.other.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.section.string-constant.end.bibtex"
name: "meta.string-constant.braces.bibtex"
patterns: [
{
include: "#string_content"
}
]
}
{
begin: "((@)String)\\s*(\\()\\s*([a-zA-Z]*)"
beginCaptures:
"1":
name: "keyword.other.string-constant.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.string-constant.begin.bibtex"
"4":
name: "variable.other.bibtex"
end: "\\)"
endCaptures:
"0":
name: "punctuation.section.string-constant.end.bibtex"
name: "meta.string-constant.parenthesis.bibtex"
patterns: [
{
include: "#string_content"
}
]
}
{
begin: "((@)[a-zA-Z]+)\\s*(\\{)\\s*([^\\s,]*)"
beginCaptures:
"1":
name: "keyword.other.entry-type.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.entry.begin.bibtex"
"4":
name: "entity.name.type.entry-key.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.section.entry.end.bibtex"
name: "meta.entry.braces.bibtex"
patterns: [
{
begin: "([a-zA-Z0-9\\!\\$\\&\\*\\+\\-\\.\\/\\:\\;\\<\\>\\?\\[\\]\\^\\_\\`\\|]+)\\s*(\\=)"
beginCaptures:
"1":
name: "string.unquoted.key.bibtex"
"2":
name: "punctuation.separator.key-value.bibtex"
end: "(?=[,}])"
name: "meta.key-assignment.bibtex"
patterns: [
{
include: "#string_content"
}
{
include: "#integer"
}
]
}
]
}
{
begin: "((@)[a-zA-Z]+)\\s*(\\()\\s*([^\\s,]*)"
beginCaptures:
"1":
name: "keyword.other.entry-type.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.entry.begin.bibtex"
"4":
name: "entity.name.type.entry-key.bibtex"
end: "\\)"
endCaptures:
"0":
name: "punctuation.section.entry.end.bibtex"
name: "meta.entry.parenthesis.bibtex"
patterns: [
{
begin: "([a-zA-Z0-9\\!\\$\\&\\*\\+\\-\\.\\/\\:\\;\\<\\>\\?\\[\\]\\^\\_\\`\\|]+)\\s*(\\=)"
beginCaptures:
"1":
name: "string.unquoted.key.bibtex"
"2":
name: "punctuation.separator.key-value.bibtex"
end: "(?=[,)])"
name: "meta.key-assignment.bibtex"
patterns: [
{
include: "#string_content"
}
{
include: "#integer"
}
]
}
]
}
{
begin: "[^@\\n]"
end: "(?=@)"
name: "comment.block.bibtex"
}
]
repository:
integer:
match: "\\d+"
name: "constant.numeric.bibtex"
nested_braces:
begin: "\\{"
beginCaptures:
"0":
name: "punctuation.definition.group.begin.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.definition.group.end.bibtex"
patterns: [
{
include: "#nested_braces"
}
]
string_content:
patterns: [
{
begin: "\""
beginCaptures:
"0":
name: "punctuation.definition.string.begin.bibtex"
end: "\""
endCaptures:
"0":
name: "punctuation.definition.string.end.bibtex"
name: "string.quoted.double.bibtex"
patterns: [
{
include: "#nested_braces"
}
]
}
{
begin: "\\{"
beginCaptures:
"0":
name: "punctuation.definition.string.begin.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.definition.string.end.bibtex"
name: "string.quoted.other.braces.bibtex"
patterns: [
{
match: "@"
name: "invalid.illegal.at-sign.bibtex"
}
{
include: "#nested_braces"
}
]
}
]
scopeName: "text.bibtex"
| true | comment: '''
Grammar based on description from http://artis.imag.fr/~PI:NAME:<NAME>END_PI/resources/xdkbibtex/bibtex_summary.html#comment
TODO: Does not support @preamble
'''
fileTypes: [
"bib"
]
name: "PI:NAME:<NAME>END_PI"
patterns: [
{
begin: "@Comment"
beginCaptures:
"0":
name: "punctuation.definition.comment.bibtex"
end: "$\\n?"
name: "comment.line.at-sign.bibtex"
}
{
begin: "((@)String)\\s*(\\{)\\s*([a-zA-Z]*)"
beginCaptures:
"1":
name: "keyword.other.string-constant.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.string-constant.begin.bibtex"
"4":
name: "variable.other.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.section.string-constant.end.bibtex"
name: "meta.string-constant.braces.bibtex"
patterns: [
{
include: "#string_content"
}
]
}
{
begin: "((@)String)\\s*(\\()\\s*([a-zA-Z]*)"
beginCaptures:
"1":
name: "keyword.other.string-constant.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.string-constant.begin.bibtex"
"4":
name: "variable.other.bibtex"
end: "\\)"
endCaptures:
"0":
name: "punctuation.section.string-constant.end.bibtex"
name: "meta.string-constant.parenthesis.bibtex"
patterns: [
{
include: "#string_content"
}
]
}
{
begin: "((@)[a-zA-Z]+)\\s*(\\{)\\s*([^\\s,]*)"
beginCaptures:
"1":
name: "keyword.other.entry-type.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.entry.begin.bibtex"
"4":
name: "entity.name.type.entry-key.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.section.entry.end.bibtex"
name: "meta.entry.braces.bibtex"
patterns: [
{
begin: "([a-zA-Z0-9\\!\\$\\&\\*\\+\\-\\.\\/\\:\\;\\<\\>\\?\\[\\]\\^\\_\\`\\|]+)\\s*(\\=)"
beginCaptures:
"1":
name: "string.unquoted.key.bibtex"
"2":
name: "punctuation.separator.key-value.bibtex"
end: "(?=[,}])"
name: "meta.key-assignment.bibtex"
patterns: [
{
include: "#string_content"
}
{
include: "#integer"
}
]
}
]
}
{
begin: "((@)[a-zA-Z]+)\\s*(\\()\\s*([^\\s,]*)"
beginCaptures:
"1":
name: "keyword.other.entry-type.bibtex"
"2":
name: "punctuation.definition.keyword.bibtex"
"3":
name: "punctuation.section.entry.begin.bibtex"
"4":
name: "entity.name.type.entry-key.bibtex"
end: "\\)"
endCaptures:
"0":
name: "punctuation.section.entry.end.bibtex"
name: "meta.entry.parenthesis.bibtex"
patterns: [
{
begin: "([a-zA-Z0-9\\!\\$\\&\\*\\+\\-\\.\\/\\:\\;\\<\\>\\?\\[\\]\\^\\_\\`\\|]+)\\s*(\\=)"
beginCaptures:
"1":
name: "string.unquoted.key.bibtex"
"2":
name: "punctuation.separator.key-value.bibtex"
end: "(?=[,)])"
name: "meta.key-assignment.bibtex"
patterns: [
{
include: "#string_content"
}
{
include: "#integer"
}
]
}
]
}
{
begin: "[^@\\n]"
end: "(?=@)"
name: "comment.block.bibtex"
}
]
repository:
integer:
match: "\\d+"
name: "constant.numeric.bibtex"
nested_braces:
begin: "\\{"
beginCaptures:
"0":
name: "punctuation.definition.group.begin.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.definition.group.end.bibtex"
patterns: [
{
include: "#nested_braces"
}
]
string_content:
patterns: [
{
begin: "\""
beginCaptures:
"0":
name: "punctuation.definition.string.begin.bibtex"
end: "\""
endCaptures:
"0":
name: "punctuation.definition.string.end.bibtex"
name: "string.quoted.double.bibtex"
patterns: [
{
include: "#nested_braces"
}
]
}
{
begin: "\\{"
beginCaptures:
"0":
name: "punctuation.definition.string.begin.bibtex"
end: "\\}"
endCaptures:
"0":
name: "punctuation.definition.string.end.bibtex"
name: "string.quoted.other.braces.bibtex"
patterns: [
{
match: "@"
name: "invalid.illegal.at-sign.bibtex"
}
{
include: "#nested_braces"
}
]
}
]
scopeName: "text.bibtex"
|
[
{
"context": "censed under the MIT license.\n\nhttps://github.com/devjam\n\nUtil.UA.browser\t\t\t\t\t: String\nUtil.UA.isIE\t\t\t\t\t\t:",
"end": 113,
"score": 0.999624490737915,
"start": 107,
"tag": "USERNAME",
"value": "devjam"
},
{
"context": "まう\n\t\t\t\tunless value?\n\t\t\t\t\tvalue = key\n\t\t\t\t\tkey = \"id\"\n\t\t\t\tary_match =[]\n\t\t\t\ti = 0\n\t\t\t\tl = @.length\n\t\t\t",
"end": 9120,
"score": 0.997479259967804,
"start": 9118,
"tag": "KEY",
"value": "id"
}
] | src/util.coffee | devjam/util.js | 0 | ###
util.js v 1.2.7
Copyright (c) 2013 SHIFTBRAIN Inc.
Licensed under the MIT license.
https://github.com/devjam
Util.UA.browser : String
Util.UA.isIE : Bool
Util.UA.isIE6 : Bool
Util.UA.isIE7 : Bool
Util.UA.isIE8 : Bool
Util.UA.isIE9 : Bool
Util.UA.isLtIE9 : Bool
Util.UA.isIOS : Bool
Util.UA.isIPhone : Bool
Util.UA.isIPad : Bool
Util.UA.isIPhone4 : Bool
Util.UA.isIPad3 : Bool
Util.UA.isAndroid : Bool
Util.UA.isAndroidMobile : Bool
Util.UA.isChrome : Bool
Util.UA.isSafari : Bool
Util.UA.isMozilla : Bool
Util.UA.isWebkit : Bool
Util.UA.isOpera : Bool
Util.UA.isPC : Bool
Util.UA.isTablet : Bool
Util.UA.isSmartPhone : Bool
Util.venderPrefix : String
Util.stats.show() : void
Util.stats.remove() : void
Util.animationFrameDelta : Number
Util.animationFrameDelta.setDelta() : void
Util.window.onResize() : void (trigger resize event)
Util.window.size(withUpdate = false) : {width:Integer, height:Integer}
Util.window.pageSize(withUpdate = false) : {width:Integer, height:Integer}
Util.window.scrollTop() : Number
Util.window.scrollBottom() : Number
Util.window.bindResize(callback) : void
Util.window.unbindResize(callback, isReset = false) : void (isReset is unbind all)
Util.cursor.over : "mouseenter touchstart"
Util.cursor.out : "mouseleave touchend"
Util.cursor.down : "mousedown touchstart"
Util.cursor.move : "mousemove touchmouve"
Util.cursor.up : "mouseup touchend"
Util.cursor.click : "mouseup touchend"
Util.cursor.clientXY(e:MouseEvent or TouchEvent) : {x:Number, y:Number}
Util.cursor.pageXY(e:MouseEvent or TouchEvent) : {x:Number, y:Number}
Util.array.setRemove(Array = Array.prototype) : Bool ary.remove(value)
Util.array.setQuery(Array = Array.prototype) : Bool ary.q(id)
Util.now(get from server = true) : Date
Util.QueryString() : Object
Util.consoleKill() : void
###
unless @console?
@console =
log: ->
class @Util
@UA = (->
_ua = navigator.userAgent.toLowerCase()
ua =
isIE: false
isIE6: false
isIE7: false
isIE8: false
isIE9: false
isLtIE9: false
isIOS: false
isIPhone: false
isIPad: false
isIPhone4: false
isIPad3: false
isAndroid: false
isAndroidMobile: false
isChrome: false
isSafari: false
isMozilla: false
isWebkit: false
isOpera: false
isPC: false
isTablet: false
isSmartPhone: false
browser: _ua
if ua.isIE = /msie\s(\d+)/.test _ua
ver = RegExp.$1
ver *= 1
ua.isIE6 = ver == 6
ua.isIE7 = ver == 7
ua.isIE8 = ver == 8
ua.isIE9 = ver == 9
ua.isLtIE9 = ver < 9
if ua.isIE7 and _ua.indexOf('trident/4.0') != -1
ua.isIE7 = false
ua.isIE8 = true
if ua.isIPhone = /i(phone|pod)/.test _ua
ua.isIPhone4 = window.devicePixelRatio == 2
if ua.isIPad = /ipad/.test _ua
isIPad3 = window.devicePixelRatio == 2
ua.isIOS = ua.isIPhone || ua.isIPad
ua.isAndroid = /android/.test _ua
ua.isAndroidMobile = /android(.+)?mobile/.test _ua
ua.isPC = !ua.isIOS && !ua.isAndroid
ua.isTablet = ua.isIPad || (ua.isAndroid && ua.isAndroidMobile)
ua.isSmartPhone = ua.isIPhone || ua.isAndroidMobile
ua.isChrome = /chrome/.test _ua
ua.isWebkit = /webkit/.test _ua
ua.isOpera = /opera/.test _ua
ua.isMozilla = _ua.indexOf("compatible") < 0 && /mozilla/.test _ua
ua.isSafari = !ua.isChrome && ua.isWebkit
ua
)()
@venderPrefix = (->
if Util.UA.isIE then return "-ms-"
if Util.UA.isWebkit then return "-webkit-"
if Util.UA.isMozilla then return "-moz-"
if Util.UA.isOpera then return "-o-"
""
)()
@stats = (->
sts = null
stsTimer = null
update = ->
if !Stats? or !sts?
return false
stsTimer = requestAnimationFrame update
sts.update()
show: (mode = 0) ->
if !Stats? or sts? or Util.UA.isLtIE9
return false
sts = new Stats()
sts.setMode(mode)
document.body.appendChild( sts.domElement )
sts.domElement.style.cssText = "position:fixed; top:0; left:0; z-index:9999999;"
update()
remove: ->
if !Stats? or !sts?
return false
if stsTimer?
cancelAnimationFrame(stsTimer)
document.body.removeChild( sts.domElement )
sts = null
)()
@animationFrameDelta = 0
(->
isDateHasNow = !!Date.now
lastTime = if isDateHasNow then Date.now() else +new Date
callbacks = []
setDelta = (calledTime)->
Util.animationFrameDelta = calledTime - lastTime
lastTime = calledTime
window.requestAnimationFrame setDelta
return
if !window.requestAnimationFrame
prefix = Util.venderPrefix.replace /-/g, ""
window.requestAnimationFrame = window[prefix + "RequestAnimationFrame"]
window.cancelAnimationFrame = window[prefix + "CancelAnimationFrame"] || window[prefix + "CancelRequestAnimationFrame"]
if !window.requestAnimationFrame
window.requestAnimationFrame = (->
id = 0
(callback, element)->
if callbacks.length == 0
id = setTimeout ->
now = if isDateHasNow then Date.now() else +new Date
#同期だと処理が溢れるかなと思って非同期を試したけど
#パフォーマンスが悪かった。他になにかいい方法がある?
#(今は同期)
cbs = callbacks
callbacks = []
while cb = cbs.shift()
cb now
return
, 16
#setTimeoutのdelay値をdelta値によって可変させてみたけど、
#具合が悪そうなので固定にした。
if $.inArray?
if typeof callback == "function" && $.inArray(callback, callbacks) == -1
callbacks.push callback
else
callbacks.push callback
id
)()
window.cancelAnimationFrame = (id)->
callbacks = []
clearTimeout id
setDelta if isDateHasNow then Date.now() else +new Date
return
)()
@window = (->
win = $ window
doc = $ document
width = 0
height = 0
pageWidth = 0
pageHeight = 0
resizeCallbacks = []
isUpdate = 0
onResize = ->
isUpdate = 3
callbacks = resizeCallbacks.concat()
for callback in callbacks
callback()
return
win.resize onResize
$(->
width = win.width()
height = win.height()
pageWidth = doc.width()
pageHeight = doc.height()
)
size: (withUpdate = false)->
if withUpdate || isUpdate & 1
isUpdate = (isUpdate | 1) ^ 1
width = win.width()
height = win.height()
if width <= 0 and height <= 0
if document.documentElement.clientWidth
width = document.documentElement.clientWidth
else if document.body.clientWidth
width = document.body.clientWidth
else if window.innerWidth
width = window.innerWidth
if document.documentElement.clientHeight
height = document.documentElement.clientHeight
else if document.body.clientHeight
height = document.body.clientHeight
else if window.innerHeight
height = window.innerHeight
width: width
height: height
pageSize: (withUpdate = false)->
if withUpdate || isUpdate & 2
isUpdate = (isUpdate | 2) ^ 2
pageWidth = doc.width()
pageHeight = doc.height()
width: pageWidth
height: pageHeight
scrollTop: ->
if window.pageYOffset?
return window.pageYOffset
return win.scrollTop()
scrollBottom: ->
if window.pageYOffset?
return window.pageYOffset + window.innerHeight
return win.scrollTop() + height
bindResize: (callback)->
if typeof callback == "function" && $.inArray(callback, resizeCallbacks) == -1
resizeCallbacks.push callback
return
unbindResize: (callback, isReset = false)->
if callback && (index = $.inArray callback, resizeCallbacks) != -1
resizeCallbacks.splice index, 1
if isReset
resizeCallbacks = []
return
)()
@cursor = (->
c =
over : "mouseenter touchstart"
out : "mouseleave touchend"
down : "mousedown touchstart"
move : "mousemove touchmouve"
up : "mouseup touchend"
click : "mouseup touchend"
clientXY : (e)=>
pos = {x:0, y:0}
if e?
if "ontouchstart" of window
if e.touches?
e = e.touches[0]
else
e = e.originalEvent.touches[0]
if e.clientX?
pos.x = e.clientX
pos.y = e.clientY
return pos
pageXY : (e)=>
pos = {x:0, y:0}
if e?
if "ontouchstart" of window
if e.touches?
e = e.touches[0]
else
e = e.originalEvent.touches[0]
if e.pageX?
pos.x = e.pageX
pos.y = e.pageY
return pos
)()
@array = (->
setRemove: (ary)->
unless ary?
ary = Array.prototype
else
unless ary instanceof Array
return false
if ary.remove?
return false
ary.remove = ->
# BUG:IE で thisがarrayでなく functionになってしまう
l = arguments.length
i = 0
while i < l
m = @.length
j = 0
while j < m
if arguments[i] == @[j]
@.splice(j, 1)
m--
else
j++
i++
@.length
true
setQuery: (ary)->
unless ary?
ary = Array.prototype
else
unless ary instanceof Array
return false
if ary.remove?
return false
ary.q = (key, value)->
# BUG:IE で thisがarrayでなく functionになってしまう
unless value?
value = key
key = "id"
ary_match =[]
i = 0
l = @.length
while i < l
item = @[i]
if item[key] == value
ary_match.push(item)
i++
if ary_match.length == 1
return ary_match[0]
else
return ary_match
true
)()
@now = (isSrv = true) ->
xmlhttp = false
d = null
if ActiveXObject? # IE5, IE6
try
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP") # MSXML3
catch e
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") # MSXML2
if !xmlhttp and XDomainRequest? then xmlhttp = new XDomainRequest()
if !xmlhttp and XMLHttpRequest? then xmlhttp = new XMLHttpRequest()
if isSrv and xmlhttp
xmlhttp.open('HEAD', '#', false)
xmlhttp.send (null)
d = xmlhttp.getResponseHeader ('Date')
if d? then return new Date(d)
new Date()
@QueryString = ((a)->
unless a?
return {}
data = {}
value = []
i = 0
l = a.length
n = 0
while i < l
ary = a[i].split('=')
if ary.length == 1 or ary[0] == "value"
value.push(decodeURIComponent(ary[0].replace(/\+/g, " ")))
else if ary.length == 2
data[ary[0]] = decodeURIComponent(ary[1].replace(/\+/g, " "))
n++
i++
if value.length > 0
if value.length == 1
if n == 0
return value[0]
else
data["value"] = value[0]
else
if n == 0
return value
else
data["value"] = value
return data
)(window.location.search.substr(1).split('&'))
@consoleKill = ->
console.log = ->
constructor: ->
throw new Error('it is static class')
| 81884 | ###
util.js v 1.2.7
Copyright (c) 2013 SHIFTBRAIN Inc.
Licensed under the MIT license.
https://github.com/devjam
Util.UA.browser : String
Util.UA.isIE : Bool
Util.UA.isIE6 : Bool
Util.UA.isIE7 : Bool
Util.UA.isIE8 : Bool
Util.UA.isIE9 : Bool
Util.UA.isLtIE9 : Bool
Util.UA.isIOS : Bool
Util.UA.isIPhone : Bool
Util.UA.isIPad : Bool
Util.UA.isIPhone4 : Bool
Util.UA.isIPad3 : Bool
Util.UA.isAndroid : Bool
Util.UA.isAndroidMobile : Bool
Util.UA.isChrome : Bool
Util.UA.isSafari : Bool
Util.UA.isMozilla : Bool
Util.UA.isWebkit : Bool
Util.UA.isOpera : Bool
Util.UA.isPC : Bool
Util.UA.isTablet : Bool
Util.UA.isSmartPhone : Bool
Util.venderPrefix : String
Util.stats.show() : void
Util.stats.remove() : void
Util.animationFrameDelta : Number
Util.animationFrameDelta.setDelta() : void
Util.window.onResize() : void (trigger resize event)
Util.window.size(withUpdate = false) : {width:Integer, height:Integer}
Util.window.pageSize(withUpdate = false) : {width:Integer, height:Integer}
Util.window.scrollTop() : Number
Util.window.scrollBottom() : Number
Util.window.bindResize(callback) : void
Util.window.unbindResize(callback, isReset = false) : void (isReset is unbind all)
Util.cursor.over : "mouseenter touchstart"
Util.cursor.out : "mouseleave touchend"
Util.cursor.down : "mousedown touchstart"
Util.cursor.move : "mousemove touchmouve"
Util.cursor.up : "mouseup touchend"
Util.cursor.click : "mouseup touchend"
Util.cursor.clientXY(e:MouseEvent or TouchEvent) : {x:Number, y:Number}
Util.cursor.pageXY(e:MouseEvent or TouchEvent) : {x:Number, y:Number}
Util.array.setRemove(Array = Array.prototype) : Bool ary.remove(value)
Util.array.setQuery(Array = Array.prototype) : Bool ary.q(id)
Util.now(get from server = true) : Date
Util.QueryString() : Object
Util.consoleKill() : void
###
unless @console?
@console =
log: ->
class @Util
@UA = (->
_ua = navigator.userAgent.toLowerCase()
ua =
isIE: false
isIE6: false
isIE7: false
isIE8: false
isIE9: false
isLtIE9: false
isIOS: false
isIPhone: false
isIPad: false
isIPhone4: false
isIPad3: false
isAndroid: false
isAndroidMobile: false
isChrome: false
isSafari: false
isMozilla: false
isWebkit: false
isOpera: false
isPC: false
isTablet: false
isSmartPhone: false
browser: _ua
if ua.isIE = /msie\s(\d+)/.test _ua
ver = RegExp.$1
ver *= 1
ua.isIE6 = ver == 6
ua.isIE7 = ver == 7
ua.isIE8 = ver == 8
ua.isIE9 = ver == 9
ua.isLtIE9 = ver < 9
if ua.isIE7 and _ua.indexOf('trident/4.0') != -1
ua.isIE7 = false
ua.isIE8 = true
if ua.isIPhone = /i(phone|pod)/.test _ua
ua.isIPhone4 = window.devicePixelRatio == 2
if ua.isIPad = /ipad/.test _ua
isIPad3 = window.devicePixelRatio == 2
ua.isIOS = ua.isIPhone || ua.isIPad
ua.isAndroid = /android/.test _ua
ua.isAndroidMobile = /android(.+)?mobile/.test _ua
ua.isPC = !ua.isIOS && !ua.isAndroid
ua.isTablet = ua.isIPad || (ua.isAndroid && ua.isAndroidMobile)
ua.isSmartPhone = ua.isIPhone || ua.isAndroidMobile
ua.isChrome = /chrome/.test _ua
ua.isWebkit = /webkit/.test _ua
ua.isOpera = /opera/.test _ua
ua.isMozilla = _ua.indexOf("compatible") < 0 && /mozilla/.test _ua
ua.isSafari = !ua.isChrome && ua.isWebkit
ua
)()
@venderPrefix = (->
if Util.UA.isIE then return "-ms-"
if Util.UA.isWebkit then return "-webkit-"
if Util.UA.isMozilla then return "-moz-"
if Util.UA.isOpera then return "-o-"
""
)()
@stats = (->
sts = null
stsTimer = null
update = ->
if !Stats? or !sts?
return false
stsTimer = requestAnimationFrame update
sts.update()
show: (mode = 0) ->
if !Stats? or sts? or Util.UA.isLtIE9
return false
sts = new Stats()
sts.setMode(mode)
document.body.appendChild( sts.domElement )
sts.domElement.style.cssText = "position:fixed; top:0; left:0; z-index:9999999;"
update()
remove: ->
if !Stats? or !sts?
return false
if stsTimer?
cancelAnimationFrame(stsTimer)
document.body.removeChild( sts.domElement )
sts = null
)()
@animationFrameDelta = 0
(->
isDateHasNow = !!Date.now
lastTime = if isDateHasNow then Date.now() else +new Date
callbacks = []
setDelta = (calledTime)->
Util.animationFrameDelta = calledTime - lastTime
lastTime = calledTime
window.requestAnimationFrame setDelta
return
if !window.requestAnimationFrame
prefix = Util.venderPrefix.replace /-/g, ""
window.requestAnimationFrame = window[prefix + "RequestAnimationFrame"]
window.cancelAnimationFrame = window[prefix + "CancelAnimationFrame"] || window[prefix + "CancelRequestAnimationFrame"]
if !window.requestAnimationFrame
window.requestAnimationFrame = (->
id = 0
(callback, element)->
if callbacks.length == 0
id = setTimeout ->
now = if isDateHasNow then Date.now() else +new Date
#同期だと処理が溢れるかなと思って非同期を試したけど
#パフォーマンスが悪かった。他になにかいい方法がある?
#(今は同期)
cbs = callbacks
callbacks = []
while cb = cbs.shift()
cb now
return
, 16
#setTimeoutのdelay値をdelta値によって可変させてみたけど、
#具合が悪そうなので固定にした。
if $.inArray?
if typeof callback == "function" && $.inArray(callback, callbacks) == -1
callbacks.push callback
else
callbacks.push callback
id
)()
window.cancelAnimationFrame = (id)->
callbacks = []
clearTimeout id
setDelta if isDateHasNow then Date.now() else +new Date
return
)()
@window = (->
win = $ window
doc = $ document
width = 0
height = 0
pageWidth = 0
pageHeight = 0
resizeCallbacks = []
isUpdate = 0
onResize = ->
isUpdate = 3
callbacks = resizeCallbacks.concat()
for callback in callbacks
callback()
return
win.resize onResize
$(->
width = win.width()
height = win.height()
pageWidth = doc.width()
pageHeight = doc.height()
)
size: (withUpdate = false)->
if withUpdate || isUpdate & 1
isUpdate = (isUpdate | 1) ^ 1
width = win.width()
height = win.height()
if width <= 0 and height <= 0
if document.documentElement.clientWidth
width = document.documentElement.clientWidth
else if document.body.clientWidth
width = document.body.clientWidth
else if window.innerWidth
width = window.innerWidth
if document.documentElement.clientHeight
height = document.documentElement.clientHeight
else if document.body.clientHeight
height = document.body.clientHeight
else if window.innerHeight
height = window.innerHeight
width: width
height: height
pageSize: (withUpdate = false)->
if withUpdate || isUpdate & 2
isUpdate = (isUpdate | 2) ^ 2
pageWidth = doc.width()
pageHeight = doc.height()
width: pageWidth
height: pageHeight
scrollTop: ->
if window.pageYOffset?
return window.pageYOffset
return win.scrollTop()
scrollBottom: ->
if window.pageYOffset?
return window.pageYOffset + window.innerHeight
return win.scrollTop() + height
bindResize: (callback)->
if typeof callback == "function" && $.inArray(callback, resizeCallbacks) == -1
resizeCallbacks.push callback
return
unbindResize: (callback, isReset = false)->
if callback && (index = $.inArray callback, resizeCallbacks) != -1
resizeCallbacks.splice index, 1
if isReset
resizeCallbacks = []
return
)()
@cursor = (->
c =
over : "mouseenter touchstart"
out : "mouseleave touchend"
down : "mousedown touchstart"
move : "mousemove touchmouve"
up : "mouseup touchend"
click : "mouseup touchend"
clientXY : (e)=>
pos = {x:0, y:0}
if e?
if "ontouchstart" of window
if e.touches?
e = e.touches[0]
else
e = e.originalEvent.touches[0]
if e.clientX?
pos.x = e.clientX
pos.y = e.clientY
return pos
pageXY : (e)=>
pos = {x:0, y:0}
if e?
if "ontouchstart" of window
if e.touches?
e = e.touches[0]
else
e = e.originalEvent.touches[0]
if e.pageX?
pos.x = e.pageX
pos.y = e.pageY
return pos
)()
@array = (->
setRemove: (ary)->
unless ary?
ary = Array.prototype
else
unless ary instanceof Array
return false
if ary.remove?
return false
ary.remove = ->
# BUG:IE で thisがarrayでなく functionになってしまう
l = arguments.length
i = 0
while i < l
m = @.length
j = 0
while j < m
if arguments[i] == @[j]
@.splice(j, 1)
m--
else
j++
i++
@.length
true
setQuery: (ary)->
unless ary?
ary = Array.prototype
else
unless ary instanceof Array
return false
if ary.remove?
return false
ary.q = (key, value)->
# BUG:IE で thisがarrayでなく functionになってしまう
unless value?
value = key
key = "<KEY>"
ary_match =[]
i = 0
l = @.length
while i < l
item = @[i]
if item[key] == value
ary_match.push(item)
i++
if ary_match.length == 1
return ary_match[0]
else
return ary_match
true
)()
@now = (isSrv = true) ->
xmlhttp = false
d = null
if ActiveXObject? # IE5, IE6
try
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP") # MSXML3
catch e
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") # MSXML2
if !xmlhttp and XDomainRequest? then xmlhttp = new XDomainRequest()
if !xmlhttp and XMLHttpRequest? then xmlhttp = new XMLHttpRequest()
if isSrv and xmlhttp
xmlhttp.open('HEAD', '#', false)
xmlhttp.send (null)
d = xmlhttp.getResponseHeader ('Date')
if d? then return new Date(d)
new Date()
@QueryString = ((a)->
unless a?
return {}
data = {}
value = []
i = 0
l = a.length
n = 0
while i < l
ary = a[i].split('=')
if ary.length == 1 or ary[0] == "value"
value.push(decodeURIComponent(ary[0].replace(/\+/g, " ")))
else if ary.length == 2
data[ary[0]] = decodeURIComponent(ary[1].replace(/\+/g, " "))
n++
i++
if value.length > 0
if value.length == 1
if n == 0
return value[0]
else
data["value"] = value[0]
else
if n == 0
return value
else
data["value"] = value
return data
)(window.location.search.substr(1).split('&'))
@consoleKill = ->
console.log = ->
constructor: ->
throw new Error('it is static class')
| true | ###
util.js v 1.2.7
Copyright (c) 2013 SHIFTBRAIN Inc.
Licensed under the MIT license.
https://github.com/devjam
Util.UA.browser : String
Util.UA.isIE : Bool
Util.UA.isIE6 : Bool
Util.UA.isIE7 : Bool
Util.UA.isIE8 : Bool
Util.UA.isIE9 : Bool
Util.UA.isLtIE9 : Bool
Util.UA.isIOS : Bool
Util.UA.isIPhone : Bool
Util.UA.isIPad : Bool
Util.UA.isIPhone4 : Bool
Util.UA.isIPad3 : Bool
Util.UA.isAndroid : Bool
Util.UA.isAndroidMobile : Bool
Util.UA.isChrome : Bool
Util.UA.isSafari : Bool
Util.UA.isMozilla : Bool
Util.UA.isWebkit : Bool
Util.UA.isOpera : Bool
Util.UA.isPC : Bool
Util.UA.isTablet : Bool
Util.UA.isSmartPhone : Bool
Util.venderPrefix : String
Util.stats.show() : void
Util.stats.remove() : void
Util.animationFrameDelta : Number
Util.animationFrameDelta.setDelta() : void
Util.window.onResize() : void (trigger resize event)
Util.window.size(withUpdate = false) : {width:Integer, height:Integer}
Util.window.pageSize(withUpdate = false) : {width:Integer, height:Integer}
Util.window.scrollTop() : Number
Util.window.scrollBottom() : Number
Util.window.bindResize(callback) : void
Util.window.unbindResize(callback, isReset = false) : void (isReset is unbind all)
Util.cursor.over : "mouseenter touchstart"
Util.cursor.out : "mouseleave touchend"
Util.cursor.down : "mousedown touchstart"
Util.cursor.move : "mousemove touchmouve"
Util.cursor.up : "mouseup touchend"
Util.cursor.click : "mouseup touchend"
Util.cursor.clientXY(e:MouseEvent or TouchEvent) : {x:Number, y:Number}
Util.cursor.pageXY(e:MouseEvent or TouchEvent) : {x:Number, y:Number}
Util.array.setRemove(Array = Array.prototype) : Bool ary.remove(value)
Util.array.setQuery(Array = Array.prototype) : Bool ary.q(id)
Util.now(get from server = true) : Date
Util.QueryString() : Object
Util.consoleKill() : void
###
unless @console?
@console =
log: ->
class @Util
@UA = (->
_ua = navigator.userAgent.toLowerCase()
ua =
isIE: false
isIE6: false
isIE7: false
isIE8: false
isIE9: false
isLtIE9: false
isIOS: false
isIPhone: false
isIPad: false
isIPhone4: false
isIPad3: false
isAndroid: false
isAndroidMobile: false
isChrome: false
isSafari: false
isMozilla: false
isWebkit: false
isOpera: false
isPC: false
isTablet: false
isSmartPhone: false
browser: _ua
if ua.isIE = /msie\s(\d+)/.test _ua
ver = RegExp.$1
ver *= 1
ua.isIE6 = ver == 6
ua.isIE7 = ver == 7
ua.isIE8 = ver == 8
ua.isIE9 = ver == 9
ua.isLtIE9 = ver < 9
if ua.isIE7 and _ua.indexOf('trident/4.0') != -1
ua.isIE7 = false
ua.isIE8 = true
if ua.isIPhone = /i(phone|pod)/.test _ua
ua.isIPhone4 = window.devicePixelRatio == 2
if ua.isIPad = /ipad/.test _ua
isIPad3 = window.devicePixelRatio == 2
ua.isIOS = ua.isIPhone || ua.isIPad
ua.isAndroid = /android/.test _ua
ua.isAndroidMobile = /android(.+)?mobile/.test _ua
ua.isPC = !ua.isIOS && !ua.isAndroid
ua.isTablet = ua.isIPad || (ua.isAndroid && ua.isAndroidMobile)
ua.isSmartPhone = ua.isIPhone || ua.isAndroidMobile
ua.isChrome = /chrome/.test _ua
ua.isWebkit = /webkit/.test _ua
ua.isOpera = /opera/.test _ua
ua.isMozilla = _ua.indexOf("compatible") < 0 && /mozilla/.test _ua
ua.isSafari = !ua.isChrome && ua.isWebkit
ua
)()
@venderPrefix = (->
if Util.UA.isIE then return "-ms-"
if Util.UA.isWebkit then return "-webkit-"
if Util.UA.isMozilla then return "-moz-"
if Util.UA.isOpera then return "-o-"
""
)()
@stats = (->
sts = null
stsTimer = null
update = ->
if !Stats? or !sts?
return false
stsTimer = requestAnimationFrame update
sts.update()
show: (mode = 0) ->
if !Stats? or sts? or Util.UA.isLtIE9
return false
sts = new Stats()
sts.setMode(mode)
document.body.appendChild( sts.domElement )
sts.domElement.style.cssText = "position:fixed; top:0; left:0; z-index:9999999;"
update()
remove: ->
if !Stats? or !sts?
return false
if stsTimer?
cancelAnimationFrame(stsTimer)
document.body.removeChild( sts.domElement )
sts = null
)()
@animationFrameDelta = 0
(->
isDateHasNow = !!Date.now
lastTime = if isDateHasNow then Date.now() else +new Date
callbacks = []
setDelta = (calledTime)->
Util.animationFrameDelta = calledTime - lastTime
lastTime = calledTime
window.requestAnimationFrame setDelta
return
if !window.requestAnimationFrame
prefix = Util.venderPrefix.replace /-/g, ""
window.requestAnimationFrame = window[prefix + "RequestAnimationFrame"]
window.cancelAnimationFrame = window[prefix + "CancelAnimationFrame"] || window[prefix + "CancelRequestAnimationFrame"]
if !window.requestAnimationFrame
window.requestAnimationFrame = (->
id = 0
(callback, element)->
if callbacks.length == 0
id = setTimeout ->
now = if isDateHasNow then Date.now() else +new Date
#同期だと処理が溢れるかなと思って非同期を試したけど
#パフォーマンスが悪かった。他になにかいい方法がある?
#(今は同期)
cbs = callbacks
callbacks = []
while cb = cbs.shift()
cb now
return
, 16
#setTimeoutのdelay値をdelta値によって可変させてみたけど、
#具合が悪そうなので固定にした。
if $.inArray?
if typeof callback == "function" && $.inArray(callback, callbacks) == -1
callbacks.push callback
else
callbacks.push callback
id
)()
window.cancelAnimationFrame = (id)->
callbacks = []
clearTimeout id
setDelta if isDateHasNow then Date.now() else +new Date
return
)()
@window = (->
win = $ window
doc = $ document
width = 0
height = 0
pageWidth = 0
pageHeight = 0
resizeCallbacks = []
isUpdate = 0
onResize = ->
isUpdate = 3
callbacks = resizeCallbacks.concat()
for callback in callbacks
callback()
return
win.resize onResize
$(->
width = win.width()
height = win.height()
pageWidth = doc.width()
pageHeight = doc.height()
)
size: (withUpdate = false)->
if withUpdate || isUpdate & 1
isUpdate = (isUpdate | 1) ^ 1
width = win.width()
height = win.height()
if width <= 0 and height <= 0
if document.documentElement.clientWidth
width = document.documentElement.clientWidth
else if document.body.clientWidth
width = document.body.clientWidth
else if window.innerWidth
width = window.innerWidth
if document.documentElement.clientHeight
height = document.documentElement.clientHeight
else if document.body.clientHeight
height = document.body.clientHeight
else if window.innerHeight
height = window.innerHeight
width: width
height: height
pageSize: (withUpdate = false)->
if withUpdate || isUpdate & 2
isUpdate = (isUpdate | 2) ^ 2
pageWidth = doc.width()
pageHeight = doc.height()
width: pageWidth
height: pageHeight
scrollTop: ->
if window.pageYOffset?
return window.pageYOffset
return win.scrollTop()
scrollBottom: ->
if window.pageYOffset?
return window.pageYOffset + window.innerHeight
return win.scrollTop() + height
bindResize: (callback)->
if typeof callback == "function" && $.inArray(callback, resizeCallbacks) == -1
resizeCallbacks.push callback
return
unbindResize: (callback, isReset = false)->
if callback && (index = $.inArray callback, resizeCallbacks) != -1
resizeCallbacks.splice index, 1
if isReset
resizeCallbacks = []
return
)()
@cursor = (->
c =
over : "mouseenter touchstart"
out : "mouseleave touchend"
down : "mousedown touchstart"
move : "mousemove touchmouve"
up : "mouseup touchend"
click : "mouseup touchend"
clientXY : (e)=>
pos = {x:0, y:0}
if e?
if "ontouchstart" of window
if e.touches?
e = e.touches[0]
else
e = e.originalEvent.touches[0]
if e.clientX?
pos.x = e.clientX
pos.y = e.clientY
return pos
pageXY : (e)=>
pos = {x:0, y:0}
if e?
if "ontouchstart" of window
if e.touches?
e = e.touches[0]
else
e = e.originalEvent.touches[0]
if e.pageX?
pos.x = e.pageX
pos.y = e.pageY
return pos
)()
@array = (->
setRemove: (ary)->
unless ary?
ary = Array.prototype
else
unless ary instanceof Array
return false
if ary.remove?
return false
ary.remove = ->
# BUG:IE で thisがarrayでなく functionになってしまう
l = arguments.length
i = 0
while i < l
m = @.length
j = 0
while j < m
if arguments[i] == @[j]
@.splice(j, 1)
m--
else
j++
i++
@.length
true
setQuery: (ary)->
unless ary?
ary = Array.prototype
else
unless ary instanceof Array
return false
if ary.remove?
return false
ary.q = (key, value)->
# BUG:IE で thisがarrayでなく functionになってしまう
unless value?
value = key
key = "PI:KEY:<KEY>END_PI"
ary_match =[]
i = 0
l = @.length
while i < l
item = @[i]
if item[key] == value
ary_match.push(item)
i++
if ary_match.length == 1
return ary_match[0]
else
return ary_match
true
)()
@now = (isSrv = true) ->
xmlhttp = false
d = null
if ActiveXObject? # IE5, IE6
try
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP") # MSXML3
catch e
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") # MSXML2
if !xmlhttp and XDomainRequest? then xmlhttp = new XDomainRequest()
if !xmlhttp and XMLHttpRequest? then xmlhttp = new XMLHttpRequest()
if isSrv and xmlhttp
xmlhttp.open('HEAD', '#', false)
xmlhttp.send (null)
d = xmlhttp.getResponseHeader ('Date')
if d? then return new Date(d)
new Date()
@QueryString = ((a)->
unless a?
return {}
data = {}
value = []
i = 0
l = a.length
n = 0
while i < l
ary = a[i].split('=')
if ary.length == 1 or ary[0] == "value"
value.push(decodeURIComponent(ary[0].replace(/\+/g, " ")))
else if ary.length == 2
data[ary[0]] = decodeURIComponent(ary[1].replace(/\+/g, " "))
n++
i++
if value.length > 0
if value.length == 1
if n == 0
return value[0]
else
data["value"] = value[0]
else
if n == 0
return value
else
data["value"] = value
return data
)(window.location.search.substr(1).split('&'))
@consoleKill = ->
console.log = ->
constructor: ->
throw new Error('it is static class')
|
[
{
"context": " $set: {\n password: ha,\n salt: salt,\n ",
"end": 655,
"score": 0.9832999110221863,
"start": 653,
"tag": "PASSWORD",
"value": "ha"
}
] | server/auth.coffee | YagamiMirai/jinrou | 18 | crypto=require 'crypto'
#ユーザー管理の何か
user=require './rpc/user.coffee'
#params: params.userid, params.password
exports.authenticate = (params,cb) ->
M.users.findOne {userid:params.userid}, (err,doc)->
unless doc?
cb {success:false}
return
unless check params.password, doc.password, doc.salt
# パスワードが違う
cb {success:false}
return
unless doc.salt?
# パスワードが古いので新しいハッシュで保存
salt = gensalt()
ha = crpassword params.password, salt
M.users.update {userid:params.userid}, {
$set: {
password: ha,
salt: salt,
},
}, {safe:true}, (err, count)->
if err?
cb {success:false}
return
# 成功
delete doc.password
doc.success=true
cb doc
else
delete doc.password
delete doc.salt
doc.success=true
cb doc
# パスワードが一致するか確かめる
exports.check = check = (raw, hash, salt)->
if salt?
return crpassword(raw, salt) == hash
else
return crpassword_old(raw) == hash
# saltを生成
exports.gensalt = gensalt = ()->
return crypto.randomBytes(32).toString 'hex'
# パスワードハッシュ化
exports.crpassword = crpassword = (raw, salt)->
return "" unless raw && salt
sha256 = crypto.createHash "sha256"
sha256.update "#{salt}#{raw}"
return sha256.digest 'hex'
# 古いパスワードハッシュ
crpassword_old = (raw)->
sha256=crypto.createHash "sha256"
md5=crypto.createHash "md5"
md5.update raw # md5でハッシュ化
sha256.update raw+md5.digest 'hex' # sha256でさらにハッシュ化
sha256.digest 'hex' # 结果を返す
| 201578 | crypto=require 'crypto'
#ユーザー管理の何か
user=require './rpc/user.coffee'
#params: params.userid, params.password
exports.authenticate = (params,cb) ->
M.users.findOne {userid:params.userid}, (err,doc)->
unless doc?
cb {success:false}
return
unless check params.password, doc.password, doc.salt
# パスワードが違う
cb {success:false}
return
unless doc.salt?
# パスワードが古いので新しいハッシュで保存
salt = gensalt()
ha = crpassword params.password, salt
M.users.update {userid:params.userid}, {
$set: {
password: <PASSWORD>,
salt: salt,
},
}, {safe:true}, (err, count)->
if err?
cb {success:false}
return
# 成功
delete doc.password
doc.success=true
cb doc
else
delete doc.password
delete doc.salt
doc.success=true
cb doc
# パスワードが一致するか確かめる
exports.check = check = (raw, hash, salt)->
if salt?
return crpassword(raw, salt) == hash
else
return crpassword_old(raw) == hash
# saltを生成
exports.gensalt = gensalt = ()->
return crypto.randomBytes(32).toString 'hex'
# パスワードハッシュ化
exports.crpassword = crpassword = (raw, salt)->
return "" unless raw && salt
sha256 = crypto.createHash "sha256"
sha256.update "#{salt}#{raw}"
return sha256.digest 'hex'
# 古いパスワードハッシュ
crpassword_old = (raw)->
sha256=crypto.createHash "sha256"
md5=crypto.createHash "md5"
md5.update raw # md5でハッシュ化
sha256.update raw+md5.digest 'hex' # sha256でさらにハッシュ化
sha256.digest 'hex' # 结果を返す
| true | crypto=require 'crypto'
#ユーザー管理の何か
user=require './rpc/user.coffee'
#params: params.userid, params.password
exports.authenticate = (params,cb) ->
M.users.findOne {userid:params.userid}, (err,doc)->
unless doc?
cb {success:false}
return
unless check params.password, doc.password, doc.salt
# パスワードが違う
cb {success:false}
return
unless doc.salt?
# パスワードが古いので新しいハッシュで保存
salt = gensalt()
ha = crpassword params.password, salt
M.users.update {userid:params.userid}, {
$set: {
password: PI:PASSWORD:<PASSWORD>END_PI,
salt: salt,
},
}, {safe:true}, (err, count)->
if err?
cb {success:false}
return
# 成功
delete doc.password
doc.success=true
cb doc
else
delete doc.password
delete doc.salt
doc.success=true
cb doc
# パスワードが一致するか確かめる
exports.check = check = (raw, hash, salt)->
if salt?
return crpassword(raw, salt) == hash
else
return crpassword_old(raw) == hash
# saltを生成
exports.gensalt = gensalt = ()->
return crypto.randomBytes(32).toString 'hex'
# パスワードハッシュ化
exports.crpassword = crpassword = (raw, salt)->
return "" unless raw && salt
sha256 = crypto.createHash "sha256"
sha256.update "#{salt}#{raw}"
return sha256.digest 'hex'
# 古いパスワードハッシュ
crpassword_old = (raw)->
sha256=crypto.createHash "sha256"
md5=crypto.createHash "md5"
md5.update raw # md5でハッシュ化
sha256.update raw+md5.digest 'hex' # sha256でさらにハッシュ化
sha256.digest 'hex' # 结果を返す
|
[
{
"context": "mEvents(\n -> Bacon.once({ bacon: Bacon.once(\"sir francis\")}).flatMapWithConcurrencyLimit(1, \".bacon\")\n ",
"end": 666,
"score": 0.9994401931762695,
"start": 655,
"tag": "NAME",
"value": "sir francis"
},
{
"context": ".flatMapWithConcurrencyLimit(1, \".bacon\")\n [\"sir francis\"])\n it \"toString\", ->\n expect(Bacon.once(1).f",
"end": 731,
"score": 0.9995208978652954,
"start": 720,
"tag": "NAME",
"value": "sir francis"
}
] | spec/specs/flatmapwithconcurrencylimit.coffee | phadej/bacon.js | 0 | describe "EventStream.flatMapWithConcurrencyLimit", ->
describe "limits the number of concurrently active spawned streams by queuing", ->
expectStreamEvents(
-> series(1, [1, 2]).flatMapWithConcurrencyLimit(1, (value) ->
series(t(2), [value, error(), value]))
[1, error(), 1, 2, error(), 2], semiunstable)
describe "works with n=2", ->
expectStreamEvents(
-> series(1, [1,2,3]).flatMapWithConcurrencyLimit(2, (value) ->
series(t(2), [value, value]))
[1, 2, 1, 2, 3, 3], semiunstable)
describe "Respects function construction rules", ->
expectStreamEvents(
-> Bacon.once({ bacon: Bacon.once("sir francis")}).flatMapWithConcurrencyLimit(1, ".bacon")
["sir francis"])
it "toString", ->
expect(Bacon.once(1).flatMapWithConcurrencyLimit(2, ->).toString())
.to.equal("Bacon.once(1).flatMapWithConcurrencyLimit(2,function)")
| 43051 | describe "EventStream.flatMapWithConcurrencyLimit", ->
describe "limits the number of concurrently active spawned streams by queuing", ->
expectStreamEvents(
-> series(1, [1, 2]).flatMapWithConcurrencyLimit(1, (value) ->
series(t(2), [value, error(), value]))
[1, error(), 1, 2, error(), 2], semiunstable)
describe "works with n=2", ->
expectStreamEvents(
-> series(1, [1,2,3]).flatMapWithConcurrencyLimit(2, (value) ->
series(t(2), [value, value]))
[1, 2, 1, 2, 3, 3], semiunstable)
describe "Respects function construction rules", ->
expectStreamEvents(
-> Bacon.once({ bacon: Bacon.once("<NAME>")}).flatMapWithConcurrencyLimit(1, ".bacon")
["<NAME>"])
it "toString", ->
expect(Bacon.once(1).flatMapWithConcurrencyLimit(2, ->).toString())
.to.equal("Bacon.once(1).flatMapWithConcurrencyLimit(2,function)")
| true | describe "EventStream.flatMapWithConcurrencyLimit", ->
describe "limits the number of concurrently active spawned streams by queuing", ->
expectStreamEvents(
-> series(1, [1, 2]).flatMapWithConcurrencyLimit(1, (value) ->
series(t(2), [value, error(), value]))
[1, error(), 1, 2, error(), 2], semiunstable)
describe "works with n=2", ->
expectStreamEvents(
-> series(1, [1,2,3]).flatMapWithConcurrencyLimit(2, (value) ->
series(t(2), [value, value]))
[1, 2, 1, 2, 3, 3], semiunstable)
describe "Respects function construction rules", ->
expectStreamEvents(
-> Bacon.once({ bacon: Bacon.once("PI:NAME:<NAME>END_PI")}).flatMapWithConcurrencyLimit(1, ".bacon")
["PI:NAME:<NAME>END_PI"])
it "toString", ->
expect(Bacon.once(1).flatMapWithConcurrencyLimit(2, ->).toString())
.to.equal("Bacon.once(1).flatMapWithConcurrencyLimit(2,function)")
|
[
{
"context": "g quote: s = \\\"hi\", ->\n # https://github.com/codecombat/aether/issues/113\n code = \"\"\"\n var s = ",
"end": 2022,
"score": 0.9995821118354797,
"start": 2012,
"tag": "USERNAME",
"value": "codecombat"
},
{
"context": "uble var\", ->\n code = \"\"\"\n var enemy = 'Bob';\n var enemy = 'Sue';\n \"\"\"\n aether",
"end": 5203,
"score": 0.9975031614303589,
"start": 5200,
"tag": "NAME",
"value": "Bob"
},
{
"context": "= \"\"\"\n var enemy = 'Bob';\n var enemy = 'Sue';\n \"\"\"\n aether = new Aether()\n aet",
"end": 5228,
"score": 0.9953838586807251,
"start": 5225,
"tag": "NAME",
"value": "Sue"
},
{
"context": "else without : #2\", ->\n # https://github.com/differentmatt/filbert/issues/44\n code = \"\"\"\n if False",
"end": 7986,
"score": 0.9995771050453186,
"start": 7973,
"tag": "USERNAME",
"value": "differentmatt"
},
{
"context": "else without : #3\", ->\n # https://github.com/differentmatt/filbert/issues/44\n code = \"\"\"\n if False",
"end": 8625,
"score": 0.9995922446250916,
"start": 8612,
"tag": "USERNAME",
"value": "differentmatt"
},
{
"context": " \"\"\"\n problemContext = stringReferences: ['Bob', 'Brak', 'Zort']\n aether = new Aether lan",
"end": 26377,
"score": 0.9997743964195251,
"start": 26374,
"tag": "NAME",
"value": "Bob"
},
{
"context": " problemContext = stringReferences: ['Bob', 'Brak', 'Zort']\n aether = new Aether language: \"",
"end": 26385,
"score": 0.9998199939727783,
"start": 26381,
"tag": "NAME",
"value": "Brak"
},
{
"context": "oblemContext = stringReferences: ['Bob', 'Brak', 'Zort']\n aether = new Aether language: \"python\",",
"end": 26393,
"score": 0.9997172355651855,
"start": 26389,
"tag": "NAME",
"value": "Zort"
},
{
"context": " \"\"\"\n problemContext = stringReferences: ['Bob', 'Brak', 'Zort']\n aether = new Aether lan",
"end": 29239,
"score": 0.9998542666435242,
"start": 29236,
"tag": "NAME",
"value": "Bob"
},
{
"context": " problemContext = stringReferences: ['Bob', 'Brak', 'Zort']\n aether = new Aether language: \"",
"end": 29247,
"score": 0.9998023509979248,
"start": 29243,
"tag": "NAME",
"value": "Brak"
},
{
"context": "oblemContext = stringReferences: ['Bob', 'Brak', 'Zort']\n aether = new Aether language: \"python\",",
"end": 29255,
"score": 0.9997432231903076,
"start": 29251,
"tag": "NAME",
"value": "Zort"
}
] | test/problem_spec.coffee | basicer/aether | 0 | Aether = require '../aether'
describe "Problem Test Suite", ->
describe "Transpile problems", ->
it "missing a closing quote: self.attack('Brak)", ->
code = """
self.attack('Brak)
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unterminated string constant")
expect(aether.problems.errors[0].hint).toEqual("Missing a quotation mark. Try `'Brak'`")
it "missing a closing quote: s = \"hi", ->
code = """
s = "hi
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unterminated string constant")
expect(aether.problems.errors[0].hint).toEqual("Missing a quotation mark. Try `\"hi\"`")
it "missing a closing quote: '", ->
code = """
'
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unterminated string constant")
expect(aether.problems.errors[0].hint).toEqual("Missing a quotation mark. Try `''`")
it "Unexpected indent", ->
code = """
x = 5
y = 7
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("Code needs to line up.")
xit "missing a closing quote: s = \"hi", ->
# https://github.com/codecombat/aether/issues/113
code = """
var s = "hi
"""
aether = new Aether
aether.transpile code
expect(aether.problems.errors.length).toEqual(3)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unclosed string.")
expect(aether.problems.errors[0].hint).toEqual("You may be missing a closing quotation mark. Try `\"hi\"`")
it "Unexpected token 'self move'", ->
code = """
self move
"""
problemContext = thisMethods: [ 'moveUp']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveUp()`")
it "Unexpected token 'self self.move'", ->
code = """
self self.move
"""
problemContext = thisMethods: [ 'moveUp']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(2)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Delete extra `self`")
it "Unexpected token 'self.moveUp())'", ->
code = """
self.moveUp())
"""
problemContext = thisMethods: [ 'moveUp']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Delete extra `)`")
it "Unexpected token 'self.moveUp()self.moveDown()'", ->
code = """
self.moveUp()self.moveDown()
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Put each command on a separate line")
it "Capitalized loop", ->
code = """
Loop:
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext, simpleLoops: true
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Should be lowercase. Try `loop`")
it "Double var", ->
code = """
var enemy = 'Bob';
var enemy = 'Sue';
"""
aether = new Aether()
aether.transpile code
expect(aether.problems.warnings.length).toEqual(1)
expect(aether.problems.warnings[0].type).toEqual('transpile')
expect(aether.problems.warnings[0].message).toEqual("'enemy' is already defined.")
expect(aether.problems.warnings[0].hint).toEqual("Don't use the 'var' keyword for 'enemy' the second time.")
it "if without :", ->
code = """
if True
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'if True'. Try `if True:`")
it "indented if without :", ->
code = """
if True:
if True
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after ' if True'. Try ` if True:`")
it "if without test clause", ->
code = """
if :
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Your if statement is missing a test clause. Try `if True:`")
it "else without : #1", ->
code = """
if False:
x = 5
else
x = 7
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
xit "else without : #2", ->
# https://github.com/differentmatt/filbert/issues/44
code = """
if False:
x = 5
else
x = 7
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
xit "else without : #3", ->
# https://github.com/differentmatt/filbert/issues/44
code = """
if False:
x = 5
else x = 7
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
it "else without : #4", ->
code = """
if True:
if False:
x = 7
else
x = 59
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
it "self.moveRight(", ->
code = """
self.moveRight(
"""
problemContext = {}
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Your parentheses must match.")
it "self.moveRight(()", ->
code = """
self.moveRight(()
"""
problemContext = {}
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Your parentheses must match.")
describe "Runtime problems", ->
it "Should capture runtime problems", ->
# 0123456789012345678901234567
code = """
var methodName = 'explode';
this[methodName]();
"""
options =
thisValue: {}
problems: {jshint_W040: {level: "ignore"}}
aether = new Aether options
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toEqual 1
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'runtime'
expect(problem.level).toEqual 'error'
expect(problem.message).toMatch /has no method/
expect(problem.range?.length).toEqual 2
[start, end] = problem.range
expect(start.ofs).toEqual 28
expect(start.row).toEqual 1
expect(start.col).toEqual 0
expect(end.ofs).toEqual 46
expect(end.row).toEqual 1
expect(end.col).toEqual 18
expect(problem.message).toMatch /Line 2/
it "Shouldn't die on invalid crazy code", ->
code = """
if (true >== true){
true;}
"""
aether = new Aether {}
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toBeGreaterThan 0
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'transpile'
expect(problem.level).toEqual 'error'
it "Shouldn't die on more invalid crazy code", ->
code = """
var coins = {'emerald': []};
coins.'emerald'.push({type: 'emerald', bountyGold: 5});
"""
aether = new Aether {}
expect(-> aether.transpile(code)).not.toThrow()
aether.run()
expect(aether.problems.errors.length).toBeGreaterThan 0
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'transpile'
expect(problem.level).toEqual 'error'
it "Should hard-cap execution to break infinite loops.", ->
code = """
while(true) {
;
}
"""
aether = new Aether {executionLimit: 9001}
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toBeGreaterThan 0
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'runtime'
expect(problem.level).toEqual 'error'
it "Should hard-cap execution after a certain limit.", ->
code = """
for (var i = 0; i < 1000; ++i) {}
return 'mojambo';
"""
aether = new Aether {executionLimit: 500}
aether.transpile(code)
expect(aether.run()).toBeUndefined()
it "Shouldn't hard-cap execution too early.", ->
code = """
for (var i = 0; i < 1000; ++i) {}
return 'mojambo';
"""
aether = new Aether {executionLimit: 9001}
aether.transpile(code)
expect(aether.run()).toEqual 'mojambo'
it "Should error on undefined property accesses.", ->
code = """
var bar = 'bar';
var foobar = foo + bar;
return foobar;
"""
aether = new Aether functionName: 'foobarFactory'
aether.transpile(code)
expect(aether.run()).not.toEqual 'undefinedbar'
expect(aether.run()).toEqual undefined
expect(aether.problems.errors).not.toEqual []
it "Access prop on null", ->
code = """
def findFlag():
return None
flag = findFlag()
x = flag.pos
return x
"""
problemContext = {}
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.run()).toEqual null
expect(aether.problems.errors).not.toEqual []
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 4: Cannot read property 'pos' of null")
expect(aether.problems.errors[0].hint).toEqual("'flag' was null. Use a null check before accessing properties. Try `if flag:`")
describe "problemContext", ->
# NOTE: the problemContext tests are roughly in the order they're checked in the code
describe "General", ->
it "Call non-this undefined function x()", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """x()"""
problemContext = thisMethods: [ 'log', 'attack' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: x is not defined")
expect(aether.problems.errors[0].hint).toEqual("")
expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 1, row: 0, col: 1 } ])
it "loop is not defined", ->
code = "loop"
aether = new Aether language: "python", simpleLoops: true
aether.transpile code
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: loop is not defined")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'loop'. Try `loop:`")
it "loop is not defined w/ newline", ->
code = """
loop
x = 5
"""
aether = new Aether language: "python", simpleLoops: true
aether.transpile code
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: loop is not defined")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'loop'. Try `loop:`")
it "loop is not defined w/o simpleLoops", ->
code = "loop"
aether = new Aether language: "python"
aether.transpile code
method = aether.createMethod
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: loop is not defined")
expect(aether.problems.errors[0].hint).toEqual("")
describe "No function", ->
it "Exact thisMethods", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
attack
"""
problemContext = thisMethods: [ 'log', 'attack' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: attack is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.attack()`")
it "Case thisMethods", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
Attack
"""
problemContext = thisMethods: [ 'log', 'attack', 'tickle' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Attack is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.attack()`")
it "Exact commonThisMethods", ->
selfValue = {}
code = """
this.attack("Brak");
"""
problemContext = commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'attack'")
expect(aether.problems.errors[0].hint).toEqual("You do not have an item equipped with the attack skill.")
it "Exact commonThisMethods #2", ->
selfValue = {}
code = """
self.moveRight()
"""
problemContext = thisMethods: ['moveUp', 'moveLeft'], commonThisMethods: ['moveRight']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveRight'")
expect(aether.problems.errors[0].hint).toEqual("You do not have an item equipped with the moveRight skill.")
it "Case commonThisMethods", ->
selfValue = {}
code = """
self.moveup()
"""
problemContext = commonThisMethods: ['moveUp']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveup'")
expect(aether.problems.errors[0].hint).toEqual("Did you mean moveUp? You do not have an item equipped with that skill.")
it "Score commonThisMethods", ->
selfValue = {}
code = """
self.movright()
"""
problemContext = thisMethods: ['moveUp', 'moveLeft'], commonThisMethods: ['moveRight']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'movright'")
expect(aether.problems.errors[0].hint).toEqual("Did you mean moveRight? You do not have an item equipped with that skill.")
it "Score commonThisMethods #2", ->
selfValue = {}
code = """
this.movright()
"""
problemContext = thisMethods: ['moveUp', 'moveLeft'], commonThisMethods: ['moveRight']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'movright'")
expect(aether.problems.errors[0].hint).toEqual("Did you mean moveRight? You do not have an item equipped with that skill.")
describe "ReferenceError", ->
it "Exact stringReferences", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
self.attack(Brak)
"""
problemContext = stringReferences: ['Brak']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Brak is not defined")
expect(aether.problems.errors[0].hint).toEqual("Missing quotes. Try `\"Brak\"`")
it "Exact thisMethods", ->
selfValue = {}
code = """
moveleft
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: moveleft is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveLeft()`")
it "Exact thisMethods with range checks", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """attack()"""
problemContext = thisMethods: [ 'log', 'attack' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(2)
expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.attack`.")
expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 8, row: 0, col: 8 } ])
expect(aether.problems.errors[1].message).toEqual("Line 1: ReferenceError: attack is not defined")
expect(aether.problems.errors[1].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 6, row: 0, col: 6 } ])
it "Exact thisProperties", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
b = buildables
"""
problemContext = thisProperties: [ 'buildables' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: buildables is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.buildables`")
it "Case this value", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, moveRight: attack}
code = """
sElf.moveRight()
"""
problemContext = thisMethods: ['moveRight']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: sElf is not defined")
expect(aether.problems.errors[0].hint).toEqual("Uppercase or lowercase problem. Try `self`")
it "Case stringReferences", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
self.attack(brak)
"""
problemContext = stringReferences: ['Bob', 'Brak', 'Zort']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: brak is not defined")
expect(aether.problems.errors[0].hint).toEqual("Missing quotes. Try `\"Brak\"`")
it "Case thisMethods", ->
selfValue = {}
code = """
this.moveright();
"""
problemContext = thisMethods: ['moveUp', 'moveRight', 'moveLeft']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveright'")
expect(aether.problems.errors[0].hint).toEqual("Uppercase or lowercase problem. Try `this.moveRight()`")
it "Case thisProperties", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
b = Buildables
"""
problemContext = thisProperties: [ 'buildables' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Buildables is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.buildables`")
it "Score this value", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
elf.moveDown()
"""
problemContext = thisMethods: [ 'moveDown' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: elf is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self`")
it "Score stringReferences", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
self.attack(brOk)
"""
problemContext = stringReferences: ['Bob', 'Brak', 'Zort']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: brOk is not defined")
expect(aether.problems.errors[0].hint).toEqual("Missing quotes. Try `\"Brak\"`")
it "Score thisMethods", ->
selfValue = {}
code = """
self.moveEight()
"""
problemContext = thisMethods: ['moveUp', 'moveRight', 'moveLeft']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveEight'")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveRight()`")
it "Score thisMethods #2", ->
selfValue = {}
code = """
movleft
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: movleft is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveLeft()`")
it "Score thisMethods #3", ->
selfValue = {}
code = """
moveeft
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: moveeft is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveLeft()`")
it "Score thisMethods #4", ->
selfValue = {}
code = """
selfmoveright
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: selfmoveright is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveRight()`")
it "Score thisProperties", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
b = Bildaables
"""
problemContext = thisProperties: [ 'buildables' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Bildaables is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.buildables`")
it "Exact commonThisMethods", ->
selfValue = {}
code = """
attack()
"""
problemContext = thisMethods: [], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: attack is not defined")
expect(aether.problems.errors[0].hint).toEqual("You do not have an item equipped with the attack skill.")
it "Case commonThisMethods", ->
selfValue = {}
code = """
ATTACK()
"""
problemContext = thisMethods: [], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: ATTACK is not defined")
expect(aether.problems.errors[0].hint).toEqual("Did you mean attack? You do not have an item equipped with that skill.")
it "Score commonThisMethods", ->
selfValue = {}
code = """
atac()
"""
problemContext = thisMethods: [], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: atac is not defined")
expect(aether.problems.errors[0].hint).toEqual("Did you mean attack? You do not have an item equipped with that skill.")
describe "Missing property", ->
it "self.self.moveUp()", ->
selfValue = {}
code = """
self.self.moveUp()
"""
problemContext = thisMethods: ['moveUp'], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: Cannot call method 'moveUp' of undefined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveUp()`")
describe "transforms.makeCheckIncompleteMembers", ->
it "Incomplete 'this' and available method", ->
selfValue = {}
code = """
this.moveUp
"""
problemContext = thisMethods: ['moveUp']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("this.moveUp has no effect. It needs parentheses: this.moveUp()")
expect(aether.problems.errors[0].hint).toEqual("")
| 17184 | Aether = require '../aether'
describe "Problem Test Suite", ->
describe "Transpile problems", ->
it "missing a closing quote: self.attack('Brak)", ->
code = """
self.attack('Brak)
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unterminated string constant")
expect(aether.problems.errors[0].hint).toEqual("Missing a quotation mark. Try `'Brak'`")
it "missing a closing quote: s = \"hi", ->
code = """
s = "hi
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unterminated string constant")
expect(aether.problems.errors[0].hint).toEqual("Missing a quotation mark. Try `\"hi\"`")
it "missing a closing quote: '", ->
code = """
'
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unterminated string constant")
expect(aether.problems.errors[0].hint).toEqual("Missing a quotation mark. Try `''`")
it "Unexpected indent", ->
code = """
x = 5
y = 7
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("Code needs to line up.")
xit "missing a closing quote: s = \"hi", ->
# https://github.com/codecombat/aether/issues/113
code = """
var s = "hi
"""
aether = new Aether
aether.transpile code
expect(aether.problems.errors.length).toEqual(3)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unclosed string.")
expect(aether.problems.errors[0].hint).toEqual("You may be missing a closing quotation mark. Try `\"hi\"`")
it "Unexpected token 'self move'", ->
code = """
self move
"""
problemContext = thisMethods: [ 'moveUp']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveUp()`")
it "Unexpected token 'self self.move'", ->
code = """
self self.move
"""
problemContext = thisMethods: [ 'moveUp']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(2)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Delete extra `self`")
it "Unexpected token 'self.moveUp())'", ->
code = """
self.moveUp())
"""
problemContext = thisMethods: [ 'moveUp']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Delete extra `)`")
it "Unexpected token 'self.moveUp()self.moveDown()'", ->
code = """
self.moveUp()self.moveDown()
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Put each command on a separate line")
it "Capitalized loop", ->
code = """
Loop:
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext, simpleLoops: true
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Should be lowercase. Try `loop`")
it "Double var", ->
code = """
var enemy = '<NAME>';
var enemy = '<NAME>';
"""
aether = new Aether()
aether.transpile code
expect(aether.problems.warnings.length).toEqual(1)
expect(aether.problems.warnings[0].type).toEqual('transpile')
expect(aether.problems.warnings[0].message).toEqual("'enemy' is already defined.")
expect(aether.problems.warnings[0].hint).toEqual("Don't use the 'var' keyword for 'enemy' the second time.")
it "if without :", ->
code = """
if True
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'if True'. Try `if True:`")
it "indented if without :", ->
code = """
if True:
if True
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after ' if True'. Try ` if True:`")
it "if without test clause", ->
code = """
if :
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Your if statement is missing a test clause. Try `if True:`")
it "else without : #1", ->
code = """
if False:
x = 5
else
x = 7
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
xit "else without : #2", ->
# https://github.com/differentmatt/filbert/issues/44
code = """
if False:
x = 5
else
x = 7
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
xit "else without : #3", ->
# https://github.com/differentmatt/filbert/issues/44
code = """
if False:
x = 5
else x = 7
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
it "else without : #4", ->
code = """
if True:
if False:
x = 7
else
x = 59
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
it "self.moveRight(", ->
code = """
self.moveRight(
"""
problemContext = {}
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Your parentheses must match.")
it "self.moveRight(()", ->
code = """
self.moveRight(()
"""
problemContext = {}
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Your parentheses must match.")
describe "Runtime problems", ->
it "Should capture runtime problems", ->
# 0123456789012345678901234567
code = """
var methodName = 'explode';
this[methodName]();
"""
options =
thisValue: {}
problems: {jshint_W040: {level: "ignore"}}
aether = new Aether options
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toEqual 1
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'runtime'
expect(problem.level).toEqual 'error'
expect(problem.message).toMatch /has no method/
expect(problem.range?.length).toEqual 2
[start, end] = problem.range
expect(start.ofs).toEqual 28
expect(start.row).toEqual 1
expect(start.col).toEqual 0
expect(end.ofs).toEqual 46
expect(end.row).toEqual 1
expect(end.col).toEqual 18
expect(problem.message).toMatch /Line 2/
it "Shouldn't die on invalid crazy code", ->
code = """
if (true >== true){
true;}
"""
aether = new Aether {}
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toBeGreaterThan 0
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'transpile'
expect(problem.level).toEqual 'error'
it "Shouldn't die on more invalid crazy code", ->
code = """
var coins = {'emerald': []};
coins.'emerald'.push({type: 'emerald', bountyGold: 5});
"""
aether = new Aether {}
expect(-> aether.transpile(code)).not.toThrow()
aether.run()
expect(aether.problems.errors.length).toBeGreaterThan 0
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'transpile'
expect(problem.level).toEqual 'error'
it "Should hard-cap execution to break infinite loops.", ->
code = """
while(true) {
;
}
"""
aether = new Aether {executionLimit: 9001}
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toBeGreaterThan 0
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'runtime'
expect(problem.level).toEqual 'error'
it "Should hard-cap execution after a certain limit.", ->
code = """
for (var i = 0; i < 1000; ++i) {}
return 'mojambo';
"""
aether = new Aether {executionLimit: 500}
aether.transpile(code)
expect(aether.run()).toBeUndefined()
it "Shouldn't hard-cap execution too early.", ->
code = """
for (var i = 0; i < 1000; ++i) {}
return 'mojambo';
"""
aether = new Aether {executionLimit: 9001}
aether.transpile(code)
expect(aether.run()).toEqual 'mojambo'
it "Should error on undefined property accesses.", ->
code = """
var bar = 'bar';
var foobar = foo + bar;
return foobar;
"""
aether = new Aether functionName: 'foobarFactory'
aether.transpile(code)
expect(aether.run()).not.toEqual 'undefinedbar'
expect(aether.run()).toEqual undefined
expect(aether.problems.errors).not.toEqual []
it "Access prop on null", ->
code = """
def findFlag():
return None
flag = findFlag()
x = flag.pos
return x
"""
problemContext = {}
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.run()).toEqual null
expect(aether.problems.errors).not.toEqual []
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 4: Cannot read property 'pos' of null")
expect(aether.problems.errors[0].hint).toEqual("'flag' was null. Use a null check before accessing properties. Try `if flag:`")
describe "problemContext", ->
# NOTE: the problemContext tests are roughly in the order they're checked in the code
describe "General", ->
it "Call non-this undefined function x()", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """x()"""
problemContext = thisMethods: [ 'log', 'attack' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: x is not defined")
expect(aether.problems.errors[0].hint).toEqual("")
expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 1, row: 0, col: 1 } ])
it "loop is not defined", ->
code = "loop"
aether = new Aether language: "python", simpleLoops: true
aether.transpile code
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: loop is not defined")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'loop'. Try `loop:`")
it "loop is not defined w/ newline", ->
code = """
loop
x = 5
"""
aether = new Aether language: "python", simpleLoops: true
aether.transpile code
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: loop is not defined")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'loop'. Try `loop:`")
it "loop is not defined w/o simpleLoops", ->
code = "loop"
aether = new Aether language: "python"
aether.transpile code
method = aether.createMethod
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: loop is not defined")
expect(aether.problems.errors[0].hint).toEqual("")
describe "No function", ->
it "Exact thisMethods", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
attack
"""
problemContext = thisMethods: [ 'log', 'attack' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: attack is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.attack()`")
it "Case thisMethods", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
Attack
"""
problemContext = thisMethods: [ 'log', 'attack', 'tickle' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Attack is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.attack()`")
it "Exact commonThisMethods", ->
selfValue = {}
code = """
this.attack("Brak");
"""
problemContext = commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'attack'")
expect(aether.problems.errors[0].hint).toEqual("You do not have an item equipped with the attack skill.")
it "Exact commonThisMethods #2", ->
selfValue = {}
code = """
self.moveRight()
"""
problemContext = thisMethods: ['moveUp', 'moveLeft'], commonThisMethods: ['moveRight']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveRight'")
expect(aether.problems.errors[0].hint).toEqual("You do not have an item equipped with the moveRight skill.")
it "Case commonThisMethods", ->
selfValue = {}
code = """
self.moveup()
"""
problemContext = commonThisMethods: ['moveUp']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveup'")
expect(aether.problems.errors[0].hint).toEqual("Did you mean moveUp? You do not have an item equipped with that skill.")
it "Score commonThisMethods", ->
selfValue = {}
code = """
self.movright()
"""
problemContext = thisMethods: ['moveUp', 'moveLeft'], commonThisMethods: ['moveRight']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'movright'")
expect(aether.problems.errors[0].hint).toEqual("Did you mean moveRight? You do not have an item equipped with that skill.")
it "Score commonThisMethods #2", ->
selfValue = {}
code = """
this.movright()
"""
problemContext = thisMethods: ['moveUp', 'moveLeft'], commonThisMethods: ['moveRight']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'movright'")
expect(aether.problems.errors[0].hint).toEqual("Did you mean moveRight? You do not have an item equipped with that skill.")
describe "ReferenceError", ->
it "Exact stringReferences", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
self.attack(Brak)
"""
problemContext = stringReferences: ['Brak']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Brak is not defined")
expect(aether.problems.errors[0].hint).toEqual("Missing quotes. Try `\"Brak\"`")
it "Exact thisMethods", ->
selfValue = {}
code = """
moveleft
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: moveleft is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveLeft()`")
it "Exact thisMethods with range checks", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """attack()"""
problemContext = thisMethods: [ 'log', 'attack' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(2)
expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.attack`.")
expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 8, row: 0, col: 8 } ])
expect(aether.problems.errors[1].message).toEqual("Line 1: ReferenceError: attack is not defined")
expect(aether.problems.errors[1].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 6, row: 0, col: 6 } ])
it "Exact thisProperties", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
b = buildables
"""
problemContext = thisProperties: [ 'buildables' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: buildables is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.buildables`")
it "Case this value", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, moveRight: attack}
code = """
sElf.moveRight()
"""
problemContext = thisMethods: ['moveRight']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: sElf is not defined")
expect(aether.problems.errors[0].hint).toEqual("Uppercase or lowercase problem. Try `self`")
it "Case stringReferences", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
self.attack(brak)
"""
problemContext = stringReferences: ['<NAME>', '<NAME>', '<NAME>']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: brak is not defined")
expect(aether.problems.errors[0].hint).toEqual("Missing quotes. Try `\"Brak\"`")
it "Case thisMethods", ->
selfValue = {}
code = """
this.moveright();
"""
problemContext = thisMethods: ['moveUp', 'moveRight', 'moveLeft']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveright'")
expect(aether.problems.errors[0].hint).toEqual("Uppercase or lowercase problem. Try `this.moveRight()`")
it "Case thisProperties", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
b = Buildables
"""
problemContext = thisProperties: [ 'buildables' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Buildables is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.buildables`")
it "Score this value", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
elf.moveDown()
"""
problemContext = thisMethods: [ 'moveDown' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: elf is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self`")
it "Score stringReferences", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
self.attack(brOk)
"""
problemContext = stringReferences: ['<NAME>', '<NAME>', '<NAME>']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: brOk is not defined")
expect(aether.problems.errors[0].hint).toEqual("Missing quotes. Try `\"Brak\"`")
it "Score thisMethods", ->
selfValue = {}
code = """
self.moveEight()
"""
problemContext = thisMethods: ['moveUp', 'moveRight', 'moveLeft']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveEight'")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveRight()`")
it "Score thisMethods #2", ->
selfValue = {}
code = """
movleft
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: movleft is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveLeft()`")
it "Score thisMethods #3", ->
selfValue = {}
code = """
moveeft
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: moveeft is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveLeft()`")
it "Score thisMethods #4", ->
selfValue = {}
code = """
selfmoveright
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: selfmoveright is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveRight()`")
it "Score thisProperties", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
b = Bildaables
"""
problemContext = thisProperties: [ 'buildables' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Bildaables is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.buildables`")
it "Exact commonThisMethods", ->
selfValue = {}
code = """
attack()
"""
problemContext = thisMethods: [], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: attack is not defined")
expect(aether.problems.errors[0].hint).toEqual("You do not have an item equipped with the attack skill.")
it "Case commonThisMethods", ->
selfValue = {}
code = """
ATTACK()
"""
problemContext = thisMethods: [], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: ATTACK is not defined")
expect(aether.problems.errors[0].hint).toEqual("Did you mean attack? You do not have an item equipped with that skill.")
it "Score commonThisMethods", ->
selfValue = {}
code = """
atac()
"""
problemContext = thisMethods: [], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: atac is not defined")
expect(aether.problems.errors[0].hint).toEqual("Did you mean attack? You do not have an item equipped with that skill.")
describe "Missing property", ->
it "self.self.moveUp()", ->
selfValue = {}
code = """
self.self.moveUp()
"""
problemContext = thisMethods: ['moveUp'], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: Cannot call method 'moveUp' of undefined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveUp()`")
describe "transforms.makeCheckIncompleteMembers", ->
it "Incomplete 'this' and available method", ->
selfValue = {}
code = """
this.moveUp
"""
problemContext = thisMethods: ['moveUp']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("this.moveUp has no effect. It needs parentheses: this.moveUp()")
expect(aether.problems.errors[0].hint).toEqual("")
| true | Aether = require '../aether'
describe "Problem Test Suite", ->
describe "Transpile problems", ->
it "missing a closing quote: self.attack('Brak)", ->
code = """
self.attack('Brak)
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unterminated string constant")
expect(aether.problems.errors[0].hint).toEqual("Missing a quotation mark. Try `'Brak'`")
it "missing a closing quote: s = \"hi", ->
code = """
s = "hi
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unterminated string constant")
expect(aether.problems.errors[0].hint).toEqual("Missing a quotation mark. Try `\"hi\"`")
it "missing a closing quote: '", ->
code = """
'
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unterminated string constant")
expect(aether.problems.errors[0].hint).toEqual("Missing a quotation mark. Try `''`")
it "Unexpected indent", ->
code = """
x = 5
y = 7
"""
aether = new Aether language: 'python'
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("Code needs to line up.")
xit "missing a closing quote: s = \"hi", ->
# https://github.com/codecombat/aether/issues/113
code = """
var s = "hi
"""
aether = new Aether
aether.transpile code
expect(aether.problems.errors.length).toEqual(3)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unclosed string.")
expect(aether.problems.errors[0].hint).toEqual("You may be missing a closing quotation mark. Try `\"hi\"`")
it "Unexpected token 'self move'", ->
code = """
self move
"""
problemContext = thisMethods: [ 'moveUp']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveUp()`")
it "Unexpected token 'self self.move'", ->
code = """
self self.move
"""
problemContext = thisMethods: [ 'moveUp']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(2)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Delete extra `self`")
it "Unexpected token 'self.moveUp())'", ->
code = """
self.moveUp())
"""
problemContext = thisMethods: [ 'moveUp']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Delete extra `)`")
it "Unexpected token 'self.moveUp()self.moveDown()'", ->
code = """
self.moveUp()self.moveDown()
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Put each command on a separate line")
it "Capitalized loop", ->
code = """
Loop:
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext, simpleLoops: true
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Should be lowercase. Try `loop`")
it "Double var", ->
code = """
var enemy = 'PI:NAME:<NAME>END_PI';
var enemy = 'PI:NAME:<NAME>END_PI';
"""
aether = new Aether()
aether.transpile code
expect(aether.problems.warnings.length).toEqual(1)
expect(aether.problems.warnings[0].type).toEqual('transpile')
expect(aether.problems.warnings[0].message).toEqual("'enemy' is already defined.")
expect(aether.problems.warnings[0].hint).toEqual("Don't use the 'var' keyword for 'enemy' the second time.")
it "if without :", ->
code = """
if True
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'if True'. Try `if True:`")
it "indented if without :", ->
code = """
if True:
if True
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after ' if True'. Try ` if True:`")
it "if without test clause", ->
code = """
if :
x = 5
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Your if statement is missing a test clause. Try `if True:`")
it "else without : #1", ->
code = """
if False:
x = 5
else
x = 7
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
xit "else without : #2", ->
# https://github.com/differentmatt/filbert/issues/44
code = """
if False:
x = 5
else
x = 7
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
xit "else without : #3", ->
# https://github.com/differentmatt/filbert/issues/44
code = """
if False:
x = 5
else x = 7
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
it "else without : #4", ->
code = """
if True:
if False:
x = 7
else
x = 59
"""
problemContext = thisMethods: [ 'moveUp', 'moveDown']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected indent")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'else'. Try `else:`")
it "self.moveRight(", ->
code = """
self.moveRight(
"""
problemContext = {}
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Your parentheses must match.")
it "self.moveRight(()", ->
code = """
self.moveRight(()
"""
problemContext = {}
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('transpile')
expect(aether.problems.errors[0].message).toEqual("Unexpected token")
expect(aether.problems.errors[0].hint).toEqual("Your parentheses must match.")
describe "Runtime problems", ->
it "Should capture runtime problems", ->
# 0123456789012345678901234567
code = """
var methodName = 'explode';
this[methodName]();
"""
options =
thisValue: {}
problems: {jshint_W040: {level: "ignore"}}
aether = new Aether options
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toEqual 1
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'runtime'
expect(problem.level).toEqual 'error'
expect(problem.message).toMatch /has no method/
expect(problem.range?.length).toEqual 2
[start, end] = problem.range
expect(start.ofs).toEqual 28
expect(start.row).toEqual 1
expect(start.col).toEqual 0
expect(end.ofs).toEqual 46
expect(end.row).toEqual 1
expect(end.col).toEqual 18
expect(problem.message).toMatch /Line 2/
it "Shouldn't die on invalid crazy code", ->
code = """
if (true >== true){
true;}
"""
aether = new Aether {}
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toBeGreaterThan 0
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'transpile'
expect(problem.level).toEqual 'error'
it "Shouldn't die on more invalid crazy code", ->
code = """
var coins = {'emerald': []};
coins.'emerald'.push({type: 'emerald', bountyGold: 5});
"""
aether = new Aether {}
expect(-> aether.transpile(code)).not.toThrow()
aether.run()
expect(aether.problems.errors.length).toBeGreaterThan 0
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'transpile'
expect(problem.level).toEqual 'error'
it "Should hard-cap execution to break infinite loops.", ->
code = """
while(true) {
;
}
"""
aether = new Aether {executionLimit: 9001}
aether.transpile(code)
aether.run()
expect(aether.problems.errors.length).toBeGreaterThan 0
problem = aether.problems.errors[0]
expect(problem.type).toEqual 'runtime'
expect(problem.level).toEqual 'error'
it "Should hard-cap execution after a certain limit.", ->
code = """
for (var i = 0; i < 1000; ++i) {}
return 'mojambo';
"""
aether = new Aether {executionLimit: 500}
aether.transpile(code)
expect(aether.run()).toBeUndefined()
it "Shouldn't hard-cap execution too early.", ->
code = """
for (var i = 0; i < 1000; ++i) {}
return 'mojambo';
"""
aether = new Aether {executionLimit: 9001}
aether.transpile(code)
expect(aether.run()).toEqual 'mojambo'
it "Should error on undefined property accesses.", ->
code = """
var bar = 'bar';
var foobar = foo + bar;
return foobar;
"""
aether = new Aether functionName: 'foobarFactory'
aether.transpile(code)
expect(aether.run()).not.toEqual 'undefinedbar'
expect(aether.run()).toEqual undefined
expect(aether.problems.errors).not.toEqual []
it "Access prop on null", ->
code = """
def findFlag():
return None
flag = findFlag()
x = flag.pos
return x
"""
problemContext = {}
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
expect(aether.run()).toEqual null
expect(aether.problems.errors).not.toEqual []
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 4: Cannot read property 'pos' of null")
expect(aether.problems.errors[0].hint).toEqual("'flag' was null. Use a null check before accessing properties. Try `if flag:`")
describe "problemContext", ->
# NOTE: the problemContext tests are roughly in the order they're checked in the code
describe "General", ->
it "Call non-this undefined function x()", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """x()"""
problemContext = thisMethods: [ 'log', 'attack' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: x is not defined")
expect(aether.problems.errors[0].hint).toEqual("")
expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 1, row: 0, col: 1 } ])
it "loop is not defined", ->
code = "loop"
aether = new Aether language: "python", simpleLoops: true
aether.transpile code
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: loop is not defined")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'loop'. Try `loop:`")
it "loop is not defined w/ newline", ->
code = """
loop
x = 5
"""
aether = new Aether language: "python", simpleLoops: true
aether.transpile code
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: loop is not defined")
expect(aether.problems.errors[0].hint).toEqual("You are missing a ':' after 'loop'. Try `loop:`")
it "loop is not defined w/o simpleLoops", ->
code = "loop"
aether = new Aether language: "python"
aether.transpile code
method = aether.createMethod
aether.run()
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: loop is not defined")
expect(aether.problems.errors[0].hint).toEqual("")
describe "No function", ->
it "Exact thisMethods", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
attack
"""
problemContext = thisMethods: [ 'log', 'attack' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: attack is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.attack()`")
it "Case thisMethods", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
Attack
"""
problemContext = thisMethods: [ 'log', 'attack', 'tickle' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Attack is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.attack()`")
it "Exact commonThisMethods", ->
selfValue = {}
code = """
this.attack("Brak");
"""
problemContext = commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'attack'")
expect(aether.problems.errors[0].hint).toEqual("You do not have an item equipped with the attack skill.")
it "Exact commonThisMethods #2", ->
selfValue = {}
code = """
self.moveRight()
"""
problemContext = thisMethods: ['moveUp', 'moveLeft'], commonThisMethods: ['moveRight']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveRight'")
expect(aether.problems.errors[0].hint).toEqual("You do not have an item equipped with the moveRight skill.")
it "Case commonThisMethods", ->
selfValue = {}
code = """
self.moveup()
"""
problemContext = commonThisMethods: ['moveUp']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveup'")
expect(aether.problems.errors[0].hint).toEqual("Did you mean moveUp? You do not have an item equipped with that skill.")
it "Score commonThisMethods", ->
selfValue = {}
code = """
self.movright()
"""
problemContext = thisMethods: ['moveUp', 'moveLeft'], commonThisMethods: ['moveRight']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'movright'")
expect(aether.problems.errors[0].hint).toEqual("Did you mean moveRight? You do not have an item equipped with that skill.")
it "Score commonThisMethods #2", ->
selfValue = {}
code = """
this.movright()
"""
problemContext = thisMethods: ['moveUp', 'moveLeft'], commonThisMethods: ['moveRight']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'movright'")
expect(aether.problems.errors[0].hint).toEqual("Did you mean moveRight? You do not have an item equipped with that skill.")
describe "ReferenceError", ->
it "Exact stringReferences", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
self.attack(Brak)
"""
problemContext = stringReferences: ['Brak']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Brak is not defined")
expect(aether.problems.errors[0].hint).toEqual("Missing quotes. Try `\"Brak\"`")
it "Exact thisMethods", ->
selfValue = {}
code = """
moveleft
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: moveleft is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveLeft()`")
it "Exact thisMethods with range checks", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """attack()"""
problemContext = thisMethods: [ 'log', 'attack' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile(code)
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(2)
expect(aether.problems.errors[0].message).toEqual("Missing `self` keyword; should be `self.attack`.")
expect(aether.problems.errors[0].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 8, row: 0, col: 8 } ])
expect(aether.problems.errors[1].message).toEqual("Line 1: ReferenceError: attack is not defined")
expect(aether.problems.errors[1].range).toEqual([ { ofs: 0, row: 0, col: 0 }, { ofs: 6, row: 0, col: 6 } ])
it "Exact thisProperties", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
b = buildables
"""
problemContext = thisProperties: [ 'buildables' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: buildables is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.buildables`")
it "Case this value", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, moveRight: attack}
code = """
sElf.moveRight()
"""
problemContext = thisMethods: ['moveRight']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: sElf is not defined")
expect(aether.problems.errors[0].hint).toEqual("Uppercase or lowercase problem. Try `self`")
it "Case stringReferences", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
self.attack(brak)
"""
problemContext = stringReferences: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: brak is not defined")
expect(aether.problems.errors[0].hint).toEqual("Missing quotes. Try `\"Brak\"`")
it "Case thisMethods", ->
selfValue = {}
code = """
this.moveright();
"""
problemContext = thisMethods: ['moveUp', 'moveRight', 'moveLeft']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveright'")
expect(aether.problems.errors[0].hint).toEqual("Uppercase or lowercase problem. Try `this.moveRight()`")
it "Case thisProperties", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
b = Buildables
"""
problemContext = thisProperties: [ 'buildables' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Buildables is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.buildables`")
it "Score this value", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
elf.moveDown()
"""
problemContext = thisMethods: [ 'moveDown' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: elf is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self`")
it "Score stringReferences", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
self.attack(brOk)
"""
problemContext = stringReferences: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: brOk is not defined")
expect(aether.problems.errors[0].hint).toEqual("Missing quotes. Try `\"Brak\"`")
it "Score thisMethods", ->
selfValue = {}
code = """
self.moveEight()
"""
problemContext = thisMethods: ['moveUp', 'moveRight', 'moveLeft']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual("runtime")
expect(aether.problems.errors[0].message).toEqual("Line 1: Object #<Object> has no method 'moveEight'")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveRight()`")
it "Score thisMethods #2", ->
selfValue = {}
code = """
movleft
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: movleft is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveLeft()`")
it "Score thisMethods #3", ->
selfValue = {}
code = """
moveeft
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: moveeft is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveLeft()`")
it "Score thisMethods #4", ->
selfValue = {}
code = """
selfmoveright
"""
problemContext = thisMethods: ['moveRight', 'moveLeft', 'moveUp', 'moveDown']
aether = new Aether language: 'python', problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: selfmoveright is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveRight()`")
it "Score thisProperties", ->
history = []
log = (s) -> history.push s
attack = -> history.push 'attack'
selfValue = {say: log, attack: attack}
code = """
b = Bildaables
"""
problemContext = thisProperties: [ 'buildables' ]
aether = new Aether language: "python", problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: Bildaables is not defined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.buildables`")
it "Exact commonThisMethods", ->
selfValue = {}
code = """
attack()
"""
problemContext = thisMethods: [], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: attack is not defined")
expect(aether.problems.errors[0].hint).toEqual("You do not have an item equipped with the attack skill.")
it "Case commonThisMethods", ->
selfValue = {}
code = """
ATTACK()
"""
problemContext = thisMethods: [], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: ATTACK is not defined")
expect(aether.problems.errors[0].hint).toEqual("Did you mean attack? You do not have an item equipped with that skill.")
it "Score commonThisMethods", ->
selfValue = {}
code = """
atac()
"""
problemContext = thisMethods: [], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: ReferenceError: atac is not defined")
expect(aether.problems.errors[0].hint).toEqual("Did you mean attack? You do not have an item equipped with that skill.")
describe "Missing property", ->
it "self.self.moveUp()", ->
selfValue = {}
code = """
self.self.moveUp()
"""
problemContext = thisMethods: ['moveUp'], commonThisMethods: ['attack']
aether = new Aether problemContext: problemContext, language: 'python'
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].type).toEqual('runtime')
expect(aether.problems.errors[0].message).toEqual("Line 1: Cannot call method 'moveUp' of undefined")
expect(aether.problems.errors[0].hint).toEqual("Try `self.moveUp()`")
describe "transforms.makeCheckIncompleteMembers", ->
it "Incomplete 'this' and available method", ->
selfValue = {}
code = """
this.moveUp
"""
problemContext = thisMethods: ['moveUp']
aether = new Aether problemContext: problemContext
aether.transpile code
method = aether.createMethod selfValue
aether.run method
expect(aether.problems.errors.length).toEqual(1)
expect(aether.problems.errors[0].message).toEqual("this.moveUp has no effect. It needs parentheses: this.moveUp()")
expect(aether.problems.errors[0].hint).toEqual("")
|
[
{
"context": " <foo> - performs bashshell command\n#\n# Author:\n# Leon van Kammen / Coderofsalvation\n#\nfs = require(\"fs\")\n\nprocess.",
"end": 392,
"score": 0.9995593428611755,
"start": 377,
"tag": "NAME",
"value": "Leon van Kammen"
}
] | node_modules/hubot-script-shellcmd/src/shellcmd.coffee | Viper702/riley-reid | 46 | # Description:
# List/Execute shellcommands from a specified folder.
#
# Dependencies:
# None
#
# Configuration
# HUBOT_SHELLCMD="bash/handler" (cp the example 'bash'-directory to your root/runtime folder)
#
# where 'handler' is a shellscript like:
#
# Commands:
# Hubot shell - list (bash)shell commands
# Hubot shell <foo> - performs bashshell command
#
# Author:
# Leon van Kammen / Coderofsalvation
#
fs = require("fs")
process.env.HUBOT_SHELLCMD = "bash/handler" if not process.env.HUBOT_SHELLCMD
if not fs.existsSync(process.env.HUBOT_SHELLCMD)
console.log process.env.HUBOT_SHELLCMD+" not found in hubot working dir..defaulting to example handler at "+__dirname+"/../bash/handler"
process.env.HUBOT_SHELLCMD = __dirname+"/../bash/handler"
process.env.HUBOT_SHELLCMD_KEYWORD = "shell" if not process.env.HUBOT_SHELLCMD_KEYWORD
module.exports = (robot) ->
run_cmd = (cmd, args, envs, cb ) ->
console.log "spawn!"
spawn = require("child_process").spawn
opts =
env: envs
child = spawn(cmd, args, opts)
child.stdout.on "data", (buffer) -> cb buffer.toString()
child.stderr.on "data", (buffer) -> cb buffer.toString()
#child.stdout.on "end", -> cb resp
robot.respond "/"+process.env.HUBOT_SHELLCMD_KEYWORD+"$/i", (msg) ->
cmd = process.env.HUBOT_SHELLCMD;
envs = process.env;
envs["HUBOT_USER_" + key.toUpperCase()] = value for key, value of msg.envelope.user
run_cmd cmd, [], envs, (text) -> msg.send text
robot.respond "/"+process.env.HUBOT_SHELLCMD_KEYWORD+" (.*)/i", (msg) ->
msg.match[0] = msg.match[0].replace(/^[a-z0-9]+$/i);
msg.match.shift();
args = msg.match[0].split(" ");
cmd = process.env.HUBOT_SHELLCMD;
envs = process.env;
envs["HUBOT_USER_" + key.toUpperCase()] = value for key, value of msg.envelope.user
run_cmd cmd, args, envs, (text) -> msg.send text.replace("\n","")
| 45876 | # Description:
# List/Execute shellcommands from a specified folder.
#
# Dependencies:
# None
#
# Configuration
# HUBOT_SHELLCMD="bash/handler" (cp the example 'bash'-directory to your root/runtime folder)
#
# where 'handler' is a shellscript like:
#
# Commands:
# Hubot shell - list (bash)shell commands
# Hubot shell <foo> - performs bashshell command
#
# Author:
# <NAME> / Coderofsalvation
#
fs = require("fs")
process.env.HUBOT_SHELLCMD = "bash/handler" if not process.env.HUBOT_SHELLCMD
if not fs.existsSync(process.env.HUBOT_SHELLCMD)
console.log process.env.HUBOT_SHELLCMD+" not found in hubot working dir..defaulting to example handler at "+__dirname+"/../bash/handler"
process.env.HUBOT_SHELLCMD = __dirname+"/../bash/handler"
process.env.HUBOT_SHELLCMD_KEYWORD = "shell" if not process.env.HUBOT_SHELLCMD_KEYWORD
module.exports = (robot) ->
run_cmd = (cmd, args, envs, cb ) ->
console.log "spawn!"
spawn = require("child_process").spawn
opts =
env: envs
child = spawn(cmd, args, opts)
child.stdout.on "data", (buffer) -> cb buffer.toString()
child.stderr.on "data", (buffer) -> cb buffer.toString()
#child.stdout.on "end", -> cb resp
robot.respond "/"+process.env.HUBOT_SHELLCMD_KEYWORD+"$/i", (msg) ->
cmd = process.env.HUBOT_SHELLCMD;
envs = process.env;
envs["HUBOT_USER_" + key.toUpperCase()] = value for key, value of msg.envelope.user
run_cmd cmd, [], envs, (text) -> msg.send text
robot.respond "/"+process.env.HUBOT_SHELLCMD_KEYWORD+" (.*)/i", (msg) ->
msg.match[0] = msg.match[0].replace(/^[a-z0-9]+$/i);
msg.match.shift();
args = msg.match[0].split(" ");
cmd = process.env.HUBOT_SHELLCMD;
envs = process.env;
envs["HUBOT_USER_" + key.toUpperCase()] = value for key, value of msg.envelope.user
run_cmd cmd, args, envs, (text) -> msg.send text.replace("\n","")
| true | # Description:
# List/Execute shellcommands from a specified folder.
#
# Dependencies:
# None
#
# Configuration
# HUBOT_SHELLCMD="bash/handler" (cp the example 'bash'-directory to your root/runtime folder)
#
# where 'handler' is a shellscript like:
#
# Commands:
# Hubot shell - list (bash)shell commands
# Hubot shell <foo> - performs bashshell command
#
# Author:
# PI:NAME:<NAME>END_PI / Coderofsalvation
#
fs = require("fs")
process.env.HUBOT_SHELLCMD = "bash/handler" if not process.env.HUBOT_SHELLCMD
if not fs.existsSync(process.env.HUBOT_SHELLCMD)
console.log process.env.HUBOT_SHELLCMD+" not found in hubot working dir..defaulting to example handler at "+__dirname+"/../bash/handler"
process.env.HUBOT_SHELLCMD = __dirname+"/../bash/handler"
process.env.HUBOT_SHELLCMD_KEYWORD = "shell" if not process.env.HUBOT_SHELLCMD_KEYWORD
module.exports = (robot) ->
run_cmd = (cmd, args, envs, cb ) ->
console.log "spawn!"
spawn = require("child_process").spawn
opts =
env: envs
child = spawn(cmd, args, opts)
child.stdout.on "data", (buffer) -> cb buffer.toString()
child.stderr.on "data", (buffer) -> cb buffer.toString()
#child.stdout.on "end", -> cb resp
robot.respond "/"+process.env.HUBOT_SHELLCMD_KEYWORD+"$/i", (msg) ->
cmd = process.env.HUBOT_SHELLCMD;
envs = process.env;
envs["HUBOT_USER_" + key.toUpperCase()] = value for key, value of msg.envelope.user
run_cmd cmd, [], envs, (text) -> msg.send text
robot.respond "/"+process.env.HUBOT_SHELLCMD_KEYWORD+" (.*)/i", (msg) ->
msg.match[0] = msg.match[0].replace(/^[a-z0-9]+$/i);
msg.match.shift();
args = msg.match[0].split(" ");
cmd = process.env.HUBOT_SHELLCMD;
envs = process.env;
envs["HUBOT_USER_" + key.toUpperCase()] = value for key, value of msg.envelope.user
run_cmd cmd, args, envs, (text) -> msg.send text.replace("\n","")
|
[
{
"context": "'\n\nclass Palsu extends nodext.Extension\n name: 'Palsu'\n config: {}\n\n makeDir: (dir, cb) ->\n fs.sta",
"end": 124,
"score": 0.604383111000061,
"start": 120,
"tag": "NAME",
"value": "alsu"
}
] | extension/palsu/main.coffee | bergie/ViePalsu | 5 | nodext = require 'nodext'
express = require 'express'
fs = require 'fs'
class Palsu extends nodext.Extension
name: 'Palsu'
config: {}
makeDir: (dir, cb) ->
fs.stat dir, (err, stat) ->
return cb() unless err
fs.mkdir dir, 0o0777, cb
configure: (server) ->
@makeDir "#{__dirname}/static/js", ->
console.log "Created static JS directory"
server.use "/static/#{@name}", express.compiler
src: "#{__dirname}/staticSrc"
dest: "#{__dirname}/static"
enable: [
'coffeescript'
]
server.use "/static/#{@name}", express.static "#{__dirname}/static"
server.use express.cookieParser()
server.use express.bodyParser()
sockets = require './sockets'
sockets.registerSockets server, @config
registerRoutes: (server) ->
routes = require './routes'
routes.registerRoutes server, @config.urlPrefix, @config.idPrefix
exports.extension = Palsu
| 118093 | nodext = require 'nodext'
express = require 'express'
fs = require 'fs'
class Palsu extends nodext.Extension
name: 'P<NAME>'
config: {}
makeDir: (dir, cb) ->
fs.stat dir, (err, stat) ->
return cb() unless err
fs.mkdir dir, 0o0777, cb
configure: (server) ->
@makeDir "#{__dirname}/static/js", ->
console.log "Created static JS directory"
server.use "/static/#{@name}", express.compiler
src: "#{__dirname}/staticSrc"
dest: "#{__dirname}/static"
enable: [
'coffeescript'
]
server.use "/static/#{@name}", express.static "#{__dirname}/static"
server.use express.cookieParser()
server.use express.bodyParser()
sockets = require './sockets'
sockets.registerSockets server, @config
registerRoutes: (server) ->
routes = require './routes'
routes.registerRoutes server, @config.urlPrefix, @config.idPrefix
exports.extension = Palsu
| true | nodext = require 'nodext'
express = require 'express'
fs = require 'fs'
class Palsu extends nodext.Extension
name: 'PPI:NAME:<NAME>END_PI'
config: {}
makeDir: (dir, cb) ->
fs.stat dir, (err, stat) ->
return cb() unless err
fs.mkdir dir, 0o0777, cb
configure: (server) ->
@makeDir "#{__dirname}/static/js", ->
console.log "Created static JS directory"
server.use "/static/#{@name}", express.compiler
src: "#{__dirname}/staticSrc"
dest: "#{__dirname}/static"
enable: [
'coffeescript'
]
server.use "/static/#{@name}", express.static "#{__dirname}/static"
server.use express.cookieParser()
server.use express.bodyParser()
sockets = require './sockets'
sockets.registerSockets server, @config
registerRoutes: (server) ->
routes = require './routes'
routes.registerRoutes server, @config.urlPrefix, @config.idPrefix
exports.extension = Palsu
|
[
{
"context": ")\n\t\tprotoNode = vert.next()\n\t\tkey = protoNode.key.split(\"/\").pop().split(\"#\").pop()\n\t\tnode[key] = protoNode.value\n\t\tnode[\"name\"] = ",
"end": 2427,
"score": 0.809501588344574,
"start": 2396,
"tag": "KEY",
"value": "split(\"/\").pop().split(\"#\").pop"
}
] | app/assets/javascripts/filters.coffee | guidocecilio/discover-smarter | 2 | # Just a log helper
log = (args...) ->
console.log.apply console, args if console.log?
String::alphaNum = ->
@.replace /[^a-zA-Z0-9]/g, ''
String::validURL = ->
pattern = new RegExp("/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/")
isUrl = pattern.test(@)
log "that " + @ + " is a URL is " + isUrl
!isUrl
String::hashCode = ->
hash = 0
i = undefined
chr = undefined
len = undefined
return hash if @length is 0
i = 0
len = @length
while i < len
chr = @charCodeAt(i)
hash = ((hash << 5) - hash) + chr
hash |= 0 # Convert to 32bit integer
i++
hash
Array::merge = (other) -> Array::push.apply @, other
GremlinGraph::searchForItem = (searchKey) ->
console.log "Searching for: " + searchKey
graph = @processPipeline @v(searchKey)
for node in graph.nodes
log "important node" + node.label
node["isTarget"] = true
bigger = @v(searchKey).both()
@processPipeline bigger, graph
edges = @v(searchKey).bothE()
@processPipeline edges, graph
# graph.nodes = _.union coreNode, outs
GremlinGraph::getOne = (searchKey) ->
@processPipeline @v(searchKey)
GremlinGraph::processPipeline = (pipeline, graph) ->
graph = {nodes:[], links:[]} if graph is undefined
@listOfIds = new Array()
while pipeline.hasNext()
item = pipeline.next()
if item instanceof Array
for element in item
@processPipeItem(element , graph)
else
@processPipeItem(item , graph)
graph
GremlinGraph::processPipeItem = (result, graph) ->
# get vertices
if (result.constructor.name is "HDTVertex")
unless result.getPropertyMap() is undefined
if result.getPropertyMap().hasNext()
id = result.getPropertyMap().next().subject
found = $.inArray id, @listOfIds
if found == -1
graph.nodes.push @vertexToNode result
@listOfIds.push id
# get edges
if (result.constructor.name is "HDTEdge")
graph.links.push @edgeToLink result
GremlinGraph::addSmartURI = (node) ->
node["smartURI"] = @hdt.dictionary.idToString(node.id, HDT.DictionarySectionRole.SUBJECT)
node
GremlinGraph::vertexToNode = (vertex) ->
id = vertex.getPropertyMap().next().subject
node =
id: id
hdtid : id
group : 1
@addSmartURI node
node["type"] = @hdt.search(node["smartURI"],"http://www.w3.org/1999/02/22-rdf-syntax-ns#type","").next().object
vert = vertex.getPropertyMap()
while vert.hasNext()
protoNode = vert.next()
key = protoNode.key.split("/").pop().split("#").pop()
node[key] = protoNode.value
node["name"] = node[key] if key is "label"
node
GremlinGraph::edgeToLink = (hdtEdge) ->
{source: hdtEdge.triple.subject, target: hdtEdge.triple.object, weight:3, label: hdtEdge.getLabel().split("/").pop().split("#").pop()}
############################################################
# Utility classes for managing the color that
############################################################
class BagItem
constructor:(@name, @colour, @icon, @iconhelper) ->
class RdfClassTypes
constructor:() ->
@classBags = []
@classBags.push(new BagItem "undefined", "#FF6B6B", """\ue085""", "question-sign")
@classBags.push(new BagItem "Document", "#4ECDC4", """\ue022""", "file")
@classBags.push(new BagItem "Location", "#556270", """\ue062""", "map-marker")
@classBags.push(new BagItem "Organization", "#C44D58", """\ue184""", "tower")
@classBags.push(new BagItem "Person", "#C7F464", """\ue008""", "user")
getItem:(name) ->
item = _.find @classBags, (item) -> name is item.name
if item is undefined then @classBags[0] else item
##############################################################################
# manages union operations in list
#############################################################################
class UnionSet
joinNodes: (graph, memo) ->
_.uniq _.union(graph.nodes, memo.nodes), false, (item, key, hdtid) ->
item.hdtid
joinLinks: (graph, memo) ->
links = _.union(graph.links, memo.links)
##############################################################################
# manages intersection operations in list
#############################################################################
class IntersectSet
joinNodes: (graph, memo) =>
@nodes = @intersection(graph.nodes, memo.nodes)
getTargetLinksInNodes:(links) =>
_.flatten _.map @nodes, (node) => _.filter links, (link) -> node.hdtid is link.target
getSourceLinksInNodes:(links) =>
_.flatten _.map @nodes, (node) => _.filter links, (link) -> node.hdtid is link.source
joinLinks: (graph, memo) =>
@getSourceLinksInNodes(@getTargetLinksInNodes(graph.links.concat(memo.links)))
push:(obj, important, c) ->
important.push obj.hdtid
c.push obj
intersection: (a, b) ->
c = []
@important = []
for inner in a
if (inner.isTarget?) and (inner.hdtid not in @important)
@push inner, @important, c
else
for outer in b
c.push inner if (inner.hdtid is outer.hdtid)
if (outer.isTarget?) and (outer.hdtid not in @important)
@push outer, @important, c
c
##############################################################################
# manages list of filters and can run union or intersection operations on them
#############################################################################
class SetManager
constructor:(@typefilter) ->
@search = []
@classTypes = new RdfClassTypes()
@typesInfo =
categoryList : {}
icons : {}
iconChars : {}
colors: {}
showTargetNodes : true
union:() ->
@mergeSets(new UnionSet())
intersection:() ->
@mergeSets(new IntersectSet())
mergeSets:(setOperation) =>
targetnodes = []
updatedGraph = _.reduce @search, ((memo, searchItem) ->
graph = searchItem.asGraph()
result = {nodes:[], links:[]}
if memo.nodes.length > 0 then result.nodes = setOperation.joinNodes( graph , memo) else result.nodes = graph.nodes
if memo.links.length > 0 then result.links = setOperation.joinLinks( graph , memo) else result.links = graph.links
result
), {nodes:[], links:[]}
targetnodes = setOperation.important
updatedGraph.links = _.uniq updatedGraph.links, false, (edge) ->
edge.target + edge.source
addIndex(updatedGraph)
_.each updatedGraph.nodes, (node) =>
@addSmartType(node)
node.visible = (node.smartType not in @typefilter) or (node.isTarget? and @typesInfo.showTargetNodes )
_.uniq updatedGraph.links, false, (link) =>
srcnode =_.find updatedGraph.nodes, (node) -> node.hdtid == link.source
trgnode =_.find updatedGraph.nodes, (node) -> node.hdtid == link.target
if srcnode[link.label] == undefined
srcnode[link.label] = trgnode.label
else
if srcnode[link.label].indexOf(trgnode.label) < 0
srcnode[link.label] = srcnode[link.label] + ", " + trgnode.label
if trgnode[link.label] == undefined
trgnode[link.label] = srcnode.label
else
if trgnode[link.label].indexOf(srcnode.label) < 0
trgnode[link.label] = trgnode[link.label] + ", " + srcnode.label
#log "updatedGraph!"
#log updatedGraph
updatedGraph
add:(searchItem) ->
@search.push (searchItem)
remove:(item) =>
# item has expected structure of op and opand
log "removing search item " + item.op + ", " + item.opand + "list [" + @search.length + "]..."
@search = _.reject @search, (searchItem) -> searchItem.match( item.op, item.opand)
log "removed search item " + item.opand + ", list is now [" + @search.length + "]"
get:(id) ->
_.find @search, (item) -> item.id is id
addIndex = (updatedGraph) ->
log "updating link..."
@idList = _.pluck updatedGraph.nodes, 'id'
updatedGraph.links = _.filter updatedGraph.links, (link) ->
@idList.indexOf(link.source) >= 0 and @idList.indexOf(link.target) >= 0
updatedGraph.nodes = _.uniq updatedGraph.nodes
updatedGraph
addSmartType: (node) =>
unless @typesInfo.categoryList[node.type]?
node.smartType = "Thing"
classType = @classTypes.getItem(node.smartType)
node.smartColour = classType.colour
node.smartIcon = classType.icon
node.smartIconHelper = classType.iconhelper
else
node.smartType = @typesInfo.categoryList[node.type]
node.smartColour = @typesInfo.colors[node.smartType]
node.smartIcon = @typesInfo.iconChars[node.smartType]
node.smartIconHelper = @typesInfo.icons[node.smartType]
node
##############################################################################
# manages url string
#############################################################################
class UriManager
constructor:(@setManager) ->
log "URI Manager created"
updateUri:() =>
filters = _.map @setManager.search, (item) ->
item.searchString
window.location.href = "#?filters=" + encodeURIComponent(filters.join ",")
#####################################################################################
# handles all events related to filters
# is responsible for creating and managing the filters, and acts as a "model" for
# other datasets to use
#####################################################################################
class smarterData.FilterManager
constructor:(@hdt) ->
_.extend @, Backbone.Events
@count = 1
@typefilter = []
@setManager = new SetManager(@typefilter)
@UriManager = new UriManager(@setManager)
@gremlinGraph = new GremlinGraph(@hdt)
@localStoreKey= "JSON"
@firstpass = true
# manages search space list
###########
# Events
###########
#------------------------
# Search events
#------------------------
$(document).on "click", ".facet-link", (e) =>
op = $(e.currentTarget).data("category")
operand = $(e.currentTarget).data("facet")
searchitem = _.last @setManager.search
searchitem.addFilter(op, operand)
@
$(document).on "change", "#search", (e, searchText) =>
log "search has changed, now updating graph"
e.stopImmediatePropagation()
if searchText?
@addSearch(searchText)
@updateGraph()
# actually takes value from change in URI
$(document).on "updatefilter", "#search", (e, filters) =>
# ensure filter not already in application
if @firstpass
_.each filters, (filter) =>
if isNaN(filter) then @addSearch(filter) else @addSearch(Number(filter))
, @
@updateGraph()
$(document).on "nodechosen", "#search", (e, searchText) =>
if searchText?
@addSearch(Number(searchText))
@updateGraph()
$(document).on "updategraph", "#search", (e, json) =>
if json?
@addGraph(json?.label,'glyphicon-filter',json?.graph)
@updateGraph()
$(document).on "intersect", "#search", (e, item) =>
@moveSearch(item.draggedId, item.targetId)
@updateGraph()
$(document).on "touchgraph", "#search", (e, json) =>
@updateGraph()
$(document).on "add-doc", "#search", (e, json) =>
log "adding doc to filters"
@addGraph("Document",'glyphicon-file',json)
@updateGraph()
#------------------------
# Type Filter events
#------------------------
$(document).on "add-filter", "#search", (e, type) =>
@typefilter.push(type)
@updateGraph()
$(document).on "remove-filter", "#search", (e, type) =>
index = @typefilter.indexOf(type)
if index > - 1
delete @typefilter[@typefilter.indexOf(type)]
@updateGraph()
$(document).on "typelist", "#search", (e, json) =>
@setManager.typesInfo = json
console.log @setManager.typesInfo
$(document).on "refrish-view", "#search", (e) =>
@updateGraph()
# used for final part of pivot search
$(document).on "searchForItems", "#search", (e, json) =>
pivotGraph =
nodes : []
links : []
idz = new Array()
for subject in json.subjects
unless subject is undefined
tempg = @gremlinGraph.searchForItem subject
#found = $.inArray tempg.id, idz
#if found == -1
pivotGraph.nodes.merge tempg.nodes
pivotGraph.links.merge tempg.links
#idz.push tempg.id
unless pivotGraph is undefined
pivotGraph.nodes = _.uniq pivotGraph.nodes, false, (item, key, id) ->
item.id
pivotGraph.links = _.uniq pivotGraph.links, false, (edge) ->
edge.target + edge.source
@addGraph(json.label,'glyphicon-filter',pivotGraph)
@updateGraph()
$(document).on "queryExecuted", "#execute", (e, pipeline) =>
log "gremlin pipeline ready for filter"
@addGremlinPipeline(pipeline) unless pipeline is undefined
@updateGraph()
log "Filter created."
$('#search').trigger('appready');
#------------------------
# updates graph after search is made
#------------------------
updateGraph: =>
@firstpass = false
@UriManager.updateUri()
$('#search').trigger "begob", @setManager.union()
# sets one of many seach spaces. allows filtering
addSearch: (searchKey) =>
log "adding search for term" + searchKey
unless searchKey is undefined
# get if @search item.id exists - if it does don't add it
ids = _.pluck @setManager.search, 'opand'
unless _.include ids, searchKey
searchItem = new SearchItem(searchKey, @gremlinGraph, @typefilter)
searchItem.on "labelremoved", @removeSearch
@setManager.add (searchItem)
# sets one of many seach spaces. allows filtering
addGremlinPipeline: (pipeline) =>
unless pipeline is undefined
gremAsJsonGraph = @gremlinGraph.processPipeline pipeline
pipeline = {}
@addGraph "Gremlin Query", "glyphicon-th-list", gremAsJsonGraph
addGraph: (name, icon, gremAsJsonGraph) =>
log "adding new gremlin graph"
graphItem = new GraphItem(name, icon, gremAsJsonGraph, @typefilter)
graphItem.on "labelremoved", @removeSearch
@setManager.add (graphItem)
removeSearch: (item) =>
@setManager.remove (item)
@updateGraph()
$("#search").trigger("change")
moveSearch: (draggedId, targetId) =>
log "dragged ID" + draggedId + ", target Id" + targetId
draggedSearchItem = @setManager.get(draggedId)
targetSearchItem = @setManager.get(targetId)
@setManager.remove (draggedSearchItem )
targetSearchItem.intersect(draggedSearchItem)
##############################
# Super class to all labels
# that are displayed
##############################
class SimpleLabel
constructor: (@op, @opand, @parentTag, @typefilter) ->
_.extend @, Backbone.Events
if isNaN @opand then @id = @opand.alphaNum() + @opand.alphaNum() else @id = @opand
@closer = ".close"
@template = """
<div id="<%= id %>" class="<%=cssstuff%>" draggable="true" alt="<%= opand %>" ><span class="glyphicon <%=icon%>"></span><%= shorttext %><a class="close">×</a>
</div>
"""
@setManager = new SetManager(@typefilter) if @typefilter?
$(document).on "click", "#" + @id + " " + @closer, (e) =>
@remove()
"ok"
render: () =>
if isNaN @opand
if @opand is "Gremlin Query"
@shorttext = "Gremlin Query"
else if @opand.validURL()
@shorttext = @opand.substr(@opand.lastIndexOf('/') + 1)
else
xx = @gremlinGraph.getOne(Number(@opand))
@shorttext = xx.nodes[0].label
else
xx = @gremlinGraph.getOne(Number(@opand))
@shorttext = xx.nodes[0].label
templateStr =_.template @template, id: @id, op: @op, opand: @opand, shorttext: @shorttext, cssstuff: @cssstuff ? "well well-sm col-sm-3", icon: @icon ? "glyphicon-search"
$(@parentTag).append (templateStr)
# drag drop events
$(document).on "dragstart", "#"+@id, (e) =>
dataTransfer = e.originalEvent.dataTransfer
dataTransfer.effectAllowed = "copy"
dataTransfer.setData "DraggedElementsId", @id
log "dragging that thang"
$(document).on "dragenter", "#"+@id, (e) ->
e.preventDefault();
this.classList.add('over')
$(document).on "dragleave", "#"+@id, (e) ->
e.preventDefault();
this.classList.remove('over')
$(document).on "dragover", "#"+@id, (e) =>
e.preventDefault();
$(document).on "drop dragdrop", "#"+@id, (e) =>
#ask container to move this down a level
draggedId = e.originalEvent.dataTransfer.getData( "DraggedElementsId")
$("#search").trigger "intersect", {draggedId: draggedId, targetId: @id}
removeElement: () =>
$("#" + @id).remove()
remove: () =>
$("#" + @id).remove()
@jsonGraph = {nodes:[], links:[]}
@.trigger "labelremoved", {op: @op, opand: @opand}
match:(filterOpz, filterOperandz) ->
match = (filterOpz == @op) && (filterOperandz == @opand)
log "matching" + @opand + " with " + filterOperandz + " is " + match
match
processGraph: () ->
log "do nothing"
asGraph: () ->
@setManager.intersection()
intersect: (graphToIntersect) =>
graphToIntersect.removeElement()
graphToIntersect.parentTag = "#"+ @id
graphToIntersect.cssstuff = "label label-primary"
@setManager.add(graphToIntersect)
graphToIntersect.render()
#@render()
##############################
# helps with the search
##############################
class GraphItem extends SimpleLabel
constructor: (@searchString, @icon, @jsonGraph, @typefilter) ->
super("searchString", @searchString, "#smartfilters", @typefilter)
@setManager.add(@processGraph())
@render()
processGraph: () ->
log "process graph"
si = new SimpleItem(@jsonGraph)
si
##############################
# helps with the search
##############################
class SimpleItem extends SimpleLabel
constructor: (@jsonGraph) ->
super("searchString", "not for display", "#smartfilters")
asGraph: () ->
@jsonGraph
##############################
# helps with the search
##############################
class SearchItem extends SimpleLabel
constructor: (@searchString, @gremlinGraph, @typefilter) ->
super("searchString",@searchString, "#smartfilters", @typefilter)
@jsonGraph = {nodes:[], links:[]}
@jsonGraph = @gremlinGraph.searchForItem(@searchString) ? {nodes:[], links:[]}
@setManager.add(@processGraph())
@render()
processGraph: () ->
log "process search item"
@jsonGraph = @gremlinGraph.searchForItem(@searchString) ? {nodes:[], links:[]}
si = new SimpleItem(@jsonGraph)
si
##############################
# helps with the search
##############################
class QueryItem extends SimpleLabel
constructor: (@pipeline, @gremlinGraph, @typefilter) ->
super("searchString","Gremlin Query", "#smartfilters", @typefilter)
log "pipeline to be rendered"
log pipeline
@icon = "glyphicon-th-list"
@setManager.add(processGraph())
@render()
processGraph: () ->
log "process queryitem"
@jsonGraph = @gremlinGraph.processPipeline(@pipeline) ? {nodes:[], links:[]}
si = new SimpleItem(@jsonGraph)
si
| 53773 | # Just a log helper
log = (args...) ->
console.log.apply console, args if console.log?
String::alphaNum = ->
@.replace /[^a-zA-Z0-9]/g, ''
String::validURL = ->
pattern = new RegExp("/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/")
isUrl = pattern.test(@)
log "that " + @ + " is a URL is " + isUrl
!isUrl
String::hashCode = ->
hash = 0
i = undefined
chr = undefined
len = undefined
return hash if @length is 0
i = 0
len = @length
while i < len
chr = @charCodeAt(i)
hash = ((hash << 5) - hash) + chr
hash |= 0 # Convert to 32bit integer
i++
hash
Array::merge = (other) -> Array::push.apply @, other
GremlinGraph::searchForItem = (searchKey) ->
console.log "Searching for: " + searchKey
graph = @processPipeline @v(searchKey)
for node in graph.nodes
log "important node" + node.label
node["isTarget"] = true
bigger = @v(searchKey).both()
@processPipeline bigger, graph
edges = @v(searchKey).bothE()
@processPipeline edges, graph
# graph.nodes = _.union coreNode, outs
GremlinGraph::getOne = (searchKey) ->
@processPipeline @v(searchKey)
GremlinGraph::processPipeline = (pipeline, graph) ->
graph = {nodes:[], links:[]} if graph is undefined
@listOfIds = new Array()
while pipeline.hasNext()
item = pipeline.next()
if item instanceof Array
for element in item
@processPipeItem(element , graph)
else
@processPipeItem(item , graph)
graph
GremlinGraph::processPipeItem = (result, graph) ->
# get vertices
if (result.constructor.name is "HDTVertex")
unless result.getPropertyMap() is undefined
if result.getPropertyMap().hasNext()
id = result.getPropertyMap().next().subject
found = $.inArray id, @listOfIds
if found == -1
graph.nodes.push @vertexToNode result
@listOfIds.push id
# get edges
if (result.constructor.name is "HDTEdge")
graph.links.push @edgeToLink result
GremlinGraph::addSmartURI = (node) ->
node["smartURI"] = @hdt.dictionary.idToString(node.id, HDT.DictionarySectionRole.SUBJECT)
node
GremlinGraph::vertexToNode = (vertex) ->
id = vertex.getPropertyMap().next().subject
node =
id: id
hdtid : id
group : 1
@addSmartURI node
node["type"] = @hdt.search(node["smartURI"],"http://www.w3.org/1999/02/22-rdf-syntax-ns#type","").next().object
vert = vertex.getPropertyMap()
while vert.hasNext()
protoNode = vert.next()
key = protoNode.key.<KEY>()
node[key] = protoNode.value
node["name"] = node[key] if key is "label"
node
GremlinGraph::edgeToLink = (hdtEdge) ->
{source: hdtEdge.triple.subject, target: hdtEdge.triple.object, weight:3, label: hdtEdge.getLabel().split("/").pop().split("#").pop()}
############################################################
# Utility classes for managing the color that
############################################################
class BagItem
constructor:(@name, @colour, @icon, @iconhelper) ->
class RdfClassTypes
constructor:() ->
@classBags = []
@classBags.push(new BagItem "undefined", "#FF6B6B", """\ue085""", "question-sign")
@classBags.push(new BagItem "Document", "#4ECDC4", """\ue022""", "file")
@classBags.push(new BagItem "Location", "#556270", """\ue062""", "map-marker")
@classBags.push(new BagItem "Organization", "#C44D58", """\ue184""", "tower")
@classBags.push(new BagItem "Person", "#C7F464", """\ue008""", "user")
getItem:(name) ->
item = _.find @classBags, (item) -> name is item.name
if item is undefined then @classBags[0] else item
##############################################################################
# manages union operations in list
#############################################################################
class UnionSet
joinNodes: (graph, memo) ->
_.uniq _.union(graph.nodes, memo.nodes), false, (item, key, hdtid) ->
item.hdtid
joinLinks: (graph, memo) ->
links = _.union(graph.links, memo.links)
##############################################################################
# manages intersection operations in list
#############################################################################
class IntersectSet
joinNodes: (graph, memo) =>
@nodes = @intersection(graph.nodes, memo.nodes)
getTargetLinksInNodes:(links) =>
_.flatten _.map @nodes, (node) => _.filter links, (link) -> node.hdtid is link.target
getSourceLinksInNodes:(links) =>
_.flatten _.map @nodes, (node) => _.filter links, (link) -> node.hdtid is link.source
joinLinks: (graph, memo) =>
@getSourceLinksInNodes(@getTargetLinksInNodes(graph.links.concat(memo.links)))
push:(obj, important, c) ->
important.push obj.hdtid
c.push obj
intersection: (a, b) ->
c = []
@important = []
for inner in a
if (inner.isTarget?) and (inner.hdtid not in @important)
@push inner, @important, c
else
for outer in b
c.push inner if (inner.hdtid is outer.hdtid)
if (outer.isTarget?) and (outer.hdtid not in @important)
@push outer, @important, c
c
##############################################################################
# manages list of filters and can run union or intersection operations on them
#############################################################################
class SetManager
constructor:(@typefilter) ->
@search = []
@classTypes = new RdfClassTypes()
@typesInfo =
categoryList : {}
icons : {}
iconChars : {}
colors: {}
showTargetNodes : true
union:() ->
@mergeSets(new UnionSet())
intersection:() ->
@mergeSets(new IntersectSet())
mergeSets:(setOperation) =>
targetnodes = []
updatedGraph = _.reduce @search, ((memo, searchItem) ->
graph = searchItem.asGraph()
result = {nodes:[], links:[]}
if memo.nodes.length > 0 then result.nodes = setOperation.joinNodes( graph , memo) else result.nodes = graph.nodes
if memo.links.length > 0 then result.links = setOperation.joinLinks( graph , memo) else result.links = graph.links
result
), {nodes:[], links:[]}
targetnodes = setOperation.important
updatedGraph.links = _.uniq updatedGraph.links, false, (edge) ->
edge.target + edge.source
addIndex(updatedGraph)
_.each updatedGraph.nodes, (node) =>
@addSmartType(node)
node.visible = (node.smartType not in @typefilter) or (node.isTarget? and @typesInfo.showTargetNodes )
_.uniq updatedGraph.links, false, (link) =>
srcnode =_.find updatedGraph.nodes, (node) -> node.hdtid == link.source
trgnode =_.find updatedGraph.nodes, (node) -> node.hdtid == link.target
if srcnode[link.label] == undefined
srcnode[link.label] = trgnode.label
else
if srcnode[link.label].indexOf(trgnode.label) < 0
srcnode[link.label] = srcnode[link.label] + ", " + trgnode.label
if trgnode[link.label] == undefined
trgnode[link.label] = srcnode.label
else
if trgnode[link.label].indexOf(srcnode.label) < 0
trgnode[link.label] = trgnode[link.label] + ", " + srcnode.label
#log "updatedGraph!"
#log updatedGraph
updatedGraph
add:(searchItem) ->
@search.push (searchItem)
remove:(item) =>
# item has expected structure of op and opand
log "removing search item " + item.op + ", " + item.opand + "list [" + @search.length + "]..."
@search = _.reject @search, (searchItem) -> searchItem.match( item.op, item.opand)
log "removed search item " + item.opand + ", list is now [" + @search.length + "]"
get:(id) ->
_.find @search, (item) -> item.id is id
addIndex = (updatedGraph) ->
log "updating link..."
@idList = _.pluck updatedGraph.nodes, 'id'
updatedGraph.links = _.filter updatedGraph.links, (link) ->
@idList.indexOf(link.source) >= 0 and @idList.indexOf(link.target) >= 0
updatedGraph.nodes = _.uniq updatedGraph.nodes
updatedGraph
addSmartType: (node) =>
unless @typesInfo.categoryList[node.type]?
node.smartType = "Thing"
classType = @classTypes.getItem(node.smartType)
node.smartColour = classType.colour
node.smartIcon = classType.icon
node.smartIconHelper = classType.iconhelper
else
node.smartType = @typesInfo.categoryList[node.type]
node.smartColour = @typesInfo.colors[node.smartType]
node.smartIcon = @typesInfo.iconChars[node.smartType]
node.smartIconHelper = @typesInfo.icons[node.smartType]
node
##############################################################################
# manages url string
#############################################################################
class UriManager
constructor:(@setManager) ->
log "URI Manager created"
updateUri:() =>
filters = _.map @setManager.search, (item) ->
item.searchString
window.location.href = "#?filters=" + encodeURIComponent(filters.join ",")
#####################################################################################
# handles all events related to filters
# is responsible for creating and managing the filters, and acts as a "model" for
# other datasets to use
#####################################################################################
class smarterData.FilterManager
constructor:(@hdt) ->
_.extend @, Backbone.Events
@count = 1
@typefilter = []
@setManager = new SetManager(@typefilter)
@UriManager = new UriManager(@setManager)
@gremlinGraph = new GremlinGraph(@hdt)
@localStoreKey= "JSON"
@firstpass = true
# manages search space list
###########
# Events
###########
#------------------------
# Search events
#------------------------
$(document).on "click", ".facet-link", (e) =>
op = $(e.currentTarget).data("category")
operand = $(e.currentTarget).data("facet")
searchitem = _.last @setManager.search
searchitem.addFilter(op, operand)
@
$(document).on "change", "#search", (e, searchText) =>
log "search has changed, now updating graph"
e.stopImmediatePropagation()
if searchText?
@addSearch(searchText)
@updateGraph()
# actually takes value from change in URI
$(document).on "updatefilter", "#search", (e, filters) =>
# ensure filter not already in application
if @firstpass
_.each filters, (filter) =>
if isNaN(filter) then @addSearch(filter) else @addSearch(Number(filter))
, @
@updateGraph()
$(document).on "nodechosen", "#search", (e, searchText) =>
if searchText?
@addSearch(Number(searchText))
@updateGraph()
$(document).on "updategraph", "#search", (e, json) =>
if json?
@addGraph(json?.label,'glyphicon-filter',json?.graph)
@updateGraph()
$(document).on "intersect", "#search", (e, item) =>
@moveSearch(item.draggedId, item.targetId)
@updateGraph()
$(document).on "touchgraph", "#search", (e, json) =>
@updateGraph()
$(document).on "add-doc", "#search", (e, json) =>
log "adding doc to filters"
@addGraph("Document",'glyphicon-file',json)
@updateGraph()
#------------------------
# Type Filter events
#------------------------
$(document).on "add-filter", "#search", (e, type) =>
@typefilter.push(type)
@updateGraph()
$(document).on "remove-filter", "#search", (e, type) =>
index = @typefilter.indexOf(type)
if index > - 1
delete @typefilter[@typefilter.indexOf(type)]
@updateGraph()
$(document).on "typelist", "#search", (e, json) =>
@setManager.typesInfo = json
console.log @setManager.typesInfo
$(document).on "refrish-view", "#search", (e) =>
@updateGraph()
# used for final part of pivot search
$(document).on "searchForItems", "#search", (e, json) =>
pivotGraph =
nodes : []
links : []
idz = new Array()
for subject in json.subjects
unless subject is undefined
tempg = @gremlinGraph.searchForItem subject
#found = $.inArray tempg.id, idz
#if found == -1
pivotGraph.nodes.merge tempg.nodes
pivotGraph.links.merge tempg.links
#idz.push tempg.id
unless pivotGraph is undefined
pivotGraph.nodes = _.uniq pivotGraph.nodes, false, (item, key, id) ->
item.id
pivotGraph.links = _.uniq pivotGraph.links, false, (edge) ->
edge.target + edge.source
@addGraph(json.label,'glyphicon-filter',pivotGraph)
@updateGraph()
$(document).on "queryExecuted", "#execute", (e, pipeline) =>
log "gremlin pipeline ready for filter"
@addGremlinPipeline(pipeline) unless pipeline is undefined
@updateGraph()
log "Filter created."
$('#search').trigger('appready');
#------------------------
# updates graph after search is made
#------------------------
updateGraph: =>
@firstpass = false
@UriManager.updateUri()
$('#search').trigger "begob", @setManager.union()
# sets one of many seach spaces. allows filtering
addSearch: (searchKey) =>
log "adding search for term" + searchKey
unless searchKey is undefined
# get if @search item.id exists - if it does don't add it
ids = _.pluck @setManager.search, 'opand'
unless _.include ids, searchKey
searchItem = new SearchItem(searchKey, @gremlinGraph, @typefilter)
searchItem.on "labelremoved", @removeSearch
@setManager.add (searchItem)
# sets one of many seach spaces. allows filtering
addGremlinPipeline: (pipeline) =>
unless pipeline is undefined
gremAsJsonGraph = @gremlinGraph.processPipeline pipeline
pipeline = {}
@addGraph "Gremlin Query", "glyphicon-th-list", gremAsJsonGraph
addGraph: (name, icon, gremAsJsonGraph) =>
log "adding new gremlin graph"
graphItem = new GraphItem(name, icon, gremAsJsonGraph, @typefilter)
graphItem.on "labelremoved", @removeSearch
@setManager.add (graphItem)
removeSearch: (item) =>
@setManager.remove (item)
@updateGraph()
$("#search").trigger("change")
moveSearch: (draggedId, targetId) =>
log "dragged ID" + draggedId + ", target Id" + targetId
draggedSearchItem = @setManager.get(draggedId)
targetSearchItem = @setManager.get(targetId)
@setManager.remove (draggedSearchItem )
targetSearchItem.intersect(draggedSearchItem)
##############################
# Super class to all labels
# that are displayed
##############################
class SimpleLabel
constructor: (@op, @opand, @parentTag, @typefilter) ->
_.extend @, Backbone.Events
if isNaN @opand then @id = @opand.alphaNum() + @opand.alphaNum() else @id = @opand
@closer = ".close"
@template = """
<div id="<%= id %>" class="<%=cssstuff%>" draggable="true" alt="<%= opand %>" ><span class="glyphicon <%=icon%>"></span><%= shorttext %><a class="close">×</a>
</div>
"""
@setManager = new SetManager(@typefilter) if @typefilter?
$(document).on "click", "#" + @id + " " + @closer, (e) =>
@remove()
"ok"
render: () =>
if isNaN @opand
if @opand is "Gremlin Query"
@shorttext = "Gremlin Query"
else if @opand.validURL()
@shorttext = @opand.substr(@opand.lastIndexOf('/') + 1)
else
xx = @gremlinGraph.getOne(Number(@opand))
@shorttext = xx.nodes[0].label
else
xx = @gremlinGraph.getOne(Number(@opand))
@shorttext = xx.nodes[0].label
templateStr =_.template @template, id: @id, op: @op, opand: @opand, shorttext: @shorttext, cssstuff: @cssstuff ? "well well-sm col-sm-3", icon: @icon ? "glyphicon-search"
$(@parentTag).append (templateStr)
# drag drop events
$(document).on "dragstart", "#"+@id, (e) =>
dataTransfer = e.originalEvent.dataTransfer
dataTransfer.effectAllowed = "copy"
dataTransfer.setData "DraggedElementsId", @id
log "dragging that thang"
$(document).on "dragenter", "#"+@id, (e) ->
e.preventDefault();
this.classList.add('over')
$(document).on "dragleave", "#"+@id, (e) ->
e.preventDefault();
this.classList.remove('over')
$(document).on "dragover", "#"+@id, (e) =>
e.preventDefault();
$(document).on "drop dragdrop", "#"+@id, (e) =>
#ask container to move this down a level
draggedId = e.originalEvent.dataTransfer.getData( "DraggedElementsId")
$("#search").trigger "intersect", {draggedId: draggedId, targetId: @id}
removeElement: () =>
$("#" + @id).remove()
remove: () =>
$("#" + @id).remove()
@jsonGraph = {nodes:[], links:[]}
@.trigger "labelremoved", {op: @op, opand: @opand}
match:(filterOpz, filterOperandz) ->
match = (filterOpz == @op) && (filterOperandz == @opand)
log "matching" + @opand + " with " + filterOperandz + " is " + match
match
processGraph: () ->
log "do nothing"
asGraph: () ->
@setManager.intersection()
intersect: (graphToIntersect) =>
graphToIntersect.removeElement()
graphToIntersect.parentTag = "#"+ @id
graphToIntersect.cssstuff = "label label-primary"
@setManager.add(graphToIntersect)
graphToIntersect.render()
#@render()
##############################
# helps with the search
##############################
class GraphItem extends SimpleLabel
constructor: (@searchString, @icon, @jsonGraph, @typefilter) ->
super("searchString", @searchString, "#smartfilters", @typefilter)
@setManager.add(@processGraph())
@render()
processGraph: () ->
log "process graph"
si = new SimpleItem(@jsonGraph)
si
##############################
# helps with the search
##############################
class SimpleItem extends SimpleLabel
constructor: (@jsonGraph) ->
super("searchString", "not for display", "#smartfilters")
asGraph: () ->
@jsonGraph
##############################
# helps with the search
##############################
class SearchItem extends SimpleLabel
constructor: (@searchString, @gremlinGraph, @typefilter) ->
super("searchString",@searchString, "#smartfilters", @typefilter)
@jsonGraph = {nodes:[], links:[]}
@jsonGraph = @gremlinGraph.searchForItem(@searchString) ? {nodes:[], links:[]}
@setManager.add(@processGraph())
@render()
processGraph: () ->
log "process search item"
@jsonGraph = @gremlinGraph.searchForItem(@searchString) ? {nodes:[], links:[]}
si = new SimpleItem(@jsonGraph)
si
##############################
# helps with the search
##############################
class QueryItem extends SimpleLabel
constructor: (@pipeline, @gremlinGraph, @typefilter) ->
super("searchString","Gremlin Query", "#smartfilters", @typefilter)
log "pipeline to be rendered"
log pipeline
@icon = "glyphicon-th-list"
@setManager.add(processGraph())
@render()
processGraph: () ->
log "process queryitem"
@jsonGraph = @gremlinGraph.processPipeline(@pipeline) ? {nodes:[], links:[]}
si = new SimpleItem(@jsonGraph)
si
| true | # Just a log helper
log = (args...) ->
console.log.apply console, args if console.log?
String::alphaNum = ->
@.replace /[^a-zA-Z0-9]/g, ''
String::validURL = ->
pattern = new RegExp("/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/")
isUrl = pattern.test(@)
log "that " + @ + " is a URL is " + isUrl
!isUrl
String::hashCode = ->
hash = 0
i = undefined
chr = undefined
len = undefined
return hash if @length is 0
i = 0
len = @length
while i < len
chr = @charCodeAt(i)
hash = ((hash << 5) - hash) + chr
hash |= 0 # Convert to 32bit integer
i++
hash
Array::merge = (other) -> Array::push.apply @, other
GremlinGraph::searchForItem = (searchKey) ->
console.log "Searching for: " + searchKey
graph = @processPipeline @v(searchKey)
for node in graph.nodes
log "important node" + node.label
node["isTarget"] = true
bigger = @v(searchKey).both()
@processPipeline bigger, graph
edges = @v(searchKey).bothE()
@processPipeline edges, graph
# graph.nodes = _.union coreNode, outs
GremlinGraph::getOne = (searchKey) ->
@processPipeline @v(searchKey)
GremlinGraph::processPipeline = (pipeline, graph) ->
graph = {nodes:[], links:[]} if graph is undefined
@listOfIds = new Array()
while pipeline.hasNext()
item = pipeline.next()
if item instanceof Array
for element in item
@processPipeItem(element , graph)
else
@processPipeItem(item , graph)
graph
GremlinGraph::processPipeItem = (result, graph) ->
# get vertices
if (result.constructor.name is "HDTVertex")
unless result.getPropertyMap() is undefined
if result.getPropertyMap().hasNext()
id = result.getPropertyMap().next().subject
found = $.inArray id, @listOfIds
if found == -1
graph.nodes.push @vertexToNode result
@listOfIds.push id
# get edges
if (result.constructor.name is "HDTEdge")
graph.links.push @edgeToLink result
GremlinGraph::addSmartURI = (node) ->
node["smartURI"] = @hdt.dictionary.idToString(node.id, HDT.DictionarySectionRole.SUBJECT)
node
GremlinGraph::vertexToNode = (vertex) ->
id = vertex.getPropertyMap().next().subject
node =
id: id
hdtid : id
group : 1
@addSmartURI node
node["type"] = @hdt.search(node["smartURI"],"http://www.w3.org/1999/02/22-rdf-syntax-ns#type","").next().object
vert = vertex.getPropertyMap()
while vert.hasNext()
protoNode = vert.next()
key = protoNode.key.PI:KEY:<KEY>END_PI()
node[key] = protoNode.value
node["name"] = node[key] if key is "label"
node
GremlinGraph::edgeToLink = (hdtEdge) ->
{source: hdtEdge.triple.subject, target: hdtEdge.triple.object, weight:3, label: hdtEdge.getLabel().split("/").pop().split("#").pop()}
############################################################
# Utility classes for managing the color that
############################################################
class BagItem
constructor:(@name, @colour, @icon, @iconhelper) ->
class RdfClassTypes
constructor:() ->
@classBags = []
@classBags.push(new BagItem "undefined", "#FF6B6B", """\ue085""", "question-sign")
@classBags.push(new BagItem "Document", "#4ECDC4", """\ue022""", "file")
@classBags.push(new BagItem "Location", "#556270", """\ue062""", "map-marker")
@classBags.push(new BagItem "Organization", "#C44D58", """\ue184""", "tower")
@classBags.push(new BagItem "Person", "#C7F464", """\ue008""", "user")
getItem:(name) ->
item = _.find @classBags, (item) -> name is item.name
if item is undefined then @classBags[0] else item
##############################################################################
# manages union operations in list
#############################################################################
class UnionSet
joinNodes: (graph, memo) ->
_.uniq _.union(graph.nodes, memo.nodes), false, (item, key, hdtid) ->
item.hdtid
joinLinks: (graph, memo) ->
links = _.union(graph.links, memo.links)
##############################################################################
# manages intersection operations in list
#############################################################################
class IntersectSet
joinNodes: (graph, memo) =>
@nodes = @intersection(graph.nodes, memo.nodes)
getTargetLinksInNodes:(links) =>
_.flatten _.map @nodes, (node) => _.filter links, (link) -> node.hdtid is link.target
getSourceLinksInNodes:(links) =>
_.flatten _.map @nodes, (node) => _.filter links, (link) -> node.hdtid is link.source
joinLinks: (graph, memo) =>
@getSourceLinksInNodes(@getTargetLinksInNodes(graph.links.concat(memo.links)))
push:(obj, important, c) ->
important.push obj.hdtid
c.push obj
intersection: (a, b) ->
c = []
@important = []
for inner in a
if (inner.isTarget?) and (inner.hdtid not in @important)
@push inner, @important, c
else
for outer in b
c.push inner if (inner.hdtid is outer.hdtid)
if (outer.isTarget?) and (outer.hdtid not in @important)
@push outer, @important, c
c
##############################################################################
# manages list of filters and can run union or intersection operations on them
#############################################################################
class SetManager
constructor:(@typefilter) ->
@search = []
@classTypes = new RdfClassTypes()
@typesInfo =
categoryList : {}
icons : {}
iconChars : {}
colors: {}
showTargetNodes : true
union:() ->
@mergeSets(new UnionSet())
intersection:() ->
@mergeSets(new IntersectSet())
mergeSets:(setOperation) =>
targetnodes = []
updatedGraph = _.reduce @search, ((memo, searchItem) ->
graph = searchItem.asGraph()
result = {nodes:[], links:[]}
if memo.nodes.length > 0 then result.nodes = setOperation.joinNodes( graph , memo) else result.nodes = graph.nodes
if memo.links.length > 0 then result.links = setOperation.joinLinks( graph , memo) else result.links = graph.links
result
), {nodes:[], links:[]}
targetnodes = setOperation.important
updatedGraph.links = _.uniq updatedGraph.links, false, (edge) ->
edge.target + edge.source
addIndex(updatedGraph)
_.each updatedGraph.nodes, (node) =>
@addSmartType(node)
node.visible = (node.smartType not in @typefilter) or (node.isTarget? and @typesInfo.showTargetNodes )
_.uniq updatedGraph.links, false, (link) =>
srcnode =_.find updatedGraph.nodes, (node) -> node.hdtid == link.source
trgnode =_.find updatedGraph.nodes, (node) -> node.hdtid == link.target
if srcnode[link.label] == undefined
srcnode[link.label] = trgnode.label
else
if srcnode[link.label].indexOf(trgnode.label) < 0
srcnode[link.label] = srcnode[link.label] + ", " + trgnode.label
if trgnode[link.label] == undefined
trgnode[link.label] = srcnode.label
else
if trgnode[link.label].indexOf(srcnode.label) < 0
trgnode[link.label] = trgnode[link.label] + ", " + srcnode.label
#log "updatedGraph!"
#log updatedGraph
updatedGraph
add:(searchItem) ->
@search.push (searchItem)
remove:(item) =>
# item has expected structure of op and opand
log "removing search item " + item.op + ", " + item.opand + "list [" + @search.length + "]..."
@search = _.reject @search, (searchItem) -> searchItem.match( item.op, item.opand)
log "removed search item " + item.opand + ", list is now [" + @search.length + "]"
get:(id) ->
_.find @search, (item) -> item.id is id
addIndex = (updatedGraph) ->
log "updating link..."
@idList = _.pluck updatedGraph.nodes, 'id'
updatedGraph.links = _.filter updatedGraph.links, (link) ->
@idList.indexOf(link.source) >= 0 and @idList.indexOf(link.target) >= 0
updatedGraph.nodes = _.uniq updatedGraph.nodes
updatedGraph
addSmartType: (node) =>
unless @typesInfo.categoryList[node.type]?
node.smartType = "Thing"
classType = @classTypes.getItem(node.smartType)
node.smartColour = classType.colour
node.smartIcon = classType.icon
node.smartIconHelper = classType.iconhelper
else
node.smartType = @typesInfo.categoryList[node.type]
node.smartColour = @typesInfo.colors[node.smartType]
node.smartIcon = @typesInfo.iconChars[node.smartType]
node.smartIconHelper = @typesInfo.icons[node.smartType]
node
##############################################################################
# manages url string
#############################################################################
class UriManager
constructor:(@setManager) ->
log "URI Manager created"
updateUri:() =>
filters = _.map @setManager.search, (item) ->
item.searchString
window.location.href = "#?filters=" + encodeURIComponent(filters.join ",")
#####################################################################################
# handles all events related to filters
# is responsible for creating and managing the filters, and acts as a "model" for
# other datasets to use
#####################################################################################
class smarterData.FilterManager
constructor:(@hdt) ->
_.extend @, Backbone.Events
@count = 1
@typefilter = []
@setManager = new SetManager(@typefilter)
@UriManager = new UriManager(@setManager)
@gremlinGraph = new GremlinGraph(@hdt)
@localStoreKey= "JSON"
@firstpass = true
# manages search space list
###########
# Events
###########
#------------------------
# Search events
#------------------------
$(document).on "click", ".facet-link", (e) =>
op = $(e.currentTarget).data("category")
operand = $(e.currentTarget).data("facet")
searchitem = _.last @setManager.search
searchitem.addFilter(op, operand)
@
$(document).on "change", "#search", (e, searchText) =>
log "search has changed, now updating graph"
e.stopImmediatePropagation()
if searchText?
@addSearch(searchText)
@updateGraph()
# actually takes value from change in URI
$(document).on "updatefilter", "#search", (e, filters) =>
# ensure filter not already in application
if @firstpass
_.each filters, (filter) =>
if isNaN(filter) then @addSearch(filter) else @addSearch(Number(filter))
, @
@updateGraph()
$(document).on "nodechosen", "#search", (e, searchText) =>
if searchText?
@addSearch(Number(searchText))
@updateGraph()
$(document).on "updategraph", "#search", (e, json) =>
if json?
@addGraph(json?.label,'glyphicon-filter',json?.graph)
@updateGraph()
$(document).on "intersect", "#search", (e, item) =>
@moveSearch(item.draggedId, item.targetId)
@updateGraph()
$(document).on "touchgraph", "#search", (e, json) =>
@updateGraph()
$(document).on "add-doc", "#search", (e, json) =>
log "adding doc to filters"
@addGraph("Document",'glyphicon-file',json)
@updateGraph()
#------------------------
# Type Filter events
#------------------------
$(document).on "add-filter", "#search", (e, type) =>
@typefilter.push(type)
@updateGraph()
$(document).on "remove-filter", "#search", (e, type) =>
index = @typefilter.indexOf(type)
if index > - 1
delete @typefilter[@typefilter.indexOf(type)]
@updateGraph()
$(document).on "typelist", "#search", (e, json) =>
@setManager.typesInfo = json
console.log @setManager.typesInfo
$(document).on "refrish-view", "#search", (e) =>
@updateGraph()
# used for final part of pivot search
$(document).on "searchForItems", "#search", (e, json) =>
pivotGraph =
nodes : []
links : []
idz = new Array()
for subject in json.subjects
unless subject is undefined
tempg = @gremlinGraph.searchForItem subject
#found = $.inArray tempg.id, idz
#if found == -1
pivotGraph.nodes.merge tempg.nodes
pivotGraph.links.merge tempg.links
#idz.push tempg.id
unless pivotGraph is undefined
pivotGraph.nodes = _.uniq pivotGraph.nodes, false, (item, key, id) ->
item.id
pivotGraph.links = _.uniq pivotGraph.links, false, (edge) ->
edge.target + edge.source
@addGraph(json.label,'glyphicon-filter',pivotGraph)
@updateGraph()
$(document).on "queryExecuted", "#execute", (e, pipeline) =>
log "gremlin pipeline ready for filter"
@addGremlinPipeline(pipeline) unless pipeline is undefined
@updateGraph()
log "Filter created."
$('#search').trigger('appready');
#------------------------
# updates graph after search is made
#------------------------
updateGraph: =>
@firstpass = false
@UriManager.updateUri()
$('#search').trigger "begob", @setManager.union()
# sets one of many seach spaces. allows filtering
addSearch: (searchKey) =>
log "adding search for term" + searchKey
unless searchKey is undefined
# get if @search item.id exists - if it does don't add it
ids = _.pluck @setManager.search, 'opand'
unless _.include ids, searchKey
searchItem = new SearchItem(searchKey, @gremlinGraph, @typefilter)
searchItem.on "labelremoved", @removeSearch
@setManager.add (searchItem)
# sets one of many seach spaces. allows filtering
addGremlinPipeline: (pipeline) =>
unless pipeline is undefined
gremAsJsonGraph = @gremlinGraph.processPipeline pipeline
pipeline = {}
@addGraph "Gremlin Query", "glyphicon-th-list", gremAsJsonGraph
addGraph: (name, icon, gremAsJsonGraph) =>
log "adding new gremlin graph"
graphItem = new GraphItem(name, icon, gremAsJsonGraph, @typefilter)
graphItem.on "labelremoved", @removeSearch
@setManager.add (graphItem)
removeSearch: (item) =>
@setManager.remove (item)
@updateGraph()
$("#search").trigger("change")
moveSearch: (draggedId, targetId) =>
log "dragged ID" + draggedId + ", target Id" + targetId
draggedSearchItem = @setManager.get(draggedId)
targetSearchItem = @setManager.get(targetId)
@setManager.remove (draggedSearchItem )
targetSearchItem.intersect(draggedSearchItem)
##############################
# Super class to all labels
# that are displayed
##############################
class SimpleLabel
constructor: (@op, @opand, @parentTag, @typefilter) ->
_.extend @, Backbone.Events
if isNaN @opand then @id = @opand.alphaNum() + @opand.alphaNum() else @id = @opand
@closer = ".close"
@template = """
<div id="<%= id %>" class="<%=cssstuff%>" draggable="true" alt="<%= opand %>" ><span class="glyphicon <%=icon%>"></span><%= shorttext %><a class="close">×</a>
</div>
"""
@setManager = new SetManager(@typefilter) if @typefilter?
$(document).on "click", "#" + @id + " " + @closer, (e) =>
@remove()
"ok"
render: () =>
if isNaN @opand
if @opand is "Gremlin Query"
@shorttext = "Gremlin Query"
else if @opand.validURL()
@shorttext = @opand.substr(@opand.lastIndexOf('/') + 1)
else
xx = @gremlinGraph.getOne(Number(@opand))
@shorttext = xx.nodes[0].label
else
xx = @gremlinGraph.getOne(Number(@opand))
@shorttext = xx.nodes[0].label
templateStr =_.template @template, id: @id, op: @op, opand: @opand, shorttext: @shorttext, cssstuff: @cssstuff ? "well well-sm col-sm-3", icon: @icon ? "glyphicon-search"
$(@parentTag).append (templateStr)
# drag drop events
$(document).on "dragstart", "#"+@id, (e) =>
dataTransfer = e.originalEvent.dataTransfer
dataTransfer.effectAllowed = "copy"
dataTransfer.setData "DraggedElementsId", @id
log "dragging that thang"
$(document).on "dragenter", "#"+@id, (e) ->
e.preventDefault();
this.classList.add('over')
$(document).on "dragleave", "#"+@id, (e) ->
e.preventDefault();
this.classList.remove('over')
$(document).on "dragover", "#"+@id, (e) =>
e.preventDefault();
$(document).on "drop dragdrop", "#"+@id, (e) =>
#ask container to move this down a level
draggedId = e.originalEvent.dataTransfer.getData( "DraggedElementsId")
$("#search").trigger "intersect", {draggedId: draggedId, targetId: @id}
removeElement: () =>
$("#" + @id).remove()
remove: () =>
$("#" + @id).remove()
@jsonGraph = {nodes:[], links:[]}
@.trigger "labelremoved", {op: @op, opand: @opand}
match:(filterOpz, filterOperandz) ->
match = (filterOpz == @op) && (filterOperandz == @opand)
log "matching" + @opand + " with " + filterOperandz + " is " + match
match
processGraph: () ->
log "do nothing"
asGraph: () ->
@setManager.intersection()
intersect: (graphToIntersect) =>
graphToIntersect.removeElement()
graphToIntersect.parentTag = "#"+ @id
graphToIntersect.cssstuff = "label label-primary"
@setManager.add(graphToIntersect)
graphToIntersect.render()
#@render()
##############################
# helps with the search
##############################
class GraphItem extends SimpleLabel
constructor: (@searchString, @icon, @jsonGraph, @typefilter) ->
super("searchString", @searchString, "#smartfilters", @typefilter)
@setManager.add(@processGraph())
@render()
processGraph: () ->
log "process graph"
si = new SimpleItem(@jsonGraph)
si
##############################
# helps with the search
##############################
class SimpleItem extends SimpleLabel
constructor: (@jsonGraph) ->
super("searchString", "not for display", "#smartfilters")
asGraph: () ->
@jsonGraph
##############################
# helps with the search
##############################
class SearchItem extends SimpleLabel
constructor: (@searchString, @gremlinGraph, @typefilter) ->
super("searchString",@searchString, "#smartfilters", @typefilter)
@jsonGraph = {nodes:[], links:[]}
@jsonGraph = @gremlinGraph.searchForItem(@searchString) ? {nodes:[], links:[]}
@setManager.add(@processGraph())
@render()
processGraph: () ->
log "process search item"
@jsonGraph = @gremlinGraph.searchForItem(@searchString) ? {nodes:[], links:[]}
si = new SimpleItem(@jsonGraph)
si
##############################
# helps with the search
##############################
class QueryItem extends SimpleLabel
constructor: (@pipeline, @gremlinGraph, @typefilter) ->
super("searchString","Gremlin Query", "#smartfilters", @typefilter)
log "pipeline to be rendered"
log pipeline
@icon = "glyphicon-th-list"
@setManager.add(processGraph())
@render()
processGraph: () ->
log "process queryitem"
@jsonGraph = @gremlinGraph.processPipeline(@pipeline) ? {nodes:[], links:[]}
si = new SimpleItem(@jsonGraph)
si
|
[
{
"context": "dule.exports =\n user:\n _id: userId\n name: 'John Smith'\n token: token\n email: 'me@my.me'\n passw",
"end": 341,
"score": 0.9995629191398621,
"start": 331,
"tag": "NAME",
"value": "John Smith"
},
{
"context": " name: 'John Smith'\n token: token\n email: 'me@my.me'\n password: 'sosecure'\n username: 'jsmith'\n",
"end": 380,
"score": 0.999908447265625,
"start": 372,
"tag": "EMAIL",
"value": "me@my.me"
},
{
"context": "token: token\n email: 'me@my.me'\n password: 'sosecure'\n username: 'jsmith'\n\n item:\n _id: itemId\n",
"end": 405,
"score": 0.9991938471794128,
"start": 397,
"tag": "PASSWORD",
"value": "sosecure"
},
{
"context": "me@my.me'\n password: 'sosecure'\n username: 'jsmith'\n\n item:\n _id: itemId\n name: 'test-item'\n ",
"end": 428,
"score": 0.9997050166130066,
"start": 422,
"tag": "USERNAME",
"value": "jsmith"
}
] | server/test/setup.coffee | stevelacy/claru | 0 | mongoose = require 'mongoose'
tungsten = require 'tungsten'
config = require '../config'
date = new Date()
itemId = String mongoose.Types.ObjectId()
userId = String mongoose.Types.ObjectId()
token = tungsten.encode
id: userId
exp: date + 345600000
, config.token.secret
module.exports =
user:
_id: userId
name: 'John Smith'
token: token
email: 'me@my.me'
password: 'sosecure'
username: 'jsmith'
item:
_id: itemId
name: 'test-item'
main: 'test.coffee'
user: userId
widget:
html: 'test.html'
| 85725 | mongoose = require 'mongoose'
tungsten = require 'tungsten'
config = require '../config'
date = new Date()
itemId = String mongoose.Types.ObjectId()
userId = String mongoose.Types.ObjectId()
token = tungsten.encode
id: userId
exp: date + 345600000
, config.token.secret
module.exports =
user:
_id: userId
name: '<NAME>'
token: token
email: '<EMAIL>'
password: '<PASSWORD>'
username: 'jsmith'
item:
_id: itemId
name: 'test-item'
main: 'test.coffee'
user: userId
widget:
html: 'test.html'
| true | mongoose = require 'mongoose'
tungsten = require 'tungsten'
config = require '../config'
date = new Date()
itemId = String mongoose.Types.ObjectId()
userId = String mongoose.Types.ObjectId()
token = tungsten.encode
id: userId
exp: date + 345600000
, config.token.secret
module.exports =
user:
_id: userId
name: 'PI:NAME:<NAME>END_PI'
token: token
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
username: 'jsmith'
item:
_id: itemId
name: 'test-item'
main: 'test.coffee'
user: userId
widget:
html: 'test.html'
|
[
{
"context": "#\n# ngModal\n# by Adam Albrecht\n# http://adamalbrecht.com\n#\n# Source Code: https:",
"end": 30,
"score": 0.9999006986618042,
"start": 17,
"tag": "NAME",
"value": "Adam Albrecht"
},
{
"context": "malbrecht.com\n#\n# Source Code: https://github.com/adamalbrecht/ngModal\n#\n# Compatible with Angular 1.2.x\n#\n\napp ",
"end": 105,
"score": 0.9987494349479675,
"start": 93,
"tag": "USERNAME",
"value": "adamalbrecht"
}
] | src/ng-modal.coffee | Ricco1/ngModal | 0 | #
# ngModal
# by Adam Albrecht
# http://adamalbrecht.com
#
# Source Code: https://github.com/adamalbrecht/ngModal
#
# Compatible with Angular 1.2.x
#
app = angular.module("ngModal", [])
app.provider "ngModalDefaults", ->
options: {
closeButtonHtml: "<span class='ng-modal-close-x'>X</span>"
hideCloseButton: false
closeOnEscape: true
closeOnOutsideClick: true
}
$get: ->
@options
set: (keyOrHash, value) ->
if typeof(keyOrHash) == 'object'
for k, v of keyOrHash
@options[k] = v
else
@options[keyOrHash] = value
app.directive 'modalDialog', ['ngModalDefaults', '$sce', '$timeout', (ngModalDefaults, $sce, $timeout) ->
restrict: 'E'
scope:
show: '='
dialogTitle: '@'
onClose: '&?'
hideCloseButton: '='
closeOnEscape: '='
closeOnOutsideClick: '='
replace: true
transclude: true
link: (scope, element, attrs) ->
scope.hCB = if scope.hideCloseButton == undefined then ngModalDefaults.hideCloseButton else scope.hideCloseButton
scope.cOE = if scope.closeOnEscape == undefined then ngModalDefaults.closeOnEscape else scope.closeOnEscape
scope.cOOC = if scope.closeOnOutsideClick == undefined then ngModalDefaults.closeOnOutsideClick else scope.closeOnOutsideClick
bindEscKeyPress = ->
if scope.cOE
document.onkeydown = (evt) ->
evt = evt || window.event
isEscape = false
if "key" in evt
isEscape = evt.key == "Escape" || evt.key == "Esc"
else
isEscape = evt.keyCode == 27
if isEscape
scope.hideModal()
unbindEscKeyPress = ->
document.onkeydown = ->
setupCloseButton = ->
scope.closeButtonHtml = $sce.trustAsHtml(ngModalDefaults.closeButtonHtml)
setupStyle = ->
scope.dialogStyle = {}
scope.dialogStyle['width'] = attrs.width if attrs.width
scope.dialogStyle['height'] = attrs.height if attrs.height
scope.hideModal = ->
scope.show = false
triggerDigest = $timeout(() ->
$timeout.cancel(triggerDigest);
)
scope.$watch('show', (newVal, oldVal) ->
if newVal && !oldVal
bindEscKeyPress()
document.getElementsByTagName("body")[0].style.overflow = "hidden";
else
unbindEscKeyPress()
document.getElementsByTagName("body")[0].style.overflow = "";
if (!newVal && oldVal) && scope.onClose?
unbindEscKeyPress()
scope.onClose()
)
setupCloseButton()
setupStyle()
template: """
<div class='ng-modal' ng-show='show'>
<div class='ng-modal-overlay' ng-click='cOOC && hideModal()'></div>
<div class='ng-modal-dialog' ng-style='dialogStyle'>
<span class='ng-modal-title' ng-show='dialogTitle && dialogTitle.length' ng-bind='dialogTitle'></span>
<div class='ng-modal-close' ng-if='!hCB' ng-click='hideModal()'>
<div ng-bind-html='closeButtonHtml'></div>
</div>
<div class='ng-modal-dialog-content' ng-transclude></div>
</div>
</div>
"""
]
| 6264 | #
# ngModal
# by <NAME>
# http://adamalbrecht.com
#
# Source Code: https://github.com/adamalbrecht/ngModal
#
# Compatible with Angular 1.2.x
#
app = angular.module("ngModal", [])
app.provider "ngModalDefaults", ->
options: {
closeButtonHtml: "<span class='ng-modal-close-x'>X</span>"
hideCloseButton: false
closeOnEscape: true
closeOnOutsideClick: true
}
$get: ->
@options
set: (keyOrHash, value) ->
if typeof(keyOrHash) == 'object'
for k, v of keyOrHash
@options[k] = v
else
@options[keyOrHash] = value
app.directive 'modalDialog', ['ngModalDefaults', '$sce', '$timeout', (ngModalDefaults, $sce, $timeout) ->
restrict: 'E'
scope:
show: '='
dialogTitle: '@'
onClose: '&?'
hideCloseButton: '='
closeOnEscape: '='
closeOnOutsideClick: '='
replace: true
transclude: true
link: (scope, element, attrs) ->
scope.hCB = if scope.hideCloseButton == undefined then ngModalDefaults.hideCloseButton else scope.hideCloseButton
scope.cOE = if scope.closeOnEscape == undefined then ngModalDefaults.closeOnEscape else scope.closeOnEscape
scope.cOOC = if scope.closeOnOutsideClick == undefined then ngModalDefaults.closeOnOutsideClick else scope.closeOnOutsideClick
bindEscKeyPress = ->
if scope.cOE
document.onkeydown = (evt) ->
evt = evt || window.event
isEscape = false
if "key" in evt
isEscape = evt.key == "Escape" || evt.key == "Esc"
else
isEscape = evt.keyCode == 27
if isEscape
scope.hideModal()
unbindEscKeyPress = ->
document.onkeydown = ->
setupCloseButton = ->
scope.closeButtonHtml = $sce.trustAsHtml(ngModalDefaults.closeButtonHtml)
setupStyle = ->
scope.dialogStyle = {}
scope.dialogStyle['width'] = attrs.width if attrs.width
scope.dialogStyle['height'] = attrs.height if attrs.height
scope.hideModal = ->
scope.show = false
triggerDigest = $timeout(() ->
$timeout.cancel(triggerDigest);
)
scope.$watch('show', (newVal, oldVal) ->
if newVal && !oldVal
bindEscKeyPress()
document.getElementsByTagName("body")[0].style.overflow = "hidden";
else
unbindEscKeyPress()
document.getElementsByTagName("body")[0].style.overflow = "";
if (!newVal && oldVal) && scope.onClose?
unbindEscKeyPress()
scope.onClose()
)
setupCloseButton()
setupStyle()
template: """
<div class='ng-modal' ng-show='show'>
<div class='ng-modal-overlay' ng-click='cOOC && hideModal()'></div>
<div class='ng-modal-dialog' ng-style='dialogStyle'>
<span class='ng-modal-title' ng-show='dialogTitle && dialogTitle.length' ng-bind='dialogTitle'></span>
<div class='ng-modal-close' ng-if='!hCB' ng-click='hideModal()'>
<div ng-bind-html='closeButtonHtml'></div>
</div>
<div class='ng-modal-dialog-content' ng-transclude></div>
</div>
</div>
"""
]
| true | #
# ngModal
# by PI:NAME:<NAME>END_PI
# http://adamalbrecht.com
#
# Source Code: https://github.com/adamalbrecht/ngModal
#
# Compatible with Angular 1.2.x
#
app = angular.module("ngModal", [])
app.provider "ngModalDefaults", ->
options: {
closeButtonHtml: "<span class='ng-modal-close-x'>X</span>"
hideCloseButton: false
closeOnEscape: true
closeOnOutsideClick: true
}
$get: ->
@options
set: (keyOrHash, value) ->
if typeof(keyOrHash) == 'object'
for k, v of keyOrHash
@options[k] = v
else
@options[keyOrHash] = value
app.directive 'modalDialog', ['ngModalDefaults', '$sce', '$timeout', (ngModalDefaults, $sce, $timeout) ->
restrict: 'E'
scope:
show: '='
dialogTitle: '@'
onClose: '&?'
hideCloseButton: '='
closeOnEscape: '='
closeOnOutsideClick: '='
replace: true
transclude: true
link: (scope, element, attrs) ->
scope.hCB = if scope.hideCloseButton == undefined then ngModalDefaults.hideCloseButton else scope.hideCloseButton
scope.cOE = if scope.closeOnEscape == undefined then ngModalDefaults.closeOnEscape else scope.closeOnEscape
scope.cOOC = if scope.closeOnOutsideClick == undefined then ngModalDefaults.closeOnOutsideClick else scope.closeOnOutsideClick
bindEscKeyPress = ->
if scope.cOE
document.onkeydown = (evt) ->
evt = evt || window.event
isEscape = false
if "key" in evt
isEscape = evt.key == "Escape" || evt.key == "Esc"
else
isEscape = evt.keyCode == 27
if isEscape
scope.hideModal()
unbindEscKeyPress = ->
document.onkeydown = ->
setupCloseButton = ->
scope.closeButtonHtml = $sce.trustAsHtml(ngModalDefaults.closeButtonHtml)
setupStyle = ->
scope.dialogStyle = {}
scope.dialogStyle['width'] = attrs.width if attrs.width
scope.dialogStyle['height'] = attrs.height if attrs.height
scope.hideModal = ->
scope.show = false
triggerDigest = $timeout(() ->
$timeout.cancel(triggerDigest);
)
scope.$watch('show', (newVal, oldVal) ->
if newVal && !oldVal
bindEscKeyPress()
document.getElementsByTagName("body")[0].style.overflow = "hidden";
else
unbindEscKeyPress()
document.getElementsByTagName("body")[0].style.overflow = "";
if (!newVal && oldVal) && scope.onClose?
unbindEscKeyPress()
scope.onClose()
)
setupCloseButton()
setupStyle()
template: """
<div class='ng-modal' ng-show='show'>
<div class='ng-modal-overlay' ng-click='cOOC && hideModal()'></div>
<div class='ng-modal-dialog' ng-style='dialogStyle'>
<span class='ng-modal-title' ng-show='dialogTitle && dialogTitle.length' ng-bind='dialogTitle'></span>
<div class='ng-modal-close' ng-if='!hCB' ng-click='hideModal()'>
<div ng-bind-html='closeButtonHtml'></div>
</div>
<div class='ng-modal-dialog-content' ng-transclude></div>
</div>
</div>
"""
]
|
[
{
"context": "peahead(null,\n name: 'engine'\n displayKey: 'smooth_name'\n source: engine.ttAdapter()\n templates:\n ",
"end": 412,
"score": 0.56847083568573,
"start": 401,
"tag": "KEY",
"value": "smooth_name"
}
] | app/assets/javascripts/shared/search_autocomplete.js.coffee | sebastiencarceles/companydata.co | 1 | $(document).on 'turbolinks:load', ->
engine = new Bloodhound(
datumTokenizer: (d) ->
Bloodhound.tokenizers.whitespace d.smooth_name
queryTokenizer: Bloodhound.tokenizers.whitespace
remote:
url: '/api/v1/companies/autocomplete?q=%QUERY'
wildcard: '%QUERY'
)
engine.initialize()
$("#js-search-autocomplete").typeahead(null,
name: 'engine'
displayKey: 'smooth_name'
source: engine.ttAdapter()
templates:
suggestion: Handlebars.compile("
<div>
{{smooth_name}}
<small>
{{city}}
{{country}}
</small>
</div>
")
).on 'typeahead:selected', (e, data) ->
$(this).closest('form').submit()
return
false | 185194 | $(document).on 'turbolinks:load', ->
engine = new Bloodhound(
datumTokenizer: (d) ->
Bloodhound.tokenizers.whitespace d.smooth_name
queryTokenizer: Bloodhound.tokenizers.whitespace
remote:
url: '/api/v1/companies/autocomplete?q=%QUERY'
wildcard: '%QUERY'
)
engine.initialize()
$("#js-search-autocomplete").typeahead(null,
name: 'engine'
displayKey: '<KEY>'
source: engine.ttAdapter()
templates:
suggestion: Handlebars.compile("
<div>
{{smooth_name}}
<small>
{{city}}
{{country}}
</small>
</div>
")
).on 'typeahead:selected', (e, data) ->
$(this).closest('form').submit()
return
false | true | $(document).on 'turbolinks:load', ->
engine = new Bloodhound(
datumTokenizer: (d) ->
Bloodhound.tokenizers.whitespace d.smooth_name
queryTokenizer: Bloodhound.tokenizers.whitespace
remote:
url: '/api/v1/companies/autocomplete?q=%QUERY'
wildcard: '%QUERY'
)
engine.initialize()
$("#js-search-autocomplete").typeahead(null,
name: 'engine'
displayKey: 'PI:KEY:<KEY>END_PI'
source: engine.ttAdapter()
templates:
suggestion: Handlebars.compile("
<div>
{{smooth_name}}
<small>
{{city}}
{{country}}
</small>
</div>
")
).on 'typeahead:selected', (e, data) ->
$(this).closest('form').submit()
return
false |
[
{
"context": "artner = new Channel\n id: '123'\n name: 'Gagosian'\n type: 'partner'\n sinon.stub(Channel.pro",
"end": 1479,
"score": 0.9995096325874329,
"start": 1471,
"tag": "NAME",
"value": "Gagosian"
},
{
"context": "eq.user.get('current_channel').name.should.equal 'Gagosian'\n @req.user.get('current_channel').type.should",
"end": 1949,
"score": 0.9897714853286743,
"start": 1941,
"tag": "NAME",
"value": "Gagosian"
},
{
"context": "artner = new Channel\n id: '123'\n name: 'Gagosian'\n type: 'partner'\n Channel.prototype.fetc",
"end": 2766,
"score": 0.9995571374893188,
"start": 2758,
"tag": "NAME",
"value": "Gagosian"
}
] | src/client/apps/switch_channel/test/index.test.coffee | artsyjian/positron | 76 | sinon = require 'sinon'
rewire = require 'rewire'
app = rewire '../'
Backbone = require 'backbone'
Channel = rewire '../../../models/channel.coffee'
User = require '../../../models/user.coffee'
{ fabricate } = require '@artsy/antigravity'
fixtures = require '../../../../test/helpers/fixtures.coffee'
describe 'authorized switch_channel (channel)', ->
beforeEach ->
user = new User fixtures().users
user.set channel_ids: ['1234']
user.set partner_ids: []
user.set type: 'Admin'
@channel = new Channel(
name: 'Artsy Editorial'
id: '1234'
type: 'editorial'
)
sinon.stub(Channel.prototype,'fetchChannelOrPartner').yieldsTo('success', @channel)
@req = user: user, login: sinon.stub(), params: id: 'foo'
@res = redirect: sinon.stub()
@next = sinon.stub()
app.__set__ 'Channel', Channel
@switch_user = app.__get__ 'switchChannel'
afterEach ->
Channel.prototype.fetchChannelOrPartner.restore()
it 'switches', ->
@switch_user @req, @res, @next
@req.user.get('current_channel').name.should.equal 'Artsy Editorial'
@req.user.get('current_channel').id.should.equal '1234'
@req.user.get('current_channel').type.should.equal 'editorial'
describe 'authorized switch_channel (partner)', ->
beforeEach ->
user = new User fixtures().users
user.set channel_ids: []
user.set partner_ids: ['123']
user.set type: 'User'
@partner = new Channel
id: '123'
name: 'Gagosian'
type: 'partner'
sinon.stub(Channel.prototype,'fetchChannelOrPartner').yieldsTo('success', @partner)
@req = user: user, login: sinon.stub(), params: id: 'foo'
@res = redirect: sinon.stub()
@next = sinon.stub()
@switch_user = app.__get__ 'switchChannel'
afterEach ->
Channel.prototype.fetchChannelOrPartner.restore()
it 'switches', ->
@switch_user @req, @res, @next
@req.user.get('current_channel').name.should.equal 'Gagosian'
@req.user.get('current_channel').type.should.equal 'partner'
describe 'non authorized switch_channel', ->
beforeEach ->
user = new User fixtures().users
user.set channel_ids: []
user.set partner_ids: []
user.set type: 'User'
@req = user: user, login: sinon.stub(), params: id: 'foo'
@res = redirect: sinon.stub()
@next = sinon.stub()
sinon.stub(Channel.prototype,'fetchChannelOrPartner').yieldsTo('error', {})
@switch_user = app.__get__ 'switchChannel'
afterEach ->
Channel.prototype.fetchChannelOrPartner.restore()
it 'returns an error if channel is not found', ->
@switch_user @req, @res, @next
@next.called.should.be.true()
it 'returns an error if unauthorized Admin in channel', ->
@partner = new Channel
id: '123'
name: 'Gagosian'
type: 'partner'
Channel.prototype.fetchChannelOrPartner.yieldsTo('success', @partner)
@switch_user @req, @res, @next
@next.called.should.be.true()
| 80666 | sinon = require 'sinon'
rewire = require 'rewire'
app = rewire '../'
Backbone = require 'backbone'
Channel = rewire '../../../models/channel.coffee'
User = require '../../../models/user.coffee'
{ fabricate } = require '@artsy/antigravity'
fixtures = require '../../../../test/helpers/fixtures.coffee'
describe 'authorized switch_channel (channel)', ->
beforeEach ->
user = new User fixtures().users
user.set channel_ids: ['1234']
user.set partner_ids: []
user.set type: 'Admin'
@channel = new Channel(
name: 'Artsy Editorial'
id: '1234'
type: 'editorial'
)
sinon.stub(Channel.prototype,'fetchChannelOrPartner').yieldsTo('success', @channel)
@req = user: user, login: sinon.stub(), params: id: 'foo'
@res = redirect: sinon.stub()
@next = sinon.stub()
app.__set__ 'Channel', Channel
@switch_user = app.__get__ 'switchChannel'
afterEach ->
Channel.prototype.fetchChannelOrPartner.restore()
it 'switches', ->
@switch_user @req, @res, @next
@req.user.get('current_channel').name.should.equal 'Artsy Editorial'
@req.user.get('current_channel').id.should.equal '1234'
@req.user.get('current_channel').type.should.equal 'editorial'
describe 'authorized switch_channel (partner)', ->
beforeEach ->
user = new User fixtures().users
user.set channel_ids: []
user.set partner_ids: ['123']
user.set type: 'User'
@partner = new Channel
id: '123'
name: '<NAME>'
type: 'partner'
sinon.stub(Channel.prototype,'fetchChannelOrPartner').yieldsTo('success', @partner)
@req = user: user, login: sinon.stub(), params: id: 'foo'
@res = redirect: sinon.stub()
@next = sinon.stub()
@switch_user = app.__get__ 'switchChannel'
afterEach ->
Channel.prototype.fetchChannelOrPartner.restore()
it 'switches', ->
@switch_user @req, @res, @next
@req.user.get('current_channel').name.should.equal '<NAME>'
@req.user.get('current_channel').type.should.equal 'partner'
describe 'non authorized switch_channel', ->
beforeEach ->
user = new User fixtures().users
user.set channel_ids: []
user.set partner_ids: []
user.set type: 'User'
@req = user: user, login: sinon.stub(), params: id: 'foo'
@res = redirect: sinon.stub()
@next = sinon.stub()
sinon.stub(Channel.prototype,'fetchChannelOrPartner').yieldsTo('error', {})
@switch_user = app.__get__ 'switchChannel'
afterEach ->
Channel.prototype.fetchChannelOrPartner.restore()
it 'returns an error if channel is not found', ->
@switch_user @req, @res, @next
@next.called.should.be.true()
it 'returns an error if unauthorized Admin in channel', ->
@partner = new Channel
id: '123'
name: '<NAME>'
type: 'partner'
Channel.prototype.fetchChannelOrPartner.yieldsTo('success', @partner)
@switch_user @req, @res, @next
@next.called.should.be.true()
| true | sinon = require 'sinon'
rewire = require 'rewire'
app = rewire '../'
Backbone = require 'backbone'
Channel = rewire '../../../models/channel.coffee'
User = require '../../../models/user.coffee'
{ fabricate } = require '@artsy/antigravity'
fixtures = require '../../../../test/helpers/fixtures.coffee'
describe 'authorized switch_channel (channel)', ->
beforeEach ->
user = new User fixtures().users
user.set channel_ids: ['1234']
user.set partner_ids: []
user.set type: 'Admin'
@channel = new Channel(
name: 'Artsy Editorial'
id: '1234'
type: 'editorial'
)
sinon.stub(Channel.prototype,'fetchChannelOrPartner').yieldsTo('success', @channel)
@req = user: user, login: sinon.stub(), params: id: 'foo'
@res = redirect: sinon.stub()
@next = sinon.stub()
app.__set__ 'Channel', Channel
@switch_user = app.__get__ 'switchChannel'
afterEach ->
Channel.prototype.fetchChannelOrPartner.restore()
it 'switches', ->
@switch_user @req, @res, @next
@req.user.get('current_channel').name.should.equal 'Artsy Editorial'
@req.user.get('current_channel').id.should.equal '1234'
@req.user.get('current_channel').type.should.equal 'editorial'
describe 'authorized switch_channel (partner)', ->
beforeEach ->
user = new User fixtures().users
user.set channel_ids: []
user.set partner_ids: ['123']
user.set type: 'User'
@partner = new Channel
id: '123'
name: 'PI:NAME:<NAME>END_PI'
type: 'partner'
sinon.stub(Channel.prototype,'fetchChannelOrPartner').yieldsTo('success', @partner)
@req = user: user, login: sinon.stub(), params: id: 'foo'
@res = redirect: sinon.stub()
@next = sinon.stub()
@switch_user = app.__get__ 'switchChannel'
afterEach ->
Channel.prototype.fetchChannelOrPartner.restore()
it 'switches', ->
@switch_user @req, @res, @next
@req.user.get('current_channel').name.should.equal 'PI:NAME:<NAME>END_PI'
@req.user.get('current_channel').type.should.equal 'partner'
describe 'non authorized switch_channel', ->
beforeEach ->
user = new User fixtures().users
user.set channel_ids: []
user.set partner_ids: []
user.set type: 'User'
@req = user: user, login: sinon.stub(), params: id: 'foo'
@res = redirect: sinon.stub()
@next = sinon.stub()
sinon.stub(Channel.prototype,'fetchChannelOrPartner').yieldsTo('error', {})
@switch_user = app.__get__ 'switchChannel'
afterEach ->
Channel.prototype.fetchChannelOrPartner.restore()
it 'returns an error if channel is not found', ->
@switch_user @req, @res, @next
@next.called.should.be.true()
it 'returns an error if unauthorized Admin in channel', ->
@partner = new Channel
id: '123'
name: 'PI:NAME:<NAME>END_PI'
type: 'partner'
Channel.prototype.fetchChannelOrPartner.yieldsTo('success', @partner)
@switch_user @req, @res, @next
@next.called.should.be.true()
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.999912440776825,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/beatmaps/search-content.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 { Paginator } from './paginator'
import { SearchPanel } from './search-panel'
import { SearchSort } from './search-sort'
import { BeatmapsetPanel } from 'beatmapset-panel'
import { Img2x } from 'img2x'
import { observe, observable } from 'mobx'
import { Observer } from 'mobx-react'
import core from 'osu-core-singleton'
import * as React from 'react'
import { a, div, p } from 'react-dom-factories'
import VirtualList from 'react-virtual-list'
el = React.createElement
beatmapsetStore = core.dataStore.beatmapsetStore
controller = core.beatmapsetSearchController
ITEM_HEIGHT = 205 # needs to be known in advance to calculate size of virtual scrolling area.
ListRender = ({ virtual, itemHeight }) ->
style = _.extend {}, virtual.style
div
style: style
div
className: 'beatmapsets__items'
virtual.items.map (row) ->
div
className: 'beatmapsets__items-row'
key: (beatmapsetId for beatmapsetId in row).join('-')
for beatmapsetId in row
div
className: 'beatmapsets__item'
key: beatmapsetId
el BeatmapsetPanel, beatmap: beatmapsetStore.get(beatmapsetId)
# stored in an observable so a rerender will occur when the HOC gets updated.
Observables = observable
BeatmapList: VirtualList()(ListRender)
numberOfColumns: if osu.isDesktop() then 2 else 1
observe Observables, 'numberOfColumns', (change) ->
if change.oldValue != change.newValue
Observables.BeatmapList = VirtualList()(ListRender)
export class SearchContent extends React.Component
componentDidMount: ->
$(window).on 'resize.beatmaps-search-content', ->
count = if osu.isDesktop() then 2 else 1
Observables.numberOfColumns = count if Observables.numberOfColumns != count
componentWillUnmount: ->
$(window).off '.beatmaps-search-content'
render: ->
el Observer, null, () =>
beatmapsetIds = controller.currentBeatmapsetIds
firstBeatmapset = beatmapsetStore.get(beatmapsetIds[0])
searchBackground = if beatmapsetIds.length > 0 then firstBeatmapset?.covers?.cover else null
supporterRequiredFilterText = controller.supporterRequiredFilterText
listCssClasses = 'beatmapsets'
listCssClasses += ' beatmapsets--dimmed' if controller.isBusy
el React.Fragment, null,
el SearchPanel,
innerRef: @props.backToTopAnchor
background: searchBackground
availableFilters: @props.availableFilters
div className: 'js-sticky-header'
div
className: 'osu-layout__row osu-layout__row--page-compact'
div className: listCssClasses,
if currentUser.id?
div
className: 'beatmapsets__sort'
el SearchSort,
filters: controller.filters
sorting: sorting()
div
className: 'beatmapsets__content'
if controller.isSupporterMissing
div className: 'beatmapsets__empty',
el Img2x,
src: '/images/layout/beatmaps/supporter-required.png'
alt: osu.trans('beatmaps.listing.search.supporter_filter', filters: supporterRequiredFilterText)
title: osu.trans('beatmaps.listing.search.supporter_filter', filters: supporterRequiredFilterText)
renderLinkToSupporterTag(supporterRequiredFilterText)
else
if beatmapsetIds.length > 0
el Observables.BeatmapList,
items: _.chunk(beatmapsetIds, Observables.numberOfColumns)
itemBuffer: 5
itemHeight: ITEM_HEIGHT
else
div className: 'beatmapsets__empty',
el Img2x,
src: '/images/layout/beatmaps/not-found.png'
alt: osu.trans("beatmaps.listing.search.not-found")
title: osu.trans("beatmaps.listing.search.not-found")
osu.trans("beatmaps.listing.search.not-found-quote")
if !controller.isSupporterMissing
div className: 'beatmapsets__paginator',
el Paginator,
error: controller.error
loading: controller.isPaging
more: controller.hasMore
sorting = ->
[field, order] = controller.filters.displaySort.split('_')
{ field, order }
renderLinkToSupporterTag = (filterText) ->
url = laroute.route('store.products.show', product: 'supporter-tag')
link = "<a href=\"#{url}\">#{osu.trans 'beatmaps.listing.search.supporter_filter_quote.link_text'}</a>"
p
dangerouslySetInnerHTML:
__html: osu.trans 'beatmaps.listing.search.supporter_filter_quote._',
filters: filterText
link: link
| 108765 | # 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 { Paginator } from './paginator'
import { SearchPanel } from './search-panel'
import { SearchSort } from './search-sort'
import { BeatmapsetPanel } from 'beatmapset-panel'
import { Img2x } from 'img2x'
import { observe, observable } from 'mobx'
import { Observer } from 'mobx-react'
import core from 'osu-core-singleton'
import * as React from 'react'
import { a, div, p } from 'react-dom-factories'
import VirtualList from 'react-virtual-list'
el = React.createElement
beatmapsetStore = core.dataStore.beatmapsetStore
controller = core.beatmapsetSearchController
ITEM_HEIGHT = 205 # needs to be known in advance to calculate size of virtual scrolling area.
ListRender = ({ virtual, itemHeight }) ->
style = _.extend {}, virtual.style
div
style: style
div
className: 'beatmapsets__items'
virtual.items.map (row) ->
div
className: 'beatmapsets__items-row'
key: (beatmapsetId for beatmapsetId in row).join('-')
for beatmapsetId in row
div
className: 'beatmapsets__item'
key: beatmapsetId
el BeatmapsetPanel, beatmap: beatmapsetStore.get(beatmapsetId)
# stored in an observable so a rerender will occur when the HOC gets updated.
Observables = observable
BeatmapList: VirtualList()(ListRender)
numberOfColumns: if osu.isDesktop() then 2 else 1
observe Observables, 'numberOfColumns', (change) ->
if change.oldValue != change.newValue
Observables.BeatmapList = VirtualList()(ListRender)
export class SearchContent extends React.Component
componentDidMount: ->
$(window).on 'resize.beatmaps-search-content', ->
count = if osu.isDesktop() then 2 else 1
Observables.numberOfColumns = count if Observables.numberOfColumns != count
componentWillUnmount: ->
$(window).off '.beatmaps-search-content'
render: ->
el Observer, null, () =>
beatmapsetIds = controller.currentBeatmapsetIds
firstBeatmapset = beatmapsetStore.get(beatmapsetIds[0])
searchBackground = if beatmapsetIds.length > 0 then firstBeatmapset?.covers?.cover else null
supporterRequiredFilterText = controller.supporterRequiredFilterText
listCssClasses = 'beatmapsets'
listCssClasses += ' beatmapsets--dimmed' if controller.isBusy
el React.Fragment, null,
el SearchPanel,
innerRef: @props.backToTopAnchor
background: searchBackground
availableFilters: @props.availableFilters
div className: 'js-sticky-header'
div
className: 'osu-layout__row osu-layout__row--page-compact'
div className: listCssClasses,
if currentUser.id?
div
className: 'beatmapsets__sort'
el SearchSort,
filters: controller.filters
sorting: sorting()
div
className: 'beatmapsets__content'
if controller.isSupporterMissing
div className: 'beatmapsets__empty',
el Img2x,
src: '/images/layout/beatmaps/supporter-required.png'
alt: osu.trans('beatmaps.listing.search.supporter_filter', filters: supporterRequiredFilterText)
title: osu.trans('beatmaps.listing.search.supporter_filter', filters: supporterRequiredFilterText)
renderLinkToSupporterTag(supporterRequiredFilterText)
else
if beatmapsetIds.length > 0
el Observables.BeatmapList,
items: _.chunk(beatmapsetIds, Observables.numberOfColumns)
itemBuffer: 5
itemHeight: ITEM_HEIGHT
else
div className: 'beatmapsets__empty',
el Img2x,
src: '/images/layout/beatmaps/not-found.png'
alt: osu.trans("beatmaps.listing.search.not-found")
title: osu.trans("beatmaps.listing.search.not-found")
osu.trans("beatmaps.listing.search.not-found-quote")
if !controller.isSupporterMissing
div className: 'beatmapsets__paginator',
el Paginator,
error: controller.error
loading: controller.isPaging
more: controller.hasMore
sorting = ->
[field, order] = controller.filters.displaySort.split('_')
{ field, order }
renderLinkToSupporterTag = (filterText) ->
url = laroute.route('store.products.show', product: 'supporter-tag')
link = "<a href=\"#{url}\">#{osu.trans 'beatmaps.listing.search.supporter_filter_quote.link_text'}</a>"
p
dangerouslySetInnerHTML:
__html: osu.trans 'beatmaps.listing.search.supporter_filter_quote._',
filters: filterText
link: link
| 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 { Paginator } from './paginator'
import { SearchPanel } from './search-panel'
import { SearchSort } from './search-sort'
import { BeatmapsetPanel } from 'beatmapset-panel'
import { Img2x } from 'img2x'
import { observe, observable } from 'mobx'
import { Observer } from 'mobx-react'
import core from 'osu-core-singleton'
import * as React from 'react'
import { a, div, p } from 'react-dom-factories'
import VirtualList from 'react-virtual-list'
el = React.createElement
beatmapsetStore = core.dataStore.beatmapsetStore
controller = core.beatmapsetSearchController
ITEM_HEIGHT = 205 # needs to be known in advance to calculate size of virtual scrolling area.
ListRender = ({ virtual, itemHeight }) ->
style = _.extend {}, virtual.style
div
style: style
div
className: 'beatmapsets__items'
virtual.items.map (row) ->
div
className: 'beatmapsets__items-row'
key: (beatmapsetId for beatmapsetId in row).join('-')
for beatmapsetId in row
div
className: 'beatmapsets__item'
key: beatmapsetId
el BeatmapsetPanel, beatmap: beatmapsetStore.get(beatmapsetId)
# stored in an observable so a rerender will occur when the HOC gets updated.
Observables = observable
BeatmapList: VirtualList()(ListRender)
numberOfColumns: if osu.isDesktop() then 2 else 1
observe Observables, 'numberOfColumns', (change) ->
if change.oldValue != change.newValue
Observables.BeatmapList = VirtualList()(ListRender)
export class SearchContent extends React.Component
componentDidMount: ->
$(window).on 'resize.beatmaps-search-content', ->
count = if osu.isDesktop() then 2 else 1
Observables.numberOfColumns = count if Observables.numberOfColumns != count
componentWillUnmount: ->
$(window).off '.beatmaps-search-content'
render: ->
el Observer, null, () =>
beatmapsetIds = controller.currentBeatmapsetIds
firstBeatmapset = beatmapsetStore.get(beatmapsetIds[0])
searchBackground = if beatmapsetIds.length > 0 then firstBeatmapset?.covers?.cover else null
supporterRequiredFilterText = controller.supporterRequiredFilterText
listCssClasses = 'beatmapsets'
listCssClasses += ' beatmapsets--dimmed' if controller.isBusy
el React.Fragment, null,
el SearchPanel,
innerRef: @props.backToTopAnchor
background: searchBackground
availableFilters: @props.availableFilters
div className: 'js-sticky-header'
div
className: 'osu-layout__row osu-layout__row--page-compact'
div className: listCssClasses,
if currentUser.id?
div
className: 'beatmapsets__sort'
el SearchSort,
filters: controller.filters
sorting: sorting()
div
className: 'beatmapsets__content'
if controller.isSupporterMissing
div className: 'beatmapsets__empty',
el Img2x,
src: '/images/layout/beatmaps/supporter-required.png'
alt: osu.trans('beatmaps.listing.search.supporter_filter', filters: supporterRequiredFilterText)
title: osu.trans('beatmaps.listing.search.supporter_filter', filters: supporterRequiredFilterText)
renderLinkToSupporterTag(supporterRequiredFilterText)
else
if beatmapsetIds.length > 0
el Observables.BeatmapList,
items: _.chunk(beatmapsetIds, Observables.numberOfColumns)
itemBuffer: 5
itemHeight: ITEM_HEIGHT
else
div className: 'beatmapsets__empty',
el Img2x,
src: '/images/layout/beatmaps/not-found.png'
alt: osu.trans("beatmaps.listing.search.not-found")
title: osu.trans("beatmaps.listing.search.not-found")
osu.trans("beatmaps.listing.search.not-found-quote")
if !controller.isSupporterMissing
div className: 'beatmapsets__paginator',
el Paginator,
error: controller.error
loading: controller.isPaging
more: controller.hasMore
sorting = ->
[field, order] = controller.filters.displaySort.split('_')
{ field, order }
renderLinkToSupporterTag = (filterText) ->
url = laroute.route('store.products.show', product: 'supporter-tag')
link = "<a href=\"#{url}\">#{osu.trans 'beatmaps.listing.search.supporter_filter_quote.link_text'}</a>"
p
dangerouslySetInnerHTML:
__html: osu.trans 'beatmaps.listing.search.supporter_filter_quote._',
filters: filterText
link: link
|
[
{
"context": "}}\n ).bind this\n\n <ListGroupItem>\n *@{@props.email}\n <span className=\"pull-right\"><Glyphicon gl",
"end": 1031,
"score": 0.7107807993888855,
"start": 1020,
"tag": "EMAIL",
"value": "props.email"
}
] | picoCTF-web/web/coffee/react-utils.coffee | jingjiey/picoCTF | 1 | Tooltip = ReactBootstrap.Tooltip
OverlayTrigger = ReactBootstrap.OverlayTrigger
Input = ReactBootstrap.Input
Row = ReactBootstrap.Row
Col = ReactBootstrap.Col
Button = ReactBootstrap.Button
Panel = ReactBootstrap.Panel
ListGroup = ReactBootstrap.ListGroup
ListGroupItem = ReactBootstrap.ListGroupItem
Glyphicon = ReactBootstrap.Glyphicon
update = React.addons.update
Hint = React.createClass
propTypes:
text: React.PropTypes.string.isRequired
render: ->
tooltip = <Tooltip>{@props.text}</Tooltip>
<OverlayTrigger placement="top" overlay={tooltip}>
<Glyphicon className="pad" glyph="question-sign" style={fontSize:"0.8em"}/>
</OverlayTrigger>
EmailWhitelistItem = React.createClass
propTypes:
email: React.PropTypes.string.isRequired
pushUpdates: React.PropTypes.func.isRequired
render: ->
removeEmail = @props.pushUpdates.bind null, ((data) ->
update data, {email_filter: {$apply: _.partial _.without, _, @props.email}}
).bind this
<ListGroupItem>
*@{@props.email}
<span className="pull-right"><Glyphicon glyph="remove" onClick={removeEmail}/></span>
</ListGroupItem>
EmailWhitelist = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: -> {}
propTypes:
pushUpdates: React.PropTypes.func.isRequired
emails: React.PropTypes.array.isRequired
addEmailDomain: (e) ->
# It would probably make more sense to this kind of validation server side.
# However, it can't cause any real issue being here.
e.preventDefault()
if _.indexOf(@props.emails, @state.emailDomain) != -1
apiNotify {status: 0, message: "This email domain has already been whitelisted."}
else if _.indexOf(@state.emailDomain, "@") != -1
apiNotify {status: 0, message: "You should not include '@'. I want the email domain that follows '@'."}
else if _.indexOf(@state.emailDomain, ".") == -1
apiNotify {status: 0, message: "Your email domain did not include a '.' as I expected. Please make sure this is an email domain."}
else
@props.pushUpdates ((data) ->
update data, {email_filter: {$push: [@state.emailDomain]}}
).bind this
createItemDisplay: ->
<ListGroup>
{@props.emails.map ((email, i) ->
<EmailWhitelistItem key={i} email={email} pushUpdates={@props.pushUpdates}/>
).bind this}
</ListGroup>
render: ->
emptyItemDisplay =
<p>The whitelist is current empty. All emails will be accepted during registration.</p>
<div>
<h4>Email Domain Whitelist</h4>
<form onSubmit={@addEmailDomain}>
<Row>
<Input type="text" addonBefore="@ Domain" valueLink={@linkState "emailDomain"}/>
</Row>
<Row>
{if @props.emails.length > 0 then @createItemDisplay() else emptyItemDisplay}
</Row>
</form>
</div>
FormEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
entry: React.PropTypes.object.isRequired
description: React.PropTypes.string
render: ->
if @props.description
hint = <Hint text={@props.description} />
else
hint = ""
<Row>
<Col md={4}>
<h4 className="pull-left">
{hint}
{@props.name}
</h4>
</Col>
<Col md={8}>
{@props.entry}
</Col>
</Row>
TextEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
type: React.PropTypes.string.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
input = <Input className="form-control" type={@props.type} value={@props.value} onChange={@props.onChange} />
<FormEntry entry={input} {...@props} />
BooleanEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
value: React.PropTypes.bool.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
button = <Button bsSize="xsmall" onClick=@props.onChange>{if @props.value then "Enabled" else "Disabled"}</Button>
<FormEntry entry={button} {...@props} />
TimeEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
value: React.PropTypes.number.isRequired
onChange: React.PropTypes.func.isRequired
componentDidMount: ->
date = new Date(@props.value)
node = React.findDOMNode(@refs.datetimepicker)
$(node).datetimepicker
defaultDate: date
inline: true,
sideBySide: true
.on "dp.change", ((e) ->
@props.onChange e.date.toDate().getTime()
).bind(this)
render: ->
timepicker = <Panel> <div ref="datetimepicker"></div> </Panel>
<FormEntry entry={timepicker} {...@props} />
OptionEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
value: React.PropTypes.string.isRequired
options: React.PropTypes.array.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
buttons = _.map @props.options, ((option) ->
onClick = ((e) ->
@props.onChange option
).bind(this)
buttonClass = if option == @props.value then "active" else ""
<Button onClick={onClick} className={buttonClass}>{option}</Button>
).bind(this)
buttonGroup =
<ButtonGroup>
{buttons}
</ButtonGroup>
<FormEntry entry={buttonGroup} {...@props} />
| 75359 | Tooltip = ReactBootstrap.Tooltip
OverlayTrigger = ReactBootstrap.OverlayTrigger
Input = ReactBootstrap.Input
Row = ReactBootstrap.Row
Col = ReactBootstrap.Col
Button = ReactBootstrap.Button
Panel = ReactBootstrap.Panel
ListGroup = ReactBootstrap.ListGroup
ListGroupItem = ReactBootstrap.ListGroupItem
Glyphicon = ReactBootstrap.Glyphicon
update = React.addons.update
Hint = React.createClass
propTypes:
text: React.PropTypes.string.isRequired
render: ->
tooltip = <Tooltip>{@props.text}</Tooltip>
<OverlayTrigger placement="top" overlay={tooltip}>
<Glyphicon className="pad" glyph="question-sign" style={fontSize:"0.8em"}/>
</OverlayTrigger>
EmailWhitelistItem = React.createClass
propTypes:
email: React.PropTypes.string.isRequired
pushUpdates: React.PropTypes.func.isRequired
render: ->
removeEmail = @props.pushUpdates.bind null, ((data) ->
update data, {email_filter: {$apply: _.partial _.without, _, @props.email}}
).bind this
<ListGroupItem>
*@{@<EMAIL>}
<span className="pull-right"><Glyphicon glyph="remove" onClick={removeEmail}/></span>
</ListGroupItem>
EmailWhitelist = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: -> {}
propTypes:
pushUpdates: React.PropTypes.func.isRequired
emails: React.PropTypes.array.isRequired
addEmailDomain: (e) ->
# It would probably make more sense to this kind of validation server side.
# However, it can't cause any real issue being here.
e.preventDefault()
if _.indexOf(@props.emails, @state.emailDomain) != -1
apiNotify {status: 0, message: "This email domain has already been whitelisted."}
else if _.indexOf(@state.emailDomain, "@") != -1
apiNotify {status: 0, message: "You should not include '@'. I want the email domain that follows '@'."}
else if _.indexOf(@state.emailDomain, ".") == -1
apiNotify {status: 0, message: "Your email domain did not include a '.' as I expected. Please make sure this is an email domain."}
else
@props.pushUpdates ((data) ->
update data, {email_filter: {$push: [@state.emailDomain]}}
).bind this
createItemDisplay: ->
<ListGroup>
{@props.emails.map ((email, i) ->
<EmailWhitelistItem key={i} email={email} pushUpdates={@props.pushUpdates}/>
).bind this}
</ListGroup>
render: ->
emptyItemDisplay =
<p>The whitelist is current empty. All emails will be accepted during registration.</p>
<div>
<h4>Email Domain Whitelist</h4>
<form onSubmit={@addEmailDomain}>
<Row>
<Input type="text" addonBefore="@ Domain" valueLink={@linkState "emailDomain"}/>
</Row>
<Row>
{if @props.emails.length > 0 then @createItemDisplay() else emptyItemDisplay}
</Row>
</form>
</div>
FormEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
entry: React.PropTypes.object.isRequired
description: React.PropTypes.string
render: ->
if @props.description
hint = <Hint text={@props.description} />
else
hint = ""
<Row>
<Col md={4}>
<h4 className="pull-left">
{hint}
{@props.name}
</h4>
</Col>
<Col md={8}>
{@props.entry}
</Col>
</Row>
TextEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
type: React.PropTypes.string.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
input = <Input className="form-control" type={@props.type} value={@props.value} onChange={@props.onChange} />
<FormEntry entry={input} {...@props} />
BooleanEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
value: React.PropTypes.bool.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
button = <Button bsSize="xsmall" onClick=@props.onChange>{if @props.value then "Enabled" else "Disabled"}</Button>
<FormEntry entry={button} {...@props} />
TimeEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
value: React.PropTypes.number.isRequired
onChange: React.PropTypes.func.isRequired
componentDidMount: ->
date = new Date(@props.value)
node = React.findDOMNode(@refs.datetimepicker)
$(node).datetimepicker
defaultDate: date
inline: true,
sideBySide: true
.on "dp.change", ((e) ->
@props.onChange e.date.toDate().getTime()
).bind(this)
render: ->
timepicker = <Panel> <div ref="datetimepicker"></div> </Panel>
<FormEntry entry={timepicker} {...@props} />
OptionEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
value: React.PropTypes.string.isRequired
options: React.PropTypes.array.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
buttons = _.map @props.options, ((option) ->
onClick = ((e) ->
@props.onChange option
).bind(this)
buttonClass = if option == @props.value then "active" else ""
<Button onClick={onClick} className={buttonClass}>{option}</Button>
).bind(this)
buttonGroup =
<ButtonGroup>
{buttons}
</ButtonGroup>
<FormEntry entry={buttonGroup} {...@props} />
| true | Tooltip = ReactBootstrap.Tooltip
OverlayTrigger = ReactBootstrap.OverlayTrigger
Input = ReactBootstrap.Input
Row = ReactBootstrap.Row
Col = ReactBootstrap.Col
Button = ReactBootstrap.Button
Panel = ReactBootstrap.Panel
ListGroup = ReactBootstrap.ListGroup
ListGroupItem = ReactBootstrap.ListGroupItem
Glyphicon = ReactBootstrap.Glyphicon
update = React.addons.update
Hint = React.createClass
propTypes:
text: React.PropTypes.string.isRequired
render: ->
tooltip = <Tooltip>{@props.text}</Tooltip>
<OverlayTrigger placement="top" overlay={tooltip}>
<Glyphicon className="pad" glyph="question-sign" style={fontSize:"0.8em"}/>
</OverlayTrigger>
EmailWhitelistItem = React.createClass
propTypes:
email: React.PropTypes.string.isRequired
pushUpdates: React.PropTypes.func.isRequired
render: ->
removeEmail = @props.pushUpdates.bind null, ((data) ->
update data, {email_filter: {$apply: _.partial _.without, _, @props.email}}
).bind this
<ListGroupItem>
*@{@PI:EMAIL:<EMAIL>END_PI}
<span className="pull-right"><Glyphicon glyph="remove" onClick={removeEmail}/></span>
</ListGroupItem>
EmailWhitelist = React.createClass
mixins: [React.addons.LinkedStateMixin]
getInitialState: -> {}
propTypes:
pushUpdates: React.PropTypes.func.isRequired
emails: React.PropTypes.array.isRequired
addEmailDomain: (e) ->
# It would probably make more sense to this kind of validation server side.
# However, it can't cause any real issue being here.
e.preventDefault()
if _.indexOf(@props.emails, @state.emailDomain) != -1
apiNotify {status: 0, message: "This email domain has already been whitelisted."}
else if _.indexOf(@state.emailDomain, "@") != -1
apiNotify {status: 0, message: "You should not include '@'. I want the email domain that follows '@'."}
else if _.indexOf(@state.emailDomain, ".") == -1
apiNotify {status: 0, message: "Your email domain did not include a '.' as I expected. Please make sure this is an email domain."}
else
@props.pushUpdates ((data) ->
update data, {email_filter: {$push: [@state.emailDomain]}}
).bind this
createItemDisplay: ->
<ListGroup>
{@props.emails.map ((email, i) ->
<EmailWhitelistItem key={i} email={email} pushUpdates={@props.pushUpdates}/>
).bind this}
</ListGroup>
render: ->
emptyItemDisplay =
<p>The whitelist is current empty. All emails will be accepted during registration.</p>
<div>
<h4>Email Domain Whitelist</h4>
<form onSubmit={@addEmailDomain}>
<Row>
<Input type="text" addonBefore="@ Domain" valueLink={@linkState "emailDomain"}/>
</Row>
<Row>
{if @props.emails.length > 0 then @createItemDisplay() else emptyItemDisplay}
</Row>
</form>
</div>
FormEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
entry: React.PropTypes.object.isRequired
description: React.PropTypes.string
render: ->
if @props.description
hint = <Hint text={@props.description} />
else
hint = ""
<Row>
<Col md={4}>
<h4 className="pull-left">
{hint}
{@props.name}
</h4>
</Col>
<Col md={8}>
{@props.entry}
</Col>
</Row>
TextEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
type: React.PropTypes.string.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
input = <Input className="form-control" type={@props.type} value={@props.value} onChange={@props.onChange} />
<FormEntry entry={input} {...@props} />
BooleanEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
value: React.PropTypes.bool.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
button = <Button bsSize="xsmall" onClick=@props.onChange>{if @props.value then "Enabled" else "Disabled"}</Button>
<FormEntry entry={button} {...@props} />
TimeEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
value: React.PropTypes.number.isRequired
onChange: React.PropTypes.func.isRequired
componentDidMount: ->
date = new Date(@props.value)
node = React.findDOMNode(@refs.datetimepicker)
$(node).datetimepicker
defaultDate: date
inline: true,
sideBySide: true
.on "dp.change", ((e) ->
@props.onChange e.date.toDate().getTime()
).bind(this)
render: ->
timepicker = <Panel> <div ref="datetimepicker"></div> </Panel>
<FormEntry entry={timepicker} {...@props} />
OptionEntry = React.createClass
propTypes:
name: React.PropTypes.string.isRequired
value: React.PropTypes.string.isRequired
options: React.PropTypes.array.isRequired
onChange: React.PropTypes.func.isRequired
render: ->
buttons = _.map @props.options, ((option) ->
onClick = ((e) ->
@props.onChange option
).bind(this)
buttonClass = if option == @props.value then "active" else ""
<Button onClick={onClick} className={buttonClass}>{option}</Button>
).bind(this)
buttonGroup =
<ButtonGroup>
{buttons}
</ButtonGroup>
<FormEntry entry={buttonGroup} {...@props} />
|
[
{
"context": " {\n id: 1\n name: 'Manager'\n }\n {\n id: ",
"end": 471,
"score": 0.7295025587081909,
"start": 464,
"tag": "NAME",
"value": "Manager"
},
{
"context": " {\n id: 2\n name: 'Admin'\n }\n ]\n resource:\n ",
"end": 551,
"score": 0.8791541457176208,
"start": 546,
"tag": "NAME",
"value": "Admin"
},
{
"context": " {\n id: 1\n name: 'Manager'\n }\n {\n id: ",
"end": 1243,
"score": 0.8381823897361755,
"start": 1236,
"tag": "NAME",
"value": "Manager"
},
{
"context": " {\n id: 2\n name: 'Admin'\n }\n ]\n resource:\n ",
"end": 1323,
"score": 0.9452231526374817,
"start": 1318,
"tag": "NAME",
"value": "Admin"
},
{
"context": " {\n id: 0\n title: 'User'\n }\n {\n id: ",
"end": 2083,
"score": 0.8562334179878235,
"start": 2079,
"tag": "NAME",
"value": "User"
},
{
"context": " {\n id: 1\n name: 'Manager'\n }\n {\n id: ",
"end": 2165,
"score": 0.9995552897453308,
"start": 2158,
"tag": "NAME",
"value": "Manager"
},
{
"context": " {\n id: 2\n name: 'Admin'\n }\n ]\n resource:\n ",
"end": 2245,
"score": 0.9996422529220581,
"start": 2240,
"tag": "NAME",
"value": "Admin"
}
] | test/unit/specs/components/bitwise.spec.coffee | dimailn/vrf | 8 | import './setup'
import {
mount
} from '@vue/test-utils'
describe 'checkbox', ->
it "simple bitwise", ->
wrapper = mount(
template: '''
<rf-form :resource="resource">
<rf-bitwise name="flags" :options="options" ref="bitwise" />
</rf-form>
'''
data: ->
options: [
{
id: 0
title: 'User'
}
{
id: 1
name: 'Manager'
}
{
id: 2
name: 'Admin'
}
]
resource:
flags: 0
)
checkboxes = wrapper.findAll('input[type="checkbox"]')
checkboxes.at(2).setChecked(true)
checkboxes.at(1).setChecked(true)
await wrapper.vm.$nextTick()
expect(wrapper.vm.resource.flags).toBe 6
it "simple bitwise inverted", ->
wrapper = mount(
template: '''
<rf-form :resource="resource">
<rf-bitwise name="flags" :options="options" ref="bitwise" inverted />
</rf-form>
'''
data: ->
options: [
{
id: 0
title: 'User'
}
{
id: 1
name: 'Manager'
}
{
id: 2
name: 'Admin'
}
]
resource:
flags: 0
)
checkboxes = wrapper.findAll('input[type="checkbox"]')
checkboxes.at(2).setChecked(false)
checkboxes.at(1).setChecked(false)
await wrapper.vm.$nextTick()
expect(wrapper.vm.resource.flags).toBe 6
it "bitwise with checkboxes", ->
wrapper = mount(
template: '''
<rf-form :resource="resource">
<rf-bitwise name="flags" ref="bitwise">
<rf-checkbox name="User" power="0" />
<rf-checkbox name="Manager" power="1" />
<rf-checkbox name="Admin" power="2" />
</rf-bitwise>
</rf-form>
'''
data: ->
options: [
{
id: 0
title: 'User'
}
{
id: 1
name: 'Manager'
}
{
id: 2
name: 'Admin'
}
]
resource:
flags: 0
)
checkboxes = wrapper.findAll('input[type="checkbox"]')
checkboxes.at(2).setChecked(true)
checkboxes.at(1).setChecked(true)
await wrapper.vm.$nextTick()
expect(wrapper.vm.resource.flags).toBe 6
| 75263 | import './setup'
import {
mount
} from '@vue/test-utils'
describe 'checkbox', ->
it "simple bitwise", ->
wrapper = mount(
template: '''
<rf-form :resource="resource">
<rf-bitwise name="flags" :options="options" ref="bitwise" />
</rf-form>
'''
data: ->
options: [
{
id: 0
title: 'User'
}
{
id: 1
name: '<NAME>'
}
{
id: 2
name: '<NAME>'
}
]
resource:
flags: 0
)
checkboxes = wrapper.findAll('input[type="checkbox"]')
checkboxes.at(2).setChecked(true)
checkboxes.at(1).setChecked(true)
await wrapper.vm.$nextTick()
expect(wrapper.vm.resource.flags).toBe 6
it "simple bitwise inverted", ->
wrapper = mount(
template: '''
<rf-form :resource="resource">
<rf-bitwise name="flags" :options="options" ref="bitwise" inverted />
</rf-form>
'''
data: ->
options: [
{
id: 0
title: 'User'
}
{
id: 1
name: '<NAME>'
}
{
id: 2
name: '<NAME>'
}
]
resource:
flags: 0
)
checkboxes = wrapper.findAll('input[type="checkbox"]')
checkboxes.at(2).setChecked(false)
checkboxes.at(1).setChecked(false)
await wrapper.vm.$nextTick()
expect(wrapper.vm.resource.flags).toBe 6
it "bitwise with checkboxes", ->
wrapper = mount(
template: '''
<rf-form :resource="resource">
<rf-bitwise name="flags" ref="bitwise">
<rf-checkbox name="User" power="0" />
<rf-checkbox name="Manager" power="1" />
<rf-checkbox name="Admin" power="2" />
</rf-bitwise>
</rf-form>
'''
data: ->
options: [
{
id: 0
title: '<NAME>'
}
{
id: 1
name: '<NAME>'
}
{
id: 2
name: '<NAME>'
}
]
resource:
flags: 0
)
checkboxes = wrapper.findAll('input[type="checkbox"]')
checkboxes.at(2).setChecked(true)
checkboxes.at(1).setChecked(true)
await wrapper.vm.$nextTick()
expect(wrapper.vm.resource.flags).toBe 6
| true | import './setup'
import {
mount
} from '@vue/test-utils'
describe 'checkbox', ->
it "simple bitwise", ->
wrapper = mount(
template: '''
<rf-form :resource="resource">
<rf-bitwise name="flags" :options="options" ref="bitwise" />
</rf-form>
'''
data: ->
options: [
{
id: 0
title: 'User'
}
{
id: 1
name: 'PI:NAME:<NAME>END_PI'
}
{
id: 2
name: 'PI:NAME:<NAME>END_PI'
}
]
resource:
flags: 0
)
checkboxes = wrapper.findAll('input[type="checkbox"]')
checkboxes.at(2).setChecked(true)
checkboxes.at(1).setChecked(true)
await wrapper.vm.$nextTick()
expect(wrapper.vm.resource.flags).toBe 6
it "simple bitwise inverted", ->
wrapper = mount(
template: '''
<rf-form :resource="resource">
<rf-bitwise name="flags" :options="options" ref="bitwise" inverted />
</rf-form>
'''
data: ->
options: [
{
id: 0
title: 'User'
}
{
id: 1
name: 'PI:NAME:<NAME>END_PI'
}
{
id: 2
name: 'PI:NAME:<NAME>END_PI'
}
]
resource:
flags: 0
)
checkboxes = wrapper.findAll('input[type="checkbox"]')
checkboxes.at(2).setChecked(false)
checkboxes.at(1).setChecked(false)
await wrapper.vm.$nextTick()
expect(wrapper.vm.resource.flags).toBe 6
it "bitwise with checkboxes", ->
wrapper = mount(
template: '''
<rf-form :resource="resource">
<rf-bitwise name="flags" ref="bitwise">
<rf-checkbox name="User" power="0" />
<rf-checkbox name="Manager" power="1" />
<rf-checkbox name="Admin" power="2" />
</rf-bitwise>
</rf-form>
'''
data: ->
options: [
{
id: 0
title: 'PI:NAME:<NAME>END_PI'
}
{
id: 1
name: 'PI:NAME:<NAME>END_PI'
}
{
id: 2
name: 'PI:NAME:<NAME>END_PI'
}
]
resource:
flags: 0
)
checkboxes = wrapper.findAll('input[type="checkbox"]')
checkboxes.at(2).setChecked(true)
checkboxes.at(1).setChecked(true)
await wrapper.vm.$nextTick()
expect(wrapper.vm.resource.flags).toBe 6
|
[
{
"context": "c test\", ->\n data = []\n obj = id: 5, name: 'test'\n data.should.be.empty\n data.push obj\n d",
"end": 396,
"score": 0.9686756134033203,
"start": 392,
"tag": "NAME",
"value": "test"
}
] | test/src/specs/eventparser.spec.coffee | 1egoman/eventparser | 0 | 'use strict';
eventparser = source("eventparser")
describe "basic tests", ->
it "standard async test", (done) ->
bool = false
bool.should.be.false
setTimeout ->
bool.should.be.false
bool = true
bool.should.be.true
150
setTimeout ->
bool.should.be.true
done()
300
it "standard sync test", ->
data = []
obj = id: 5, name: 'test'
data.should.be.empty
data.push obj
data.should.have.length 1
# soft equal
data[0].should.be.eql obj
# hard equal
data[0].should.be.equal obj
# Now on to a `real` test
it "eventparser should be awesome", ->
eventparser.should.have.keys 'awesome'
eventparser.awesome.should.be.a 'function'
eventparser.awesome().should.be.equal 'awesome' | 61214 | 'use strict';
eventparser = source("eventparser")
describe "basic tests", ->
it "standard async test", (done) ->
bool = false
bool.should.be.false
setTimeout ->
bool.should.be.false
bool = true
bool.should.be.true
150
setTimeout ->
bool.should.be.true
done()
300
it "standard sync test", ->
data = []
obj = id: 5, name: '<NAME>'
data.should.be.empty
data.push obj
data.should.have.length 1
# soft equal
data[0].should.be.eql obj
# hard equal
data[0].should.be.equal obj
# Now on to a `real` test
it "eventparser should be awesome", ->
eventparser.should.have.keys 'awesome'
eventparser.awesome.should.be.a 'function'
eventparser.awesome().should.be.equal 'awesome' | true | 'use strict';
eventparser = source("eventparser")
describe "basic tests", ->
it "standard async test", (done) ->
bool = false
bool.should.be.false
setTimeout ->
bool.should.be.false
bool = true
bool.should.be.true
150
setTimeout ->
bool.should.be.true
done()
300
it "standard sync test", ->
data = []
obj = id: 5, name: 'PI:NAME:<NAME>END_PI'
data.should.be.empty
data.push obj
data.should.have.length 1
# soft equal
data[0].should.be.eql obj
# hard equal
data[0].should.be.equal obj
# Now on to a `real` test
it "eventparser should be awesome", ->
eventparser.should.have.keys 'awesome'
eventparser.awesome.should.be.a 'function'
eventparser.awesome().should.be.equal 'awesome' |
[
{
"context": "w(\n index: index\n code: code\n name: name\n price: displayPrice(price, rounded)\n )\n ",
"end": 566,
"score": 0.6180253028869629,
"start": 562,
"tag": "NAME",
"value": "name"
}
] | kirppu/static_src/js/checkout/item_receipt_table.coffee | tracon/kirppu | 0 | class @ItemReceiptTable
# @param {Object} options
# @param {str} [optional] options.caption
# @param {bool} [optional] options.autoNumber
constructor: (options=null) ->
options = Object.assign(
caption: null
autoNumber: false
splitTitle: false
, options
)
@_table = Template.item_receipt_table(options)
@_table = $(@_table)
@body = @_table.find("tbody")
createRow: (index, code, name, price=null, rounded=false) ->
row = Template.item_receipt_table_row(
index: index
code: code
name: name
price: displayPrice(price, rounded)
)
return $(row)
row: (args) ->
row = Template.item_receipt_table_row(args)
return $(row)
render: () -> @_table
| 30433 | class @ItemReceiptTable
# @param {Object} options
# @param {str} [optional] options.caption
# @param {bool} [optional] options.autoNumber
constructor: (options=null) ->
options = Object.assign(
caption: null
autoNumber: false
splitTitle: false
, options
)
@_table = Template.item_receipt_table(options)
@_table = $(@_table)
@body = @_table.find("tbody")
createRow: (index, code, name, price=null, rounded=false) ->
row = Template.item_receipt_table_row(
index: index
code: code
name: <NAME>
price: displayPrice(price, rounded)
)
return $(row)
row: (args) ->
row = Template.item_receipt_table_row(args)
return $(row)
render: () -> @_table
| true | class @ItemReceiptTable
# @param {Object} options
# @param {str} [optional] options.caption
# @param {bool} [optional] options.autoNumber
constructor: (options=null) ->
options = Object.assign(
caption: null
autoNumber: false
splitTitle: false
, options
)
@_table = Template.item_receipt_table(options)
@_table = $(@_table)
@body = @_table.find("tbody")
createRow: (index, code, name, price=null, rounded=false) ->
row = Template.item_receipt_table_row(
index: index
code: code
name: PI:NAME:<NAME>END_PI
price: displayPrice(price, rounded)
)
return $(row)
row: (args) ->
row = Template.item_receipt_table_row(args)
return $(row)
render: () -> @_table
|
[
{
"context": "uerystring'\n_ = require 'underscore'\n\nFLICKR_KEY=\"9ff0fef9b6c8e4509682e9576b9480f3\"\n\nmodule.exports = (query, options = {}, callback",
"end": 137,
"score": 0.9997614026069641,
"start": 105,
"tag": "KEY",
"value": "9ff0fef9b6c8e4509682e9576b9480f3"
}
] | lib/flickr_search.coffee | KyleAMathews/react-flickr-example | 2 | request = require 'superagent'
querystring = require 'querystring'
_ = require 'underscore'
FLICKR_KEY="9ff0fef9b6c8e4509682e9576b9480f3"
module.exports = (query, options = {}, callback) ->
tags = query.split(' ').join(',')
defaultOptions =
method: 'flickr.photos.search'
api_key: FLICKR_KEY
tags: tags
tag_mode: 'all'
per_page: 100
page: 1
format: 'json'
media: 'photos'
sort: 'interestingness-desc'
nojsoncallback: 1
combinedOptions = _.extend defaultOptions, options
strOptions = querystring.stringify(combinedOptions)
url = "https://api.flickr.com/services/rest/?#{strOptions}"
console.log url
request url, (res) ->
generateFlickrImageURL = (data) ->
return {
large: "https://farm#{data.farm}.staticflickr.com/#{data.server}/#{data.id}_#{data.secret}_z.jpg"
medium: "https://farm#{data.farm}.staticflickr.com/#{data.server}/#{data.id}_#{data.secret}_n.jpg"
title: data.title
id: data.id
}
photos = []
for photo in res.body.photos.photo
photos.push generateFlickrImageURL(photo)
return callback(null, photos)
return null
| 76815 | request = require 'superagent'
querystring = require 'querystring'
_ = require 'underscore'
FLICKR_KEY="<KEY>"
module.exports = (query, options = {}, callback) ->
tags = query.split(' ').join(',')
defaultOptions =
method: 'flickr.photos.search'
api_key: FLICKR_KEY
tags: tags
tag_mode: 'all'
per_page: 100
page: 1
format: 'json'
media: 'photos'
sort: 'interestingness-desc'
nojsoncallback: 1
combinedOptions = _.extend defaultOptions, options
strOptions = querystring.stringify(combinedOptions)
url = "https://api.flickr.com/services/rest/?#{strOptions}"
console.log url
request url, (res) ->
generateFlickrImageURL = (data) ->
return {
large: "https://farm#{data.farm}.staticflickr.com/#{data.server}/#{data.id}_#{data.secret}_z.jpg"
medium: "https://farm#{data.farm}.staticflickr.com/#{data.server}/#{data.id}_#{data.secret}_n.jpg"
title: data.title
id: data.id
}
photos = []
for photo in res.body.photos.photo
photos.push generateFlickrImageURL(photo)
return callback(null, photos)
return null
| true | request = require 'superagent'
querystring = require 'querystring'
_ = require 'underscore'
FLICKR_KEY="PI:KEY:<KEY>END_PI"
module.exports = (query, options = {}, callback) ->
tags = query.split(' ').join(',')
defaultOptions =
method: 'flickr.photos.search'
api_key: FLICKR_KEY
tags: tags
tag_mode: 'all'
per_page: 100
page: 1
format: 'json'
media: 'photos'
sort: 'interestingness-desc'
nojsoncallback: 1
combinedOptions = _.extend defaultOptions, options
strOptions = querystring.stringify(combinedOptions)
url = "https://api.flickr.com/services/rest/?#{strOptions}"
console.log url
request url, (res) ->
generateFlickrImageURL = (data) ->
return {
large: "https://farm#{data.farm}.staticflickr.com/#{data.server}/#{data.id}_#{data.secret}_z.jpg"
medium: "https://farm#{data.farm}.staticflickr.com/#{data.server}/#{data.id}_#{data.secret}_n.jpg"
title: data.title
id: data.id
}
photos = []
for photo in res.body.photos.photo
photos.push generateFlickrImageURL(photo)
return callback(null, photos)
return null
|
[
{
"context": "xpect(c.outPorts.ports).to.have.keys [\n 'out'\n ]\n done()\n c.once 'network',",
"end": 9198,
"score": 0.5112891793251038,
"start": 9195,
"tag": "KEY",
"value": "out"
}
] | spec/Subgraph.coffee | aretecode/noflo-built | 1 | if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/
chai = require 'chai' unless chai
noflo = require '../src/lib/NoFlo.coffee'
path = require 'path'
root = path.resolve __dirname, '../'
urlPrefix = './'
else
noflo = require 'noflo'
root = 'noflo'
urlPrefix = '/'
describe 'NoFlo Graph component', ->
c = null
g = null
loader = null
before (done) ->
loader = new noflo.ComponentLoader root
loader.listComponents done
beforeEach (done) ->
loader.load 'Graph', (err, instance) ->
return done err if err
c = instance
g = noflo.internalSocket.createSocket()
c.inPorts.graph.attach g
done()
Split = ->
inst = new noflo.Component
inst.inPorts.add 'in',
datatype: 'all'
inst.outPorts.add 'out',
datatype: 'all'
inst.process (input, output) ->
data = input.getData 'in'
output.sendDone
out: data
SubgraphMerge = ->
inst = new noflo.Component
inst.inPorts.add 'in',
datatype: 'all'
inst.outPorts.add 'out',
datatype: 'all'
inst.forwardBrackets = {}
inst.process (input, output) ->
packet = input.get 'in'
return output.done() unless packet.type is 'data'
output.sendDone
out: packet.data
describe 'initially', ->
it 'should be ready', ->
chai.expect(c.ready).to.be.true
it 'should not contain a network', ->
chai.expect(c.network).to.be.null
it 'should have a baseDir', ->
chai.expect(c.baseDir).to.equal root
it 'should only have the graph inport', ->
chai.expect(c.inPorts.ports).to.have.keys ['graph']
chai.expect(c.outPorts.ports).to.be.empty
describe 'with JSON graph definition', ->
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', (network) ->
network.loader.components.Split = Split
network.loader.registerComponent '', 'Merge', SubgraphMerge
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.start (err) ->
done err if err
g.send
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
it 'should expose available ports', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
]
chai.expect(c.outPorts.ports).to.be.empty
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
connections: [
src:
process: 'Merge'
port: 'out'
tgt:
process: 'Split'
port: 'in'
]
it 'should update description from the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
chai.expect(c.description).to.equal 'Hello, World!'
done()
c.once 'network', (network) ->
network.loader.components.Split = Split
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
chai.expect(c.description).to.equal 'Hello, World!'
c.start (err) ->
done err if err
g.send
properties:
description: 'Hello, World!'
processes:
Split:
component: 'Split'
it 'should expose only exported ports when they exist', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send
outports:
out:
process: 'Split'
port: 'out'
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
connections: [
src:
process: 'Merge'
port: 'out'
tgt:
process: 'Split'
port: 'in'
]
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
done()
ins.send 'Foo'
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send
inports:
in:
process: 'Merge'
port: 'in'
outports:
out:
process: 'Split'
port: 'out'
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
connections: [
src:
process: 'Merge'
port: 'out'
tgt:
process: 'Split'
port: 'in'
]
describe 'with a Graph instance', ->
gr = new noflo.Graph 'Hello, world'
gr.baseDir = root
gr.addNode 'Split', 'Split'
gr.addNode 'Merge', 'Merge'
gr.addEdge 'Merge', 'out', 'Split', 'in'
gr.addInport 'in', 'Merge', 'in'
gr.addOutport 'out', 'Split', 'out'
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send gr
chai.expect(c.ready).to.be.false
it 'should expose available ports', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
'in'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send gr
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
done()
ins.send 'Foo'
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send gr
describe 'with a FBP file with INPORTs and OUTPORTs', ->
file = "#{urlPrefix}spec/fixtures/subgraph.fbp"
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
chai.expect(c.ready).to.be.false
it 'should expose available ports', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
'in'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
received = false
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
received = true
out.on 'disconnect', ->
chai.expect(received, 'should have transmitted data').to.equal true
done()
ins.connect()
ins.send 'Foo'
ins.disconnect()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
describe 'with a FBP file with legacy EXPORTS', ->
file = "#{urlPrefix}spec/fixtures/subgraph_legacy.fbp"
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
chai.expect(c.ready).to.be.false
it 'should expose available ports', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
'in'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
it 'should have disambiguated the exported ports', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.network.graph.exports).to.be.empty
chai.expect(c.network.graph.inports).to.be.not.empty
chai.expect(c.network.graph.inports.in).to.be.an 'object'
chai.expect(c.network.graph.outports).to.be.not.empty
chai.expect(c.network.graph.outports.out).to.be.an 'object'
done()
c.once 'network', ->
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
g.send file
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
received = false
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
received = true
out.on 'disconnect', ->
chai.expect(received, 'should have transmitted data').to.equal true
done()
ins.connect()
ins.send 'Foo'
ins.disconnect()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
describe 'when a subgraph is used as a component', ->
createSplit = ->
c = new noflo.Component
c.inPorts.add 'in',
required: true
datatype: 'string'
default: 'default-value',
c.outPorts.add 'out',
datatype: 'string'
c.process (input, output) ->
data = input.getData 'in'
output.sendDone
out: data
grDefaults = new noflo.Graph 'Child Graph Using Defaults'
grDefaults.addNode 'SplitIn', 'Split'
grDefaults.addNode 'SplitOut', 'Split'
grDefaults.addInport 'in', 'SplitIn', 'in'
grDefaults.addOutport 'out', 'SplitOut', 'out'
grDefaults.addEdge 'SplitIn', 'out', 'SplitOut', 'in'
grInitials = new noflo.Graph 'Child Graph Using Initials'
grInitials.addNode 'SplitIn', 'Split'
grInitials.addNode 'SplitOut', 'Split'
grInitials.addInport 'in', 'SplitIn', 'in'
grInitials.addOutport 'out', 'SplitOut', 'out'
grInitials.addInitial 'initial-value', 'SplitIn', 'in'
grInitials.addEdge 'SplitIn', 'out', 'SplitOut', 'in'
it 'should send defaults', (done) ->
@timeout 6000
cl = new noflo.ComponentLoader root
cl.listComponents (err, components) ->
return done err if err
cl.components.Split = createSplit
cl.components.Defaults = grDefaults
cl.components.Initials = grInitials
cl.load 'Defaults', (err, inst) ->
o = noflo.internalSocket.createSocket()
inst.outPorts.out.attach o
o.once 'data', (data) ->
chai.expect(data).to.equal 'default-value'
done()
inst.start()
it 'should send initials', (done) ->
@timeout 6000
cl = new noflo.ComponentLoader root
cl.listComponents (err, components) ->
return done err if err
cl.components.Split = createSplit
cl.components.Defaults = grDefaults
cl.components.Initials = grInitials
cl.load 'Initials', (err, inst) ->
o = noflo.internalSocket.createSocket()
inst.outPorts.out.attach o
o.once 'data', (data) ->
chai.expect(data).to.equal 'initial-value'
done()
inst.start()
it 'should not send defaults when an inport is attached externally', (done) ->
@timeout 6000
cl = new noflo.ComponentLoader root
cl.listComponents (err, components) ->
return done err if err
cl.components.Split = createSplit
cl.components.Defaults = grDefaults
cl.components.Initials = grInitials
cl.load 'Defaults', (err, inst) ->
i = noflo.internalSocket.createSocket()
o = noflo.internalSocket.createSocket()
inst.inPorts.in.attach i
inst.outPorts.out.attach o
o.once 'data', (data) ->
chai.expect(data).to.equal 'Foo'
done()
inst.start()
i.send 'Foo'
| 24615 | if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/
chai = require 'chai' unless chai
noflo = require '../src/lib/NoFlo.coffee'
path = require 'path'
root = path.resolve __dirname, '../'
urlPrefix = './'
else
noflo = require 'noflo'
root = 'noflo'
urlPrefix = '/'
describe 'NoFlo Graph component', ->
c = null
g = null
loader = null
before (done) ->
loader = new noflo.ComponentLoader root
loader.listComponents done
beforeEach (done) ->
loader.load 'Graph', (err, instance) ->
return done err if err
c = instance
g = noflo.internalSocket.createSocket()
c.inPorts.graph.attach g
done()
Split = ->
inst = new noflo.Component
inst.inPorts.add 'in',
datatype: 'all'
inst.outPorts.add 'out',
datatype: 'all'
inst.process (input, output) ->
data = input.getData 'in'
output.sendDone
out: data
SubgraphMerge = ->
inst = new noflo.Component
inst.inPorts.add 'in',
datatype: 'all'
inst.outPorts.add 'out',
datatype: 'all'
inst.forwardBrackets = {}
inst.process (input, output) ->
packet = input.get 'in'
return output.done() unless packet.type is 'data'
output.sendDone
out: packet.data
describe 'initially', ->
it 'should be ready', ->
chai.expect(c.ready).to.be.true
it 'should not contain a network', ->
chai.expect(c.network).to.be.null
it 'should have a baseDir', ->
chai.expect(c.baseDir).to.equal root
it 'should only have the graph inport', ->
chai.expect(c.inPorts.ports).to.have.keys ['graph']
chai.expect(c.outPorts.ports).to.be.empty
describe 'with JSON graph definition', ->
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', (network) ->
network.loader.components.Split = Split
network.loader.registerComponent '', 'Merge', SubgraphMerge
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.start (err) ->
done err if err
g.send
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
it 'should expose available ports', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
]
chai.expect(c.outPorts.ports).to.be.empty
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
connections: [
src:
process: 'Merge'
port: 'out'
tgt:
process: 'Split'
port: 'in'
]
it 'should update description from the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
chai.expect(c.description).to.equal 'Hello, World!'
done()
c.once 'network', (network) ->
network.loader.components.Split = Split
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
chai.expect(c.description).to.equal 'Hello, World!'
c.start (err) ->
done err if err
g.send
properties:
description: 'Hello, World!'
processes:
Split:
component: 'Split'
it 'should expose only exported ports when they exist', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send
outports:
out:
process: 'Split'
port: 'out'
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
connections: [
src:
process: 'Merge'
port: 'out'
tgt:
process: 'Split'
port: 'in'
]
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
done()
ins.send 'Foo'
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send
inports:
in:
process: 'Merge'
port: 'in'
outports:
out:
process: 'Split'
port: 'out'
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
connections: [
src:
process: 'Merge'
port: 'out'
tgt:
process: 'Split'
port: 'in'
]
describe 'with a Graph instance', ->
gr = new noflo.Graph 'Hello, world'
gr.baseDir = root
gr.addNode 'Split', 'Split'
gr.addNode 'Merge', 'Merge'
gr.addEdge 'Merge', 'out', 'Split', 'in'
gr.addInport 'in', 'Merge', 'in'
gr.addOutport 'out', 'Split', 'out'
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send gr
chai.expect(c.ready).to.be.false
it 'should expose available ports', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
'in'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send gr
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
done()
ins.send 'Foo'
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send gr
describe 'with a FBP file with INPORTs and OUTPORTs', ->
file = "#{urlPrefix}spec/fixtures/subgraph.fbp"
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
chai.expect(c.ready).to.be.false
it 'should expose available ports', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
'in'
]
chai.expect(c.outPorts.ports).to.have.keys [
'<KEY>'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
received = false
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
received = true
out.on 'disconnect', ->
chai.expect(received, 'should have transmitted data').to.equal true
done()
ins.connect()
ins.send 'Foo'
ins.disconnect()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
describe 'with a FBP file with legacy EXPORTS', ->
file = "#{urlPrefix}spec/fixtures/subgraph_legacy.fbp"
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
chai.expect(c.ready).to.be.false
it 'should expose available ports', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
'in'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
it 'should have disambiguated the exported ports', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.network.graph.exports).to.be.empty
chai.expect(c.network.graph.inports).to.be.not.empty
chai.expect(c.network.graph.inports.in).to.be.an 'object'
chai.expect(c.network.graph.outports).to.be.not.empty
chai.expect(c.network.graph.outports.out).to.be.an 'object'
done()
c.once 'network', ->
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
g.send file
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
received = false
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
received = true
out.on 'disconnect', ->
chai.expect(received, 'should have transmitted data').to.equal true
done()
ins.connect()
ins.send 'Foo'
ins.disconnect()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
describe 'when a subgraph is used as a component', ->
createSplit = ->
c = new noflo.Component
c.inPorts.add 'in',
required: true
datatype: 'string'
default: 'default-value',
c.outPorts.add 'out',
datatype: 'string'
c.process (input, output) ->
data = input.getData 'in'
output.sendDone
out: data
grDefaults = new noflo.Graph 'Child Graph Using Defaults'
grDefaults.addNode 'SplitIn', 'Split'
grDefaults.addNode 'SplitOut', 'Split'
grDefaults.addInport 'in', 'SplitIn', 'in'
grDefaults.addOutport 'out', 'SplitOut', 'out'
grDefaults.addEdge 'SplitIn', 'out', 'SplitOut', 'in'
grInitials = new noflo.Graph 'Child Graph Using Initials'
grInitials.addNode 'SplitIn', 'Split'
grInitials.addNode 'SplitOut', 'Split'
grInitials.addInport 'in', 'SplitIn', 'in'
grInitials.addOutport 'out', 'SplitOut', 'out'
grInitials.addInitial 'initial-value', 'SplitIn', 'in'
grInitials.addEdge 'SplitIn', 'out', 'SplitOut', 'in'
it 'should send defaults', (done) ->
@timeout 6000
cl = new noflo.ComponentLoader root
cl.listComponents (err, components) ->
return done err if err
cl.components.Split = createSplit
cl.components.Defaults = grDefaults
cl.components.Initials = grInitials
cl.load 'Defaults', (err, inst) ->
o = noflo.internalSocket.createSocket()
inst.outPorts.out.attach o
o.once 'data', (data) ->
chai.expect(data).to.equal 'default-value'
done()
inst.start()
it 'should send initials', (done) ->
@timeout 6000
cl = new noflo.ComponentLoader root
cl.listComponents (err, components) ->
return done err if err
cl.components.Split = createSplit
cl.components.Defaults = grDefaults
cl.components.Initials = grInitials
cl.load 'Initials', (err, inst) ->
o = noflo.internalSocket.createSocket()
inst.outPorts.out.attach o
o.once 'data', (data) ->
chai.expect(data).to.equal 'initial-value'
done()
inst.start()
it 'should not send defaults when an inport is attached externally', (done) ->
@timeout 6000
cl = new noflo.ComponentLoader root
cl.listComponents (err, components) ->
return done err if err
cl.components.Split = createSplit
cl.components.Defaults = grDefaults
cl.components.Initials = grInitials
cl.load 'Defaults', (err, inst) ->
i = noflo.internalSocket.createSocket()
o = noflo.internalSocket.createSocket()
inst.inPorts.in.attach i
inst.outPorts.out.attach o
o.once 'data', (data) ->
chai.expect(data).to.equal 'Foo'
done()
inst.start()
i.send 'Foo'
| true | if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/
chai = require 'chai' unless chai
noflo = require '../src/lib/NoFlo.coffee'
path = require 'path'
root = path.resolve __dirname, '../'
urlPrefix = './'
else
noflo = require 'noflo'
root = 'noflo'
urlPrefix = '/'
describe 'NoFlo Graph component', ->
c = null
g = null
loader = null
before (done) ->
loader = new noflo.ComponentLoader root
loader.listComponents done
beforeEach (done) ->
loader.load 'Graph', (err, instance) ->
return done err if err
c = instance
g = noflo.internalSocket.createSocket()
c.inPorts.graph.attach g
done()
Split = ->
inst = new noflo.Component
inst.inPorts.add 'in',
datatype: 'all'
inst.outPorts.add 'out',
datatype: 'all'
inst.process (input, output) ->
data = input.getData 'in'
output.sendDone
out: data
SubgraphMerge = ->
inst = new noflo.Component
inst.inPorts.add 'in',
datatype: 'all'
inst.outPorts.add 'out',
datatype: 'all'
inst.forwardBrackets = {}
inst.process (input, output) ->
packet = input.get 'in'
return output.done() unless packet.type is 'data'
output.sendDone
out: packet.data
describe 'initially', ->
it 'should be ready', ->
chai.expect(c.ready).to.be.true
it 'should not contain a network', ->
chai.expect(c.network).to.be.null
it 'should have a baseDir', ->
chai.expect(c.baseDir).to.equal root
it 'should only have the graph inport', ->
chai.expect(c.inPorts.ports).to.have.keys ['graph']
chai.expect(c.outPorts.ports).to.be.empty
describe 'with JSON graph definition', ->
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', (network) ->
network.loader.components.Split = Split
network.loader.registerComponent '', 'Merge', SubgraphMerge
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.start (err) ->
done err if err
g.send
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
it 'should expose available ports', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
]
chai.expect(c.outPorts.ports).to.be.empty
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
connections: [
src:
process: 'Merge'
port: 'out'
tgt:
process: 'Split'
port: 'in'
]
it 'should update description from the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
chai.expect(c.description).to.equal 'Hello, World!'
done()
c.once 'network', (network) ->
network.loader.components.Split = Split
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
chai.expect(c.description).to.equal 'Hello, World!'
c.start (err) ->
done err if err
g.send
properties:
description: 'Hello, World!'
processes:
Split:
component: 'Split'
it 'should expose only exported ports when they exist', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send
outports:
out:
process: 'Split'
port: 'out'
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
connections: [
src:
process: 'Merge'
port: 'out'
tgt:
process: 'Split'
port: 'in'
]
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
done()
ins.send 'Foo'
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send
inports:
in:
process: 'Merge'
port: 'in'
outports:
out:
process: 'Split'
port: 'out'
processes:
Split:
component: 'Split'
Merge:
component: 'Merge'
connections: [
src:
process: 'Merge'
port: 'out'
tgt:
process: 'Split'
port: 'in'
]
describe 'with a Graph instance', ->
gr = new noflo.Graph 'Hello, world'
gr.baseDir = root
gr.addNode 'Split', 'Split'
gr.addNode 'Merge', 'Merge'
gr.addEdge 'Merge', 'out', 'Split', 'in'
gr.addInport 'in', 'Merge', 'in'
gr.addOutport 'out', 'Split', 'out'
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send gr
chai.expect(c.ready).to.be.false
it 'should expose available ports', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
'in'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send gr
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
done()
ins.send 'Foo'
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send gr
describe 'with a FBP file with INPORTs and OUTPORTs', ->
file = "#{urlPrefix}spec/fixtures/subgraph.fbp"
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
chai.expect(c.ready).to.be.false
it 'should expose available ports', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
'in'
]
chai.expect(c.outPorts.ports).to.have.keys [
'PI:KEY:<KEY>END_PI'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
received = false
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
received = true
out.on 'disconnect', ->
chai.expect(received, 'should have transmitted data').to.equal true
done()
ins.connect()
ins.send 'Foo'
ins.disconnect()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
describe 'with a FBP file with legacy EXPORTS', ->
file = "#{urlPrefix}spec/fixtures/subgraph_legacy.fbp"
it 'should emit a ready event after network has been loaded', (done) ->
@timeout 6000
c.baseDir = root
c.once 'ready', ->
chai.expect(c.network).not.to.be.null
chai.expect(c.ready).to.be.true
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
chai.expect(c.ready).to.be.false
it 'should expose available ports', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.inPorts.ports).to.have.keys [
'graph'
'in'
]
chai.expect(c.outPorts.ports).to.have.keys [
'out'
]
done()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
it 'should have disambiguated the exported ports', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
chai.expect(c.network.graph.exports).to.be.empty
chai.expect(c.network.graph.inports).to.be.not.empty
chai.expect(c.network.graph.inports.in).to.be.an 'object'
chai.expect(c.network.graph.outports).to.be.not.empty
chai.expect(c.network.graph.outports.out).to.be.an 'object'
done()
c.once 'network', ->
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
g.send file
it 'should be able to run the graph', (done) ->
c.baseDir = root
@timeout 6000
c.once 'ready', ->
ins = noflo.internalSocket.createSocket()
out = noflo.internalSocket.createSocket()
c.inPorts['in'].attach ins
c.outPorts['out'].attach out
received = false
out.on 'data', (data) ->
chai.expect(data).to.equal 'Foo'
received = true
out.on 'disconnect', ->
chai.expect(received, 'should have transmitted data').to.equal true
done()
ins.connect()
ins.send 'Foo'
ins.disconnect()
c.once 'network', ->
chai.expect(c.ready).to.be.false
chai.expect(c.network).not.to.be.null
c.network.loader.components.Split = Split
c.network.loader.components.Merge = SubgraphMerge
c.start (err) ->
done err if err
g.send file
describe 'when a subgraph is used as a component', ->
createSplit = ->
c = new noflo.Component
c.inPorts.add 'in',
required: true
datatype: 'string'
default: 'default-value',
c.outPorts.add 'out',
datatype: 'string'
c.process (input, output) ->
data = input.getData 'in'
output.sendDone
out: data
grDefaults = new noflo.Graph 'Child Graph Using Defaults'
grDefaults.addNode 'SplitIn', 'Split'
grDefaults.addNode 'SplitOut', 'Split'
grDefaults.addInport 'in', 'SplitIn', 'in'
grDefaults.addOutport 'out', 'SplitOut', 'out'
grDefaults.addEdge 'SplitIn', 'out', 'SplitOut', 'in'
grInitials = new noflo.Graph 'Child Graph Using Initials'
grInitials.addNode 'SplitIn', 'Split'
grInitials.addNode 'SplitOut', 'Split'
grInitials.addInport 'in', 'SplitIn', 'in'
grInitials.addOutport 'out', 'SplitOut', 'out'
grInitials.addInitial 'initial-value', 'SplitIn', 'in'
grInitials.addEdge 'SplitIn', 'out', 'SplitOut', 'in'
it 'should send defaults', (done) ->
@timeout 6000
cl = new noflo.ComponentLoader root
cl.listComponents (err, components) ->
return done err if err
cl.components.Split = createSplit
cl.components.Defaults = grDefaults
cl.components.Initials = grInitials
cl.load 'Defaults', (err, inst) ->
o = noflo.internalSocket.createSocket()
inst.outPorts.out.attach o
o.once 'data', (data) ->
chai.expect(data).to.equal 'default-value'
done()
inst.start()
it 'should send initials', (done) ->
@timeout 6000
cl = new noflo.ComponentLoader root
cl.listComponents (err, components) ->
return done err if err
cl.components.Split = createSplit
cl.components.Defaults = grDefaults
cl.components.Initials = grInitials
cl.load 'Initials', (err, inst) ->
o = noflo.internalSocket.createSocket()
inst.outPorts.out.attach o
o.once 'data', (data) ->
chai.expect(data).to.equal 'initial-value'
done()
inst.start()
it 'should not send defaults when an inport is attached externally', (done) ->
@timeout 6000
cl = new noflo.ComponentLoader root
cl.listComponents (err, components) ->
return done err if err
cl.components.Split = createSplit
cl.components.Defaults = grDefaults
cl.components.Initials = grInitials
cl.load 'Defaults', (err, inst) ->
i = noflo.internalSocket.createSocket()
o = noflo.internalSocket.createSocket()
inst.inPorts.in.attach i
inst.outPorts.out.attach o
o.once 'data', (data) ->
chai.expect(data).to.equal 'Foo'
done()
inst.start()
i.send 'Foo'
|
[
{
"context": "if err? then return next err\n user.password = hash\n next()\n\n\nUser.methods.comparePassword = (ca",
"end": 685,
"score": 0.800606906414032,
"start": 681,
"tag": "PASSWORD",
"value": "hash"
}
] | src/server/models/users.coffee | FindBoat/moolo | 0 | bcrypt = require 'bcrypt-nodejs'
mongoose = require 'mongoose'
User = new mongoose.Schema
email: type: String, unique: true, lowercase: true
password: String
profile:
name: type: String, default: ''
gender: type: String, default: ''
location: type: String, default: ''
website: type: String, default: ''
picture: type: String, default: ''
# Hash password before saving.
User.pre 'save', (next) ->
user = this
unless user.isModified 'password' then return next()
bcrypt.genSalt 5, (err, salt) ->
if err? then return next err
bcrypt.hash user.password, salt, null, (err, hash) ->
if err? then return next err
user.password = hash
next()
User.methods.comparePassword = (candidatePassword, cb) ->
bcrypt.compare candidatePassword, this.password, (err, isMatch) ->
if err? then return cb err
cb null, isMatch
module.exports = mongoose.model 'User', User
| 134520 | bcrypt = require 'bcrypt-nodejs'
mongoose = require 'mongoose'
User = new mongoose.Schema
email: type: String, unique: true, lowercase: true
password: String
profile:
name: type: String, default: ''
gender: type: String, default: ''
location: type: String, default: ''
website: type: String, default: ''
picture: type: String, default: ''
# Hash password before saving.
User.pre 'save', (next) ->
user = this
unless user.isModified 'password' then return next()
bcrypt.genSalt 5, (err, salt) ->
if err? then return next err
bcrypt.hash user.password, salt, null, (err, hash) ->
if err? then return next err
user.password = <PASSWORD>
next()
User.methods.comparePassword = (candidatePassword, cb) ->
bcrypt.compare candidatePassword, this.password, (err, isMatch) ->
if err? then return cb err
cb null, isMatch
module.exports = mongoose.model 'User', User
| true | bcrypt = require 'bcrypt-nodejs'
mongoose = require 'mongoose'
User = new mongoose.Schema
email: type: String, unique: true, lowercase: true
password: String
profile:
name: type: String, default: ''
gender: type: String, default: ''
location: type: String, default: ''
website: type: String, default: ''
picture: type: String, default: ''
# Hash password before saving.
User.pre 'save', (next) ->
user = this
unless user.isModified 'password' then return next()
bcrypt.genSalt 5, (err, salt) ->
if err? then return next err
bcrypt.hash user.password, salt, null, (err, hash) ->
if err? then return next err
user.password = PI:PASSWORD:<PASSWORD>END_PI
next()
User.methods.comparePassword = (candidatePassword, cb) ->
bcrypt.compare candidatePassword, this.password, (err, isMatch) ->
if err? then return cb err
cb null, isMatch
module.exports = mongoose.model 'User', User
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991028904914856,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/disabled/test-dgram-unix-anon.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")
Buffer = require("buffer").Buffer
fs = require("fs")
dgram = require("dgram")
server = undefined
client = undefined
server_path = "/tmp/dgram_server_sock"
messages_to_send = [
new Buffer("First message to send")
new Buffer("Second message to send")
new Buffer("Third message to send")
new Buffer("Fourth message to send")
]
timer = undefined
server = dgram.createSocket("unix_dgram")
server.bind server_path
server.messages = []
server.on "message", (msg, rinfo) ->
console.log "server got: " + msg
assert.strictEqual rinfo.address, "" # anon client sending
server.messages.push msg.toString()
if server.messages.length is messages_to_send.length
server.messages.forEach (m, i) ->
assert.strictEqual m, messages_to_send[i].toString()
return
server.close()
client.close()
return
server.on "listening", ->
console.log "server is listening"
client = dgram.createSocket("unix_dgram")
messages_to_send.forEach (m) ->
client.send m, 0, m.length, server_path, (err, bytes) ->
if err
console.log "Caught error in client send."
throw err
console.log "client wrote " + bytes + " bytes."
return
return
client.on "close", ->
clearTimeout timer if server.fd is null
return
return
server.on "close", ->
clearTimeout timer if client.fd is null
return
timer = setTimeout(->
throw new Error("Timeout")return
, 500)
| 130260 | # 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")
Buffer = require("buffer").Buffer
fs = require("fs")
dgram = require("dgram")
server = undefined
client = undefined
server_path = "/tmp/dgram_server_sock"
messages_to_send = [
new Buffer("First message to send")
new Buffer("Second message to send")
new Buffer("Third message to send")
new Buffer("Fourth message to send")
]
timer = undefined
server = dgram.createSocket("unix_dgram")
server.bind server_path
server.messages = []
server.on "message", (msg, rinfo) ->
console.log "server got: " + msg
assert.strictEqual rinfo.address, "" # anon client sending
server.messages.push msg.toString()
if server.messages.length is messages_to_send.length
server.messages.forEach (m, i) ->
assert.strictEqual m, messages_to_send[i].toString()
return
server.close()
client.close()
return
server.on "listening", ->
console.log "server is listening"
client = dgram.createSocket("unix_dgram")
messages_to_send.forEach (m) ->
client.send m, 0, m.length, server_path, (err, bytes) ->
if err
console.log "Caught error in client send."
throw err
console.log "client wrote " + bytes + " bytes."
return
return
client.on "close", ->
clearTimeout timer if server.fd is null
return
return
server.on "close", ->
clearTimeout timer if client.fd is null
return
timer = setTimeout(->
throw new Error("Timeout")return
, 500)
| 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")
Buffer = require("buffer").Buffer
fs = require("fs")
dgram = require("dgram")
server = undefined
client = undefined
server_path = "/tmp/dgram_server_sock"
messages_to_send = [
new Buffer("First message to send")
new Buffer("Second message to send")
new Buffer("Third message to send")
new Buffer("Fourth message to send")
]
timer = undefined
server = dgram.createSocket("unix_dgram")
server.bind server_path
server.messages = []
server.on "message", (msg, rinfo) ->
console.log "server got: " + msg
assert.strictEqual rinfo.address, "" # anon client sending
server.messages.push msg.toString()
if server.messages.length is messages_to_send.length
server.messages.forEach (m, i) ->
assert.strictEqual m, messages_to_send[i].toString()
return
server.close()
client.close()
return
server.on "listening", ->
console.log "server is listening"
client = dgram.createSocket("unix_dgram")
messages_to_send.forEach (m) ->
client.send m, 0, m.length, server_path, (err, bytes) ->
if err
console.log "Caught error in client send."
throw err
console.log "client wrote " + bytes + " bytes."
return
return
client.on "close", ->
clearTimeout timer if server.fd is null
return
return
server.on "close", ->
clearTimeout timer if client.fd is null
return
timer = setTimeout(->
throw new Error("Timeout")return
, 500)
|
[
{
"context": " L.mapbox.accessToken = config.accessToken || 'pk.eyJ1IjoiZ2luYS1hbGFza2EiLCJhIjoiN0lJVnk5QSJ9.CsQYpUUXtdCpnUdwurAYcQ';\n @map = L.mapbox.map(mapel.data('target'), c",
"end": 2005,
"score": 0.9997062087059021,
"start": 1935,
"tag": "KEY",
"value": "pk.eyJ1IjoiZ2luYS1hbGFza2EiLCJhIjoiN0lJVnk5QSJ9.CsQYpUUXtdCpnUdwurAYcQ"
}
] | app/assets/javascripts/maps.js.coffee | gina-alaska/gina-catalog | 0 | class Layers
constructor: (@mapel, @map, @selector = 'layer') ->
@config = @mapel.data()
setup: () ->
layers = {}
layersForControl = {
}
# = L.featureGroup()
for el in @mapel.find('layer')
klass = @determineLayerClass(el)
layers[klass.zoomable] ||= L.featureGroup()
layer = new klass(el, layers[klass.zoomable])
layer.zoom(@)
layersForControl[layer.config.name] = layer.getLayer()
layers[true].addTo(@map) if layers[true]?
layers[false].addTo(@map) if layers[false]?
@zoomTo(layers[true], @config.maxZoom) if @config.fitAll
layersForControl['DNR Orthos'] = L.tileLayer('http://gis2.dnr.alaska.gov/terrapixel/ips/tilesets/SPOT5_SDMI_ORTHO_RGB/SPOT5_SDMI_ORTHO_RGB/default/smerc/{z}/{y}/{x}.png?INSTANCE=ortho')
layersForControl['GINA Topos'] = L.tileLayer('http://tiles.gina.alaska.edu/tilesrv/drg/tile/{x}/{y}/{z}.png?GOGC=220EAC1F05E4')
L.control.layers(null, layersForControl, { position: 'topleft' }).addTo(@map)
L.control.coordinates(
position: 'bottomleft'
decimals: 3
decimalSeperator: '.'
labelTemplateLat: 'Lat: {y}'
labelTemplateLng: 'Lon: {x}'
enableUserInput: false
useDMS: false
useLatLngOrder: true
markerType: L.marker
markerProps: {}
).addTo @map
zoomTo: (layer, maxZoom) ->
@map.whenReady =>
setTimeout(=>
bounds = layer.getBounds()
if bounds.isValid()
@map.fitBounds(bounds, { padding: [30,30], maxZoom: maxZoom })
, 1000)
determineLayerClass: (el) ->
switch $(el).data('type')
when "GeoJSON"
GeoJSONLayer
when "WMS"
WMSLayer
when "TMS"
TMSLayer
else
GeoJSONLayer
$(document).on 'ready turbolinks:load init_map', ->
mapel = $('[data-behavior="map"]')
if mapel.length > 0
config = mapel.data()
L.mapbox.accessToken = config.accessToken || 'pk.eyJ1IjoiZ2luYS1hbGFza2EiLCJhIjoiN0lJVnk5QSJ9.CsQYpUUXtdCpnUdwurAYcQ';
@map = L.mapbox.map(mapel.data('target'), config.mapboxId, config);
@map.setView([64.245, -152.051], 3);
mapel.data('map', @map)
layers = new Layers(mapel, @map)
layers.setup();
$(document).on 'click', '[data-behavior="highlight-markers"]', (e) ->
e.preventDefault()
map = $('[data-behavior="map"]').data('map')
el = $(this).data('target')
$(el).parents('.leaflet-marker-pane').find('.active').removeClass('active')
$(el).addClass('active')
wkt = new Wkt.Wkt($(this).data('zoomto'))
geom = wkt.toObject()
if wkt.type == 'point'
map.setView(geom.getLatLng(), 10)
else
map.fitBounds(geom.getBounds(), padding: [10, 10])
$(el).addClass('active')
| 116052 | class Layers
constructor: (@mapel, @map, @selector = 'layer') ->
@config = @mapel.data()
setup: () ->
layers = {}
layersForControl = {
}
# = L.featureGroup()
for el in @mapel.find('layer')
klass = @determineLayerClass(el)
layers[klass.zoomable] ||= L.featureGroup()
layer = new klass(el, layers[klass.zoomable])
layer.zoom(@)
layersForControl[layer.config.name] = layer.getLayer()
layers[true].addTo(@map) if layers[true]?
layers[false].addTo(@map) if layers[false]?
@zoomTo(layers[true], @config.maxZoom) if @config.fitAll
layersForControl['DNR Orthos'] = L.tileLayer('http://gis2.dnr.alaska.gov/terrapixel/ips/tilesets/SPOT5_SDMI_ORTHO_RGB/SPOT5_SDMI_ORTHO_RGB/default/smerc/{z}/{y}/{x}.png?INSTANCE=ortho')
layersForControl['GINA Topos'] = L.tileLayer('http://tiles.gina.alaska.edu/tilesrv/drg/tile/{x}/{y}/{z}.png?GOGC=220EAC1F05E4')
L.control.layers(null, layersForControl, { position: 'topleft' }).addTo(@map)
L.control.coordinates(
position: 'bottomleft'
decimals: 3
decimalSeperator: '.'
labelTemplateLat: 'Lat: {y}'
labelTemplateLng: 'Lon: {x}'
enableUserInput: false
useDMS: false
useLatLngOrder: true
markerType: L.marker
markerProps: {}
).addTo @map
zoomTo: (layer, maxZoom) ->
@map.whenReady =>
setTimeout(=>
bounds = layer.getBounds()
if bounds.isValid()
@map.fitBounds(bounds, { padding: [30,30], maxZoom: maxZoom })
, 1000)
determineLayerClass: (el) ->
switch $(el).data('type')
when "GeoJSON"
GeoJSONLayer
when "WMS"
WMSLayer
when "TMS"
TMSLayer
else
GeoJSONLayer
$(document).on 'ready turbolinks:load init_map', ->
mapel = $('[data-behavior="map"]')
if mapel.length > 0
config = mapel.data()
L.mapbox.accessToken = config.accessToken || '<KEY>';
@map = L.mapbox.map(mapel.data('target'), config.mapboxId, config);
@map.setView([64.245, -152.051], 3);
mapel.data('map', @map)
layers = new Layers(mapel, @map)
layers.setup();
$(document).on 'click', '[data-behavior="highlight-markers"]', (e) ->
e.preventDefault()
map = $('[data-behavior="map"]').data('map')
el = $(this).data('target')
$(el).parents('.leaflet-marker-pane').find('.active').removeClass('active')
$(el).addClass('active')
wkt = new Wkt.Wkt($(this).data('zoomto'))
geom = wkt.toObject()
if wkt.type == 'point'
map.setView(geom.getLatLng(), 10)
else
map.fitBounds(geom.getBounds(), padding: [10, 10])
$(el).addClass('active')
| true | class Layers
constructor: (@mapel, @map, @selector = 'layer') ->
@config = @mapel.data()
setup: () ->
layers = {}
layersForControl = {
}
# = L.featureGroup()
for el in @mapel.find('layer')
klass = @determineLayerClass(el)
layers[klass.zoomable] ||= L.featureGroup()
layer = new klass(el, layers[klass.zoomable])
layer.zoom(@)
layersForControl[layer.config.name] = layer.getLayer()
layers[true].addTo(@map) if layers[true]?
layers[false].addTo(@map) if layers[false]?
@zoomTo(layers[true], @config.maxZoom) if @config.fitAll
layersForControl['DNR Orthos'] = L.tileLayer('http://gis2.dnr.alaska.gov/terrapixel/ips/tilesets/SPOT5_SDMI_ORTHO_RGB/SPOT5_SDMI_ORTHO_RGB/default/smerc/{z}/{y}/{x}.png?INSTANCE=ortho')
layersForControl['GINA Topos'] = L.tileLayer('http://tiles.gina.alaska.edu/tilesrv/drg/tile/{x}/{y}/{z}.png?GOGC=220EAC1F05E4')
L.control.layers(null, layersForControl, { position: 'topleft' }).addTo(@map)
L.control.coordinates(
position: 'bottomleft'
decimals: 3
decimalSeperator: '.'
labelTemplateLat: 'Lat: {y}'
labelTemplateLng: 'Lon: {x}'
enableUserInput: false
useDMS: false
useLatLngOrder: true
markerType: L.marker
markerProps: {}
).addTo @map
zoomTo: (layer, maxZoom) ->
@map.whenReady =>
setTimeout(=>
bounds = layer.getBounds()
if bounds.isValid()
@map.fitBounds(bounds, { padding: [30,30], maxZoom: maxZoom })
, 1000)
determineLayerClass: (el) ->
switch $(el).data('type')
when "GeoJSON"
GeoJSONLayer
when "WMS"
WMSLayer
when "TMS"
TMSLayer
else
GeoJSONLayer
$(document).on 'ready turbolinks:load init_map', ->
mapel = $('[data-behavior="map"]')
if mapel.length > 0
config = mapel.data()
L.mapbox.accessToken = config.accessToken || 'PI:KEY:<KEY>END_PI';
@map = L.mapbox.map(mapel.data('target'), config.mapboxId, config);
@map.setView([64.245, -152.051], 3);
mapel.data('map', @map)
layers = new Layers(mapel, @map)
layers.setup();
$(document).on 'click', '[data-behavior="highlight-markers"]', (e) ->
e.preventDefault()
map = $('[data-behavior="map"]').data('map')
el = $(this).data('target')
$(el).parents('.leaflet-marker-pane').find('.active').removeClass('active')
$(el).addClass('active')
wkt = new Wkt.Wkt($(this).data('zoomto'))
geom = wkt.toObject()
if wkt.type == 'point'
map.setView(geom.getLatLng(), 10)
else
map.fitBounds(geom.getBounds(), padding: [10, 10])
$(el).addClass('active')
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999085664749146,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/_components/comment-show-more.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 core from 'osu-core-singleton'
import * as React from 'react'
import { button, div, span } from 'react-dom-factories'
import { ShowMoreLink } from 'show-more-link'
import { Spinner } from 'spinner'
el = React.createElement
uiState = core.dataStore.uiState
bn = 'comment-show-more'
export class CommentShowMore extends React.PureComponent
@defaultProps = modifiers: []
constructor: (props) ->
super props
@state =
loading: false
componentWillUnmount: =>
@xhr?.abort()
render: =>
return null if @props.comments.length >= @props.total
return null unless (uiState.comments.hasMoreComments[@props.parent?.id ? null] ? true)
blockClass = osu.classWithModifiers bn, @props.modifiers
if 'top' in @props.modifiers
remaining = @props.total - @props.comments.length
modifiers = ['comments']
if 'changelog' in @props.modifiers
modifiers.push('t-greyviolet-darker')
else
modifiers.push('t-ddd')
el ShowMoreLink,
loading: @state.loading
hasMore: true
callback: @load
modifiers: modifiers
remaining: remaining
else
div className: blockClass,
if @state.loading
el Spinner
else
button
className: "#{bn}__link"
onClick: @load
@props.label ? osu.trans('common.buttons.show_more')
load: =>
@setState loading: true
params =
commentable_type: @props.parent?.commentable_type ? @props.commentableType
commentable_id: @props.parent?.commentable_id ? @props.commentableId
parent_id: @props.parent?.id ? 0
sort: uiState.comments.currentSort
lastComment = _.last(@props.comments)
if lastComment?
params.cursor =
id: lastComment.id
created_at: lastComment.createdAt
votes_count: lastComment.votesCount
@xhr = $.ajax laroute.route('comments.index'),
data: params
dataType: 'json'
.done (data) =>
$.publish 'comments:added', data
.always =>
@setState loading: false
| 40216 | # 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 core from 'osu-core-singleton'
import * as React from 'react'
import { button, div, span } from 'react-dom-factories'
import { ShowMoreLink } from 'show-more-link'
import { Spinner } from 'spinner'
el = React.createElement
uiState = core.dataStore.uiState
bn = 'comment-show-more'
export class CommentShowMore extends React.PureComponent
@defaultProps = modifiers: []
constructor: (props) ->
super props
@state =
loading: false
componentWillUnmount: =>
@xhr?.abort()
render: =>
return null if @props.comments.length >= @props.total
return null unless (uiState.comments.hasMoreComments[@props.parent?.id ? null] ? true)
blockClass = osu.classWithModifiers bn, @props.modifiers
if 'top' in @props.modifiers
remaining = @props.total - @props.comments.length
modifiers = ['comments']
if 'changelog' in @props.modifiers
modifiers.push('t-greyviolet-darker')
else
modifiers.push('t-ddd')
el ShowMoreLink,
loading: @state.loading
hasMore: true
callback: @load
modifiers: modifiers
remaining: remaining
else
div className: blockClass,
if @state.loading
el Spinner
else
button
className: "#{bn}__link"
onClick: @load
@props.label ? osu.trans('common.buttons.show_more')
load: =>
@setState loading: true
params =
commentable_type: @props.parent?.commentable_type ? @props.commentableType
commentable_id: @props.parent?.commentable_id ? @props.commentableId
parent_id: @props.parent?.id ? 0
sort: uiState.comments.currentSort
lastComment = _.last(@props.comments)
if lastComment?
params.cursor =
id: lastComment.id
created_at: lastComment.createdAt
votes_count: lastComment.votesCount
@xhr = $.ajax laroute.route('comments.index'),
data: params
dataType: 'json'
.done (data) =>
$.publish 'comments:added', data
.always =>
@setState loading: false
| 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 core from 'osu-core-singleton'
import * as React from 'react'
import { button, div, span } from 'react-dom-factories'
import { ShowMoreLink } from 'show-more-link'
import { Spinner } from 'spinner'
el = React.createElement
uiState = core.dataStore.uiState
bn = 'comment-show-more'
export class CommentShowMore extends React.PureComponent
@defaultProps = modifiers: []
constructor: (props) ->
super props
@state =
loading: false
componentWillUnmount: =>
@xhr?.abort()
render: =>
return null if @props.comments.length >= @props.total
return null unless (uiState.comments.hasMoreComments[@props.parent?.id ? null] ? true)
blockClass = osu.classWithModifiers bn, @props.modifiers
if 'top' in @props.modifiers
remaining = @props.total - @props.comments.length
modifiers = ['comments']
if 'changelog' in @props.modifiers
modifiers.push('t-greyviolet-darker')
else
modifiers.push('t-ddd')
el ShowMoreLink,
loading: @state.loading
hasMore: true
callback: @load
modifiers: modifiers
remaining: remaining
else
div className: blockClass,
if @state.loading
el Spinner
else
button
className: "#{bn}__link"
onClick: @load
@props.label ? osu.trans('common.buttons.show_more')
load: =>
@setState loading: true
params =
commentable_type: @props.parent?.commentable_type ? @props.commentableType
commentable_id: @props.parent?.commentable_id ? @props.commentableId
parent_id: @props.parent?.id ? 0
sort: uiState.comments.currentSort
lastComment = _.last(@props.comments)
if lastComment?
params.cursor =
id: lastComment.id
created_at: lastComment.createdAt
votes_count: lastComment.votesCount
@xhr = $.ajax laroute.route('comments.index'),
data: params
dataType: 'json'
.done (data) =>
$.publish 'comments:added', data
.always =>
@setState loading: false
|
[
{
"context": "###*\n@author Adrien Brault <adrien.brault@gmail.com>\n###\n\ndefine 'Coffixi/co",
"end": 26,
"score": 0.9998946189880371,
"start": 13,
"tag": "NAME",
"value": "Adrien Brault"
},
{
"context": "###*\n@author Adrien Brault <adrien.brault@gmail.com>\n###\n\ndefine 'Coffixi/core/Polygon', [\n './Point",
"end": 51,
"score": 0.9999282956123352,
"start": 28,
"tag": "EMAIL",
"value": "adrien.brault@gmail.com"
},
{
"context": "aycasting to test hits\n # https://github.com/substack/point-in-polygon/blob/master/index.js\n i = 0",
"end": 1843,
"score": 0.661207914352417,
"start": 1835,
"tag": "USERNAME",
"value": "substack"
}
] | src/Coffixi/core/Polygon.coffee | namuol/Coffixi | 1 | ###*
@author Adrien Brault <adrien.brault@gmail.com>
###
define 'Coffixi/core/Polygon', [
'./Point'
], (
Point
) ->
###*
@class Polygon
@constructor
@param points* {Array<Point>|Array<Number>|Point...|Number...} This can be an array of Points that form the polygon,
a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be
all the points of the polygon e.g. `new Polygon(new Point(), new Point(), ...)`, or the
arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are
Numbers.
###
class Polygon
constructor: (points) ->
#if points isn't an array, use arguments as the array
points = Array::slice.call(arguments) unless points instanceof Array
#if this is a flat array of numbers, convert it to points
if typeof points[0] is "number"
p = []
i = 0
il = points.length
while i < il
p.push new Point(points[i], points[i + 1])
i += 2
points = p
###*
@property points {Array<Point>}
###
@points = points
###*
Creates a clone of this polygon
@method clone
@return {Polygon} a copy of the polygon
###
clone: ->
points = []
i = 0
while i < @points.length
points.push @points[i].clone()
i++
new Polygon(points)
###*
Checks if the x, and y coords passed to this function are contained within this polygon
@method contains
@param x {Number} The X coord of the point to test
@param y {Number} The Y coord of the point to test
@return {Boolean} if the x/y coords are within this polygon
###
contains: (x, y) ->
inside = false
# use some raycasting to test hits
# https://github.com/substack/point-in-polygon/blob/master/index.js
i = 0
j = @points.length - 1
while i < @points.length
xi = @points[i].x
yi = @points[i].y
xj = @points[j].x
yj = @points[j].y
intersect = ((yi > y) isnt (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
inside = not inside if intersect
j = i++
inside
| 107721 | ###*
@author <NAME> <<EMAIL>>
###
define 'Coffixi/core/Polygon', [
'./Point'
], (
Point
) ->
###*
@class Polygon
@constructor
@param points* {Array<Point>|Array<Number>|Point...|Number...} This can be an array of Points that form the polygon,
a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be
all the points of the polygon e.g. `new Polygon(new Point(), new Point(), ...)`, or the
arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are
Numbers.
###
class Polygon
constructor: (points) ->
#if points isn't an array, use arguments as the array
points = Array::slice.call(arguments) unless points instanceof Array
#if this is a flat array of numbers, convert it to points
if typeof points[0] is "number"
p = []
i = 0
il = points.length
while i < il
p.push new Point(points[i], points[i + 1])
i += 2
points = p
###*
@property points {Array<Point>}
###
@points = points
###*
Creates a clone of this polygon
@method clone
@return {Polygon} a copy of the polygon
###
clone: ->
points = []
i = 0
while i < @points.length
points.push @points[i].clone()
i++
new Polygon(points)
###*
Checks if the x, and y coords passed to this function are contained within this polygon
@method contains
@param x {Number} The X coord of the point to test
@param y {Number} The Y coord of the point to test
@return {Boolean} if the x/y coords are within this polygon
###
contains: (x, y) ->
inside = false
# use some raycasting to test hits
# https://github.com/substack/point-in-polygon/blob/master/index.js
i = 0
j = @points.length - 1
while i < @points.length
xi = @points[i].x
yi = @points[i].y
xj = @points[j].x
yj = @points[j].y
intersect = ((yi > y) isnt (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
inside = not inside if intersect
j = i++
inside
| true | ###*
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
define 'Coffixi/core/Polygon', [
'./Point'
], (
Point
) ->
###*
@class Polygon
@constructor
@param points* {Array<Point>|Array<Number>|Point...|Number...} This can be an array of Points that form the polygon,
a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be
all the points of the polygon e.g. `new Polygon(new Point(), new Point(), ...)`, or the
arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are
Numbers.
###
class Polygon
constructor: (points) ->
#if points isn't an array, use arguments as the array
points = Array::slice.call(arguments) unless points instanceof Array
#if this is a flat array of numbers, convert it to points
if typeof points[0] is "number"
p = []
i = 0
il = points.length
while i < il
p.push new Point(points[i], points[i + 1])
i += 2
points = p
###*
@property points {Array<Point>}
###
@points = points
###*
Creates a clone of this polygon
@method clone
@return {Polygon} a copy of the polygon
###
clone: ->
points = []
i = 0
while i < @points.length
points.push @points[i].clone()
i++
new Polygon(points)
###*
Checks if the x, and y coords passed to this function are contained within this polygon
@method contains
@param x {Number} The X coord of the point to test
@param y {Number} The Y coord of the point to test
@return {Boolean} if the x/y coords are within this polygon
###
contains: (x, y) ->
inside = false
# use some raycasting to test hits
# https://github.com/substack/point-in-polygon/blob/master/index.js
i = 0
j = @points.length - 1
while i < @points.length
xi = @points[i].x
yi = @points[i].y
xj = @points[j].x
yj = @points[j].y
intersect = ((yi > y) isnt (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
inside = not inside if intersect
j = i++
inside
|
[
{
"context": "req.body.password is '' then invalids.password = 'password'\n\n if invalids.email or invalids.password\n re",
"end": 1349,
"score": 0.9992021322250366,
"start": 1341,
"tag": "PASSWORD",
"value": "password"
}
] | controllers/users_controller.coffee | develvad/NodeCMS | 1 | User = require("../models/User").UsersModelo
crypto = require('crypto')
_auth = (user, req, res) ->
user.updated = Date.now()
hash = crypto.createHash("md5")
user.token = hash.update(JSON.stringify(user), "utf8").digest("hex")
user.save((error) ->
if not error
req.session.user = user
res.redirect('/panel')
#res.render('panel/dashboard', {user:user})
###
return res.send(
status: 200
user: _cleanupUser(user)
#token: user.token
)
###
else
console.log error
return res.send(
status: 400
message: "User can't be authenticated"
)
)
# OPTIMIZE: return send error directly from here
_comparePass = (user, pass) ->
hash = crypto.createHash("md5")
if user.password
if user.password isnt hash.update(pass, "utf8").digest("hex")
return false
return true
exports.panel = (req, res, next) ->
res.render('panel/index', {user:req.session.user})
exports.isLoggedIn = (req, res, next) ->
if req.session.user
next()
else
res.redirect("/")
# Checking email and password params
exports.hasEmailPassword = (req, res, next) ->
invalids = {}
if not req.body.email or req.body.email is '' then invalids.email = 'email'
if not req.body.password or req.body.password is '' then invalids.password = 'password'
if invalids.email or invalids.password
return res.send(
status: 400
invalids: invalids
message: "missing fields"
)
else
next()
# Checking if User exist by email in db
exports.userExists = (req, res, next) ->
# Check if login with email or username
User.findOne(email:req.body.email, (err, user) ->
if err or not user
return res.send(
message: "El usuario no existe"
status: 404
)
)
next()
# Checking if user.password isn't req.body.password
exports.validEmailPassword = (req, res, next) ->
User.findOne(email:req.body.email, (err, user) =>
if user
if not _comparePass(user, req.body.password)
return res.send(
message: "Password incorrecto"
status: 401
)
else
next()
)
exports.auth = (req, res, next) ->
User.findOne(email:req.body.email, (err, user) ->
if user
_auth(user, req, res)
)
exports.perfil = (req, res, next) ->
res.render('panel/index', user: req.session.user)
exports.editar = (req, res, next) ->
User.findOne(_id: req.body._id, (err, user) ->
if not err
console.log req.body
user.name = req.body.name
user.surname = req.body.surname
user.locality = req.body.locality
user.street = req.body.street
user.tel = req.body.tel
user.save((err) ->
if not err
req.session.user = user
res.redirect('/panel')
)
)
exports.logout = (req, res, next) ->
if req.request and req.request.user then req.request.user = {} # remove session
if req.session and req.session.user then req.session.user = {}
res.redirect('/')
| 25253 | User = require("../models/User").UsersModelo
crypto = require('crypto')
_auth = (user, req, res) ->
user.updated = Date.now()
hash = crypto.createHash("md5")
user.token = hash.update(JSON.stringify(user), "utf8").digest("hex")
user.save((error) ->
if not error
req.session.user = user
res.redirect('/panel')
#res.render('panel/dashboard', {user:user})
###
return res.send(
status: 200
user: _cleanupUser(user)
#token: user.token
)
###
else
console.log error
return res.send(
status: 400
message: "User can't be authenticated"
)
)
# OPTIMIZE: return send error directly from here
_comparePass = (user, pass) ->
hash = crypto.createHash("md5")
if user.password
if user.password isnt hash.update(pass, "utf8").digest("hex")
return false
return true
exports.panel = (req, res, next) ->
res.render('panel/index', {user:req.session.user})
exports.isLoggedIn = (req, res, next) ->
if req.session.user
next()
else
res.redirect("/")
# Checking email and password params
exports.hasEmailPassword = (req, res, next) ->
invalids = {}
if not req.body.email or req.body.email is '' then invalids.email = 'email'
if not req.body.password or req.body.password is '' then invalids.password = '<PASSWORD>'
if invalids.email or invalids.password
return res.send(
status: 400
invalids: invalids
message: "missing fields"
)
else
next()
# Checking if User exist by email in db
exports.userExists = (req, res, next) ->
# Check if login with email or username
User.findOne(email:req.body.email, (err, user) ->
if err or not user
return res.send(
message: "El usuario no existe"
status: 404
)
)
next()
# Checking if user.password isn't req.body.password
exports.validEmailPassword = (req, res, next) ->
User.findOne(email:req.body.email, (err, user) =>
if user
if not _comparePass(user, req.body.password)
return res.send(
message: "Password incorrecto"
status: 401
)
else
next()
)
exports.auth = (req, res, next) ->
User.findOne(email:req.body.email, (err, user) ->
if user
_auth(user, req, res)
)
exports.perfil = (req, res, next) ->
res.render('panel/index', user: req.session.user)
exports.editar = (req, res, next) ->
User.findOne(_id: req.body._id, (err, user) ->
if not err
console.log req.body
user.name = req.body.name
user.surname = req.body.surname
user.locality = req.body.locality
user.street = req.body.street
user.tel = req.body.tel
user.save((err) ->
if not err
req.session.user = user
res.redirect('/panel')
)
)
exports.logout = (req, res, next) ->
if req.request and req.request.user then req.request.user = {} # remove session
if req.session and req.session.user then req.session.user = {}
res.redirect('/')
| true | User = require("../models/User").UsersModelo
crypto = require('crypto')
_auth = (user, req, res) ->
user.updated = Date.now()
hash = crypto.createHash("md5")
user.token = hash.update(JSON.stringify(user), "utf8").digest("hex")
user.save((error) ->
if not error
req.session.user = user
res.redirect('/panel')
#res.render('panel/dashboard', {user:user})
###
return res.send(
status: 200
user: _cleanupUser(user)
#token: user.token
)
###
else
console.log error
return res.send(
status: 400
message: "User can't be authenticated"
)
)
# OPTIMIZE: return send error directly from here
_comparePass = (user, pass) ->
hash = crypto.createHash("md5")
if user.password
if user.password isnt hash.update(pass, "utf8").digest("hex")
return false
return true
exports.panel = (req, res, next) ->
res.render('panel/index', {user:req.session.user})
exports.isLoggedIn = (req, res, next) ->
if req.session.user
next()
else
res.redirect("/")
# Checking email and password params
exports.hasEmailPassword = (req, res, next) ->
invalids = {}
if not req.body.email or req.body.email is '' then invalids.email = 'email'
if not req.body.password or req.body.password is '' then invalids.password = 'PI:PASSWORD:<PASSWORD>END_PI'
if invalids.email or invalids.password
return res.send(
status: 400
invalids: invalids
message: "missing fields"
)
else
next()
# Checking if User exist by email in db
exports.userExists = (req, res, next) ->
# Check if login with email or username
User.findOne(email:req.body.email, (err, user) ->
if err or not user
return res.send(
message: "El usuario no existe"
status: 404
)
)
next()
# Checking if user.password isn't req.body.password
exports.validEmailPassword = (req, res, next) ->
User.findOne(email:req.body.email, (err, user) =>
if user
if not _comparePass(user, req.body.password)
return res.send(
message: "Password incorrecto"
status: 401
)
else
next()
)
exports.auth = (req, res, next) ->
User.findOne(email:req.body.email, (err, user) ->
if user
_auth(user, req, res)
)
exports.perfil = (req, res, next) ->
res.render('panel/index', user: req.session.user)
exports.editar = (req, res, next) ->
User.findOne(_id: req.body._id, (err, user) ->
if not err
console.log req.body
user.name = req.body.name
user.surname = req.body.surname
user.locality = req.body.locality
user.street = req.body.street
user.tel = req.body.tel
user.save((err) ->
if not err
req.session.user = user
res.redirect('/panel')
)
)
exports.logout = (req, res, next) ->
if req.request and req.request.user then req.request.user = {} # remove session
if req.session and req.session.user then req.session.user = {}
res.redirect('/')
|
[
{
"context": "# author LeFnord\n# email pscholz.le@gmail.com\n# date 2013-08-28",
"end": 16,
"score": 0.9927151203155518,
"start": 9,
"tag": "NAME",
"value": "LeFnord"
},
{
"context": "# author LeFnord\n# email pscholz.le@gmail.com\n# date 2013-08-28\n# ===========================",
"end": 46,
"score": 0.9999271631240845,
"start": 26,
"tag": "EMAIL",
"value": "pscholz.le@gmail.com"
}
] | assets/javascripts/visuals.coffee | LeFnord/xmi-viewer | 0 | # author LeFnord
# email pscholz.le@gmail.com
# date 2013-08-28
# ==============================================================================
# application specifiic code
width = 960
height = 1000
margin = 10
pad = margin / 2
radius = 7
yfixed = pad + radius
color = d3.scale.category20()
colors = [
[
'rgb(228,26,28)'
'rgba(228,26,28,0.66)'
'rgba(228,26,28,0.13)'
]
[
'rgb(55,126,184)'
'rgba(55,126,184,0.66)'
'rgba(55,126,184,0.13)'
]
[
'rgb(77,175,74)'
'rgba(77,175,74,0.66)'
'rgba(77,175,74,0.13)'
]
[
'rgb(152,78,163)'
'rgba(152,78,163,0.66)'
'rgba(152,78,163,0.13)'
]
[
'rgb(255,127,0)'
'rgba(255,127,0,0.66)'
'rgba(255,127,0,0.13)'
]
[
'rgb(215,225,51)'
'rgba(215,225,51,0.66)'
'rgba(215,225,51,0.13)'
]
[
'rgb(166,86,40)'
'rgba(166,86,40,0.66)'
'rgba(166,86,40,0.13)'
]
[
'rgb(247,129,191)'
'rgba(247,129,191,0.66)'
'rgba(247,129,191,0.13)'
]
[
'rgb(153,153,153)'
'rgba(153,153,153,0.66)'
'rgba(153,153,153,0.13)'
]
]
$("a.file").on "click", (event) ->
event.preventDefault()
path = $(this).attr("href")
getClaimData path
@getClaimData = (path) ->
$.ajax
url: path
dataType: "json"
success: (response) ->
$("#content").empty()
$('#arc').remove()
$(".info").remove()
$(".info-list").remove()
buildGraph response
$(".info-list").on "click", (event) ->
makeLinksActive this
return
makeLinksActive = (reference) ->
hrefValue = $(reference).attr("href")
if hrefValue
cssColor = $(reference).css 'color'
klass = hrefValue.substring(1,hrefValue.length)
if $(reference).hasClass 'inactive-link'
$(reference).removeClass 'inactive-link'
$("path." + klass).show()
newBGColor = cssColor.replace(/\)/,',0.13)').replace(/rgb/,'rgba')
newBorderColor = cssColor.replace(/\)/,',0.9)').replace(/rgb/,'rgba')
$("tspan ." + klass).css({'background-color': newBGColor,'border-color':newBorderColor})
else
$(reference).addClass 'inactive-link'
$("path." + klass).hide()
newBGColor = cssColor.replace(/\)/,',0.0)').replace(/rgb/,'rgba')
newBorderColor = cssColor.replace(/\)/,',0.23)').replace(/rgb/,'rgba')
$("tspan ." + klass).css({'background-color': newBGColor,'border-color':newBorderColor})
return
# all for graph bulding
buildGraph = (graph) ->
width = $(window).width() - $(window).width() / 13;
height = $(window).height() * 1.7;
writeClaims graph.nodes
svg = d3.select("#content").append("svg").attr("id", "arc").attr("width", width).attr("height", height)
plot = svg.append("g").attr("id", "plot").attr("transform", "translate(" + 0 + ", " + pad * 25 + ")")
height += 150
if graph.links?
claim_links_d = 'b'
links_d = 't'
else
claim_links_d = 't'
links_d = 'b'
linearLayout graph.nodes
arcLinks graph.nodes,graph.node_links,'grey',claim_links_d,'claims'
$("#head").append "<span class='navbar-text info name'>" + graph.name + "</span>"
$("#head").append "<span class='navbar-text info claims'>#Claims: " + graph.nodes.length + "</span>"
$("#head").append "<span class='navbar-text info link_claims'>#Links: " + graph.node_links.length + "</span>"
list_index = 0
for k,v of graph.links
act_color = colors[list_index]
list_index += 1
arcLinks graph.nodes,v,act_color[1],links_d,k
$("#legend").append "<li role='presentation'><a role='menuitem' tabindex='-1' href='#" + k + "' class='info-list' style='cursor:pointer;color:" + act_color[0] + "'><i class='fa fa-link'/> #" + k + ": " + v.length + "</a></li>"
drawNodes graph.nodes
list_index = 0
for k,v of graph.links
act_color = colors[list_index]
list_index += 1
color_named_entities k, act_color[1], act_color[2]
draw_line_between_nes k, v
linearLayout = (nodes) ->
xscale = d3.scale.linear().domain([
0
nodes.length - 1
]).range([
radius * 2
width - margin - radius * 2
])
nodes.forEach (d, i) ->
d.x = xscale(i)
d.y = yfixed + height / 3
return
return
drawNodes = (nodes) ->
d3.select("#plot").selectAll(".node").data(nodes).enter().append("circle").attr("class", "node").attr("id", (d, i) ->
"node_" + d.id
).attr("name", (d, i) ->
d.name
).attr("cx", (d, i) ->
d.x
).attr("cy", (d, i) ->
d.y
).attr("r", (d, i) ->
radius
).style('cursor','pointer').style("fill", (d, i) ->
color 7
).on "click", (d, i) ->
# hideClaim d
seeClaim d
d3.select(this).transition()
.duration(450)
.delay(50)
.attr("r",15)
addTooltip d, d.index, 'node-index'
return
return
arcLinks = (nodes,links,color,d,klass) ->
links.forEach (d, i) ->
d.source = (if isNaN(d.source) then d.source else (nodes.where id: d.source)[0])
d.target = (if isNaN(d.target) then d.target else (nodes.where id: d.target)[0])
return
drawLinks links,color,d,klass
return
drawLinks = (links,color,d,klass) ->
# scale to generate radians (just for lower-half of circle)
if d == 't'
radians = d3.scale.linear().range([
-Math.PI / 2
Math.PI / 2
])
else
radians = d3.scale.linear().range([
Math.PI / 2
3 * Math.PI / 2
])
arc = d3.svg.line.radial().interpolate("monotone").tension(1).angle((d) ->
radians d
)
link = "link "+d
d3.select("#plot").selectAll(link).data(links).enter().append("path").attr("class", "link " + klass).attr("transform", (d, i) ->
xshift = d.source.x + (d.target.x - d.source.x) / 2
# ToDo 2014-04-10:
yshift = yfixed + height / 3
"translate(" + xshift + ", " + yshift + ")"
).style({'stroke-width': 2,'stroke':color}).on("mouseover", (d,i) ->
d3.select(this).style({'stroke': 'black', 'stroke-width': 3, 'cursor':'pointer'}).transition().duration(2000).delay(100).each "end", ->
d3.select(this).style({'stroke': color, 'stroke-width': 2})
).on("click", (d, i) ->
addTooltipToLink d, klass
d3.selectAll("#tooltip").transition().duration(2000).delay(100).attr("y", "57px").each "end", ->
d3.select(this).transition().duration(2000).delay(100).style('opacity',0).each "end", ->
d3.select(this).remove()
return
return
).attr "d", (d, i) ->
xdist = Math.abs(d.source.x - d.target.x)
arc.radius xdist / 2
points = d3.range(0, Math.ceil(xdist / 3))
radians.domain [
0
points.length - 1
]
arc points
return
# add tooltips
addTooltipToLink = (link, klass) ->
unless klass is 'claims'
# addTooltip link.source_relatum, link.source_relatum.content
# addTooltip link.target_relatum, link.target_relatum.content
else
addTooltip link.source, link.source.name
addTooltip link.target, link.target.name
return
addTooltip = (circle,text,klass) ->
x = parseFloat(circle.x)
y = parseFloat(circle.y)
r = parseFloat(5)
if klass?
tooltip = d3.select("#plot").append("text").text(text).attr("x", x).attr("y", y).attr("dy", r * 1.2).attr("class", klass).attr("id","node_index_" + circle.index)
else
tooltip = d3.select("#plot").append("text").text(text).attr("x", x).attr("y", y).attr("dy", -r * 2).attr("id", "tooltip")
offset = tooltip.node().getBBox().width / 2
if (x - offset) < 0
tooltip.attr "text-anchor", "start"
tooltip.attr "dx", -r
else if (x + offset) > (width - margin)
tooltip.attr "text-anchor", "end"
tooltip.attr "dx", r
else
tooltip.attr "text-anchor", "middle"
tooltip.attr "dx", 0
return
# claims (node texts)
writeClaims = (claims) ->
claims.forEach (item, i) ->
d3.select("#content").append("tspan")
.attr("class","claim").attr("id", (d) ->
"claim_" + item.id
).html( (d) ->
"<span class='index'>" + item.index + ".</span> <span class='claim_content'>" + item.content + "</span>"
).insert("span").attr("class","closer").style('text-color','rgba(76, 76, 76,0.5)').text("×").on "click", (d, i) ->
hideClaim item
return
d3.selectAll(".claim").call d3.behavior.drag().on("drag", moveClaim)
return
seeClaim = (node,top) ->
top = top
top = '57px' unless top?
d3.select("#claim_"+node.id)
.transition()
.duration(250)
.delay(50)
.style({'display':'inline','opacity':1,'top':'57px'})
$(".claim").css
zIndex: 0
$("#claim_"+node.id).css
zIndex: 3
return
hideClaim = (node) ->
d3.select("#claim_"+node.id).transition().duration(450).delay(50).style({'display':'none','opacity':0})
d3.select("#node_"+node.id).transition()
.duration(450)
.delay(50)
.attr("r",radius)
d3.select("#node_index_" + node.index).transition()
.style({"opacity":0})
.duration(400)
.delay(50)
.remove()
return
moveClaim = ->
pos = $(this).offset()
ypos = pos.top
windowHeigth = $(document).height()
eleHeigth = $(this).height()
$(".claim").css
zIndex: 0
$(this).css
zIndex: 3
if d3.event.y + eleHeigth <= windowHeigth
$(this).css
top: "+=" + (d3.event.y - pos.top) + "px"
if d3.event.y - eleHeigth / 2 > windowHeigth
$(this).css
top: (d3.event.y - eleHeigth * 2) + "px"
if d3.event.y <= 57
$(this).css
top: "57px"
return
# relevant to named entities
color_named_entities = (klass,lColor,color) ->
unless klass == 'claims'
$("tspan." + klass).css({'background-color': color, 'border':'2px solid '+lColor})
# $("tspan." + klass).css({'background-color': color})
draw_line_between_nes = (klass,links) ->
# console.log klass
# console.log links
| 15958 | # author <NAME>
# email <EMAIL>
# date 2013-08-28
# ==============================================================================
# application specifiic code
width = 960
height = 1000
margin = 10
pad = margin / 2
radius = 7
yfixed = pad + radius
color = d3.scale.category20()
colors = [
[
'rgb(228,26,28)'
'rgba(228,26,28,0.66)'
'rgba(228,26,28,0.13)'
]
[
'rgb(55,126,184)'
'rgba(55,126,184,0.66)'
'rgba(55,126,184,0.13)'
]
[
'rgb(77,175,74)'
'rgba(77,175,74,0.66)'
'rgba(77,175,74,0.13)'
]
[
'rgb(152,78,163)'
'rgba(152,78,163,0.66)'
'rgba(152,78,163,0.13)'
]
[
'rgb(255,127,0)'
'rgba(255,127,0,0.66)'
'rgba(255,127,0,0.13)'
]
[
'rgb(215,225,51)'
'rgba(215,225,51,0.66)'
'rgba(215,225,51,0.13)'
]
[
'rgb(166,86,40)'
'rgba(166,86,40,0.66)'
'rgba(166,86,40,0.13)'
]
[
'rgb(247,129,191)'
'rgba(247,129,191,0.66)'
'rgba(247,129,191,0.13)'
]
[
'rgb(153,153,153)'
'rgba(153,153,153,0.66)'
'rgba(153,153,153,0.13)'
]
]
$("a.file").on "click", (event) ->
event.preventDefault()
path = $(this).attr("href")
getClaimData path
@getClaimData = (path) ->
$.ajax
url: path
dataType: "json"
success: (response) ->
$("#content").empty()
$('#arc').remove()
$(".info").remove()
$(".info-list").remove()
buildGraph response
$(".info-list").on "click", (event) ->
makeLinksActive this
return
makeLinksActive = (reference) ->
hrefValue = $(reference).attr("href")
if hrefValue
cssColor = $(reference).css 'color'
klass = hrefValue.substring(1,hrefValue.length)
if $(reference).hasClass 'inactive-link'
$(reference).removeClass 'inactive-link'
$("path." + klass).show()
newBGColor = cssColor.replace(/\)/,',0.13)').replace(/rgb/,'rgba')
newBorderColor = cssColor.replace(/\)/,',0.9)').replace(/rgb/,'rgba')
$("tspan ." + klass).css({'background-color': newBGColor,'border-color':newBorderColor})
else
$(reference).addClass 'inactive-link'
$("path." + klass).hide()
newBGColor = cssColor.replace(/\)/,',0.0)').replace(/rgb/,'rgba')
newBorderColor = cssColor.replace(/\)/,',0.23)').replace(/rgb/,'rgba')
$("tspan ." + klass).css({'background-color': newBGColor,'border-color':newBorderColor})
return
# all for graph bulding
buildGraph = (graph) ->
width = $(window).width() - $(window).width() / 13;
height = $(window).height() * 1.7;
writeClaims graph.nodes
svg = d3.select("#content").append("svg").attr("id", "arc").attr("width", width).attr("height", height)
plot = svg.append("g").attr("id", "plot").attr("transform", "translate(" + 0 + ", " + pad * 25 + ")")
height += 150
if graph.links?
claim_links_d = 'b'
links_d = 't'
else
claim_links_d = 't'
links_d = 'b'
linearLayout graph.nodes
arcLinks graph.nodes,graph.node_links,'grey',claim_links_d,'claims'
$("#head").append "<span class='navbar-text info name'>" + graph.name + "</span>"
$("#head").append "<span class='navbar-text info claims'>#Claims: " + graph.nodes.length + "</span>"
$("#head").append "<span class='navbar-text info link_claims'>#Links: " + graph.node_links.length + "</span>"
list_index = 0
for k,v of graph.links
act_color = colors[list_index]
list_index += 1
arcLinks graph.nodes,v,act_color[1],links_d,k
$("#legend").append "<li role='presentation'><a role='menuitem' tabindex='-1' href='#" + k + "' class='info-list' style='cursor:pointer;color:" + act_color[0] + "'><i class='fa fa-link'/> #" + k + ": " + v.length + "</a></li>"
drawNodes graph.nodes
list_index = 0
for k,v of graph.links
act_color = colors[list_index]
list_index += 1
color_named_entities k, act_color[1], act_color[2]
draw_line_between_nes k, v
linearLayout = (nodes) ->
xscale = d3.scale.linear().domain([
0
nodes.length - 1
]).range([
radius * 2
width - margin - radius * 2
])
nodes.forEach (d, i) ->
d.x = xscale(i)
d.y = yfixed + height / 3
return
return
drawNodes = (nodes) ->
d3.select("#plot").selectAll(".node").data(nodes).enter().append("circle").attr("class", "node").attr("id", (d, i) ->
"node_" + d.id
).attr("name", (d, i) ->
d.name
).attr("cx", (d, i) ->
d.x
).attr("cy", (d, i) ->
d.y
).attr("r", (d, i) ->
radius
).style('cursor','pointer').style("fill", (d, i) ->
color 7
).on "click", (d, i) ->
# hideClaim d
seeClaim d
d3.select(this).transition()
.duration(450)
.delay(50)
.attr("r",15)
addTooltip d, d.index, 'node-index'
return
return
arcLinks = (nodes,links,color,d,klass) ->
links.forEach (d, i) ->
d.source = (if isNaN(d.source) then d.source else (nodes.where id: d.source)[0])
d.target = (if isNaN(d.target) then d.target else (nodes.where id: d.target)[0])
return
drawLinks links,color,d,klass
return
drawLinks = (links,color,d,klass) ->
# scale to generate radians (just for lower-half of circle)
if d == 't'
radians = d3.scale.linear().range([
-Math.PI / 2
Math.PI / 2
])
else
radians = d3.scale.linear().range([
Math.PI / 2
3 * Math.PI / 2
])
arc = d3.svg.line.radial().interpolate("monotone").tension(1).angle((d) ->
radians d
)
link = "link "+d
d3.select("#plot").selectAll(link).data(links).enter().append("path").attr("class", "link " + klass).attr("transform", (d, i) ->
xshift = d.source.x + (d.target.x - d.source.x) / 2
# ToDo 2014-04-10:
yshift = yfixed + height / 3
"translate(" + xshift + ", " + yshift + ")"
).style({'stroke-width': 2,'stroke':color}).on("mouseover", (d,i) ->
d3.select(this).style({'stroke': 'black', 'stroke-width': 3, 'cursor':'pointer'}).transition().duration(2000).delay(100).each "end", ->
d3.select(this).style({'stroke': color, 'stroke-width': 2})
).on("click", (d, i) ->
addTooltipToLink d, klass
d3.selectAll("#tooltip").transition().duration(2000).delay(100).attr("y", "57px").each "end", ->
d3.select(this).transition().duration(2000).delay(100).style('opacity',0).each "end", ->
d3.select(this).remove()
return
return
).attr "d", (d, i) ->
xdist = Math.abs(d.source.x - d.target.x)
arc.radius xdist / 2
points = d3.range(0, Math.ceil(xdist / 3))
radians.domain [
0
points.length - 1
]
arc points
return
# add tooltips
addTooltipToLink = (link, klass) ->
unless klass is 'claims'
# addTooltip link.source_relatum, link.source_relatum.content
# addTooltip link.target_relatum, link.target_relatum.content
else
addTooltip link.source, link.source.name
addTooltip link.target, link.target.name
return
addTooltip = (circle,text,klass) ->
x = parseFloat(circle.x)
y = parseFloat(circle.y)
r = parseFloat(5)
if klass?
tooltip = d3.select("#plot").append("text").text(text).attr("x", x).attr("y", y).attr("dy", r * 1.2).attr("class", klass).attr("id","node_index_" + circle.index)
else
tooltip = d3.select("#plot").append("text").text(text).attr("x", x).attr("y", y).attr("dy", -r * 2).attr("id", "tooltip")
offset = tooltip.node().getBBox().width / 2
if (x - offset) < 0
tooltip.attr "text-anchor", "start"
tooltip.attr "dx", -r
else if (x + offset) > (width - margin)
tooltip.attr "text-anchor", "end"
tooltip.attr "dx", r
else
tooltip.attr "text-anchor", "middle"
tooltip.attr "dx", 0
return
# claims (node texts)
writeClaims = (claims) ->
claims.forEach (item, i) ->
d3.select("#content").append("tspan")
.attr("class","claim").attr("id", (d) ->
"claim_" + item.id
).html( (d) ->
"<span class='index'>" + item.index + ".</span> <span class='claim_content'>" + item.content + "</span>"
).insert("span").attr("class","closer").style('text-color','rgba(76, 76, 76,0.5)').text("×").on "click", (d, i) ->
hideClaim item
return
d3.selectAll(".claim").call d3.behavior.drag().on("drag", moveClaim)
return
seeClaim = (node,top) ->
top = top
top = '57px' unless top?
d3.select("#claim_"+node.id)
.transition()
.duration(250)
.delay(50)
.style({'display':'inline','opacity':1,'top':'57px'})
$(".claim").css
zIndex: 0
$("#claim_"+node.id).css
zIndex: 3
return
hideClaim = (node) ->
d3.select("#claim_"+node.id).transition().duration(450).delay(50).style({'display':'none','opacity':0})
d3.select("#node_"+node.id).transition()
.duration(450)
.delay(50)
.attr("r",radius)
d3.select("#node_index_" + node.index).transition()
.style({"opacity":0})
.duration(400)
.delay(50)
.remove()
return
moveClaim = ->
pos = $(this).offset()
ypos = pos.top
windowHeigth = $(document).height()
eleHeigth = $(this).height()
$(".claim").css
zIndex: 0
$(this).css
zIndex: 3
if d3.event.y + eleHeigth <= windowHeigth
$(this).css
top: "+=" + (d3.event.y - pos.top) + "px"
if d3.event.y - eleHeigth / 2 > windowHeigth
$(this).css
top: (d3.event.y - eleHeigth * 2) + "px"
if d3.event.y <= 57
$(this).css
top: "57px"
return
# relevant to named entities
color_named_entities = (klass,lColor,color) ->
unless klass == 'claims'
$("tspan." + klass).css({'background-color': color, 'border':'2px solid '+lColor})
# $("tspan." + klass).css({'background-color': color})
draw_line_between_nes = (klass,links) ->
# console.log klass
# console.log links
| true | # author PI:NAME:<NAME>END_PI
# email PI:EMAIL:<EMAIL>END_PI
# date 2013-08-28
# ==============================================================================
# application specifiic code
width = 960
height = 1000
margin = 10
pad = margin / 2
radius = 7
yfixed = pad + radius
color = d3.scale.category20()
colors = [
[
'rgb(228,26,28)'
'rgba(228,26,28,0.66)'
'rgba(228,26,28,0.13)'
]
[
'rgb(55,126,184)'
'rgba(55,126,184,0.66)'
'rgba(55,126,184,0.13)'
]
[
'rgb(77,175,74)'
'rgba(77,175,74,0.66)'
'rgba(77,175,74,0.13)'
]
[
'rgb(152,78,163)'
'rgba(152,78,163,0.66)'
'rgba(152,78,163,0.13)'
]
[
'rgb(255,127,0)'
'rgba(255,127,0,0.66)'
'rgba(255,127,0,0.13)'
]
[
'rgb(215,225,51)'
'rgba(215,225,51,0.66)'
'rgba(215,225,51,0.13)'
]
[
'rgb(166,86,40)'
'rgba(166,86,40,0.66)'
'rgba(166,86,40,0.13)'
]
[
'rgb(247,129,191)'
'rgba(247,129,191,0.66)'
'rgba(247,129,191,0.13)'
]
[
'rgb(153,153,153)'
'rgba(153,153,153,0.66)'
'rgba(153,153,153,0.13)'
]
]
$("a.file").on "click", (event) ->
event.preventDefault()
path = $(this).attr("href")
getClaimData path
@getClaimData = (path) ->
$.ajax
url: path
dataType: "json"
success: (response) ->
$("#content").empty()
$('#arc').remove()
$(".info").remove()
$(".info-list").remove()
buildGraph response
$(".info-list").on "click", (event) ->
makeLinksActive this
return
makeLinksActive = (reference) ->
hrefValue = $(reference).attr("href")
if hrefValue
cssColor = $(reference).css 'color'
klass = hrefValue.substring(1,hrefValue.length)
if $(reference).hasClass 'inactive-link'
$(reference).removeClass 'inactive-link'
$("path." + klass).show()
newBGColor = cssColor.replace(/\)/,',0.13)').replace(/rgb/,'rgba')
newBorderColor = cssColor.replace(/\)/,',0.9)').replace(/rgb/,'rgba')
$("tspan ." + klass).css({'background-color': newBGColor,'border-color':newBorderColor})
else
$(reference).addClass 'inactive-link'
$("path." + klass).hide()
newBGColor = cssColor.replace(/\)/,',0.0)').replace(/rgb/,'rgba')
newBorderColor = cssColor.replace(/\)/,',0.23)').replace(/rgb/,'rgba')
$("tspan ." + klass).css({'background-color': newBGColor,'border-color':newBorderColor})
return
# all for graph bulding
buildGraph = (graph) ->
width = $(window).width() - $(window).width() / 13;
height = $(window).height() * 1.7;
writeClaims graph.nodes
svg = d3.select("#content").append("svg").attr("id", "arc").attr("width", width).attr("height", height)
plot = svg.append("g").attr("id", "plot").attr("transform", "translate(" + 0 + ", " + pad * 25 + ")")
height += 150
if graph.links?
claim_links_d = 'b'
links_d = 't'
else
claim_links_d = 't'
links_d = 'b'
linearLayout graph.nodes
arcLinks graph.nodes,graph.node_links,'grey',claim_links_d,'claims'
$("#head").append "<span class='navbar-text info name'>" + graph.name + "</span>"
$("#head").append "<span class='navbar-text info claims'>#Claims: " + graph.nodes.length + "</span>"
$("#head").append "<span class='navbar-text info link_claims'>#Links: " + graph.node_links.length + "</span>"
list_index = 0
for k,v of graph.links
act_color = colors[list_index]
list_index += 1
arcLinks graph.nodes,v,act_color[1],links_d,k
$("#legend").append "<li role='presentation'><a role='menuitem' tabindex='-1' href='#" + k + "' class='info-list' style='cursor:pointer;color:" + act_color[0] + "'><i class='fa fa-link'/> #" + k + ": " + v.length + "</a></li>"
drawNodes graph.nodes
list_index = 0
for k,v of graph.links
act_color = colors[list_index]
list_index += 1
color_named_entities k, act_color[1], act_color[2]
draw_line_between_nes k, v
linearLayout = (nodes) ->
xscale = d3.scale.linear().domain([
0
nodes.length - 1
]).range([
radius * 2
width - margin - radius * 2
])
nodes.forEach (d, i) ->
d.x = xscale(i)
d.y = yfixed + height / 3
return
return
drawNodes = (nodes) ->
d3.select("#plot").selectAll(".node").data(nodes).enter().append("circle").attr("class", "node").attr("id", (d, i) ->
"node_" + d.id
).attr("name", (d, i) ->
d.name
).attr("cx", (d, i) ->
d.x
).attr("cy", (d, i) ->
d.y
).attr("r", (d, i) ->
radius
).style('cursor','pointer').style("fill", (d, i) ->
color 7
).on "click", (d, i) ->
# hideClaim d
seeClaim d
d3.select(this).transition()
.duration(450)
.delay(50)
.attr("r",15)
addTooltip d, d.index, 'node-index'
return
return
arcLinks = (nodes,links,color,d,klass) ->
links.forEach (d, i) ->
d.source = (if isNaN(d.source) then d.source else (nodes.where id: d.source)[0])
d.target = (if isNaN(d.target) then d.target else (nodes.where id: d.target)[0])
return
drawLinks links,color,d,klass
return
drawLinks = (links,color,d,klass) ->
# scale to generate radians (just for lower-half of circle)
if d == 't'
radians = d3.scale.linear().range([
-Math.PI / 2
Math.PI / 2
])
else
radians = d3.scale.linear().range([
Math.PI / 2
3 * Math.PI / 2
])
arc = d3.svg.line.radial().interpolate("monotone").tension(1).angle((d) ->
radians d
)
link = "link "+d
d3.select("#plot").selectAll(link).data(links).enter().append("path").attr("class", "link " + klass).attr("transform", (d, i) ->
xshift = d.source.x + (d.target.x - d.source.x) / 2
# ToDo 2014-04-10:
yshift = yfixed + height / 3
"translate(" + xshift + ", " + yshift + ")"
).style({'stroke-width': 2,'stroke':color}).on("mouseover", (d,i) ->
d3.select(this).style({'stroke': 'black', 'stroke-width': 3, 'cursor':'pointer'}).transition().duration(2000).delay(100).each "end", ->
d3.select(this).style({'stroke': color, 'stroke-width': 2})
).on("click", (d, i) ->
addTooltipToLink d, klass
d3.selectAll("#tooltip").transition().duration(2000).delay(100).attr("y", "57px").each "end", ->
d3.select(this).transition().duration(2000).delay(100).style('opacity',0).each "end", ->
d3.select(this).remove()
return
return
).attr "d", (d, i) ->
xdist = Math.abs(d.source.x - d.target.x)
arc.radius xdist / 2
points = d3.range(0, Math.ceil(xdist / 3))
radians.domain [
0
points.length - 1
]
arc points
return
# add tooltips
addTooltipToLink = (link, klass) ->
unless klass is 'claims'
# addTooltip link.source_relatum, link.source_relatum.content
# addTooltip link.target_relatum, link.target_relatum.content
else
addTooltip link.source, link.source.name
addTooltip link.target, link.target.name
return
addTooltip = (circle,text,klass) ->
x = parseFloat(circle.x)
y = parseFloat(circle.y)
r = parseFloat(5)
if klass?
tooltip = d3.select("#plot").append("text").text(text).attr("x", x).attr("y", y).attr("dy", r * 1.2).attr("class", klass).attr("id","node_index_" + circle.index)
else
tooltip = d3.select("#plot").append("text").text(text).attr("x", x).attr("y", y).attr("dy", -r * 2).attr("id", "tooltip")
offset = tooltip.node().getBBox().width / 2
if (x - offset) < 0
tooltip.attr "text-anchor", "start"
tooltip.attr "dx", -r
else if (x + offset) > (width - margin)
tooltip.attr "text-anchor", "end"
tooltip.attr "dx", r
else
tooltip.attr "text-anchor", "middle"
tooltip.attr "dx", 0
return
# claims (node texts)
writeClaims = (claims) ->
claims.forEach (item, i) ->
d3.select("#content").append("tspan")
.attr("class","claim").attr("id", (d) ->
"claim_" + item.id
).html( (d) ->
"<span class='index'>" + item.index + ".</span> <span class='claim_content'>" + item.content + "</span>"
).insert("span").attr("class","closer").style('text-color','rgba(76, 76, 76,0.5)').text("×").on "click", (d, i) ->
hideClaim item
return
d3.selectAll(".claim").call d3.behavior.drag().on("drag", moveClaim)
return
seeClaim = (node,top) ->
top = top
top = '57px' unless top?
d3.select("#claim_"+node.id)
.transition()
.duration(250)
.delay(50)
.style({'display':'inline','opacity':1,'top':'57px'})
$(".claim").css
zIndex: 0
$("#claim_"+node.id).css
zIndex: 3
return
hideClaim = (node) ->
d3.select("#claim_"+node.id).transition().duration(450).delay(50).style({'display':'none','opacity':0})
d3.select("#node_"+node.id).transition()
.duration(450)
.delay(50)
.attr("r",radius)
d3.select("#node_index_" + node.index).transition()
.style({"opacity":0})
.duration(400)
.delay(50)
.remove()
return
moveClaim = ->
pos = $(this).offset()
ypos = pos.top
windowHeigth = $(document).height()
eleHeigth = $(this).height()
$(".claim").css
zIndex: 0
$(this).css
zIndex: 3
if d3.event.y + eleHeigth <= windowHeigth
$(this).css
top: "+=" + (d3.event.y - pos.top) + "px"
if d3.event.y - eleHeigth / 2 > windowHeigth
$(this).css
top: (d3.event.y - eleHeigth * 2) + "px"
if d3.event.y <= 57
$(this).css
top: "57px"
return
# relevant to named entities
color_named_entities = (klass,lColor,color) ->
unless klass == 'claims'
$("tspan." + klass).css({'background-color': color, 'border':'2px solid '+lColor})
# $("tspan." + klass).css({'background-color': color})
draw_line_between_nes = (klass,links) ->
# console.log klass
# console.log links
|
[
{
"context": "datesLengthOf/.test(content)\n assert /'username', { min: 6 }/.test(content)\n\n describe 'genera",
"end": 5305,
"score": 0.825215220451355,
"start": 5297,
"tag": "USERNAME",
"value": "username"
},
{
"context": " owner: 'rwx'\n name: 'staff'\n plural: 'staff'\n ",
"end": 7531,
"score": 0.5825809240341187,
"start": 7526,
"tag": "NAME",
"value": "staff"
},
{
"context": " owner: 'rwx'\n name: 'staff'\n plural: 'staff'\n ",
"end": 10392,
"score": 0.7587754726409912,
"start": 10387,
"tag": "NAME",
"value": "staff"
},
{
"context": " owner: 'rwx'\n name: 'staff'\n plural: 'staff'\n ",
"end": 13216,
"score": 0.7522546052932739,
"start": 13211,
"tag": "NAME",
"value": "staff"
}
] | spec/lib/models-generator.coffee | CureApp/loopback-with-admin | 13 |
{ normalize } = require 'path'
fs = require 'fs-extra'
ModelsGenerator = require '../../src/lib/models-generator'
ModelDefinition = require '../../src/lib/model-definition'
ModelConfigGenerator = require '../../src/lib/model-config-generator'
describe 'ModelsGenerator', ->
describe 'constructor', ->
before ->
{ @createModelDefinitions } = ModelsGenerator::
ModelsGenerator::createModelDefinitions = ->
model1: true
model2: true
after ->
ModelsGenerator::createModelDefinitions = @createModelDefinitions
it 'generate ModelConfigGenerator with array of models', ->
mGenerator = new ModelsGenerator()
assert mGenerator.modelConfigGenerator instanceof ModelConfigGenerator
describe 'createModelDefinitions', ->
it 'creates models included in customDefinitions', ->
customDefinitions = a: {}
defs = new ModelsGenerator().createModelDefinitions(customDefinitions)
assert defs.hasOwnProperty 'a'
assert not defs.hasOwnProperty 'b'
describe 'modelConfigGenerator', ->
it 'has model config with models included in customDefinitions', ->
customDefinitions = a: {}
mcGenerator = new ModelsGenerator(customDefinitions).modelConfigGenerator
mergedConfig = mcGenerator.getMergedConfig('model-config')
assert mergedConfig.hasOwnProperty 'a'
assert not mergedConfig.hasOwnProperty 'b'
describe 'getEmptyJSContent', ->
it 'returns valid JS code', ->
vm = require 'vm'
mGenerator = new ModelsGenerator()
context = vm.createContext module: {}
vm.runInContext(mGenerator.getEmptyJSContent(), context)
describe 'getJSContent', ->
it 'return valid js code with empty array validations', ->
mGenerator = new ModelsGenerator()
definition = []
result = mGenerator.getJSContent(definition)
# just exists function placeholder
assert /module\.exports = function\(Model\) \{/.test(result)
it 'return valid js code with empty validations', ->
mGenerator = new ModelsGenerator()
result = mGenerator.getJSContent(null)
# just exists function placeholder
assert /module\.exports = function\(Model\) \{/.test(result)
it 'return valid js code with validation methods', ->
mGenerator = new ModelsGenerator()
definition = [
username:
required: true
min: 6,
max: 10,
pattern: '^[a-z]'
]
result = mGenerator.getJSContent(definition)
assert /validatesPresenceOf\('username'\)/.test(result)
assert /validatesFormatOf\('username', \{ with: \/\^\[a-z\]\/ \}\)/.test(result)
assert /validatesLengthOf\('username', \{ max: 10 \}\)/.test(result)
assert /validatesLengthOf\('username', \{ min: 6 \}\)/.test(result)
describe 'generateJSONandJS', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/a/b/c'
fs.mkdirsSync @generator.destinationDir
@modelName = 'test-model'
@contents = test: true
@generator.generateJSONandJS(@modelName, @contents)
after ->
fs.removeSync __dirname + '/a'
it 'generate JSON file', ->
assert fs.existsSync(@generator.destinationDir + '/test-model.json') is true
assert.deepEqual require(@generator.destinationDir + '/test-model.json'), {test: true}
it 'generate JS file', ->
assert fs.existsSync(@generator.destinationDir + '/test-model.json') is true
content = fs.readFileSync(@generator.destinationDir + '/test-model.js', 'utf8')
assert content is @generator.getEmptyJSContent()
describe 'generateJSONandJS, when give the validation define', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/a/b/c'
fs.mkdirsSync @generator.destinationDir
@modelName = 'test-model'
@definition =
patient:
name: 'patient',
plural: 'patient',
properties:
email:
required: false
username:
type: 'string'
required: true
validations: [
username:
max: 10
min: 6
]
modelDefinition = @generator.createModelDefinitions @definition
@generator.generateJSONandJS(@modelName, modelDefinition.patient)
after ->
fs.removeSync __dirname + '/a'
it 'generate non empty JS file', ->
content = fs.readFileSync(@generator.destinationDir + '/test-model.js', 'utf8')
assert /validatesLengthOf/.test(content)
assert /'username', { min: 6 }/.test(content)
describe 'generateBuiltinModels', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/b/c/d'
fs.mkdirsSync @generator.destinationDir
@modelName = 'test-model'
@contents = JSON.stringify test: true
@generator.generateBuiltinModels(@modelName, @contents)
after ->
fs.removeSync __dirname + '/b'
it 'generate four JSON files', ->
assert fs.readdirSync(@generator.destinationDir).length is 8
it 'generate JS file', ->
assert fs.readdirSync(@generator.destinationDir).length is 8
describe 'generateDefinitionFiles', ->
describe 'reset', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/c'
@generator.modelConfigGenerator.destinationPath = __dirname + '/c'
fs.mkdirsSync __dirname + '/c'
it 'remove dir if exists', ->
@generator.reset()
assert fs.existsSync(@generator.destinationDir) is false
it 'do nothing if dir does not exist', ->
=> @generator.reset()
describe 'generate', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'returns generated models and configs', ->
generated = @generator.generate()
assert generated.hasOwnProperty 'config'
assert generated.hasOwnProperty 'names'
assert generated.names instanceof Array
assert generated.names.length is 4
assert typeof generated.config is 'object'
describe 'generate, when give the relation define, and owner permission is read only', ->
before ->
ownerPermission = 'r'
define =
staff:
aclType:
owner: 'rwx'
name: 'staff'
plural: 'staff'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
'job-with-staffId':
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
aclType:
owner: ownerPermission
name: 'job',
plural: 'job',
base: 'PersistedModel',
idInjection: true,
properties: {},
validations: [],
relations:
staff:
type: 'belongsTo', model: 'staff', foreignKey: 'staffId'
@generator = new ModelsGenerator(define)
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'generate JSON file include related models', (done) ->
@generator.generate()
fs.readFile __dirname + '/d/staff.json', 'utf8', (err, data) ->
acls = JSON.parse(data).acls
acl = [
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__create__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__delete__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__destroyById__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__updateById__job"
]
assert.deepEqual acls.splice(8, 4), acl
done()
describe 'generate, when give the relation define, and owner permission is undefined', ->
before ->
# job aclType = ''
define =
staff:
aclType:
owner: 'rwx'
name: 'staff'
plural: 'staff'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
'job-with-staffId':
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
aclType: ''
name: 'job',
plural: 'job',
base: 'PersistedModel',
idInjection: true,
properties: {},
validations: [],
relations:
staff:
type: 'belongsTo', model: 'staff', foreignKey: 'staffId'
@generator = new ModelsGenerator(define)
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'generate JSON file include related models', (done) ->
@generator.generate()
fs.readFile __dirname + '/d/staff.json', 'utf8', (err, data) ->
acls = JSON.parse(data).acls
acl = [
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__create__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__delete__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__destroyById__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__updateById__job"
]
assert.deepEqual acls.splice(8, 4), acl
done()
describe 'generate, when give the relation define, and owner permission is read-write', ->
before ->
ownerPermission = 'rw'
define =
staff:
aclType:
owner: 'rwx'
name: 'staff'
plural: 'staff'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
'job-with-staffId':
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
aclType:
owner: ownerPermission
name: 'job',
plural: 'job',
base: 'PersistedModel',
idInjection: true,
properties: {},
validations: [],
relations:
staff:
type: 'belongsTo', model: 'staff', foreignKey: 'staffId'
@generator = new ModelsGenerator(define)
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'generate JSON file does not include related models', (done) ->
@generator.generate()
fs.readFile __dirname + '/d/staff.json', 'utf8', (err, data) ->
acls = JSON.parse(data).acls
acl = []
assert.deepEqual acls.splice(8, 4), acl
done()
| 153612 |
{ normalize } = require 'path'
fs = require 'fs-extra'
ModelsGenerator = require '../../src/lib/models-generator'
ModelDefinition = require '../../src/lib/model-definition'
ModelConfigGenerator = require '../../src/lib/model-config-generator'
describe 'ModelsGenerator', ->
describe 'constructor', ->
before ->
{ @createModelDefinitions } = ModelsGenerator::
ModelsGenerator::createModelDefinitions = ->
model1: true
model2: true
after ->
ModelsGenerator::createModelDefinitions = @createModelDefinitions
it 'generate ModelConfigGenerator with array of models', ->
mGenerator = new ModelsGenerator()
assert mGenerator.modelConfigGenerator instanceof ModelConfigGenerator
describe 'createModelDefinitions', ->
it 'creates models included in customDefinitions', ->
customDefinitions = a: {}
defs = new ModelsGenerator().createModelDefinitions(customDefinitions)
assert defs.hasOwnProperty 'a'
assert not defs.hasOwnProperty 'b'
describe 'modelConfigGenerator', ->
it 'has model config with models included in customDefinitions', ->
customDefinitions = a: {}
mcGenerator = new ModelsGenerator(customDefinitions).modelConfigGenerator
mergedConfig = mcGenerator.getMergedConfig('model-config')
assert mergedConfig.hasOwnProperty 'a'
assert not mergedConfig.hasOwnProperty 'b'
describe 'getEmptyJSContent', ->
it 'returns valid JS code', ->
vm = require 'vm'
mGenerator = new ModelsGenerator()
context = vm.createContext module: {}
vm.runInContext(mGenerator.getEmptyJSContent(), context)
describe 'getJSContent', ->
it 'return valid js code with empty array validations', ->
mGenerator = new ModelsGenerator()
definition = []
result = mGenerator.getJSContent(definition)
# just exists function placeholder
assert /module\.exports = function\(Model\) \{/.test(result)
it 'return valid js code with empty validations', ->
mGenerator = new ModelsGenerator()
result = mGenerator.getJSContent(null)
# just exists function placeholder
assert /module\.exports = function\(Model\) \{/.test(result)
it 'return valid js code with validation methods', ->
mGenerator = new ModelsGenerator()
definition = [
username:
required: true
min: 6,
max: 10,
pattern: '^[a-z]'
]
result = mGenerator.getJSContent(definition)
assert /validatesPresenceOf\('username'\)/.test(result)
assert /validatesFormatOf\('username', \{ with: \/\^\[a-z\]\/ \}\)/.test(result)
assert /validatesLengthOf\('username', \{ max: 10 \}\)/.test(result)
assert /validatesLengthOf\('username', \{ min: 6 \}\)/.test(result)
describe 'generateJSONandJS', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/a/b/c'
fs.mkdirsSync @generator.destinationDir
@modelName = 'test-model'
@contents = test: true
@generator.generateJSONandJS(@modelName, @contents)
after ->
fs.removeSync __dirname + '/a'
it 'generate JSON file', ->
assert fs.existsSync(@generator.destinationDir + '/test-model.json') is true
assert.deepEqual require(@generator.destinationDir + '/test-model.json'), {test: true}
it 'generate JS file', ->
assert fs.existsSync(@generator.destinationDir + '/test-model.json') is true
content = fs.readFileSync(@generator.destinationDir + '/test-model.js', 'utf8')
assert content is @generator.getEmptyJSContent()
describe 'generateJSONandJS, when give the validation define', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/a/b/c'
fs.mkdirsSync @generator.destinationDir
@modelName = 'test-model'
@definition =
patient:
name: 'patient',
plural: 'patient',
properties:
email:
required: false
username:
type: 'string'
required: true
validations: [
username:
max: 10
min: 6
]
modelDefinition = @generator.createModelDefinitions @definition
@generator.generateJSONandJS(@modelName, modelDefinition.patient)
after ->
fs.removeSync __dirname + '/a'
it 'generate non empty JS file', ->
content = fs.readFileSync(@generator.destinationDir + '/test-model.js', 'utf8')
assert /validatesLengthOf/.test(content)
assert /'username', { min: 6 }/.test(content)
describe 'generateBuiltinModels', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/b/c/d'
fs.mkdirsSync @generator.destinationDir
@modelName = 'test-model'
@contents = JSON.stringify test: true
@generator.generateBuiltinModels(@modelName, @contents)
after ->
fs.removeSync __dirname + '/b'
it 'generate four JSON files', ->
assert fs.readdirSync(@generator.destinationDir).length is 8
it 'generate JS file', ->
assert fs.readdirSync(@generator.destinationDir).length is 8
describe 'generateDefinitionFiles', ->
describe 'reset', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/c'
@generator.modelConfigGenerator.destinationPath = __dirname + '/c'
fs.mkdirsSync __dirname + '/c'
it 'remove dir if exists', ->
@generator.reset()
assert fs.existsSync(@generator.destinationDir) is false
it 'do nothing if dir does not exist', ->
=> @generator.reset()
describe 'generate', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'returns generated models and configs', ->
generated = @generator.generate()
assert generated.hasOwnProperty 'config'
assert generated.hasOwnProperty 'names'
assert generated.names instanceof Array
assert generated.names.length is 4
assert typeof generated.config is 'object'
describe 'generate, when give the relation define, and owner permission is read only', ->
before ->
ownerPermission = 'r'
define =
staff:
aclType:
owner: 'rwx'
name: '<NAME>'
plural: 'staff'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
'job-with-staffId':
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
aclType:
owner: ownerPermission
name: 'job',
plural: 'job',
base: 'PersistedModel',
idInjection: true,
properties: {},
validations: [],
relations:
staff:
type: 'belongsTo', model: 'staff', foreignKey: 'staffId'
@generator = new ModelsGenerator(define)
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'generate JSON file include related models', (done) ->
@generator.generate()
fs.readFile __dirname + '/d/staff.json', 'utf8', (err, data) ->
acls = JSON.parse(data).acls
acl = [
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__create__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__delete__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__destroyById__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__updateById__job"
]
assert.deepEqual acls.splice(8, 4), acl
done()
describe 'generate, when give the relation define, and owner permission is undefined', ->
before ->
# job aclType = ''
define =
staff:
aclType:
owner: 'rwx'
name: '<NAME>'
plural: 'staff'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
'job-with-staffId':
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
aclType: ''
name: 'job',
plural: 'job',
base: 'PersistedModel',
idInjection: true,
properties: {},
validations: [],
relations:
staff:
type: 'belongsTo', model: 'staff', foreignKey: 'staffId'
@generator = new ModelsGenerator(define)
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'generate JSON file include related models', (done) ->
@generator.generate()
fs.readFile __dirname + '/d/staff.json', 'utf8', (err, data) ->
acls = JSON.parse(data).acls
acl = [
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__create__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__delete__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__destroyById__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__updateById__job"
]
assert.deepEqual acls.splice(8, 4), acl
done()
describe 'generate, when give the relation define, and owner permission is read-write', ->
before ->
ownerPermission = 'rw'
define =
staff:
aclType:
owner: 'rwx'
name: '<NAME>'
plural: 'staff'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
'job-with-staffId':
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
aclType:
owner: ownerPermission
name: 'job',
plural: 'job',
base: 'PersistedModel',
idInjection: true,
properties: {},
validations: [],
relations:
staff:
type: 'belongsTo', model: 'staff', foreignKey: 'staffId'
@generator = new ModelsGenerator(define)
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'generate JSON file does not include related models', (done) ->
@generator.generate()
fs.readFile __dirname + '/d/staff.json', 'utf8', (err, data) ->
acls = JSON.parse(data).acls
acl = []
assert.deepEqual acls.splice(8, 4), acl
done()
| true |
{ normalize } = require 'path'
fs = require 'fs-extra'
ModelsGenerator = require '../../src/lib/models-generator'
ModelDefinition = require '../../src/lib/model-definition'
ModelConfigGenerator = require '../../src/lib/model-config-generator'
describe 'ModelsGenerator', ->
describe 'constructor', ->
before ->
{ @createModelDefinitions } = ModelsGenerator::
ModelsGenerator::createModelDefinitions = ->
model1: true
model2: true
after ->
ModelsGenerator::createModelDefinitions = @createModelDefinitions
it 'generate ModelConfigGenerator with array of models', ->
mGenerator = new ModelsGenerator()
assert mGenerator.modelConfigGenerator instanceof ModelConfigGenerator
describe 'createModelDefinitions', ->
it 'creates models included in customDefinitions', ->
customDefinitions = a: {}
defs = new ModelsGenerator().createModelDefinitions(customDefinitions)
assert defs.hasOwnProperty 'a'
assert not defs.hasOwnProperty 'b'
describe 'modelConfigGenerator', ->
it 'has model config with models included in customDefinitions', ->
customDefinitions = a: {}
mcGenerator = new ModelsGenerator(customDefinitions).modelConfigGenerator
mergedConfig = mcGenerator.getMergedConfig('model-config')
assert mergedConfig.hasOwnProperty 'a'
assert not mergedConfig.hasOwnProperty 'b'
describe 'getEmptyJSContent', ->
it 'returns valid JS code', ->
vm = require 'vm'
mGenerator = new ModelsGenerator()
context = vm.createContext module: {}
vm.runInContext(mGenerator.getEmptyJSContent(), context)
describe 'getJSContent', ->
it 'return valid js code with empty array validations', ->
mGenerator = new ModelsGenerator()
definition = []
result = mGenerator.getJSContent(definition)
# just exists function placeholder
assert /module\.exports = function\(Model\) \{/.test(result)
it 'return valid js code with empty validations', ->
mGenerator = new ModelsGenerator()
result = mGenerator.getJSContent(null)
# just exists function placeholder
assert /module\.exports = function\(Model\) \{/.test(result)
it 'return valid js code with validation methods', ->
mGenerator = new ModelsGenerator()
definition = [
username:
required: true
min: 6,
max: 10,
pattern: '^[a-z]'
]
result = mGenerator.getJSContent(definition)
assert /validatesPresenceOf\('username'\)/.test(result)
assert /validatesFormatOf\('username', \{ with: \/\^\[a-z\]\/ \}\)/.test(result)
assert /validatesLengthOf\('username', \{ max: 10 \}\)/.test(result)
assert /validatesLengthOf\('username', \{ min: 6 \}\)/.test(result)
describe 'generateJSONandJS', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/a/b/c'
fs.mkdirsSync @generator.destinationDir
@modelName = 'test-model'
@contents = test: true
@generator.generateJSONandJS(@modelName, @contents)
after ->
fs.removeSync __dirname + '/a'
it 'generate JSON file', ->
assert fs.existsSync(@generator.destinationDir + '/test-model.json') is true
assert.deepEqual require(@generator.destinationDir + '/test-model.json'), {test: true}
it 'generate JS file', ->
assert fs.existsSync(@generator.destinationDir + '/test-model.json') is true
content = fs.readFileSync(@generator.destinationDir + '/test-model.js', 'utf8')
assert content is @generator.getEmptyJSContent()
describe 'generateJSONandJS, when give the validation define', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/a/b/c'
fs.mkdirsSync @generator.destinationDir
@modelName = 'test-model'
@definition =
patient:
name: 'patient',
plural: 'patient',
properties:
email:
required: false
username:
type: 'string'
required: true
validations: [
username:
max: 10
min: 6
]
modelDefinition = @generator.createModelDefinitions @definition
@generator.generateJSONandJS(@modelName, modelDefinition.patient)
after ->
fs.removeSync __dirname + '/a'
it 'generate non empty JS file', ->
content = fs.readFileSync(@generator.destinationDir + '/test-model.js', 'utf8')
assert /validatesLengthOf/.test(content)
assert /'username', { min: 6 }/.test(content)
describe 'generateBuiltinModels', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/b/c/d'
fs.mkdirsSync @generator.destinationDir
@modelName = 'test-model'
@contents = JSON.stringify test: true
@generator.generateBuiltinModels(@modelName, @contents)
after ->
fs.removeSync __dirname + '/b'
it 'generate four JSON files', ->
assert fs.readdirSync(@generator.destinationDir).length is 8
it 'generate JS file', ->
assert fs.readdirSync(@generator.destinationDir).length is 8
describe 'generateDefinitionFiles', ->
describe 'reset', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/c'
@generator.modelConfigGenerator.destinationPath = __dirname + '/c'
fs.mkdirsSync __dirname + '/c'
it 'remove dir if exists', ->
@generator.reset()
assert fs.existsSync(@generator.destinationDir) is false
it 'do nothing if dir does not exist', ->
=> @generator.reset()
describe 'generate', ->
before ->
@generator = new ModelsGenerator()
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'returns generated models and configs', ->
generated = @generator.generate()
assert generated.hasOwnProperty 'config'
assert generated.hasOwnProperty 'names'
assert generated.names instanceof Array
assert generated.names.length is 4
assert typeof generated.config is 'object'
describe 'generate, when give the relation define, and owner permission is read only', ->
before ->
ownerPermission = 'r'
define =
staff:
aclType:
owner: 'rwx'
name: 'PI:NAME:<NAME>END_PI'
plural: 'staff'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
'job-with-staffId':
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
aclType:
owner: ownerPermission
name: 'job',
plural: 'job',
base: 'PersistedModel',
idInjection: true,
properties: {},
validations: [],
relations:
staff:
type: 'belongsTo', model: 'staff', foreignKey: 'staffId'
@generator = new ModelsGenerator(define)
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'generate JSON file include related models', (done) ->
@generator.generate()
fs.readFile __dirname + '/d/staff.json', 'utf8', (err, data) ->
acls = JSON.parse(data).acls
acl = [
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__create__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__delete__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__destroyById__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__updateById__job"
]
assert.deepEqual acls.splice(8, 4), acl
done()
describe 'generate, when give the relation define, and owner permission is undefined', ->
before ->
# job aclType = ''
define =
staff:
aclType:
owner: 'rwx'
name: 'PI:NAME:<NAME>END_PI'
plural: 'staff'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
'job-with-staffId':
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
aclType: ''
name: 'job',
plural: 'job',
base: 'PersistedModel',
idInjection: true,
properties: {},
validations: [],
relations:
staff:
type: 'belongsTo', model: 'staff', foreignKey: 'staffId'
@generator = new ModelsGenerator(define)
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'generate JSON file include related models', (done) ->
@generator.generate()
fs.readFile __dirname + '/d/staff.json', 'utf8', (err, data) ->
acls = JSON.parse(data).acls
acl = [
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__create__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__delete__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__destroyById__job"
,
accessType : "WRITE"
permission : "DENY"
principalId : "$owner"
principalType : "ROLE"
property : "__updateById__job"
]
assert.deepEqual acls.splice(8, 4), acl
done()
describe 'generate, when give the relation define, and owner permission is read-write', ->
before ->
ownerPermission = 'rw'
define =
staff:
aclType:
owner: 'rwx'
name: 'PI:NAME:<NAME>END_PI'
plural: 'staff'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
'job-with-staffId':
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
type: 'hasMany', model: 'staff', foreignKey: 'staffId'
job:
aclType:
owner: ownerPermission
name: 'job',
plural: 'job',
base: 'PersistedModel',
idInjection: true,
properties: {},
validations: [],
relations:
staff:
type: 'belongsTo', model: 'staff', foreignKey: 'staffId'
@generator = new ModelsGenerator(define)
@generator.destinationDir = __dirname + '/d'
@generator.modelConfigGenerator.destinationPath = __dirname + '/d'
fs.mkdirsSync __dirname + '/d'
after ->
fs.removeSync __dirname + '/d'
it 'generate JSON file does not include related models', (done) ->
@generator.generate()
fs.readFile __dirname + '/d/staff.json', 'utf8', (err, data) ->
acls = JSON.parse(data).acls
acl = []
assert.deepEqual acls.splice(8, 4), acl
done()
|
[
{
"context": " User.removeQ()\n .then ->\n User.register('test1', 'test')\n .then (user)->\n token = user.g",
"end": 458,
"score": 0.877412736415863,
"start": 453,
"tag": "USERNAME",
"value": "test1"
},
{
"context": "'\n payload: JSON.stringify({\n token: 'somethingcool'\n type: 'ios'\n })\n headers:\n ",
"end": 2053,
"score": 0.8061625957489014,
"start": 2040,
"tag": "PASSWORD",
"value": "somethingcool"
},
{
"context": "'\n payload: JSON.stringify({\n token: 'awesometoken'\n type: 'android'\n })\n headers:\n",
"end": 2498,
"score": 0.9009819030761719,
"start": 2486,
"tag": "PASSWORD",
"value": "awesometoken"
},
{
"context": "'\n payload: JSON.stringify({\n token: 'somethingcool'\n type: 'ios'\n })\n headers:\n ",
"end": 2965,
"score": 0.7848294973373413,
"start": 2952,
"tag": "PASSWORD",
"value": "somethingcool"
}
] | test/integration/device.coffee | ethanmick/fastchat-server | 7 | 'use strict'
#
# FastChat
# 2015
#
should = require('chai').should()
mongoose = require('mongoose-q')()
User = require('../../lib/model/user')
Server = require '../../lib/server'
describe 'Devices', ->
user = null
s = null
before (done)->
mongoose.connect process.env.MONGOLAB_URI
s = new Server(port: process.env.PORT or 6190)
s.setup().then ->
s.start()
.then ->
User.removeQ()
.then ->
User.register('test1', 'test')
.then (user)->
token = user.generateRandomToken()
user.accessToken.push token
[user, user.saveQ()]
.spread (u)->
user = u
done()
.done()
it 'should be empty when you first request a token', (done)->
req =
url: '/user/device'
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 200
res.headers['content-type'].should.match /json/
res.result.should.be.empty
done()
it 'should return an error if you send nothing in the post request', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 400
res.headers['content-type'].should.match /json/
should.exist res.result.error
done()
it 'should return an error if you send not ios or android', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: 'something'
type: 'windows_phone'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 400
res.headers['content-type'].should.match /json/
should.exist res.result.error
done()
it 'should let you create an iOS device', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: 'somethingcool'
type: 'ios'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 201
res.headers['content-type'].should.match /json/
should.exist res.result
done()
it 'should let you create an Android device', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: 'awesometoken'
type: 'android'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 201
res.headers['content-type'].should.match /json/
should.exist res.result
done()
it 'should update your device if you sent in the same token', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: 'somethingcool'
type: 'ios'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 200
res.headers['content-type'].should.match /json/
should.exist res.result
done()
it 'should show all your devices when you request them', (done)->
req =
url: '/user/device'
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 200
res.headers['content-type'].should.match /json/
res.result.should.have.length 2
done()
after (done)->
mongoose.disconnect()
s.stop().then ->
done()
| 112727 | 'use strict'
#
# FastChat
# 2015
#
should = require('chai').should()
mongoose = require('mongoose-q')()
User = require('../../lib/model/user')
Server = require '../../lib/server'
describe 'Devices', ->
user = null
s = null
before (done)->
mongoose.connect process.env.MONGOLAB_URI
s = new Server(port: process.env.PORT or 6190)
s.setup().then ->
s.start()
.then ->
User.removeQ()
.then ->
User.register('test1', 'test')
.then (user)->
token = user.generateRandomToken()
user.accessToken.push token
[user, user.saveQ()]
.spread (u)->
user = u
done()
.done()
it 'should be empty when you first request a token', (done)->
req =
url: '/user/device'
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 200
res.headers['content-type'].should.match /json/
res.result.should.be.empty
done()
it 'should return an error if you send nothing in the post request', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 400
res.headers['content-type'].should.match /json/
should.exist res.result.error
done()
it 'should return an error if you send not ios or android', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: 'something'
type: 'windows_phone'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 400
res.headers['content-type'].should.match /json/
should.exist res.result.error
done()
it 'should let you create an iOS device', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: '<PASSWORD>'
type: 'ios'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 201
res.headers['content-type'].should.match /json/
should.exist res.result
done()
it 'should let you create an Android device', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: '<PASSWORD>'
type: 'android'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 201
res.headers['content-type'].should.match /json/
should.exist res.result
done()
it 'should update your device if you sent in the same token', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: '<PASSWORD>'
type: 'ios'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 200
res.headers['content-type'].should.match /json/
should.exist res.result
done()
it 'should show all your devices when you request them', (done)->
req =
url: '/user/device'
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 200
res.headers['content-type'].should.match /json/
res.result.should.have.length 2
done()
after (done)->
mongoose.disconnect()
s.stop().then ->
done()
| true | 'use strict'
#
# FastChat
# 2015
#
should = require('chai').should()
mongoose = require('mongoose-q')()
User = require('../../lib/model/user')
Server = require '../../lib/server'
describe 'Devices', ->
user = null
s = null
before (done)->
mongoose.connect process.env.MONGOLAB_URI
s = new Server(port: process.env.PORT or 6190)
s.setup().then ->
s.start()
.then ->
User.removeQ()
.then ->
User.register('test1', 'test')
.then (user)->
token = user.generateRandomToken()
user.accessToken.push token
[user, user.saveQ()]
.spread (u)->
user = u
done()
.done()
it 'should be empty when you first request a token', (done)->
req =
url: '/user/device'
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 200
res.headers['content-type'].should.match /json/
res.result.should.be.empty
done()
it 'should return an error if you send nothing in the post request', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 400
res.headers['content-type'].should.match /json/
should.exist res.result.error
done()
it 'should return an error if you send not ios or android', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: 'something'
type: 'windows_phone'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 400
res.headers['content-type'].should.match /json/
should.exist res.result.error
done()
it 'should let you create an iOS device', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: 'PI:PASSWORD:<PASSWORD>END_PI'
type: 'ios'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 201
res.headers['content-type'].should.match /json/
should.exist res.result
done()
it 'should let you create an Android device', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: 'PI:PASSWORD:<PASSWORD>END_PI'
type: 'android'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 201
res.headers['content-type'].should.match /json/
should.exist res.result
done()
it 'should update your device if you sent in the same token', (done)->
req =
method: 'POST'
url: '/user/device'
payload: JSON.stringify({
token: 'PI:PASSWORD:<PASSWORD>END_PI'
type: 'ios'
})
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 200
res.headers['content-type'].should.match /json/
should.exist res.result
done()
it 'should show all your devices when you request them', (done)->
req =
url: '/user/device'
headers:
Authorization: "Bearer #{user.accessToken[0]}"
s.server.inject req, (res)->
res.statusCode.should.equal 200
res.headers['content-type'].should.match /json/
res.result.should.have.length 2
done()
after (done)->
mongoose.disconnect()
s.stop().then ->
done()
|
[
{
"context": " id: 'footer-wrapper'\n \"Copyright (c) David Stein\"\n\n PageController = React.createClass\n displa",
"end": 1607,
"score": 0.9996232390403748,
"start": 1596,
"tag": "NAME",
"value": "David Stein"
},
{
"context": "ntDidMount: ->\n if location.host.startsWith \"127.0.0.1\"\n setInterval(@updateContent, 1000)\n ",
"end": 2196,
"score": 0.9976974129676819,
"start": 2187,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | coffee/views/page_controller.coffee | davidbstein/static-blog | 0 | dependencies =
React: "react"
cx: 'cx'
$: "jquery"
CommonmarkElement: "external/commonmark-react/commonmark_react"
hljs_shim: "highlight"
# copy/pastable require.js hacks
define (_v for _, _v of dependencies), () ->
_i=0; @[_k] = arguments[_i++] for _k of dependencies
#/hacks
d = React.DOM
Header = React.createFactory React.createClass
displayName: "HeaderView"
getInitialState: ->
@scrollTop = 0
$(window).scroll (e) =>
new_st = $(window).scrollTop()
if new_st < 64 or new_st < @scrollTop
@setState hidden: false
else
@setState hidden: true
@scrollTop = new_st
hidden: false
render: ->
d.header
className: cx
hidden: @state.hidden
d.div
id: "header-background"
d.div
id: "header-content"
d.div
className: "title"
d.a href: "/", "stein"
d.ul {},
d.li {}, d.a href: "/blog/index.html", "blog"
d.li {}, d.a href: "/about/index.html", "about"
Content = React.createFactory React.createClass
displayName: "ContentView"
render: ->
d.div
id: 'content-wrapper'
d.div
id: 'content-wrapper-bg'
d.div
id: 'content-wrapper-fg'
CommonmarkElement
raw: "#{@props.content}"
showTableOfContents: window.showTableOfContents
Footer = React.createFactory React.createClass
displayName: "FooterView"
render: ->
d.div
id: 'footer-wrapper'
"Copyright (c) David Stein"
PageController = React.createClass
displayName: "PageController"
propTypes:
content: React.PropTypes.string
getInitialState: ->
updated_content: null
updateContent: ->
if location.pathname.endsWith "html"
filename = location.pathname.match(/(.*?)\.html$/)[1]
path = "/raw#{filename}.md"
else
path = "/raw#{location.pathname}index.md"
$.get path, (data) =>
if data != @state.updated_content
@setState updated_content: data
componentDidMount: ->
if location.host.startsWith "127.0.0.1"
setInterval(@updateContent, 1000)
do @highlight_code
componentDidUpdate: ->
do @highlight_code
highlight_code: ->
$("code").each (i, element) =>
hljs.highlightBlock element
render: ->
d.div className: "wrapper",
Header {}
Content
content: @state.updated_content ? @props.content
Footer {}
| 105371 | dependencies =
React: "react"
cx: 'cx'
$: "jquery"
CommonmarkElement: "external/commonmark-react/commonmark_react"
hljs_shim: "highlight"
# copy/pastable require.js hacks
define (_v for _, _v of dependencies), () ->
_i=0; @[_k] = arguments[_i++] for _k of dependencies
#/hacks
d = React.DOM
Header = React.createFactory React.createClass
displayName: "HeaderView"
getInitialState: ->
@scrollTop = 0
$(window).scroll (e) =>
new_st = $(window).scrollTop()
if new_st < 64 or new_st < @scrollTop
@setState hidden: false
else
@setState hidden: true
@scrollTop = new_st
hidden: false
render: ->
d.header
className: cx
hidden: @state.hidden
d.div
id: "header-background"
d.div
id: "header-content"
d.div
className: "title"
d.a href: "/", "stein"
d.ul {},
d.li {}, d.a href: "/blog/index.html", "blog"
d.li {}, d.a href: "/about/index.html", "about"
Content = React.createFactory React.createClass
displayName: "ContentView"
render: ->
d.div
id: 'content-wrapper'
d.div
id: 'content-wrapper-bg'
d.div
id: 'content-wrapper-fg'
CommonmarkElement
raw: "#{@props.content}"
showTableOfContents: window.showTableOfContents
Footer = React.createFactory React.createClass
displayName: "FooterView"
render: ->
d.div
id: 'footer-wrapper'
"Copyright (c) <NAME>"
PageController = React.createClass
displayName: "PageController"
propTypes:
content: React.PropTypes.string
getInitialState: ->
updated_content: null
updateContent: ->
if location.pathname.endsWith "html"
filename = location.pathname.match(/(.*?)\.html$/)[1]
path = "/raw#{filename}.md"
else
path = "/raw#{location.pathname}index.md"
$.get path, (data) =>
if data != @state.updated_content
@setState updated_content: data
componentDidMount: ->
if location.host.startsWith "127.0.0.1"
setInterval(@updateContent, 1000)
do @highlight_code
componentDidUpdate: ->
do @highlight_code
highlight_code: ->
$("code").each (i, element) =>
hljs.highlightBlock element
render: ->
d.div className: "wrapper",
Header {}
Content
content: @state.updated_content ? @props.content
Footer {}
| true | dependencies =
React: "react"
cx: 'cx'
$: "jquery"
CommonmarkElement: "external/commonmark-react/commonmark_react"
hljs_shim: "highlight"
# copy/pastable require.js hacks
define (_v for _, _v of dependencies), () ->
_i=0; @[_k] = arguments[_i++] for _k of dependencies
#/hacks
d = React.DOM
Header = React.createFactory React.createClass
displayName: "HeaderView"
getInitialState: ->
@scrollTop = 0
$(window).scroll (e) =>
new_st = $(window).scrollTop()
if new_st < 64 or new_st < @scrollTop
@setState hidden: false
else
@setState hidden: true
@scrollTop = new_st
hidden: false
render: ->
d.header
className: cx
hidden: @state.hidden
d.div
id: "header-background"
d.div
id: "header-content"
d.div
className: "title"
d.a href: "/", "stein"
d.ul {},
d.li {}, d.a href: "/blog/index.html", "blog"
d.li {}, d.a href: "/about/index.html", "about"
Content = React.createFactory React.createClass
displayName: "ContentView"
render: ->
d.div
id: 'content-wrapper'
d.div
id: 'content-wrapper-bg'
d.div
id: 'content-wrapper-fg'
CommonmarkElement
raw: "#{@props.content}"
showTableOfContents: window.showTableOfContents
Footer = React.createFactory React.createClass
displayName: "FooterView"
render: ->
d.div
id: 'footer-wrapper'
"Copyright (c) PI:NAME:<NAME>END_PI"
PageController = React.createClass
displayName: "PageController"
propTypes:
content: React.PropTypes.string
getInitialState: ->
updated_content: null
updateContent: ->
if location.pathname.endsWith "html"
filename = location.pathname.match(/(.*?)\.html$/)[1]
path = "/raw#{filename}.md"
else
path = "/raw#{location.pathname}index.md"
$.get path, (data) =>
if data != @state.updated_content
@setState updated_content: data
componentDidMount: ->
if location.host.startsWith "127.0.0.1"
setInterval(@updateContent, 1000)
do @highlight_code
componentDidUpdate: ->
do @highlight_code
highlight_code: ->
$("code").each (i, element) =>
hljs.highlightBlock element
render: ->
d.div className: "wrapper",
Header {}
Content
content: @state.updated_content ? @props.content
Footer {}
|
[
{
"context": "###\n# Copyright (C) 2012 jareiko / http://www.jareiko.net/\n###\n\ndefine [\n], () ->\n",
"end": 32,
"score": 0.9982678294181824,
"start": 25,
"tag": "USERNAME",
"value": "jareiko"
},
{
"context": " @tiles = {}\n\n hasTile: (tX, tY) ->\n key = tX + ',' + tY\n key in @tiles\n\n getTile: (tX, tY) ->\n",
"end": 268,
"score": 0.9344226121902466,
"start": 258,
"tag": "KEY",
"value": "tX + ',' +"
},
{
"context": "\n hasTile: (tX, tY) ->\n key = tX + ',' + tY\n key in @tiles\n\n getTile: (tX, tY) ->\n ",
"end": 271,
"score": 0.9623831510543823,
"start": 270,
"tag": "KEY",
"value": "Y"
},
{
"context": "ey in @tiles\n\n getTile: (tX, tY) ->\n key = tX + ',' + tY\n @tiles[key]\n\n setTile: (tX, tY, tile) ->",
"end": 343,
"score": 0.9608444571495056,
"start": 330,
"tag": "KEY",
"value": "tX + ',' + tY"
},
{
"context": "s[key]\n\n setTile: (tX, tY, tile) ->\n key = tX + ',' + tY\n @tiles[key] = tile\n\n addObject: (x, y, o",
"end": 419,
"score": 0.9896320700645447,
"start": 406,
"tag": "KEY",
"value": "tX + ',' + tY"
},
{
"context": ")\n tY = Math.floor(y / @gridSize)\n key = tX + ',' + tY\n # tile = @tiles[key] ?= []\n tile = @ti",
"end": 578,
"score": 0.9962722659111023,
"start": 565,
"tag": "KEY",
"value": "tX + ',' + tY"
},
{
"context": "\n for tX in [tMinX...tMaxX]\n key = tX + ',' + tY\n tile = @tiles[key]\n if tile",
"end": 1019,
"score": 0.9821505546569824,
"start": 1009,
"tag": "KEY",
"value": "tX + ',' +"
},
{
"context": "tX in [tMinX...tMaxX]\n key = tX + ',' + tY\n tile = @tiles[key]\n if tile? t",
"end": 1022,
"score": 0.9938974976539612,
"start": 1021,
"tag": "KEY",
"value": "Y"
},
{
"context": " tile actually touches the circle.\n key = tX + ',' + tY\n tile = @tiles[key] or (@tiles[key] =",
"end": 1923,
"score": 0.81531822681427,
"start": 1913,
"tag": "KEY",
"value": "tX + ',' +"
},
{
"context": "y touches the circle.\n key = tX + ',' + tY\n tile = @tiles[key] or (@tiles[key] = []",
"end": 1926,
"score": 0.7173003554344177,
"start": 1925,
"tag": "KEY",
"value": "Y"
}
] | server/public/scripts/util/hash2d.coffee | triggerrally/triggerrally.github.io | 1 | ###
# Copyright (C) 2012 jareiko / http://www.jareiko.net/
###
define [
], () ->
exports = {}
class exports.Hash2D
# Hashes objects into a grid of square tiles.
constructor: (@gridSize) ->
@tiles = {}
hasTile: (tX, tY) ->
key = tX + ',' + tY
key in @tiles
getTile: (tX, tY) ->
key = tX + ',' + tY
@tiles[key]
setTile: (tX, tY, tile) ->
key = tX + ',' + tY
@tiles[key] = tile
addObject: (x, y, object) ->
tX = Math.floor(x / @gridSize)
tY = Math.floor(y / @gridSize)
key = tX + ',' + tY
# tile = @tiles[key] ?= []
tile = @tiles[key] or (@tiles[key] = [])
tile.push object
return
getObjects: (minX, minY, maxX, maxY) ->
tMinX = Math.floor(minX / @gridSize)
tMaxX = Math.ceil(maxX / @gridSize)
tMinY = Math.floor(minY / @gridSize)
tMaxY = Math.ceil(maxY / @gridSize)
tiles = []
for tY in [tMinY...tMaxY]
for tX in [tMinX...tMaxX]
key = tX + ',' + tY
tile = @tiles[key]
if tile? then tiles.push tile
return [].concat.apply([], tiles)
# Hashes references to objects. When querying a region, returns each object
# only once even if it appears in multiple tiles.
class exports.IndirectHash2D extends exports.Hash2D
constructor: (gridSize) ->
super gridSize
@objects = []
@nextId = 0
# Add an object to all tiles touched by a circle.
addCircle: (x, y, radius, object) ->
tCenterX = x / @gridSize
tCenterY = y / @gridSize
tRad = radius / @gridSize
tMinX = Math.floor(tCenterX - tRad)
tMaxX = Math.ceil(tCenterX + tRad)
tMinY = Math.floor(tCenterY - tRad)
tMaxY = Math.ceil(tCenterY + tRad)
for tY in [tMinY...tMaxY]
for tX in [tMinX...tMaxX]
# TODO: Check that this tile actually touches the circle.
key = tX + ',' + tY
tile = @tiles[key] or (@tiles[key] = [])
tile.push @nextId
@objects[@nextId++] = object
return
getObjects: (minX, minY, maxX, maxY) ->
ids = super minX, minY, maxX, maxY
idSet = []
for id in ids
idSet[id] = true
return (@objects[id] for id of idSet)
return exports
| 62381 | ###
# Copyright (C) 2012 jareiko / http://www.jareiko.net/
###
define [
], () ->
exports = {}
class exports.Hash2D
# Hashes objects into a grid of square tiles.
constructor: (@gridSize) ->
@tiles = {}
hasTile: (tX, tY) ->
key = <KEY> t<KEY>
key in @tiles
getTile: (tX, tY) ->
key = <KEY>
@tiles[key]
setTile: (tX, tY, tile) ->
key = <KEY>
@tiles[key] = tile
addObject: (x, y, object) ->
tX = Math.floor(x / @gridSize)
tY = Math.floor(y / @gridSize)
key = <KEY>
# tile = @tiles[key] ?= []
tile = @tiles[key] or (@tiles[key] = [])
tile.push object
return
getObjects: (minX, minY, maxX, maxY) ->
tMinX = Math.floor(minX / @gridSize)
tMaxX = Math.ceil(maxX / @gridSize)
tMinY = Math.floor(minY / @gridSize)
tMaxY = Math.ceil(maxY / @gridSize)
tiles = []
for tY in [tMinY...tMaxY]
for tX in [tMinX...tMaxX]
key = <KEY> t<KEY>
tile = @tiles[key]
if tile? then tiles.push tile
return [].concat.apply([], tiles)
# Hashes references to objects. When querying a region, returns each object
# only once even if it appears in multiple tiles.
class exports.IndirectHash2D extends exports.Hash2D
constructor: (gridSize) ->
super gridSize
@objects = []
@nextId = 0
# Add an object to all tiles touched by a circle.
addCircle: (x, y, radius, object) ->
tCenterX = x / @gridSize
tCenterY = y / @gridSize
tRad = radius / @gridSize
tMinX = Math.floor(tCenterX - tRad)
tMaxX = Math.ceil(tCenterX + tRad)
tMinY = Math.floor(tCenterY - tRad)
tMaxY = Math.ceil(tCenterY + tRad)
for tY in [tMinY...tMaxY]
for tX in [tMinX...tMaxX]
# TODO: Check that this tile actually touches the circle.
key = <KEY> t<KEY>
tile = @tiles[key] or (@tiles[key] = [])
tile.push @nextId
@objects[@nextId++] = object
return
getObjects: (minX, minY, maxX, maxY) ->
ids = super minX, minY, maxX, maxY
idSet = []
for id in ids
idSet[id] = true
return (@objects[id] for id of idSet)
return exports
| true | ###
# Copyright (C) 2012 jareiko / http://www.jareiko.net/
###
define [
], () ->
exports = {}
class exports.Hash2D
# Hashes objects into a grid of square tiles.
constructor: (@gridSize) ->
@tiles = {}
hasTile: (tX, tY) ->
key = PI:KEY:<KEY>END_PI tPI:KEY:<KEY>END_PI
key in @tiles
getTile: (tX, tY) ->
key = PI:KEY:<KEY>END_PI
@tiles[key]
setTile: (tX, tY, tile) ->
key = PI:KEY:<KEY>END_PI
@tiles[key] = tile
addObject: (x, y, object) ->
tX = Math.floor(x / @gridSize)
tY = Math.floor(y / @gridSize)
key = PI:KEY:<KEY>END_PI
# tile = @tiles[key] ?= []
tile = @tiles[key] or (@tiles[key] = [])
tile.push object
return
getObjects: (minX, minY, maxX, maxY) ->
tMinX = Math.floor(minX / @gridSize)
tMaxX = Math.ceil(maxX / @gridSize)
tMinY = Math.floor(minY / @gridSize)
tMaxY = Math.ceil(maxY / @gridSize)
tiles = []
for tY in [tMinY...tMaxY]
for tX in [tMinX...tMaxX]
key = PI:KEY:<KEY>END_PI tPI:KEY:<KEY>END_PI
tile = @tiles[key]
if tile? then tiles.push tile
return [].concat.apply([], tiles)
# Hashes references to objects. When querying a region, returns each object
# only once even if it appears in multiple tiles.
class exports.IndirectHash2D extends exports.Hash2D
constructor: (gridSize) ->
super gridSize
@objects = []
@nextId = 0
# Add an object to all tiles touched by a circle.
addCircle: (x, y, radius, object) ->
tCenterX = x / @gridSize
tCenterY = y / @gridSize
tRad = radius / @gridSize
tMinX = Math.floor(tCenterX - tRad)
tMaxX = Math.ceil(tCenterX + tRad)
tMinY = Math.floor(tCenterY - tRad)
tMaxY = Math.ceil(tCenterY + tRad)
for tY in [tMinY...tMaxY]
for tX in [tMinX...tMaxX]
# TODO: Check that this tile actually touches the circle.
key = PI:KEY:<KEY>END_PI tPI:KEY:<KEY>END_PI
tile = @tiles[key] or (@tiles[key] = [])
tile.push @nextId
@objects[@nextId++] = object
return
getObjects: (minX, minY, maxX, maxY) ->
ids = super minX, minY, maxX, maxY
idSet = []
for id in ids
idSet[id] = true
return (@objects[id] for id of idSet)
return exports
|
[
{
"context": " $scope.data ||= {}\n $scope.data.username = 'Anonymous ' + Math.floor(Math.random() * 1000)\n\n $scope.",
"end": 843,
"score": 0.9823928475379944,
"start": 834,
"tag": "USERNAME",
"value": "Anonymous"
},
{
"context": "= ->\n PubNub.init({\n subscribe_key : 'sub-c-45d9072c-b7df-11e2-bfb6-02ee2ddab7fe'\n publish_key : 'pub-c-8715dc2e-2ee3-49a",
"end": 990,
"score": 0.9996453523635864,
"start": 948,
"tag": "KEY",
"value": "sub-c-45d9072c-b7df-11e2-bfb6-02ee2ddab7fe"
},
{
"context": "-11e2-bfb6-02ee2ddab7fe'\n publish_key : 'pub-c-8715dc2e-2ee3-49ac-9dc5-410b6a282723'\n uuid : Math.floor(Math.random()",
"end": 1059,
"score": 0.9996483325958252,
"start": 1017,
"tag": "KEY",
"value": "pub-c-8715dc2e-2ee3-49ac-9dc5-410b6a282723"
},
{
"context": "om_chat\n message:\n username: 'RoomBot'\n message: $scope.data.username + \" ju",
"end": 3737,
"score": 0.9996011257171631,
"start": 3730,
"tag": "USERNAME",
"value": "RoomBot"
},
{
"context": "'$chat'\n message:\n username: 'RoomBot'\n message: \"Welcome to '\" + $scope.dat",
"end": 4284,
"score": 0.9996151328086853,
"start": 4277,
"tag": "USERNAME",
"value": "RoomBot"
},
{
"context": "a.room_chat\n message:\n username: 'RoomBot'\n message: $scope.data.username + \" just",
"end": 8981,
"score": 0.999474048614502,
"start": 8974,
"tag": "USERNAME",
"value": "RoomBot"
},
{
"context": " message: $scope.data.username + \" just took 'admin'!\"\n\n $scope.init()\n",
"end": 9043,
"score": 0.9764620661735535,
"start": 9038,
"tag": "USERNAME",
"value": "admin"
}
] | app/scripts/app.coffee | pubnub/angularjs-agile-poker | 0 | 'use strict'
###
We set up the app with 3 main routes: login, lobby, and room
###
angular.module('AgilePoker', ['pubnub.angular.service'])
.config ($routeProvider) ->
$routeProvider
.when '/lobby',
templateUrl: 'views/lobby.html'
controller: 'LobbyCtrl'
.when '/login',
templateUrl: 'views/login.html'
controller: 'LoginCtrl'
.when '/rooms/:id',
templateUrl: 'views/room.html'
controller: 'RoomCtrl'
.otherwise
redirectTo: '/login'
###
The login controller is responsible for initializing PubNub
with the specified user id and directing the user to the Lobby
###
angular.module('AgilePoker')
.controller 'LoginCtrl', ($scope, $rootScope, $location, PubNub) ->
$rootScope.data ||= {}
$scope.data ||= {}
$scope.data.username = 'Anonymous ' + Math.floor(Math.random() * 1000)
$scope.join = ->
PubNub.init({
subscribe_key : 'sub-c-45d9072c-b7df-11e2-bfb6-02ee2ddab7fe'
publish_key : 'pub-c-8715dc2e-2ee3-49ac-9dc5-410b6a282723'
uuid : Math.floor(Math.random() * 1000000) + '__' + $scope.data.username
})
$rootScope.data.username = $scope.data.username
$location.path '/lobby'
###
The Chat service encapsulates chat functionality into an
easily include-able form.
###
ChatService =
init: ($scope, $location, PubNub, room) ->
$scope.sendChat = ->
if $scope.data.message
PubNub.ngPublish
channel: room
message:
username: $scope.data.username
message: $scope.data.message
$scope.data.message = ''
$scope.$on PubNub.ngMsgEv(room), (ngEvent, payload) ->
history = "[" + payload.message.username + "] " + payload.message.message + "\n" + $('#chat_history').html()
$('#chat_history').html(history)
$scope.$on PubNub.ngPrsEv(room), ->
$scope.$apply -> $scope.users = PubNub.map PubNub.ngListPresence(room), (x) -> x.replace(/\w+__/, "")
$scope.logout = (path) -> $location.path(path) if path
$scope.leave = (path) ->
PubNub.ngUnsubscribe({channel:room})
$location.path(path) if path
PubNub.ngSubscribe {channel: room}
PubNub.ngHistory {channel: room, count:500}
PubNub.ngHereNow {channel: room}
###
The lobby controller
###
angular.module('AgilePoker')
.controller 'LobbyCtrl', ($scope, $rootScope, $location, PubNub) ->
$location.path '/login' unless $rootScope.data
$scope.init = ->
$scope.data = {}
$scope.data.room = 'lobby'
$scope.data.room_ctrl = '$lobby$ctrl'
$scope.data.room_chat = '$lobby$chat'
$scope.data.username = $rootScope.data?.username
$scope.data.rooms ||= []
PubNub.ngSubscribe {channel: $scope.data.room_ctrl}
PubNub.ngHistory {channel: $scope.data.room_ctrl, count:500}
ChatService.init($scope, $location, PubNub, $scope.data.room_chat)
$scope.$on PubNub.ngMsgEv($scope.data.room_ctrl), (ngEvent, payload) ->
unless payload && _($scope.data.rooms).find( (x) -> (x.name == payload.message.room.name) )
$scope.$apply -> $scope.data.rooms.push payload.message.room
$scope.createRoom = ->
if $scope.data.new_room.name
message =
type: 'create_room'
username: $scope.data.username
room: $scope.data.new_room
### Publish to the control channel to "create" the room ###
PubNub.ngPublish
channel: $scope.data.room_ctrl
message: message
### Publish to the lobby chat channel to notify users of the room creation ###
PubNub.ngPublish
channel: $scope.data.room_chat
message:
username: 'RoomBot'
message: $scope.data.username + " just created room '<a href=\"#/rooms/" + $scope.data.new_room.name + "\">" + $scope.data.new_room.name + "</a>'"
### Publish to the admin channel to initialize the room administrator ###
PubNub.ngPublish
channel: $scope.data.new_room.name + '$admn'
message: message
### Publish to the room chat channel to welcome users ###
PubNub.ngPublish
channel: $scope.data.new_room.name + '$chat'
message:
username: 'RoomBot'
message: "Welcome to '" + $scope.data.new_room.name + "'"
$scope.data.showCreate = false
$scope.init()
angular.module('AgilePoker')
.controller 'RoomCtrl', ($scope, $rootScope, $routeParams, $location, PubNub) ->
$location.path '/join' unless $rootScope.data
$scope.init = ->
$scope.data ||= {}
$scope.data.room = $routeParams.id
$scope.data.room_lobby = '$lobby$ctrl'
$scope.data.room_admn = $routeParams.id + '$admn'
$scope.data.room_ctrl = $routeParams.id + '$ctrl'
$scope.data.room_chat = $routeParams.id + '$chat'
$scope.data.username = $rootScope.data?.username
$scope.data.votes = {}
$scope.data.votevalues = [ 0, '½', 1, 2, 3, 5, 8, 13, 20, 40 ]
$scope.data.myvote = null
$scope.data.reveal = false
$('#chat_history').val('')
PubNub.ngSubscribe {channel:$scope.data.room_ctrl}
PubNub.ngSubscribe {channel:$scope.data.room_admn}
###
There are a few types of messages: admin (create/reveal),
control (enter/leave/vote), and chat (handled by ChatService)
###
$scope.$on PubNub.ngMsgEv($scope.data.room_ctrl), (ngEvent, payload) ->
if payload.message.type == 'vote' && !$scope.data.reveal
$scope.$apply ->
$scope.data.myvote = payload.message.value if payload.message.username == $scope.data.username
$scope.data.votes[payload.message.username] = payload.message
$scope.$on PubNub.ngMsgEv($scope.data.room_admn), (ngEvent, payload) ->
if payload.message.type == 'create_room'
$scope.$apply -> $scope.data.admin = payload.message.username
if payload.message.type == 'reset'
$scope.$apply ->
$scope.data.reveal = null
$scope.data.consensus = null
$scope.data.consensus_value = null
$scope.data.votes = {}
history = "***Voting was reset.\n" + $('#chat_history').html()
$('#chat_history').html(history)
if payload.message.type == 'reveal'
$scope.data.votes = payload.message.votes
$scope.$apply ->
$scope.data.reveal = true
$scope.data.consensus = payload.message.consensus
$scope.data.consensus_value = payload.message.consensus_value
if payload.message.votes
votes = _(payload.message.votes).map( (vote) -> vote.username + " voted " + vote.value ).join(", ")
history = "***Votes revealed: " + votes + "\n" + $('#chat_history').html()
$('#chat_history').html(history)
PubNub.ngHistory {channel:$scope.data.room_ctrl,count:500}
PubNub.ngHistory {channel:$scope.data.room_admn,count:500}
ChatService.init($scope, $location, PubNub, $scope.data.room_chat)
###
Voting entails publishing a vote message including your username
on the control channel
###
$scope.vote = (value) ->
PubNub.ngPublish
channel: $scope.data.room_ctrl
message:
type: 'vote'
value: value
username: $scope.data.username
###
Reveal entails publishing a reveal message on the admin channel with the
full voting results
###
$scope.reveal = ->
_($scope.data.votes).forEach (x) -> x.displayvalue = x.value
### Compute consensus with underscore 'countBy' and taking item with max count ###
voteCounts = _($scope.data.votes).countBy (x) -> x.value
max_key = null
max_val = -1
_(voteCounts).forEach (count, value) ->
if (count == max_val)
### unset max_key in case of a collision ###
max_key = null
else
if (count > max_val)
max_key = value
max_val = count
PubNub.ngPublish
channel: $scope.data.room_admn
message:
type: 'reveal'
votes: $scope.data.votes
consensus: !!max_key
consensus_value: if max_key then max_key else null
username: $scope.data.username
###
Reset entails publishing a reset message on the admin channel
###
$scope.reset = ->
PubNub.ngPublish
channel: $scope.data.room_admn
message:
type: 'reset'
$scope.isAdmin = ->
!$scope.data.admin || ($scope.data.username == $scope.data.admin)
$scope.takeAdmin = ->
PubNub.ngPublish
channel: $scope.data.room_admn
message:
type: 'create_room'
username: $scope.data.username
room: $scope.data.new_room
PubNub.ngPublish
channel: $scope.data.room_chat
message:
username: 'RoomBot'
message: $scope.data.username + " just took 'admin'!"
$scope.init()
| 73298 | 'use strict'
###
We set up the app with 3 main routes: login, lobby, and room
###
angular.module('AgilePoker', ['pubnub.angular.service'])
.config ($routeProvider) ->
$routeProvider
.when '/lobby',
templateUrl: 'views/lobby.html'
controller: 'LobbyCtrl'
.when '/login',
templateUrl: 'views/login.html'
controller: 'LoginCtrl'
.when '/rooms/:id',
templateUrl: 'views/room.html'
controller: 'RoomCtrl'
.otherwise
redirectTo: '/login'
###
The login controller is responsible for initializing PubNub
with the specified user id and directing the user to the Lobby
###
angular.module('AgilePoker')
.controller 'LoginCtrl', ($scope, $rootScope, $location, PubNub) ->
$rootScope.data ||= {}
$scope.data ||= {}
$scope.data.username = 'Anonymous ' + Math.floor(Math.random() * 1000)
$scope.join = ->
PubNub.init({
subscribe_key : '<KEY>'
publish_key : '<KEY>'
uuid : Math.floor(Math.random() * 1000000) + '__' + $scope.data.username
})
$rootScope.data.username = $scope.data.username
$location.path '/lobby'
###
The Chat service encapsulates chat functionality into an
easily include-able form.
###
ChatService =
init: ($scope, $location, PubNub, room) ->
$scope.sendChat = ->
if $scope.data.message
PubNub.ngPublish
channel: room
message:
username: $scope.data.username
message: $scope.data.message
$scope.data.message = ''
$scope.$on PubNub.ngMsgEv(room), (ngEvent, payload) ->
history = "[" + payload.message.username + "] " + payload.message.message + "\n" + $('#chat_history').html()
$('#chat_history').html(history)
$scope.$on PubNub.ngPrsEv(room), ->
$scope.$apply -> $scope.users = PubNub.map PubNub.ngListPresence(room), (x) -> x.replace(/\w+__/, "")
$scope.logout = (path) -> $location.path(path) if path
$scope.leave = (path) ->
PubNub.ngUnsubscribe({channel:room})
$location.path(path) if path
PubNub.ngSubscribe {channel: room}
PubNub.ngHistory {channel: room, count:500}
PubNub.ngHereNow {channel: room}
###
The lobby controller
###
angular.module('AgilePoker')
.controller 'LobbyCtrl', ($scope, $rootScope, $location, PubNub) ->
$location.path '/login' unless $rootScope.data
$scope.init = ->
$scope.data = {}
$scope.data.room = 'lobby'
$scope.data.room_ctrl = '$lobby$ctrl'
$scope.data.room_chat = '$lobby$chat'
$scope.data.username = $rootScope.data?.username
$scope.data.rooms ||= []
PubNub.ngSubscribe {channel: $scope.data.room_ctrl}
PubNub.ngHistory {channel: $scope.data.room_ctrl, count:500}
ChatService.init($scope, $location, PubNub, $scope.data.room_chat)
$scope.$on PubNub.ngMsgEv($scope.data.room_ctrl), (ngEvent, payload) ->
unless payload && _($scope.data.rooms).find( (x) -> (x.name == payload.message.room.name) )
$scope.$apply -> $scope.data.rooms.push payload.message.room
$scope.createRoom = ->
if $scope.data.new_room.name
message =
type: 'create_room'
username: $scope.data.username
room: $scope.data.new_room
### Publish to the control channel to "create" the room ###
PubNub.ngPublish
channel: $scope.data.room_ctrl
message: message
### Publish to the lobby chat channel to notify users of the room creation ###
PubNub.ngPublish
channel: $scope.data.room_chat
message:
username: 'RoomBot'
message: $scope.data.username + " just created room '<a href=\"#/rooms/" + $scope.data.new_room.name + "\">" + $scope.data.new_room.name + "</a>'"
### Publish to the admin channel to initialize the room administrator ###
PubNub.ngPublish
channel: $scope.data.new_room.name + '$admn'
message: message
### Publish to the room chat channel to welcome users ###
PubNub.ngPublish
channel: $scope.data.new_room.name + '$chat'
message:
username: 'RoomBot'
message: "Welcome to '" + $scope.data.new_room.name + "'"
$scope.data.showCreate = false
$scope.init()
angular.module('AgilePoker')
.controller 'RoomCtrl', ($scope, $rootScope, $routeParams, $location, PubNub) ->
$location.path '/join' unless $rootScope.data
$scope.init = ->
$scope.data ||= {}
$scope.data.room = $routeParams.id
$scope.data.room_lobby = '$lobby$ctrl'
$scope.data.room_admn = $routeParams.id + '$admn'
$scope.data.room_ctrl = $routeParams.id + '$ctrl'
$scope.data.room_chat = $routeParams.id + '$chat'
$scope.data.username = $rootScope.data?.username
$scope.data.votes = {}
$scope.data.votevalues = [ 0, '½', 1, 2, 3, 5, 8, 13, 20, 40 ]
$scope.data.myvote = null
$scope.data.reveal = false
$('#chat_history').val('')
PubNub.ngSubscribe {channel:$scope.data.room_ctrl}
PubNub.ngSubscribe {channel:$scope.data.room_admn}
###
There are a few types of messages: admin (create/reveal),
control (enter/leave/vote), and chat (handled by ChatService)
###
$scope.$on PubNub.ngMsgEv($scope.data.room_ctrl), (ngEvent, payload) ->
if payload.message.type == 'vote' && !$scope.data.reveal
$scope.$apply ->
$scope.data.myvote = payload.message.value if payload.message.username == $scope.data.username
$scope.data.votes[payload.message.username] = payload.message
$scope.$on PubNub.ngMsgEv($scope.data.room_admn), (ngEvent, payload) ->
if payload.message.type == 'create_room'
$scope.$apply -> $scope.data.admin = payload.message.username
if payload.message.type == 'reset'
$scope.$apply ->
$scope.data.reveal = null
$scope.data.consensus = null
$scope.data.consensus_value = null
$scope.data.votes = {}
history = "***Voting was reset.\n" + $('#chat_history').html()
$('#chat_history').html(history)
if payload.message.type == 'reveal'
$scope.data.votes = payload.message.votes
$scope.$apply ->
$scope.data.reveal = true
$scope.data.consensus = payload.message.consensus
$scope.data.consensus_value = payload.message.consensus_value
if payload.message.votes
votes = _(payload.message.votes).map( (vote) -> vote.username + " voted " + vote.value ).join(", ")
history = "***Votes revealed: " + votes + "\n" + $('#chat_history').html()
$('#chat_history').html(history)
PubNub.ngHistory {channel:$scope.data.room_ctrl,count:500}
PubNub.ngHistory {channel:$scope.data.room_admn,count:500}
ChatService.init($scope, $location, PubNub, $scope.data.room_chat)
###
Voting entails publishing a vote message including your username
on the control channel
###
$scope.vote = (value) ->
PubNub.ngPublish
channel: $scope.data.room_ctrl
message:
type: 'vote'
value: value
username: $scope.data.username
###
Reveal entails publishing a reveal message on the admin channel with the
full voting results
###
$scope.reveal = ->
_($scope.data.votes).forEach (x) -> x.displayvalue = x.value
### Compute consensus with underscore 'countBy' and taking item with max count ###
voteCounts = _($scope.data.votes).countBy (x) -> x.value
max_key = null
max_val = -1
_(voteCounts).forEach (count, value) ->
if (count == max_val)
### unset max_key in case of a collision ###
max_key = null
else
if (count > max_val)
max_key = value
max_val = count
PubNub.ngPublish
channel: $scope.data.room_admn
message:
type: 'reveal'
votes: $scope.data.votes
consensus: !!max_key
consensus_value: if max_key then max_key else null
username: $scope.data.username
###
Reset entails publishing a reset message on the admin channel
###
$scope.reset = ->
PubNub.ngPublish
channel: $scope.data.room_admn
message:
type: 'reset'
$scope.isAdmin = ->
!$scope.data.admin || ($scope.data.username == $scope.data.admin)
$scope.takeAdmin = ->
PubNub.ngPublish
channel: $scope.data.room_admn
message:
type: 'create_room'
username: $scope.data.username
room: $scope.data.new_room
PubNub.ngPublish
channel: $scope.data.room_chat
message:
username: 'RoomBot'
message: $scope.data.username + " just took 'admin'!"
$scope.init()
| true | 'use strict'
###
We set up the app with 3 main routes: login, lobby, and room
###
angular.module('AgilePoker', ['pubnub.angular.service'])
.config ($routeProvider) ->
$routeProvider
.when '/lobby',
templateUrl: 'views/lobby.html'
controller: 'LobbyCtrl'
.when '/login',
templateUrl: 'views/login.html'
controller: 'LoginCtrl'
.when '/rooms/:id',
templateUrl: 'views/room.html'
controller: 'RoomCtrl'
.otherwise
redirectTo: '/login'
###
The login controller is responsible for initializing PubNub
with the specified user id and directing the user to the Lobby
###
angular.module('AgilePoker')
.controller 'LoginCtrl', ($scope, $rootScope, $location, PubNub) ->
$rootScope.data ||= {}
$scope.data ||= {}
$scope.data.username = 'Anonymous ' + Math.floor(Math.random() * 1000)
$scope.join = ->
PubNub.init({
subscribe_key : 'PI:KEY:<KEY>END_PI'
publish_key : 'PI:KEY:<KEY>END_PI'
uuid : Math.floor(Math.random() * 1000000) + '__' + $scope.data.username
})
$rootScope.data.username = $scope.data.username
$location.path '/lobby'
###
The Chat service encapsulates chat functionality into an
easily include-able form.
###
ChatService =
init: ($scope, $location, PubNub, room) ->
$scope.sendChat = ->
if $scope.data.message
PubNub.ngPublish
channel: room
message:
username: $scope.data.username
message: $scope.data.message
$scope.data.message = ''
$scope.$on PubNub.ngMsgEv(room), (ngEvent, payload) ->
history = "[" + payload.message.username + "] " + payload.message.message + "\n" + $('#chat_history').html()
$('#chat_history').html(history)
$scope.$on PubNub.ngPrsEv(room), ->
$scope.$apply -> $scope.users = PubNub.map PubNub.ngListPresence(room), (x) -> x.replace(/\w+__/, "")
$scope.logout = (path) -> $location.path(path) if path
$scope.leave = (path) ->
PubNub.ngUnsubscribe({channel:room})
$location.path(path) if path
PubNub.ngSubscribe {channel: room}
PubNub.ngHistory {channel: room, count:500}
PubNub.ngHereNow {channel: room}
###
The lobby controller
###
angular.module('AgilePoker')
.controller 'LobbyCtrl', ($scope, $rootScope, $location, PubNub) ->
$location.path '/login' unless $rootScope.data
$scope.init = ->
$scope.data = {}
$scope.data.room = 'lobby'
$scope.data.room_ctrl = '$lobby$ctrl'
$scope.data.room_chat = '$lobby$chat'
$scope.data.username = $rootScope.data?.username
$scope.data.rooms ||= []
PubNub.ngSubscribe {channel: $scope.data.room_ctrl}
PubNub.ngHistory {channel: $scope.data.room_ctrl, count:500}
ChatService.init($scope, $location, PubNub, $scope.data.room_chat)
$scope.$on PubNub.ngMsgEv($scope.data.room_ctrl), (ngEvent, payload) ->
unless payload && _($scope.data.rooms).find( (x) -> (x.name == payload.message.room.name) )
$scope.$apply -> $scope.data.rooms.push payload.message.room
$scope.createRoom = ->
if $scope.data.new_room.name
message =
type: 'create_room'
username: $scope.data.username
room: $scope.data.new_room
### Publish to the control channel to "create" the room ###
PubNub.ngPublish
channel: $scope.data.room_ctrl
message: message
### Publish to the lobby chat channel to notify users of the room creation ###
PubNub.ngPublish
channel: $scope.data.room_chat
message:
username: 'RoomBot'
message: $scope.data.username + " just created room '<a href=\"#/rooms/" + $scope.data.new_room.name + "\">" + $scope.data.new_room.name + "</a>'"
### Publish to the admin channel to initialize the room administrator ###
PubNub.ngPublish
channel: $scope.data.new_room.name + '$admn'
message: message
### Publish to the room chat channel to welcome users ###
PubNub.ngPublish
channel: $scope.data.new_room.name + '$chat'
message:
username: 'RoomBot'
message: "Welcome to '" + $scope.data.new_room.name + "'"
$scope.data.showCreate = false
$scope.init()
angular.module('AgilePoker')
.controller 'RoomCtrl', ($scope, $rootScope, $routeParams, $location, PubNub) ->
$location.path '/join' unless $rootScope.data
$scope.init = ->
$scope.data ||= {}
$scope.data.room = $routeParams.id
$scope.data.room_lobby = '$lobby$ctrl'
$scope.data.room_admn = $routeParams.id + '$admn'
$scope.data.room_ctrl = $routeParams.id + '$ctrl'
$scope.data.room_chat = $routeParams.id + '$chat'
$scope.data.username = $rootScope.data?.username
$scope.data.votes = {}
$scope.data.votevalues = [ 0, '½', 1, 2, 3, 5, 8, 13, 20, 40 ]
$scope.data.myvote = null
$scope.data.reveal = false
$('#chat_history').val('')
PubNub.ngSubscribe {channel:$scope.data.room_ctrl}
PubNub.ngSubscribe {channel:$scope.data.room_admn}
###
There are a few types of messages: admin (create/reveal),
control (enter/leave/vote), and chat (handled by ChatService)
###
$scope.$on PubNub.ngMsgEv($scope.data.room_ctrl), (ngEvent, payload) ->
if payload.message.type == 'vote' && !$scope.data.reveal
$scope.$apply ->
$scope.data.myvote = payload.message.value if payload.message.username == $scope.data.username
$scope.data.votes[payload.message.username] = payload.message
$scope.$on PubNub.ngMsgEv($scope.data.room_admn), (ngEvent, payload) ->
if payload.message.type == 'create_room'
$scope.$apply -> $scope.data.admin = payload.message.username
if payload.message.type == 'reset'
$scope.$apply ->
$scope.data.reveal = null
$scope.data.consensus = null
$scope.data.consensus_value = null
$scope.data.votes = {}
history = "***Voting was reset.\n" + $('#chat_history').html()
$('#chat_history').html(history)
if payload.message.type == 'reveal'
$scope.data.votes = payload.message.votes
$scope.$apply ->
$scope.data.reveal = true
$scope.data.consensus = payload.message.consensus
$scope.data.consensus_value = payload.message.consensus_value
if payload.message.votes
votes = _(payload.message.votes).map( (vote) -> vote.username + " voted " + vote.value ).join(", ")
history = "***Votes revealed: " + votes + "\n" + $('#chat_history').html()
$('#chat_history').html(history)
PubNub.ngHistory {channel:$scope.data.room_ctrl,count:500}
PubNub.ngHistory {channel:$scope.data.room_admn,count:500}
ChatService.init($scope, $location, PubNub, $scope.data.room_chat)
###
Voting entails publishing a vote message including your username
on the control channel
###
$scope.vote = (value) ->
PubNub.ngPublish
channel: $scope.data.room_ctrl
message:
type: 'vote'
value: value
username: $scope.data.username
###
Reveal entails publishing a reveal message on the admin channel with the
full voting results
###
$scope.reveal = ->
_($scope.data.votes).forEach (x) -> x.displayvalue = x.value
### Compute consensus with underscore 'countBy' and taking item with max count ###
voteCounts = _($scope.data.votes).countBy (x) -> x.value
max_key = null
max_val = -1
_(voteCounts).forEach (count, value) ->
if (count == max_val)
### unset max_key in case of a collision ###
max_key = null
else
if (count > max_val)
max_key = value
max_val = count
PubNub.ngPublish
channel: $scope.data.room_admn
message:
type: 'reveal'
votes: $scope.data.votes
consensus: !!max_key
consensus_value: if max_key then max_key else null
username: $scope.data.username
###
Reset entails publishing a reset message on the admin channel
###
$scope.reset = ->
PubNub.ngPublish
channel: $scope.data.room_admn
message:
type: 'reset'
$scope.isAdmin = ->
!$scope.data.admin || ($scope.data.username == $scope.data.admin)
$scope.takeAdmin = ->
PubNub.ngPublish
channel: $scope.data.room_admn
message:
type: 'create_room'
username: $scope.data.username
room: $scope.data.new_room
PubNub.ngPublish
channel: $scope.data.room_chat
message:
username: 'RoomBot'
message: $scope.data.username + " just took 'admin'!"
$scope.init()
|
[
{
"context": "ructions: http://minijs.com/plugins/7/slider\n# By: Matthieu Aussaguel, http://www.mynameismatthieu.com, @mattaussaguel\n",
"end": 118,
"score": 0.9998982548713684,
"start": 100,
"tag": "NAME",
"value": "Matthieu Aussaguel"
},
{
"context": "tthieu Aussaguel, http://www.mynameismatthieu.com, @mattaussaguel\n# Version: 1.0 Stable\n# More info: http://minijs.",
"end": 167,
"score": 0.9996017813682556,
"start": 153,
"tag": "USERNAME",
"value": "@mattaussaguel"
}
] | resources/js/miniSlider.coffee | seidnur/test | 1 | #
# miniSlider, a slider plugin for jQuery
# Instructions: http://minijs.com/plugins/7/slider
# By: Matthieu Aussaguel, http://www.mynameismatthieu.com, @mattaussaguel
# Version: 1.0 Stable
# More info: http://minijs.com/
#
class Slide
constructor: (@element, @index, @options) ->
@element.css { position: 'absolute', top: 0, left: @index * @element.width() }
class Slider
constructor: (@container, @options) ->
@state = 'waiting'
@size =
height: @container.height()
width: @container.width()
@container.css({ overflow: 'hidden', position: 'absolute', top: 0, left: 0 })
.wrap("<div class='#{@options.containerClass}' style='position: relative; overflow: hidden;'/>")
@wrapper = @container.parent()
@initSlides()
appendNavigation: ->
@wrapper.after(@nextLink())
.after(@previousLink())
@nextLink().on 'click', =>
@stopAutoplay()
@next()
return false
@previousLink().on 'click', =>
@stopAutoplay()
@previous()
return false
appendPagination: ->
@wrapper.after(@pagination())
@pagination().on 'click', 'a', (e) =>
@to (($ e.currentTarget).data().index - 1 )
@stopAutoplay()
return false
previousLink: -> @$previousLink ||= $('<a />', { html: @options.previousBtnContent, class: @options.previousBtnClass, href: '#' })
nextLink: -> @$nextLink ||= $('<a />', { html: @options.nextBtnContent, class: @options.nextBtnClass, href: '#' })
pagination: ->
unless @$pagination
@$pagination = $('<ul />', class: @options.paginationClass)
@$pagination.append("<li><a href='#' data-index='#{index + 1}'>#{index + 1}</a></li>") for slide, index in @slides
@$pagination
currentPaginationElement: -> @pagination().find("li:eq(#{@currentIndex})")
count: -> @slides.length
initSlides: ->
# Create array of slide objects
@slides = []
@container.children().each (index, element) =>
@slides.push(new Slide($(element), index, @options))
@container.css('width', @size.width * @slides.length)
@initTracker()
currentSlideElement: -> @slideElementForIndex @currentIndex
previousSlideElement: -> @slideElementForIndex @previousIndex
nextSlideElement: -> @slideElementForIndex @nextIndex
slideElementForIndex: (index) -> @slides[index].element
initTracker: ->
@currentIndex = 0
@previousIndex = @count() - 1
@nextIndex = 1
@addCssClasses()
updateTracker: (newIndex) ->
@removeCssClasses()
@currentIndex = newIndex
@previousIndex = if newIndex is 0 then @count() - 1 else newIndex - 1
@nextIndex = if newIndex is @count() - 1 then 0 else newIndex + 1
@addCssClasses()
addCssClasses: ->
@currentSlideElement().addClass @options.currentClass
@previousSlideElement().addClass @options.previousClass
@nextSlideElement().addClass @options.nextClass
@currentPaginationElement().addClass(@options.currentPaginationClass)
removeCssClasses: ->
@currentSlideElement().removeClass @options.currentClass
@previousSlideElement().removeClass @options.previousClass
@nextSlideElement().removeClass @options.nextClass
@currentPaginationElement().removeClass(@options.currentPaginationClass)
playing: -> @autoplayId?
startAutoPlay: ->
@autoplayId = window.setInterval =>
@next()
, @options.delay
stopAutoplay: ->
if @playing()
clearInterval @autoplayId
@autoplayId = null
play: ->
@startAutoPlay()
if @options.pauseOnHover
@container.children()
.on('mouseover', =>
@pause()
).on('mouseleave', =>
@resume()
)
next: -> @to @nextIndex
previous: -> @to @previousIndex
callAnimationCallbackFunction: (functionName, index) ->
@options[functionName](@slideElementForIndex(index),index + 1)
to: (index) ->
unless @state is 'animating'
@state = 'animating'
@callAnimationCallbackFunction 'onTransition', index
@container.animate({ left: 0 - (@size.width * index) }, @options.transitionSpeed, @options.transitionEasing, =>
@updateTracker index
@state = 'waiting'
@callAnimationCallbackFunction 'onComplete', index
)
pause: -> @stopAutoplay()
resume: -> @startAutoPlay()
$ ->
$.miniSlider = (element, options) ->
# default plugin settings
@defaults =
# general
autoPlay: true # autoplay slides
delay: 3000 # delay between slides
containerClass: 'slider-container' # slider container class name
# slides
currentClass: 'current' # current slide class name
previousClass: 'previous' # previous slide class name
nextClass: 'next' # next slide class name
# transition
transitionSpeed: 500 # transition speed between slides
transitionEasing: '' # easing animation for the slides transition
# navigation
pauseOnHover: false # pause on mouse over
showNavigation: true # show next/previous buttons
previousBtnClass: 'previous-btn' # previous button class
nextBtnClass: 'next-btn' # next button class
previousBtnContent: '‹' # previous button html content
nextBtnContent: '›' # next button html content
showPagination: true # show slider pagination
paginationClass: 'pagination' # pagination wrapper class
currentPaginationClass: 'current-pagination' # current pagination list item class
# callbacks
onLoad: -> # Function(), called when miniSlider is loading
onReady: -> # Function(), called when miniSlider is ready
onTransition: -> # Function(slide, number), called when the slide is in sliding
onComplete: -> # Function(slide, number), called when the slide transition is complete
## public variables
# plugin settings
@settings = {}
# jQuery version of DOM element attached to the plugin
@$element = $ element
# slider object
@slider = {}
## public methods
# get particular plugin setting
@getSetting = (settingKey) ->
@settings[settingKey]
# call one of the plugin setting functions
@callSettingFunction = (functionName) ->
@settings[functionName]()
# init function
@init = ->
@settings = $.extend {}, @defaults, options
@callSettingFunction 'onLoad'
@slider = new Slider(@$element, @settings)
@slider.appendPagination() if @getSetting 'showPagination'
@slider.appendNavigation() if @getSetting 'showNavigation'
@callSettingFunction 'onReady'
@slider.play() if @getSetting 'autoPlay'
# initialise the plugin
@init()
this
$.fn.miniSlider = (options) ->
return this.each ->
if undefined == $(this).data 'miniSlider'
plugin = new $.miniSlider this, options
$(this).data 'miniSlider', plugin | 135599 | #
# miniSlider, a slider plugin for jQuery
# Instructions: http://minijs.com/plugins/7/slider
# By: <NAME>, http://www.mynameismatthieu.com, @mattaussaguel
# Version: 1.0 Stable
# More info: http://minijs.com/
#
class Slide
constructor: (@element, @index, @options) ->
@element.css { position: 'absolute', top: 0, left: @index * @element.width() }
class Slider
constructor: (@container, @options) ->
@state = 'waiting'
@size =
height: @container.height()
width: @container.width()
@container.css({ overflow: 'hidden', position: 'absolute', top: 0, left: 0 })
.wrap("<div class='#{@options.containerClass}' style='position: relative; overflow: hidden;'/>")
@wrapper = @container.parent()
@initSlides()
appendNavigation: ->
@wrapper.after(@nextLink())
.after(@previousLink())
@nextLink().on 'click', =>
@stopAutoplay()
@next()
return false
@previousLink().on 'click', =>
@stopAutoplay()
@previous()
return false
appendPagination: ->
@wrapper.after(@pagination())
@pagination().on 'click', 'a', (e) =>
@to (($ e.currentTarget).data().index - 1 )
@stopAutoplay()
return false
previousLink: -> @$previousLink ||= $('<a />', { html: @options.previousBtnContent, class: @options.previousBtnClass, href: '#' })
nextLink: -> @$nextLink ||= $('<a />', { html: @options.nextBtnContent, class: @options.nextBtnClass, href: '#' })
pagination: ->
unless @$pagination
@$pagination = $('<ul />', class: @options.paginationClass)
@$pagination.append("<li><a href='#' data-index='#{index + 1}'>#{index + 1}</a></li>") for slide, index in @slides
@$pagination
currentPaginationElement: -> @pagination().find("li:eq(#{@currentIndex})")
count: -> @slides.length
initSlides: ->
# Create array of slide objects
@slides = []
@container.children().each (index, element) =>
@slides.push(new Slide($(element), index, @options))
@container.css('width', @size.width * @slides.length)
@initTracker()
currentSlideElement: -> @slideElementForIndex @currentIndex
previousSlideElement: -> @slideElementForIndex @previousIndex
nextSlideElement: -> @slideElementForIndex @nextIndex
slideElementForIndex: (index) -> @slides[index].element
initTracker: ->
@currentIndex = 0
@previousIndex = @count() - 1
@nextIndex = 1
@addCssClasses()
updateTracker: (newIndex) ->
@removeCssClasses()
@currentIndex = newIndex
@previousIndex = if newIndex is 0 then @count() - 1 else newIndex - 1
@nextIndex = if newIndex is @count() - 1 then 0 else newIndex + 1
@addCssClasses()
addCssClasses: ->
@currentSlideElement().addClass @options.currentClass
@previousSlideElement().addClass @options.previousClass
@nextSlideElement().addClass @options.nextClass
@currentPaginationElement().addClass(@options.currentPaginationClass)
removeCssClasses: ->
@currentSlideElement().removeClass @options.currentClass
@previousSlideElement().removeClass @options.previousClass
@nextSlideElement().removeClass @options.nextClass
@currentPaginationElement().removeClass(@options.currentPaginationClass)
playing: -> @autoplayId?
startAutoPlay: ->
@autoplayId = window.setInterval =>
@next()
, @options.delay
stopAutoplay: ->
if @playing()
clearInterval @autoplayId
@autoplayId = null
play: ->
@startAutoPlay()
if @options.pauseOnHover
@container.children()
.on('mouseover', =>
@pause()
).on('mouseleave', =>
@resume()
)
next: -> @to @nextIndex
previous: -> @to @previousIndex
callAnimationCallbackFunction: (functionName, index) ->
@options[functionName](@slideElementForIndex(index),index + 1)
to: (index) ->
unless @state is 'animating'
@state = 'animating'
@callAnimationCallbackFunction 'onTransition', index
@container.animate({ left: 0 - (@size.width * index) }, @options.transitionSpeed, @options.transitionEasing, =>
@updateTracker index
@state = 'waiting'
@callAnimationCallbackFunction 'onComplete', index
)
pause: -> @stopAutoplay()
resume: -> @startAutoPlay()
$ ->
$.miniSlider = (element, options) ->
# default plugin settings
@defaults =
# general
autoPlay: true # autoplay slides
delay: 3000 # delay between slides
containerClass: 'slider-container' # slider container class name
# slides
currentClass: 'current' # current slide class name
previousClass: 'previous' # previous slide class name
nextClass: 'next' # next slide class name
# transition
transitionSpeed: 500 # transition speed between slides
transitionEasing: '' # easing animation for the slides transition
# navigation
pauseOnHover: false # pause on mouse over
showNavigation: true # show next/previous buttons
previousBtnClass: 'previous-btn' # previous button class
nextBtnClass: 'next-btn' # next button class
previousBtnContent: '‹' # previous button html content
nextBtnContent: '›' # next button html content
showPagination: true # show slider pagination
paginationClass: 'pagination' # pagination wrapper class
currentPaginationClass: 'current-pagination' # current pagination list item class
# callbacks
onLoad: -> # Function(), called when miniSlider is loading
onReady: -> # Function(), called when miniSlider is ready
onTransition: -> # Function(slide, number), called when the slide is in sliding
onComplete: -> # Function(slide, number), called when the slide transition is complete
## public variables
# plugin settings
@settings = {}
# jQuery version of DOM element attached to the plugin
@$element = $ element
# slider object
@slider = {}
## public methods
# get particular plugin setting
@getSetting = (settingKey) ->
@settings[settingKey]
# call one of the plugin setting functions
@callSettingFunction = (functionName) ->
@settings[functionName]()
# init function
@init = ->
@settings = $.extend {}, @defaults, options
@callSettingFunction 'onLoad'
@slider = new Slider(@$element, @settings)
@slider.appendPagination() if @getSetting 'showPagination'
@slider.appendNavigation() if @getSetting 'showNavigation'
@callSettingFunction 'onReady'
@slider.play() if @getSetting 'autoPlay'
# initialise the plugin
@init()
this
$.fn.miniSlider = (options) ->
return this.each ->
if undefined == $(this).data 'miniSlider'
plugin = new $.miniSlider this, options
$(this).data 'miniSlider', plugin | true | #
# miniSlider, a slider plugin for jQuery
# Instructions: http://minijs.com/plugins/7/slider
# By: PI:NAME:<NAME>END_PI, http://www.mynameismatthieu.com, @mattaussaguel
# Version: 1.0 Stable
# More info: http://minijs.com/
#
class Slide
constructor: (@element, @index, @options) ->
@element.css { position: 'absolute', top: 0, left: @index * @element.width() }
class Slider
constructor: (@container, @options) ->
@state = 'waiting'
@size =
height: @container.height()
width: @container.width()
@container.css({ overflow: 'hidden', position: 'absolute', top: 0, left: 0 })
.wrap("<div class='#{@options.containerClass}' style='position: relative; overflow: hidden;'/>")
@wrapper = @container.parent()
@initSlides()
appendNavigation: ->
@wrapper.after(@nextLink())
.after(@previousLink())
@nextLink().on 'click', =>
@stopAutoplay()
@next()
return false
@previousLink().on 'click', =>
@stopAutoplay()
@previous()
return false
appendPagination: ->
@wrapper.after(@pagination())
@pagination().on 'click', 'a', (e) =>
@to (($ e.currentTarget).data().index - 1 )
@stopAutoplay()
return false
previousLink: -> @$previousLink ||= $('<a />', { html: @options.previousBtnContent, class: @options.previousBtnClass, href: '#' })
nextLink: -> @$nextLink ||= $('<a />', { html: @options.nextBtnContent, class: @options.nextBtnClass, href: '#' })
pagination: ->
unless @$pagination
@$pagination = $('<ul />', class: @options.paginationClass)
@$pagination.append("<li><a href='#' data-index='#{index + 1}'>#{index + 1}</a></li>") for slide, index in @slides
@$pagination
currentPaginationElement: -> @pagination().find("li:eq(#{@currentIndex})")
count: -> @slides.length
initSlides: ->
# Create array of slide objects
@slides = []
@container.children().each (index, element) =>
@slides.push(new Slide($(element), index, @options))
@container.css('width', @size.width * @slides.length)
@initTracker()
currentSlideElement: -> @slideElementForIndex @currentIndex
previousSlideElement: -> @slideElementForIndex @previousIndex
nextSlideElement: -> @slideElementForIndex @nextIndex
slideElementForIndex: (index) -> @slides[index].element
initTracker: ->
@currentIndex = 0
@previousIndex = @count() - 1
@nextIndex = 1
@addCssClasses()
updateTracker: (newIndex) ->
@removeCssClasses()
@currentIndex = newIndex
@previousIndex = if newIndex is 0 then @count() - 1 else newIndex - 1
@nextIndex = if newIndex is @count() - 1 then 0 else newIndex + 1
@addCssClasses()
addCssClasses: ->
@currentSlideElement().addClass @options.currentClass
@previousSlideElement().addClass @options.previousClass
@nextSlideElement().addClass @options.nextClass
@currentPaginationElement().addClass(@options.currentPaginationClass)
removeCssClasses: ->
@currentSlideElement().removeClass @options.currentClass
@previousSlideElement().removeClass @options.previousClass
@nextSlideElement().removeClass @options.nextClass
@currentPaginationElement().removeClass(@options.currentPaginationClass)
playing: -> @autoplayId?
startAutoPlay: ->
@autoplayId = window.setInterval =>
@next()
, @options.delay
stopAutoplay: ->
if @playing()
clearInterval @autoplayId
@autoplayId = null
play: ->
@startAutoPlay()
if @options.pauseOnHover
@container.children()
.on('mouseover', =>
@pause()
).on('mouseleave', =>
@resume()
)
next: -> @to @nextIndex
previous: -> @to @previousIndex
callAnimationCallbackFunction: (functionName, index) ->
@options[functionName](@slideElementForIndex(index),index + 1)
to: (index) ->
unless @state is 'animating'
@state = 'animating'
@callAnimationCallbackFunction 'onTransition', index
@container.animate({ left: 0 - (@size.width * index) }, @options.transitionSpeed, @options.transitionEasing, =>
@updateTracker index
@state = 'waiting'
@callAnimationCallbackFunction 'onComplete', index
)
pause: -> @stopAutoplay()
resume: -> @startAutoPlay()
$ ->
$.miniSlider = (element, options) ->
# default plugin settings
@defaults =
# general
autoPlay: true # autoplay slides
delay: 3000 # delay between slides
containerClass: 'slider-container' # slider container class name
# slides
currentClass: 'current' # current slide class name
previousClass: 'previous' # previous slide class name
nextClass: 'next' # next slide class name
# transition
transitionSpeed: 500 # transition speed between slides
transitionEasing: '' # easing animation for the slides transition
# navigation
pauseOnHover: false # pause on mouse over
showNavigation: true # show next/previous buttons
previousBtnClass: 'previous-btn' # previous button class
nextBtnClass: 'next-btn' # next button class
previousBtnContent: '‹' # previous button html content
nextBtnContent: '›' # next button html content
showPagination: true # show slider pagination
paginationClass: 'pagination' # pagination wrapper class
currentPaginationClass: 'current-pagination' # current pagination list item class
# callbacks
onLoad: -> # Function(), called when miniSlider is loading
onReady: -> # Function(), called when miniSlider is ready
onTransition: -> # Function(slide, number), called when the slide is in sliding
onComplete: -> # Function(slide, number), called when the slide transition is complete
## public variables
# plugin settings
@settings = {}
# jQuery version of DOM element attached to the plugin
@$element = $ element
# slider object
@slider = {}
## public methods
# get particular plugin setting
@getSetting = (settingKey) ->
@settings[settingKey]
# call one of the plugin setting functions
@callSettingFunction = (functionName) ->
@settings[functionName]()
# init function
@init = ->
@settings = $.extend {}, @defaults, options
@callSettingFunction 'onLoad'
@slider = new Slider(@$element, @settings)
@slider.appendPagination() if @getSetting 'showPagination'
@slider.appendNavigation() if @getSetting 'showNavigation'
@callSettingFunction 'onReady'
@slider.play() if @getSetting 'autoPlay'
# initialise the plugin
@init()
this
$.fn.miniSlider = (options) ->
return this.each ->
if undefined == $(this).data 'miniSlider'
plugin = new $.miniSlider this, options
$(this).data 'miniSlider', plugin |
[
{
"context": ": process.env.HUBOT_XMPP_USERNAME\n password: process.env.HUBOT_XMPP_PASSWORD\n host: process.env.HUBOT_XMPP_HOST\n por",
"end": 2465,
"score": 0.9983234405517578,
"start": 2434,
"tag": "PASSWORD",
"value": "process.env.HUBOT_XMPP_PASSWORD"
}
] | src/hubot-single-user-xmpp.coffee | black-roland/hubot-single-user-xmpp | 1 | try
{ Adapter, TextMessage, User } = require 'hubot'
catch
prequire = require 'parent-require'
{ Adapter, TextMessage, User } = prequire 'hubot'
xmpp = require 'simple-xmpp'
class XMPPAdapter extends Adapter
reconnectInterval: 30000
constructor: (robot) ->
@robot = robot
@admin = process.env.HUBOT_XMPP_ADMIN_JID
@xmpp = xmpp
send: (envelope, messages...) =>
@xmpp.send envelope.room or envelope.user.jid, "#{str}" for str in messages
emote: (envelope, messages...) =>
@send envelope, "* #{str}" for str in messages
reply: (envelope, messages...) =>
@send envelope, messages
online: () =>
@robot.logger.info 'Hubot online, ready to go!'
@emit if @connected then 'reconnected' else 'connected'
@connected = true
clearInterval @reconnectTimer if @reconnectTimer
@reconnectTimer = false
@xmpp.subscribe @admin
chat: (from, message) =>
@robot.logger.debug "Received message: #{message} from: #{from}"
# ignore messages not from admin
return @robot.logger.debug "Ignoring message" unless from == @admin
user = new User from,
jid: from
room: from
# remove Hubot name from message
message = message.replace new RegExp("^#{ process.env.HUBOT_NAME or 'Hubot' } ", 'i')
message = message.replace new RegExp("^#{ process.env.HUBOT_ALIAS } ", 'i') if process.env.HUBOT_ALIAS
# prefix all messages with hubot name
message = "#{ process.env.HUBOT_NAME or 'Hubot' } #{ message }"
message = new TextMessage(user, message)
@receive message
subscribe: (from) =>
@robot.logger.debug "Accepting subscription from #{from}"
@xmpp.acceptSubscription from if from == @admin
error: (err) =>
@robot.logger.error 'XMPP error', err
reconnect: () =>
return if @reconnectTimer
@robot.logger.info 'Connection lost'
@reconnectTimer = setInterval () =>
@robot.logger.info 'Reconnecting...'
@xmpp.removeListener 'online', @online
@xmpp.removeListener 'chat', @chat
@xmpp.removeListener 'subscribe', @subscribe
@xmpp.removeListener 'error', @error
@xmpp.conn.removeListener 'end', @reconnect
@connect()
, @reconnectInterval
connect: () =>
@xmpp.on 'online', @online
@xmpp.on 'chat', @chat
@xmpp.on 'subscribe', @subscribe
@xmpp.on 'error', @error
@xmpp.connect
jid: process.env.HUBOT_XMPP_USERNAME
password: process.env.HUBOT_XMPP_PASSWORD
host: process.env.HUBOT_XMPP_HOST
port: process.env.HUBOT_XMPP_PORT or 5222
@xmpp.conn.on 'end', @reconnect
run: =>
return @robot.logger.error 'Undefined HUBOT_XMPP_ADMIN_JID' unless @admin
@connect()
module.exports.use = (robot) ->
new XMPPAdapter robot
| 75551 | try
{ Adapter, TextMessage, User } = require 'hubot'
catch
prequire = require 'parent-require'
{ Adapter, TextMessage, User } = prequire 'hubot'
xmpp = require 'simple-xmpp'
class XMPPAdapter extends Adapter
reconnectInterval: 30000
constructor: (robot) ->
@robot = robot
@admin = process.env.HUBOT_XMPP_ADMIN_JID
@xmpp = xmpp
send: (envelope, messages...) =>
@xmpp.send envelope.room or envelope.user.jid, "#{str}" for str in messages
emote: (envelope, messages...) =>
@send envelope, "* #{str}" for str in messages
reply: (envelope, messages...) =>
@send envelope, messages
online: () =>
@robot.logger.info 'Hubot online, ready to go!'
@emit if @connected then 'reconnected' else 'connected'
@connected = true
clearInterval @reconnectTimer if @reconnectTimer
@reconnectTimer = false
@xmpp.subscribe @admin
chat: (from, message) =>
@robot.logger.debug "Received message: #{message} from: #{from}"
# ignore messages not from admin
return @robot.logger.debug "Ignoring message" unless from == @admin
user = new User from,
jid: from
room: from
# remove Hubot name from message
message = message.replace new RegExp("^#{ process.env.HUBOT_NAME or 'Hubot' } ", 'i')
message = message.replace new RegExp("^#{ process.env.HUBOT_ALIAS } ", 'i') if process.env.HUBOT_ALIAS
# prefix all messages with hubot name
message = "#{ process.env.HUBOT_NAME or 'Hubot' } #{ message }"
message = new TextMessage(user, message)
@receive message
subscribe: (from) =>
@robot.logger.debug "Accepting subscription from #{from}"
@xmpp.acceptSubscription from if from == @admin
error: (err) =>
@robot.logger.error 'XMPP error', err
reconnect: () =>
return if @reconnectTimer
@robot.logger.info 'Connection lost'
@reconnectTimer = setInterval () =>
@robot.logger.info 'Reconnecting...'
@xmpp.removeListener 'online', @online
@xmpp.removeListener 'chat', @chat
@xmpp.removeListener 'subscribe', @subscribe
@xmpp.removeListener 'error', @error
@xmpp.conn.removeListener 'end', @reconnect
@connect()
, @reconnectInterval
connect: () =>
@xmpp.on 'online', @online
@xmpp.on 'chat', @chat
@xmpp.on 'subscribe', @subscribe
@xmpp.on 'error', @error
@xmpp.connect
jid: process.env.HUBOT_XMPP_USERNAME
password: <PASSWORD>
host: process.env.HUBOT_XMPP_HOST
port: process.env.HUBOT_XMPP_PORT or 5222
@xmpp.conn.on 'end', @reconnect
run: =>
return @robot.logger.error 'Undefined HUBOT_XMPP_ADMIN_JID' unless @admin
@connect()
module.exports.use = (robot) ->
new XMPPAdapter robot
| true | try
{ Adapter, TextMessage, User } = require 'hubot'
catch
prequire = require 'parent-require'
{ Adapter, TextMessage, User } = prequire 'hubot'
xmpp = require 'simple-xmpp'
class XMPPAdapter extends Adapter
reconnectInterval: 30000
constructor: (robot) ->
@robot = robot
@admin = process.env.HUBOT_XMPP_ADMIN_JID
@xmpp = xmpp
send: (envelope, messages...) =>
@xmpp.send envelope.room or envelope.user.jid, "#{str}" for str in messages
emote: (envelope, messages...) =>
@send envelope, "* #{str}" for str in messages
reply: (envelope, messages...) =>
@send envelope, messages
online: () =>
@robot.logger.info 'Hubot online, ready to go!'
@emit if @connected then 'reconnected' else 'connected'
@connected = true
clearInterval @reconnectTimer if @reconnectTimer
@reconnectTimer = false
@xmpp.subscribe @admin
chat: (from, message) =>
@robot.logger.debug "Received message: #{message} from: #{from}"
# ignore messages not from admin
return @robot.logger.debug "Ignoring message" unless from == @admin
user = new User from,
jid: from
room: from
# remove Hubot name from message
message = message.replace new RegExp("^#{ process.env.HUBOT_NAME or 'Hubot' } ", 'i')
message = message.replace new RegExp("^#{ process.env.HUBOT_ALIAS } ", 'i') if process.env.HUBOT_ALIAS
# prefix all messages with hubot name
message = "#{ process.env.HUBOT_NAME or 'Hubot' } #{ message }"
message = new TextMessage(user, message)
@receive message
subscribe: (from) =>
@robot.logger.debug "Accepting subscription from #{from}"
@xmpp.acceptSubscription from if from == @admin
error: (err) =>
@robot.logger.error 'XMPP error', err
reconnect: () =>
return if @reconnectTimer
@robot.logger.info 'Connection lost'
@reconnectTimer = setInterval () =>
@robot.logger.info 'Reconnecting...'
@xmpp.removeListener 'online', @online
@xmpp.removeListener 'chat', @chat
@xmpp.removeListener 'subscribe', @subscribe
@xmpp.removeListener 'error', @error
@xmpp.conn.removeListener 'end', @reconnect
@connect()
, @reconnectInterval
connect: () =>
@xmpp.on 'online', @online
@xmpp.on 'chat', @chat
@xmpp.on 'subscribe', @subscribe
@xmpp.on 'error', @error
@xmpp.connect
jid: process.env.HUBOT_XMPP_USERNAME
password: PI:PASSWORD:<PASSWORD>END_PI
host: process.env.HUBOT_XMPP_HOST
port: process.env.HUBOT_XMPP_PORT or 5222
@xmpp.conn.on 'end', @reconnect
run: =>
return @robot.logger.error 'Undefined HUBOT_XMPP_ADMIN_JID' unless @admin
@connect()
module.exports.use = (robot) ->
new XMPPAdapter robot
|
[
{
"context": "###\nCopyright 2017 Balena\n\nLicensed under the Apache License, Version 2.",
"end": 22,
"score": 0.6200683116912842,
"start": 19,
"tag": "NAME",
"value": "Bal"
}
] | lib/actions/local/scan.coffee | edmooney/balena-cli | 0 | ###
Copyright 2017 Balena
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
dockerInfoProperties = [
'Containers'
'ContainersRunning'
'ContainersPaused'
'ContainersStopped'
'Images'
'Driver'
'SystemTime'
'KernelVersion'
'OperatingSystem'
'Architecture'
]
dockerVersionProperties = [
'Version'
'ApiVersion'
]
module.exports =
signature: 'local scan'
description: 'Scan for balenaOS devices in your local network'
help: '''
Examples:
$ balena local scan
$ balena local scan --timeout 120
$ balena local scan --verbose
'''
options: [
signature: 'verbose'
boolean: true
description: 'Display full info'
alias: 'v'
,
signature: 'timeout'
parameter: 'timeout'
description: 'Scan timeout in seconds'
alias: 't'
]
primary: true
root: true
action: (params, options, done) ->
Promise = require('bluebird')
_ = require('lodash')
prettyjson = require('prettyjson')
{ discover } = require('balena-sync')
{ SpinnerPromise } = require('resin-cli-visuals')
{ dockerPort, dockerTimeout } = require('./common')
dockerUtils = require('../../utils/docker')
{ exitWithExpectedError } = require('../../utils/patterns')
if options.timeout?
options.timeout *= 1000
Promise.try ->
new SpinnerPromise
promise: discover.discoverLocalBalenaOsDevices(options.timeout)
startMessage: 'Scanning for local balenaOS devices..'
stopMessage: 'Reporting scan results'
.filter ({ address }) ->
Promise.try ->
docker = dockerUtils.createClient(host: address, port: dockerPort, timeout: dockerTimeout)
docker.pingAsync()
.return(true)
.catchReturn(false)
.tap (devices) ->
if _.isEmpty(devices)
exitWithExpectedError('Could not find any balenaOS devices in the local network')
.map ({ host, address }) ->
docker = dockerUtils.createClient(host: address, port: dockerPort, timeout: dockerTimeout)
Promise.props
dockerInfo: docker.infoAsync().catchReturn('Could not get Docker info')
dockerVersion: docker.versionAsync().catchReturn('Could not get Docker version')
.then ({ dockerInfo, dockerVersion }) ->
if not options.verbose
dockerInfo = _.pick(dockerInfo, dockerInfoProperties) if _.isObject(dockerInfo)
dockerVersion = _.pick(dockerVersion, dockerVersionProperties) if _.isObject(dockerVersion)
return { host, address, dockerInfo, dockerVersion }
.then (devicesInfo) ->
console.log(prettyjson.render(devicesInfo, noColor: true))
.nodeify(done)
| 190085 | ###
Copyright 2017 <NAME>ena
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
dockerInfoProperties = [
'Containers'
'ContainersRunning'
'ContainersPaused'
'ContainersStopped'
'Images'
'Driver'
'SystemTime'
'KernelVersion'
'OperatingSystem'
'Architecture'
]
dockerVersionProperties = [
'Version'
'ApiVersion'
]
module.exports =
signature: 'local scan'
description: 'Scan for balenaOS devices in your local network'
help: '''
Examples:
$ balena local scan
$ balena local scan --timeout 120
$ balena local scan --verbose
'''
options: [
signature: 'verbose'
boolean: true
description: 'Display full info'
alias: 'v'
,
signature: 'timeout'
parameter: 'timeout'
description: 'Scan timeout in seconds'
alias: 't'
]
primary: true
root: true
action: (params, options, done) ->
Promise = require('bluebird')
_ = require('lodash')
prettyjson = require('prettyjson')
{ discover } = require('balena-sync')
{ SpinnerPromise } = require('resin-cli-visuals')
{ dockerPort, dockerTimeout } = require('./common')
dockerUtils = require('../../utils/docker')
{ exitWithExpectedError } = require('../../utils/patterns')
if options.timeout?
options.timeout *= 1000
Promise.try ->
new SpinnerPromise
promise: discover.discoverLocalBalenaOsDevices(options.timeout)
startMessage: 'Scanning for local balenaOS devices..'
stopMessage: 'Reporting scan results'
.filter ({ address }) ->
Promise.try ->
docker = dockerUtils.createClient(host: address, port: dockerPort, timeout: dockerTimeout)
docker.pingAsync()
.return(true)
.catchReturn(false)
.tap (devices) ->
if _.isEmpty(devices)
exitWithExpectedError('Could not find any balenaOS devices in the local network')
.map ({ host, address }) ->
docker = dockerUtils.createClient(host: address, port: dockerPort, timeout: dockerTimeout)
Promise.props
dockerInfo: docker.infoAsync().catchReturn('Could not get Docker info')
dockerVersion: docker.versionAsync().catchReturn('Could not get Docker version')
.then ({ dockerInfo, dockerVersion }) ->
if not options.verbose
dockerInfo = _.pick(dockerInfo, dockerInfoProperties) if _.isObject(dockerInfo)
dockerVersion = _.pick(dockerVersion, dockerVersionProperties) if _.isObject(dockerVersion)
return { host, address, dockerInfo, dockerVersion }
.then (devicesInfo) ->
console.log(prettyjson.render(devicesInfo, noColor: true))
.nodeify(done)
| true | ###
Copyright 2017 PI:NAME:<NAME>END_PIena
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
dockerInfoProperties = [
'Containers'
'ContainersRunning'
'ContainersPaused'
'ContainersStopped'
'Images'
'Driver'
'SystemTime'
'KernelVersion'
'OperatingSystem'
'Architecture'
]
dockerVersionProperties = [
'Version'
'ApiVersion'
]
module.exports =
signature: 'local scan'
description: 'Scan for balenaOS devices in your local network'
help: '''
Examples:
$ balena local scan
$ balena local scan --timeout 120
$ balena local scan --verbose
'''
options: [
signature: 'verbose'
boolean: true
description: 'Display full info'
alias: 'v'
,
signature: 'timeout'
parameter: 'timeout'
description: 'Scan timeout in seconds'
alias: 't'
]
primary: true
root: true
action: (params, options, done) ->
Promise = require('bluebird')
_ = require('lodash')
prettyjson = require('prettyjson')
{ discover } = require('balena-sync')
{ SpinnerPromise } = require('resin-cli-visuals')
{ dockerPort, dockerTimeout } = require('./common')
dockerUtils = require('../../utils/docker')
{ exitWithExpectedError } = require('../../utils/patterns')
if options.timeout?
options.timeout *= 1000
Promise.try ->
new SpinnerPromise
promise: discover.discoverLocalBalenaOsDevices(options.timeout)
startMessage: 'Scanning for local balenaOS devices..'
stopMessage: 'Reporting scan results'
.filter ({ address }) ->
Promise.try ->
docker = dockerUtils.createClient(host: address, port: dockerPort, timeout: dockerTimeout)
docker.pingAsync()
.return(true)
.catchReturn(false)
.tap (devices) ->
if _.isEmpty(devices)
exitWithExpectedError('Could not find any balenaOS devices in the local network')
.map ({ host, address }) ->
docker = dockerUtils.createClient(host: address, port: dockerPort, timeout: dockerTimeout)
Promise.props
dockerInfo: docker.infoAsync().catchReturn('Could not get Docker info')
dockerVersion: docker.versionAsync().catchReturn('Could not get Docker version')
.then ({ dockerInfo, dockerVersion }) ->
if not options.verbose
dockerInfo = _.pick(dockerInfo, dockerInfoProperties) if _.isObject(dockerInfo)
dockerVersion = _.pick(dockerVersion, dockerVersionProperties) if _.isObject(dockerVersion)
return { host, address, dockerInfo, dockerVersion }
.then (devicesInfo) ->
console.log(prettyjson.render(devicesInfo, noColor: true))
.nodeify(done)
|
[
{
"context": "# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplan",
"end": 18,
"score": 0.999886691570282,
"start": 10,
"tag": "NAME",
"value": "Tim Knip"
},
{
"context": "orplanner.com/ / tim at floorplanner.com\n# @author aladjev.andrew@gmail.com\n\n#= require new_src/core/geometry\n#= require new_",
"end": 110,
"score": 0.9999265074729919,
"start": 86,
"tag": "EMAIL",
"value": "aladjev.andrew@gmail.com"
}
] | source/javascripts/new_src/loaders/collada/polygons.coffee | andrew-aladev/three.js | 0 | # @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
# @author aladjev.andrew@gmail.com
#= require new_src/core/geometry
#= require new_src/loaders/collada/input
class Polygons
constructor: ->
@material = ""
@count = 0
@inputs = []
@vcount = null
@p = []
@geometry = new THREE.Geometry()
setVertices: (vertices) ->
length = @inputs.length
for i in [0...length]
if @inputs[i].source is vertices.id
@inputs[i].source = vertices.input["POSITION"].source
parse: (element) ->
@material = element.getAttribute "material"
@count = THREE.ColladaLoader._attr_as_int element, "count", 0
length = element.childNodes.length
for i in [0...length]
child = element.childNodes[i]
switch child.nodeName
when "input"
@inputs.push new THREE.Collada.Input().parse(element.childNodes[i])
when "vcount"
@vcount = THREE.ColladaLoader._ints child.textContent
when "p"
@p.push THREE.ColladaLoader._ints child.textContent
when "ph"
console.warn "polygon holes not yet supported!"
this
namespace "THREE.Collada", (exports) ->
exports.Polygons = Polygons | 170464 | # @author <NAME> / http://www.floorplanner.com/ / tim at floorplanner.com
# @author <EMAIL>
#= require new_src/core/geometry
#= require new_src/loaders/collada/input
class Polygons
constructor: ->
@material = ""
@count = 0
@inputs = []
@vcount = null
@p = []
@geometry = new THREE.Geometry()
setVertices: (vertices) ->
length = @inputs.length
for i in [0...length]
if @inputs[i].source is vertices.id
@inputs[i].source = vertices.input["POSITION"].source
parse: (element) ->
@material = element.getAttribute "material"
@count = THREE.ColladaLoader._attr_as_int element, "count", 0
length = element.childNodes.length
for i in [0...length]
child = element.childNodes[i]
switch child.nodeName
when "input"
@inputs.push new THREE.Collada.Input().parse(element.childNodes[i])
when "vcount"
@vcount = THREE.ColladaLoader._ints child.textContent
when "p"
@p.push THREE.ColladaLoader._ints child.textContent
when "ph"
console.warn "polygon holes not yet supported!"
this
namespace "THREE.Collada", (exports) ->
exports.Polygons = Polygons | true | # @author PI:NAME:<NAME>END_PI / http://www.floorplanner.com/ / tim at floorplanner.com
# @author PI:EMAIL:<EMAIL>END_PI
#= require new_src/core/geometry
#= require new_src/loaders/collada/input
class Polygons
constructor: ->
@material = ""
@count = 0
@inputs = []
@vcount = null
@p = []
@geometry = new THREE.Geometry()
setVertices: (vertices) ->
length = @inputs.length
for i in [0...length]
if @inputs[i].source is vertices.id
@inputs[i].source = vertices.input["POSITION"].source
parse: (element) ->
@material = element.getAttribute "material"
@count = THREE.ColladaLoader._attr_as_int element, "count", 0
length = element.childNodes.length
for i in [0...length]
child = element.childNodes[i]
switch child.nodeName
when "input"
@inputs.push new THREE.Collada.Input().parse(element.childNodes[i])
when "vcount"
@vcount = THREE.ColladaLoader._ints child.textContent
when "p"
@p.push THREE.ColladaLoader._ints child.textContent
when "ph"
console.warn "polygon holes not yet supported!"
this
namespace "THREE.Collada", (exports) ->
exports.Polygons = Polygons |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.