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": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999146461486816,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/profile-page/play-time.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 * as React from 'react'
import { span } from 'react-dom-factories'
import { ValueDisplay } from 'value-display'
el = React.createElement
export PlayTime = ({stats}) ->
playTime = moment.duration stats.play_time, 'seconds'
daysLeftOver = Math.floor playTime.asDays()
hours = playTime.hours()
totalMinutes = Math.floor playTime.asMinutes()
minutes = totalMinutes % 60 # account for seconds rounding
titleValue = Math.round(playTime.asHours())
titleUnit = 'hours'
if titleValue < 2
titleValue = totalMinutes
titleUnit = 'minutes'
title = osu.transChoice("common.count.#{titleUnit}", titleValue)
timeString = ''
timeString = "#{osu.formatNumber(daysLeftOver)}d " if daysLeftOver > 0
timeString += "#{hours}h #{minutes}m"
el ValueDisplay,
label: osu.trans('users.show.stats.play_time')
value:
span
title: title
'data-tooltip-position': 'bottom center'
timeString
| 84176 | # 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 * as React from 'react'
import { span } from 'react-dom-factories'
import { ValueDisplay } from 'value-display'
el = React.createElement
export PlayTime = ({stats}) ->
playTime = moment.duration stats.play_time, 'seconds'
daysLeftOver = Math.floor playTime.asDays()
hours = playTime.hours()
totalMinutes = Math.floor playTime.asMinutes()
minutes = totalMinutes % 60 # account for seconds rounding
titleValue = Math.round(playTime.asHours())
titleUnit = 'hours'
if titleValue < 2
titleValue = totalMinutes
titleUnit = 'minutes'
title = osu.transChoice("common.count.#{titleUnit}", titleValue)
timeString = ''
timeString = "#{osu.formatNumber(daysLeftOver)}d " if daysLeftOver > 0
timeString += "#{hours}h #{minutes}m"
el ValueDisplay,
label: osu.trans('users.show.stats.play_time')
value:
span
title: title
'data-tooltip-position': 'bottom center'
timeString
| 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 * as React from 'react'
import { span } from 'react-dom-factories'
import { ValueDisplay } from 'value-display'
el = React.createElement
export PlayTime = ({stats}) ->
playTime = moment.duration stats.play_time, 'seconds'
daysLeftOver = Math.floor playTime.asDays()
hours = playTime.hours()
totalMinutes = Math.floor playTime.asMinutes()
minutes = totalMinutes % 60 # account for seconds rounding
titleValue = Math.round(playTime.asHours())
titleUnit = 'hours'
if titleValue < 2
titleValue = totalMinutes
titleUnit = 'minutes'
title = osu.transChoice("common.count.#{titleUnit}", titleValue)
timeString = ''
timeString = "#{osu.formatNumber(daysLeftOver)}d " if daysLeftOver > 0
timeString += "#{hours}h #{minutes}m"
el ValueDisplay,
label: osu.trans('users.show.stats.play_time')
value:
span
title: title
'data-tooltip-position': 'bottom center'
timeString
|
[
{
"context": "gration script\n copyright 2fours LLC\n written by Adam Patacchiola adam@2fours.com\n\n###\nenv = process.env.SURESPOT_E",
"end": 79,
"score": 0.9998798370361328,
"start": 63,
"tag": "NAME",
"value": "Adam Patacchiola"
},
{
"context": "copyright 2fours LLC\n written by Adam Patacchiola adam@2fours.com\n\n###\nenv = process.env.SURESPOT_ENV ? 'Local' # o",
"end": 95,
"score": 0.9999237060546875,
"start": 80,
"tag": "EMAIL",
"value": "adam@2fours.com"
},
{
"context": "= process.env.SURESPOT_REDIS_SENTINEL_HOSTNAME ? \"127.0.0.1\"\nredisPassword = process.env.SURESPOT_REDIS_PASSW",
"end": 2207,
"score": 0.9997522830963135,
"start": 2198,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "tinel\n sentinel = redis.createClient(26379, \"127.0.0.1\", {logger: logger})\n tempclient = sentinel.g",
"end": 3781,
"score": 0.9997348785400391,
"start": 3772,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | server/migration2/deleteCUs.coffee | SchoolOfFreelancing/SureSpot | 1 | ###
db migration script
copyright 2fours LLC
written by Adam Patacchiola adam@2fours.com
###
env = process.env.SURESPOT_ENV ? 'Local' # one of "Local","Stage", "Prod"
async = require 'async'
_ = require 'underscore'
cdb = require '../cdb'
common = require '../common'
#constants
USERNAME_LENGTH = 20
CONTROL_MESSAGE_HISTORY = 100
MAX_MESSAGE_LENGTH = 500000
MAX_HTTP_REQUEST_LENGTH = 500000
NUM_CORES = parseInt(process.env.SURESPOT_CORES) ? 4
GCM_TTL = 604800
oneYear = 31536000000
oneDay = 86400
#config
#rate limit to MESSAGE_RATE_LIMIT_RATE / MESSAGE_RATE_LIMIT_SECS (seconds) (allows us to get request specific on top of iptables)
RATE_LIMITING_MESSAGE=process.env.SURESPOT_RATE_LIMITING_MESSAGE is "true"
RATE_LIMIT_BUCKET_MESSAGE = process.env.SURESPOT_RATE_LIMIT_BUCKET_MESSAGE ? 5
RATE_LIMIT_SECS_MESSAGE = process.env.SURESPOT_RATE_LIMIT_SECS_MESSAGE ? 10
RATE_LIMIT_RATE_MESSAGE = process.env.SURESPOT_RATE_LIMIT_RATE_MESSAGE ? 100
MESSAGES_PER_USER = process.env.SURESPOT_MESSAGES_PER_USER ? 500
debugLevel = process.env.SURESPOT_DEBUG_LEVEL ? 'debug'
database = process.env.SURESPOT_DB ? 0
socketPort = process.env.SURESPOT_SOCKET ? 8080
googleApiKey = process.env.SURESPOT_GOOGLE_API_KEY
googleClientId = process.env.SURESPOT_GOOGLE_CLIENT_ID
googleClientSecret = process.env.SURESPOT_GOOGLE_CLIENT_SECRET
googleRedirectUrl = process.env.SURESPOT_GOOGLE_REDIRECT_URL
googleOauth2Code = process.env.SURESPOT_GOOGLE_OAUTH2_CODE
rackspaceApiKey = process.env.SURESPOT_RACKSPACE_API_KEY
rackspaceCdnImageBaseUrl = process.env.SURESPOT_RACKSPACE_IMAGE_CDN_URL
rackspaceCdnVoiceBaseUrl = process.env.SURESPOT_RACKSPACE_VOICE_CDN_URL
rackspaceImageContainer = process.env.SURESPOT_RACKSPACE_IMAGE_CONTAINER
rackspaceVoiceContainer = process.env.SURESPOT_RACKSPACE_VOICE_CONTAINER
rackspaceUsername = process.env.SURESPOT_RACKSPACE_USERNAME
iapSecret = process.env.SURESPOT_IAP_SECRET
sessionSecret = process.env.SURESPOT_SESSION_SECRET
logConsole = process.env.SURESPOT_LOG_CONSOLE is "true"
redisPort = process.env.REDIS_PORT
redisSentinelPort = parseInt(process.env.SURESPOT_REDIS_SENTINEL_PORT) ? 6379
redisSentinelHostname = process.env.SURESPOT_REDIS_SENTINEL_HOSTNAME ? "127.0.0.1"
redisPassword = process.env.SURESPOT_REDIS_PASSWORD ? null
useRedisSentinel = process.env.SURESPOT_USE_REDIS_SENTINEL is "true"
bindAddress = process.env.SURESPOT_BIND_ADDRESS ? "0.0.0.0"
dontUseSSL = process.env.SURESPOT_DONT_USE_SSL is "true"
apnGateway = process.env.SURESPOT_APN_GATEWAY
useSSL = not dontUseSSL
http = if useSSL then require 'https' else require 'http'
sio = undefined
sessionStore = undefined
rc = undefined
rcs = undefined
pub = undefined
sub = undefined
redback = undefined
client = undefined
client2 = undefined
app = undefined
ssloptions = undefined
oauth2Client = undefined
iapClient = undefined
cdb.connect (err) ->
if err?
console.log 'could not connect to cassandra'
process.exit(1)
redis = undefined
if useRedisSentinel
redis = require 'redis-sentinel-client'
else
#use forked redis
redis = require 'redis'
createRedisClient = (database, port, host, password) ->
if port? and host?
tempclient = null
if useRedisSentinel
sentinel = redis.createClient(port,host, {logger: logger})
tempclient = sentinel.getMaster()
sentinel.on 'error', (err) -> logger.error err
tempclient.on 'error', (err) -> logger.error err
else
tempclient = redis.createClient(port,host)
if password?
tempclient.auth password
#if database?
# tempclient.select database
#return tempclient
else
return tempclient
else
logger.debug "creating local redis client"
tempclient = null
if useRedisSentinel
sentinel = redis.createClient(26379, "127.0.0.1", {logger: logger})
tempclient = sentinel.getMaster()
sentinel.on 'error', (err) -> logger.error err
tempclient.on 'error', (err) -> logger.error err
else
tempclient = redis.createClient()
if database?
tempclient.select database
return tempclient
else
return tempclient
rc = createRedisClient database, redisSentinelPort, redisSentinelHostname, redisPassword
rc.keys "cu:*", (err, ms) ->
console.log "error #{err}" && process.exit(10) if err?
console.log "deleting #{ms.length} sets of messages"
count = 0
async.each(
ms
(counterkey, callback) ->
console.log "deleting #{counterkey} #{++count}"
rc.del counterkey, (err, result) ->
return callback err if err?
callback()
(err) ->
return console.log "error #{err}" if err?
console.log "deleted #{count}"
)
| 200271 | ###
db migration script
copyright 2fours LLC
written by <NAME> <EMAIL>
###
env = process.env.SURESPOT_ENV ? 'Local' # one of "Local","Stage", "Prod"
async = require 'async'
_ = require 'underscore'
cdb = require '../cdb'
common = require '../common'
#constants
USERNAME_LENGTH = 20
CONTROL_MESSAGE_HISTORY = 100
MAX_MESSAGE_LENGTH = 500000
MAX_HTTP_REQUEST_LENGTH = 500000
NUM_CORES = parseInt(process.env.SURESPOT_CORES) ? 4
GCM_TTL = 604800
oneYear = 31536000000
oneDay = 86400
#config
#rate limit to MESSAGE_RATE_LIMIT_RATE / MESSAGE_RATE_LIMIT_SECS (seconds) (allows us to get request specific on top of iptables)
RATE_LIMITING_MESSAGE=process.env.SURESPOT_RATE_LIMITING_MESSAGE is "true"
RATE_LIMIT_BUCKET_MESSAGE = process.env.SURESPOT_RATE_LIMIT_BUCKET_MESSAGE ? 5
RATE_LIMIT_SECS_MESSAGE = process.env.SURESPOT_RATE_LIMIT_SECS_MESSAGE ? 10
RATE_LIMIT_RATE_MESSAGE = process.env.SURESPOT_RATE_LIMIT_RATE_MESSAGE ? 100
MESSAGES_PER_USER = process.env.SURESPOT_MESSAGES_PER_USER ? 500
debugLevel = process.env.SURESPOT_DEBUG_LEVEL ? 'debug'
database = process.env.SURESPOT_DB ? 0
socketPort = process.env.SURESPOT_SOCKET ? 8080
googleApiKey = process.env.SURESPOT_GOOGLE_API_KEY
googleClientId = process.env.SURESPOT_GOOGLE_CLIENT_ID
googleClientSecret = process.env.SURESPOT_GOOGLE_CLIENT_SECRET
googleRedirectUrl = process.env.SURESPOT_GOOGLE_REDIRECT_URL
googleOauth2Code = process.env.SURESPOT_GOOGLE_OAUTH2_CODE
rackspaceApiKey = process.env.SURESPOT_RACKSPACE_API_KEY
rackspaceCdnImageBaseUrl = process.env.SURESPOT_RACKSPACE_IMAGE_CDN_URL
rackspaceCdnVoiceBaseUrl = process.env.SURESPOT_RACKSPACE_VOICE_CDN_URL
rackspaceImageContainer = process.env.SURESPOT_RACKSPACE_IMAGE_CONTAINER
rackspaceVoiceContainer = process.env.SURESPOT_RACKSPACE_VOICE_CONTAINER
rackspaceUsername = process.env.SURESPOT_RACKSPACE_USERNAME
iapSecret = process.env.SURESPOT_IAP_SECRET
sessionSecret = process.env.SURESPOT_SESSION_SECRET
logConsole = process.env.SURESPOT_LOG_CONSOLE is "true"
redisPort = process.env.REDIS_PORT
redisSentinelPort = parseInt(process.env.SURESPOT_REDIS_SENTINEL_PORT) ? 6379
redisSentinelHostname = process.env.SURESPOT_REDIS_SENTINEL_HOSTNAME ? "127.0.0.1"
redisPassword = process.env.SURESPOT_REDIS_PASSWORD ? null
useRedisSentinel = process.env.SURESPOT_USE_REDIS_SENTINEL is "true"
bindAddress = process.env.SURESPOT_BIND_ADDRESS ? "0.0.0.0"
dontUseSSL = process.env.SURESPOT_DONT_USE_SSL is "true"
apnGateway = process.env.SURESPOT_APN_GATEWAY
useSSL = not dontUseSSL
http = if useSSL then require 'https' else require 'http'
sio = undefined
sessionStore = undefined
rc = undefined
rcs = undefined
pub = undefined
sub = undefined
redback = undefined
client = undefined
client2 = undefined
app = undefined
ssloptions = undefined
oauth2Client = undefined
iapClient = undefined
cdb.connect (err) ->
if err?
console.log 'could not connect to cassandra'
process.exit(1)
redis = undefined
if useRedisSentinel
redis = require 'redis-sentinel-client'
else
#use forked redis
redis = require 'redis'
createRedisClient = (database, port, host, password) ->
if port? and host?
tempclient = null
if useRedisSentinel
sentinel = redis.createClient(port,host, {logger: logger})
tempclient = sentinel.getMaster()
sentinel.on 'error', (err) -> logger.error err
tempclient.on 'error', (err) -> logger.error err
else
tempclient = redis.createClient(port,host)
if password?
tempclient.auth password
#if database?
# tempclient.select database
#return tempclient
else
return tempclient
else
logger.debug "creating local redis client"
tempclient = null
if useRedisSentinel
sentinel = redis.createClient(26379, "127.0.0.1", {logger: logger})
tempclient = sentinel.getMaster()
sentinel.on 'error', (err) -> logger.error err
tempclient.on 'error', (err) -> logger.error err
else
tempclient = redis.createClient()
if database?
tempclient.select database
return tempclient
else
return tempclient
rc = createRedisClient database, redisSentinelPort, redisSentinelHostname, redisPassword
rc.keys "cu:*", (err, ms) ->
console.log "error #{err}" && process.exit(10) if err?
console.log "deleting #{ms.length} sets of messages"
count = 0
async.each(
ms
(counterkey, callback) ->
console.log "deleting #{counterkey} #{++count}"
rc.del counterkey, (err, result) ->
return callback err if err?
callback()
(err) ->
return console.log "error #{err}" if err?
console.log "deleted #{count}"
)
| true | ###
db migration script
copyright 2fours LLC
written by PI:NAME:<NAME>END_PI PI:EMAIL:<EMAIL>END_PI
###
env = process.env.SURESPOT_ENV ? 'Local' # one of "Local","Stage", "Prod"
async = require 'async'
_ = require 'underscore'
cdb = require '../cdb'
common = require '../common'
#constants
USERNAME_LENGTH = 20
CONTROL_MESSAGE_HISTORY = 100
MAX_MESSAGE_LENGTH = 500000
MAX_HTTP_REQUEST_LENGTH = 500000
NUM_CORES = parseInt(process.env.SURESPOT_CORES) ? 4
GCM_TTL = 604800
oneYear = 31536000000
oneDay = 86400
#config
#rate limit to MESSAGE_RATE_LIMIT_RATE / MESSAGE_RATE_LIMIT_SECS (seconds) (allows us to get request specific on top of iptables)
RATE_LIMITING_MESSAGE=process.env.SURESPOT_RATE_LIMITING_MESSAGE is "true"
RATE_LIMIT_BUCKET_MESSAGE = process.env.SURESPOT_RATE_LIMIT_BUCKET_MESSAGE ? 5
RATE_LIMIT_SECS_MESSAGE = process.env.SURESPOT_RATE_LIMIT_SECS_MESSAGE ? 10
RATE_LIMIT_RATE_MESSAGE = process.env.SURESPOT_RATE_LIMIT_RATE_MESSAGE ? 100
MESSAGES_PER_USER = process.env.SURESPOT_MESSAGES_PER_USER ? 500
debugLevel = process.env.SURESPOT_DEBUG_LEVEL ? 'debug'
database = process.env.SURESPOT_DB ? 0
socketPort = process.env.SURESPOT_SOCKET ? 8080
googleApiKey = process.env.SURESPOT_GOOGLE_API_KEY
googleClientId = process.env.SURESPOT_GOOGLE_CLIENT_ID
googleClientSecret = process.env.SURESPOT_GOOGLE_CLIENT_SECRET
googleRedirectUrl = process.env.SURESPOT_GOOGLE_REDIRECT_URL
googleOauth2Code = process.env.SURESPOT_GOOGLE_OAUTH2_CODE
rackspaceApiKey = process.env.SURESPOT_RACKSPACE_API_KEY
rackspaceCdnImageBaseUrl = process.env.SURESPOT_RACKSPACE_IMAGE_CDN_URL
rackspaceCdnVoiceBaseUrl = process.env.SURESPOT_RACKSPACE_VOICE_CDN_URL
rackspaceImageContainer = process.env.SURESPOT_RACKSPACE_IMAGE_CONTAINER
rackspaceVoiceContainer = process.env.SURESPOT_RACKSPACE_VOICE_CONTAINER
rackspaceUsername = process.env.SURESPOT_RACKSPACE_USERNAME
iapSecret = process.env.SURESPOT_IAP_SECRET
sessionSecret = process.env.SURESPOT_SESSION_SECRET
logConsole = process.env.SURESPOT_LOG_CONSOLE is "true"
redisPort = process.env.REDIS_PORT
redisSentinelPort = parseInt(process.env.SURESPOT_REDIS_SENTINEL_PORT) ? 6379
redisSentinelHostname = process.env.SURESPOT_REDIS_SENTINEL_HOSTNAME ? "127.0.0.1"
redisPassword = process.env.SURESPOT_REDIS_PASSWORD ? null
useRedisSentinel = process.env.SURESPOT_USE_REDIS_SENTINEL is "true"
bindAddress = process.env.SURESPOT_BIND_ADDRESS ? "0.0.0.0"
dontUseSSL = process.env.SURESPOT_DONT_USE_SSL is "true"
apnGateway = process.env.SURESPOT_APN_GATEWAY
useSSL = not dontUseSSL
http = if useSSL then require 'https' else require 'http'
sio = undefined
sessionStore = undefined
rc = undefined
rcs = undefined
pub = undefined
sub = undefined
redback = undefined
client = undefined
client2 = undefined
app = undefined
ssloptions = undefined
oauth2Client = undefined
iapClient = undefined
cdb.connect (err) ->
if err?
console.log 'could not connect to cassandra'
process.exit(1)
redis = undefined
if useRedisSentinel
redis = require 'redis-sentinel-client'
else
#use forked redis
redis = require 'redis'
createRedisClient = (database, port, host, password) ->
if port? and host?
tempclient = null
if useRedisSentinel
sentinel = redis.createClient(port,host, {logger: logger})
tempclient = sentinel.getMaster()
sentinel.on 'error', (err) -> logger.error err
tempclient.on 'error', (err) -> logger.error err
else
tempclient = redis.createClient(port,host)
if password?
tempclient.auth password
#if database?
# tempclient.select database
#return tempclient
else
return tempclient
else
logger.debug "creating local redis client"
tempclient = null
if useRedisSentinel
sentinel = redis.createClient(26379, "127.0.0.1", {logger: logger})
tempclient = sentinel.getMaster()
sentinel.on 'error', (err) -> logger.error err
tempclient.on 'error', (err) -> logger.error err
else
tempclient = redis.createClient()
if database?
tempclient.select database
return tempclient
else
return tempclient
rc = createRedisClient database, redisSentinelPort, redisSentinelHostname, redisPassword
rc.keys "cu:*", (err, ms) ->
console.log "error #{err}" && process.exit(10) if err?
console.log "deleting #{ms.length} sets of messages"
count = 0
async.each(
ms
(counterkey, callback) ->
console.log "deleting #{counterkey} #{++count}"
rc.del counterkey, (err, result) ->
return callback err if err?
callback()
(err) ->
return console.log "error #{err}" if err?
console.log "deleted #{count}"
)
|
[
{
"context": "ndingFoo.base, @base\n equal ascendingFoo.key, 'foo.bar'\n equal ascendingFoo.descending, no\n equal ",
"end": 10094,
"score": 0.9812456965446472,
"start": 10087,
"tag": "KEY",
"value": "foo.bar"
},
{
"context": "dingFoo.base, @base\n equal descendingFoo.key, 'foo.bar'\n equal descendingFoo.descending, yes\n\n test ",
"end": 10207,
"score": 0.983908474445343,
"start": 10200,
"tag": "KEY",
"value": "foo.bar"
},
{
"context": " equal index.base, @base\n equal index.key, 'length'\n strictEqual @set.indexedBy('length'), index\n",
"end": 11547,
"score": 0.8605318069458008,
"start": 11541,
"tag": "KEY",
"value": "length"
}
] | tests/batman/set/set_test.coffee | davidcornu/batman | 0 | basicSetTestSuite = ->
test "isEmpty() on an empty set returns true", ->
ok @set.isEmpty()
ok @set.get 'isEmpty'
test "has(item) on an empty set returns false", ->
equal @set.has('foo'), false
test "has(undefined) returns false", ->
equal @set.has(undefined), false
test "has(item) for an item with isEqual defined returns true if another item isEqual to that item", ->
itemA = {isEqual: -> true}
itemB = {isEqual: -> true}
@set.add(itemA)
equal @set.has(itemB), true
test "has(item) for an item with isEqual defined returns false if no other item isEqual to that item", ->
itemA = {isEqual: -> true}
itemB = {isEqual: -> false}
@set.add(itemA)
equal @set.has(itemB), false
test "at(index) returns the item at that index", ->
@set.add(0, 1, 2, 3, 4)
equal @set.at(0), 0
equal @set.at(2), 2
equal @set.at(4), 4
test "at(index) returns undefined when there is no item at that index", ->
@set.add(true)
equal @set.at(0), true
equal @set.at(32), undefined
equal @set.at(-7), undefined
test "add(items...) adds the items to the set, such that has(item) returns true for each item, and increments the set's length accordingly", ->
deepEqual @set.add('foo', 'bar'), ['foo', 'bar']
equal @set.length, 2
equal @set.has('foo'), true
equal @set.has('bar'), true
test "add(items...) only increments length for items which weren't already there, and only returns items which weren't already there", ->
deepEqual @set.add('foo'), ['foo']
deepEqual @set.add('foo', 'bar'), ['bar']
deepEqual @set.add('baz', 'baz'), ['baz']
equal @set.length, 3
test "remove(items...) removes the items from the set, returning the item and not touching any others", ->
@set.add('foo', o1={}, o2={}, o3={})
equal @set.length, 4
deepEqual @set.remove(o2, o3), [o2, o3]
equal @set.length, 2
equal @set.has('foo'), true
equal @set.has(o1), true
equal @set.has(o2), false
equal @set.has(o3), false
test "remove(items...) returns an array of only the items that were there in the first place", ->
@set.add('foo')
@set.add('baz')
deepEqual @set.remove('foo', 'bar'), ['foo']
deepEqual @set.remove('foo'), []
test "remove(items...) only decrements length for items that are there to be removed", ->
@set.add('foo', 'bar', 'baz')
@set.remove('foo', 'qux')
@set.remove('bar', 'bar')
equal @set.length, 1
test "find(f) returns the first item for which f is true", 1, ->
@set.add(1, 2, 3, 5)
result = @set.find (n) -> n % 2 is 0
equal result, 2
test "find(f) returns undefined when f is false for all items", 1, ->
@set.add(1, 2)
result = @set.find -> false
equal result, undefined
test "find(f) works with booleans", 2, ->
@set.add(false, true)
result = @set.find (item) -> item is true
equal result, true
@set.clear()
@set.add(true, false)
result = @set.find (item) -> item is false
equal result, false
test "merge(other) returns a merged set without changing the original", ->
@set.add('foo', 'bar', 'baz')
other = new Batman.Set
other.add('qux', 'buzz')
merged = @set.merge(other)
for v in ['foo', 'bar', 'baz', 'qux', 'buzz']
ok merged.has(v)
equal merged.length, 5
ok !@set.has('qux')
ok !@set.has('buzz')
test "add(items...) fires length observers", ->
@set.observe 'length', spy = createSpy()
@set.add('foo')
deepEqual spy.lastCallArguments, [1, 0, 'length']
@set.add('baz', 'bar')
deepEqual spy.lastCallArguments, [3, 1, 'length']
equal spy.callCount, 2
@set.add('bar')
equal spy.callCount, 2
test "add(items...) fires itemsWereAdded handlers", ->
@set.on 'itemsWereAdded', spy = createSpy()
@set.add('foo')
deepEqual spy.lastCallArguments[0], ['foo']
@set.add('baz', 'bar')
deepEqual spy.lastCallArguments[0], ['baz', 'bar']
equal spy.callCount, 2
@set.add('bar')
equal spy.callCount, 2
test "remove(items...) fires length observers", ->
@set.observe 'length', spy = createSpy()
@set.add('foo')
@set.remove('foo')
deepEqual spy.lastCallArguments, [0, 1, 'length']
equal spy.callCount, 2
@set.remove('foo')
equal spy.callCount, 2
test "remove(items...) fires itemsWereRemoved handlers", ->
@set.on 'itemsWereRemoved', spy = createSpy()
@set.add('foo')
@set.remove('foo')
deepEqual spy.lastCallArguments[0], ['foo']
equal spy.callCount, 1
@set.remove('foo')
equal spy.callCount, 1
test "clear() fires length observers", ->
spy = createSpy()
@set.observe('length', spy)
@set.add('foo', 'bar')
@set.clear()
equal spy.callCount, 2, 'clear() fires length observers'
test "clear() fires itemsWereRemoved handlers", ->
spy = createSpy()
@set.on('itemsWereRemoved', spy)
@set.add('foo', 'bar')
@set.clear()
equal spy.callCount, 1, 'clear() fires itemsWereRemoved handlers'
test "replace() doesn't fire length observers if the size didn't change", ->
spy = createSpy()
other = new Batman.Set
other.add('baz', 'cux')
@set.add('foo', 'bar')
@set.observe('length', spy)
@set.replace(other)
equal spy.callCount, 0, 'replaces() fires length observers'
test "replace() fires length observers if the size has changed", ->
spy = createSpy()
other = new Batman.Set
other.add('baz', 'cux', 'cuux')
@set.add('foo', 'bar')
@set.observe('length', spy)
@set.replace(other)
equal spy.callCount, 1, 'replaces() fires length observers'
test "replace() fires item-based mutation events for Batman.Set", ->
addedSpy = createSpy()
removedSpy = createSpy()
other = new Batman.Set
other.add('baz', 'cux')
@set.add('foo', 'bar')
@set.on('itemsWereAdded', addedSpy)
@set.on('itemsWereRemoved', removedSpy)
@set.replace(other)
equal addedSpy.callCount, 1, 'replaces() fires itemsWereAdded observers'
equal removedSpy.callCount, 1, 'replaces() fires itemsWereRemoved observers'
test "replace() removes existing items", ->
spy = createSpy()
other = new Batman.Set
other.add('baz', 'cux')
@set.add('foo', 'bar')
@set.replace(other)
deepEqual @set.toArray(), other.toArray()
test "filter() returns a set", ->
@set.add 'foo', 'bar', 'baz'
@filtered = @set.filter (v) -> v.slice(0, 1) is 'b'
equal @filtered.length, 2
ok @filtered.has 'bar'
ok @filtered.has 'baz'
test "using .has(key) in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'hasFoo', => @set.has('foo')
obj.observe 'hasFoo', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 1
@set.remove('foo')
equal observer.callCount, 2
test ".observe('isEmpty') fires when the value actually changes", ->
@set.add('foo')
@set.observe 'isEmpty', observer = createSpy()
@set.add('bar')
equal observer.callCount, 0
@set.remove('bar')
equal observer.callCount, 0
@set.remove('foo')
equal observer.callCount, 1
@set.add('foo')
equal observer.callCount, 2
test "using .toArray() in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'array', => @set.toArray()
obj.observe 'array', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 2
test "using .forEach() in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'foreach', => @set.forEach(->); []
obj.observe 'foreach', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 2
test "using .merge() in an accessor registers the original and merged sets as sources of the property", ->
obj = new Batman.Object
otherSet = new Batman.Set
obj.accessor 'mergedWithOther', => @set.merge(otherSet)
obj.observe 'mergedWithOther', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 2
otherSet.add('baz')
equal observer.callCount, 3
test "using .find() in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'firstBiggerThan2', => @set.find (n) -> n > 2
obj.observe 'firstBiggerThan2', observer = createSpy()
@set.add(3)
equal observer.callCount, 1
strictEqual obj.get('firstBiggerThan2'), 3
@set.add(4)
equal observer.callCount, 1
strictEqual obj.get('firstBiggerThan2'), 3
@set.remove(3)
equal observer.callCount, 2
strictEqual obj.get('firstBiggerThan2'), 4
test "using .toJSON() returns a serializable array representation of the set", ->
set = new Batman.Set
set.add new Batman.Object foo: 'bar'
set.add new Batman.Object bar: 'baz'
deepEqual set.toJSON(), [{foo: 'bar'}, {bar: 'baz'}]
sortAndIndexSuite = ->
test "sortedBy(property, order) returns a cached SetSort", ->
ascendingFoo = @set.sortedBy('foo')
strictEqual @set.sortedBy('foo'), ascendingFoo
descendingFoo = @set.sortedBy('foo', 'desc')
strictEqual @set.sortedBy('foo', 'desc'), descendingFoo
notEqual ascendingFoo, descendingFoo
equal ascendingFoo.base, @base
equal ascendingFoo.key, 'foo'
equal ascendingFoo.descending, no
equal descendingFoo.base, @base
equal descendingFoo.key, 'foo'
equal descendingFoo.descending, yes
test "sortedBy(deepProperty, order) returns a cached SetSort", ->
ascendingFoo = @set.sortedBy('foo.bar')
strictEqual @set.sortedBy('foo.bar'), ascendingFoo
descendingFoo = @set.sortedBy('foo.bar', 'desc')
strictEqual @set.sortedBy('foo.bar', 'desc'), descendingFoo
notEqual ascendingFoo, descendingFoo
equal ascendingFoo.base, @base
equal ascendingFoo.key, 'foo.bar'
equal ascendingFoo.descending, no
equal descendingFoo.base, @base
equal descendingFoo.key, 'foo.bar'
equal descendingFoo.descending, yes
test "get('sortedBy.name') returns .sortedBy('name')", ->
strictEqual @set.get('sortedBy.name'), @set.sortedBy('name')
test "get('sortedByDescending.name') returns .sortedBy('name', 'desc')", ->
strictEqual @set.get('sortedByDescending.name'), @set.sortedBy('name', 'desc')
test "sortedBy(deepProperty) sorts by the deep property instead of traversing the keypath", ->
sort = @set.sortedBy('foo.bar')
deepEqual sort.toArray(), [@o1, @o2, @o3]
test "get('sortedBy').get(deepProperty) sorts by the deep property instead of traversing the keypath", ->
sort = @set.get('sortedBy').get('foo.bar')
deepEqual sort.toArray(), [@o1, @o2, @o3]
test "sortedBy(deepProperty, 'desc') sorts by the deep property instead of traversing the keypath", ->
sort = @set.sortedBy('foo.bar', 'desc')
deepEqual sort.toArray(), [@o3, @o2, @o1]
test "get('sortedByDescending').get(deepProperty) sorts by the deep property instead of traversing the keypath", ->
sort = @set.get('sortedByDescending').get('foo.bar')
deepEqual sort.toArray(), [@o3, @o2, @o1]
test "indexedBy(key) returns a memoized Batman.SetIndex for that key", ->
index = @set.indexedBy('length')
ok index instanceof Batman.SetIndex
equal index.base, @base
equal index.key, 'length'
strictEqual @set.indexedBy('length'), index
test "get('indexedBy.someKey') returns the same index as indexedBy(key)", ->
strictEqual @set.get('indexedBy.length'), @set.indexedBy('length')
test "indexedBy(deepProperty) indexes by the deep property instead of traversing the keypath", ->
index = @set.indexedBy('foo.bar')
deepEqual index.get(2).toArray(), [@o2]
test "get('indexedBy').get(deepProperty) indexes by the deep property instead of traversing the keypath", ->
index = @set.get('indexedBy').get('foo.bar')
deepEqual index.get(2).toArray(), [@o2]
test "indexedByUnique(key) returns a memoized UniqueSetIndex for that key", ->
Batman.developer.suppress =>
index = @set.indexedByUnique('foo')
ok index instanceof Batman.UniqueSetIndex
equal index.base, @base
equal index.key, 'foo'
strictEqual @set.indexedByUnique('foo'), index
test "get('indexedByUnique.foo') returns a memoized UniqueSetIndex for the key 'foo'", ->
Batman.developer.suppress =>
strictEqual @set.get('indexedByUnique.foo'), @set.indexedByUnique('foo')
QUnit.module 'Batman.Set',
setup: ->
@set = new Batman.Set
basicSetTestSuite()
QUnit.module 'Batman.SetIntersection set polymorphism',
setup: ->
@set = new Batman.SetIntersection(new Batman.Set, new Batman.Set)
basicSetTestSuite()
QUnit.module 'Batman.SetUnion set polymorphism',
setup: ->
@set = new Batman.SetUnion(new Batman.Set, new Batman.Set)
basicSetTestSuite()
QUnit.module 'Batman.Set indexedBy and SortedBy' ,
setup: ->
@base = @set = new Batman.Set
@set.add @o3 =
foo:
bar: 3
@set.add @o1 =
foo:
bar: 1
@set.add @o2 =
foo:
bar: 2
sortAndIndexSuite()
QUnit.module "Batman.SetSort set polymorphism",
setup: ->
set = new Batman.Set
@set = set.sortedBy('')
basicSetTestSuite()
QUnit.module 'Batman.SetSort indexedBy and SortedBy' ,
setup: ->
@base = new Batman.Set
@set = @base.sortedBy('')
@set.add @o3 =
foo:
bar: 3
@set.add @o1 =
foo:
bar: 1
@set.add @o2 =
foo:
bar: 2
sortAndIndexSuite()
| 3790 | basicSetTestSuite = ->
test "isEmpty() on an empty set returns true", ->
ok @set.isEmpty()
ok @set.get 'isEmpty'
test "has(item) on an empty set returns false", ->
equal @set.has('foo'), false
test "has(undefined) returns false", ->
equal @set.has(undefined), false
test "has(item) for an item with isEqual defined returns true if another item isEqual to that item", ->
itemA = {isEqual: -> true}
itemB = {isEqual: -> true}
@set.add(itemA)
equal @set.has(itemB), true
test "has(item) for an item with isEqual defined returns false if no other item isEqual to that item", ->
itemA = {isEqual: -> true}
itemB = {isEqual: -> false}
@set.add(itemA)
equal @set.has(itemB), false
test "at(index) returns the item at that index", ->
@set.add(0, 1, 2, 3, 4)
equal @set.at(0), 0
equal @set.at(2), 2
equal @set.at(4), 4
test "at(index) returns undefined when there is no item at that index", ->
@set.add(true)
equal @set.at(0), true
equal @set.at(32), undefined
equal @set.at(-7), undefined
test "add(items...) adds the items to the set, such that has(item) returns true for each item, and increments the set's length accordingly", ->
deepEqual @set.add('foo', 'bar'), ['foo', 'bar']
equal @set.length, 2
equal @set.has('foo'), true
equal @set.has('bar'), true
test "add(items...) only increments length for items which weren't already there, and only returns items which weren't already there", ->
deepEqual @set.add('foo'), ['foo']
deepEqual @set.add('foo', 'bar'), ['bar']
deepEqual @set.add('baz', 'baz'), ['baz']
equal @set.length, 3
test "remove(items...) removes the items from the set, returning the item and not touching any others", ->
@set.add('foo', o1={}, o2={}, o3={})
equal @set.length, 4
deepEqual @set.remove(o2, o3), [o2, o3]
equal @set.length, 2
equal @set.has('foo'), true
equal @set.has(o1), true
equal @set.has(o2), false
equal @set.has(o3), false
test "remove(items...) returns an array of only the items that were there in the first place", ->
@set.add('foo')
@set.add('baz')
deepEqual @set.remove('foo', 'bar'), ['foo']
deepEqual @set.remove('foo'), []
test "remove(items...) only decrements length for items that are there to be removed", ->
@set.add('foo', 'bar', 'baz')
@set.remove('foo', 'qux')
@set.remove('bar', 'bar')
equal @set.length, 1
test "find(f) returns the first item for which f is true", 1, ->
@set.add(1, 2, 3, 5)
result = @set.find (n) -> n % 2 is 0
equal result, 2
test "find(f) returns undefined when f is false for all items", 1, ->
@set.add(1, 2)
result = @set.find -> false
equal result, undefined
test "find(f) works with booleans", 2, ->
@set.add(false, true)
result = @set.find (item) -> item is true
equal result, true
@set.clear()
@set.add(true, false)
result = @set.find (item) -> item is false
equal result, false
test "merge(other) returns a merged set without changing the original", ->
@set.add('foo', 'bar', 'baz')
other = new Batman.Set
other.add('qux', 'buzz')
merged = @set.merge(other)
for v in ['foo', 'bar', 'baz', 'qux', 'buzz']
ok merged.has(v)
equal merged.length, 5
ok !@set.has('qux')
ok !@set.has('buzz')
test "add(items...) fires length observers", ->
@set.observe 'length', spy = createSpy()
@set.add('foo')
deepEqual spy.lastCallArguments, [1, 0, 'length']
@set.add('baz', 'bar')
deepEqual spy.lastCallArguments, [3, 1, 'length']
equal spy.callCount, 2
@set.add('bar')
equal spy.callCount, 2
test "add(items...) fires itemsWereAdded handlers", ->
@set.on 'itemsWereAdded', spy = createSpy()
@set.add('foo')
deepEqual spy.lastCallArguments[0], ['foo']
@set.add('baz', 'bar')
deepEqual spy.lastCallArguments[0], ['baz', 'bar']
equal spy.callCount, 2
@set.add('bar')
equal spy.callCount, 2
test "remove(items...) fires length observers", ->
@set.observe 'length', spy = createSpy()
@set.add('foo')
@set.remove('foo')
deepEqual spy.lastCallArguments, [0, 1, 'length']
equal spy.callCount, 2
@set.remove('foo')
equal spy.callCount, 2
test "remove(items...) fires itemsWereRemoved handlers", ->
@set.on 'itemsWereRemoved', spy = createSpy()
@set.add('foo')
@set.remove('foo')
deepEqual spy.lastCallArguments[0], ['foo']
equal spy.callCount, 1
@set.remove('foo')
equal spy.callCount, 1
test "clear() fires length observers", ->
spy = createSpy()
@set.observe('length', spy)
@set.add('foo', 'bar')
@set.clear()
equal spy.callCount, 2, 'clear() fires length observers'
test "clear() fires itemsWereRemoved handlers", ->
spy = createSpy()
@set.on('itemsWereRemoved', spy)
@set.add('foo', 'bar')
@set.clear()
equal spy.callCount, 1, 'clear() fires itemsWereRemoved handlers'
test "replace() doesn't fire length observers if the size didn't change", ->
spy = createSpy()
other = new Batman.Set
other.add('baz', 'cux')
@set.add('foo', 'bar')
@set.observe('length', spy)
@set.replace(other)
equal spy.callCount, 0, 'replaces() fires length observers'
test "replace() fires length observers if the size has changed", ->
spy = createSpy()
other = new Batman.Set
other.add('baz', 'cux', 'cuux')
@set.add('foo', 'bar')
@set.observe('length', spy)
@set.replace(other)
equal spy.callCount, 1, 'replaces() fires length observers'
test "replace() fires item-based mutation events for Batman.Set", ->
addedSpy = createSpy()
removedSpy = createSpy()
other = new Batman.Set
other.add('baz', 'cux')
@set.add('foo', 'bar')
@set.on('itemsWereAdded', addedSpy)
@set.on('itemsWereRemoved', removedSpy)
@set.replace(other)
equal addedSpy.callCount, 1, 'replaces() fires itemsWereAdded observers'
equal removedSpy.callCount, 1, 'replaces() fires itemsWereRemoved observers'
test "replace() removes existing items", ->
spy = createSpy()
other = new Batman.Set
other.add('baz', 'cux')
@set.add('foo', 'bar')
@set.replace(other)
deepEqual @set.toArray(), other.toArray()
test "filter() returns a set", ->
@set.add 'foo', 'bar', 'baz'
@filtered = @set.filter (v) -> v.slice(0, 1) is 'b'
equal @filtered.length, 2
ok @filtered.has 'bar'
ok @filtered.has 'baz'
test "using .has(key) in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'hasFoo', => @set.has('foo')
obj.observe 'hasFoo', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 1
@set.remove('foo')
equal observer.callCount, 2
test ".observe('isEmpty') fires when the value actually changes", ->
@set.add('foo')
@set.observe 'isEmpty', observer = createSpy()
@set.add('bar')
equal observer.callCount, 0
@set.remove('bar')
equal observer.callCount, 0
@set.remove('foo')
equal observer.callCount, 1
@set.add('foo')
equal observer.callCount, 2
test "using .toArray() in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'array', => @set.toArray()
obj.observe 'array', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 2
test "using .forEach() in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'foreach', => @set.forEach(->); []
obj.observe 'foreach', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 2
test "using .merge() in an accessor registers the original and merged sets as sources of the property", ->
obj = new Batman.Object
otherSet = new Batman.Set
obj.accessor 'mergedWithOther', => @set.merge(otherSet)
obj.observe 'mergedWithOther', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 2
otherSet.add('baz')
equal observer.callCount, 3
test "using .find() in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'firstBiggerThan2', => @set.find (n) -> n > 2
obj.observe 'firstBiggerThan2', observer = createSpy()
@set.add(3)
equal observer.callCount, 1
strictEqual obj.get('firstBiggerThan2'), 3
@set.add(4)
equal observer.callCount, 1
strictEqual obj.get('firstBiggerThan2'), 3
@set.remove(3)
equal observer.callCount, 2
strictEqual obj.get('firstBiggerThan2'), 4
test "using .toJSON() returns a serializable array representation of the set", ->
set = new Batman.Set
set.add new Batman.Object foo: 'bar'
set.add new Batman.Object bar: 'baz'
deepEqual set.toJSON(), [{foo: 'bar'}, {bar: 'baz'}]
sortAndIndexSuite = ->
test "sortedBy(property, order) returns a cached SetSort", ->
ascendingFoo = @set.sortedBy('foo')
strictEqual @set.sortedBy('foo'), ascendingFoo
descendingFoo = @set.sortedBy('foo', 'desc')
strictEqual @set.sortedBy('foo', 'desc'), descendingFoo
notEqual ascendingFoo, descendingFoo
equal ascendingFoo.base, @base
equal ascendingFoo.key, 'foo'
equal ascendingFoo.descending, no
equal descendingFoo.base, @base
equal descendingFoo.key, 'foo'
equal descendingFoo.descending, yes
test "sortedBy(deepProperty, order) returns a cached SetSort", ->
ascendingFoo = @set.sortedBy('foo.bar')
strictEqual @set.sortedBy('foo.bar'), ascendingFoo
descendingFoo = @set.sortedBy('foo.bar', 'desc')
strictEqual @set.sortedBy('foo.bar', 'desc'), descendingFoo
notEqual ascendingFoo, descendingFoo
equal ascendingFoo.base, @base
equal ascendingFoo.key, '<KEY>'
equal ascendingFoo.descending, no
equal descendingFoo.base, @base
equal descendingFoo.key, '<KEY>'
equal descendingFoo.descending, yes
test "get('sortedBy.name') returns .sortedBy('name')", ->
strictEqual @set.get('sortedBy.name'), @set.sortedBy('name')
test "get('sortedByDescending.name') returns .sortedBy('name', 'desc')", ->
strictEqual @set.get('sortedByDescending.name'), @set.sortedBy('name', 'desc')
test "sortedBy(deepProperty) sorts by the deep property instead of traversing the keypath", ->
sort = @set.sortedBy('foo.bar')
deepEqual sort.toArray(), [@o1, @o2, @o3]
test "get('sortedBy').get(deepProperty) sorts by the deep property instead of traversing the keypath", ->
sort = @set.get('sortedBy').get('foo.bar')
deepEqual sort.toArray(), [@o1, @o2, @o3]
test "sortedBy(deepProperty, 'desc') sorts by the deep property instead of traversing the keypath", ->
sort = @set.sortedBy('foo.bar', 'desc')
deepEqual sort.toArray(), [@o3, @o2, @o1]
test "get('sortedByDescending').get(deepProperty) sorts by the deep property instead of traversing the keypath", ->
sort = @set.get('sortedByDescending').get('foo.bar')
deepEqual sort.toArray(), [@o3, @o2, @o1]
test "indexedBy(key) returns a memoized Batman.SetIndex for that key", ->
index = @set.indexedBy('length')
ok index instanceof Batman.SetIndex
equal index.base, @base
equal index.key, '<KEY>'
strictEqual @set.indexedBy('length'), index
test "get('indexedBy.someKey') returns the same index as indexedBy(key)", ->
strictEqual @set.get('indexedBy.length'), @set.indexedBy('length')
test "indexedBy(deepProperty) indexes by the deep property instead of traversing the keypath", ->
index = @set.indexedBy('foo.bar')
deepEqual index.get(2).toArray(), [@o2]
test "get('indexedBy').get(deepProperty) indexes by the deep property instead of traversing the keypath", ->
index = @set.get('indexedBy').get('foo.bar')
deepEqual index.get(2).toArray(), [@o2]
test "indexedByUnique(key) returns a memoized UniqueSetIndex for that key", ->
Batman.developer.suppress =>
index = @set.indexedByUnique('foo')
ok index instanceof Batman.UniqueSetIndex
equal index.base, @base
equal index.key, 'foo'
strictEqual @set.indexedByUnique('foo'), index
test "get('indexedByUnique.foo') returns a memoized UniqueSetIndex for the key 'foo'", ->
Batman.developer.suppress =>
strictEqual @set.get('indexedByUnique.foo'), @set.indexedByUnique('foo')
QUnit.module 'Batman.Set',
setup: ->
@set = new Batman.Set
basicSetTestSuite()
QUnit.module 'Batman.SetIntersection set polymorphism',
setup: ->
@set = new Batman.SetIntersection(new Batman.Set, new Batman.Set)
basicSetTestSuite()
QUnit.module 'Batman.SetUnion set polymorphism',
setup: ->
@set = new Batman.SetUnion(new Batman.Set, new Batman.Set)
basicSetTestSuite()
QUnit.module 'Batman.Set indexedBy and SortedBy' ,
setup: ->
@base = @set = new Batman.Set
@set.add @o3 =
foo:
bar: 3
@set.add @o1 =
foo:
bar: 1
@set.add @o2 =
foo:
bar: 2
sortAndIndexSuite()
QUnit.module "Batman.SetSort set polymorphism",
setup: ->
set = new Batman.Set
@set = set.sortedBy('')
basicSetTestSuite()
QUnit.module 'Batman.SetSort indexedBy and SortedBy' ,
setup: ->
@base = new Batman.Set
@set = @base.sortedBy('')
@set.add @o3 =
foo:
bar: 3
@set.add @o1 =
foo:
bar: 1
@set.add @o2 =
foo:
bar: 2
sortAndIndexSuite()
| true | basicSetTestSuite = ->
test "isEmpty() on an empty set returns true", ->
ok @set.isEmpty()
ok @set.get 'isEmpty'
test "has(item) on an empty set returns false", ->
equal @set.has('foo'), false
test "has(undefined) returns false", ->
equal @set.has(undefined), false
test "has(item) for an item with isEqual defined returns true if another item isEqual to that item", ->
itemA = {isEqual: -> true}
itemB = {isEqual: -> true}
@set.add(itemA)
equal @set.has(itemB), true
test "has(item) for an item with isEqual defined returns false if no other item isEqual to that item", ->
itemA = {isEqual: -> true}
itemB = {isEqual: -> false}
@set.add(itemA)
equal @set.has(itemB), false
test "at(index) returns the item at that index", ->
@set.add(0, 1, 2, 3, 4)
equal @set.at(0), 0
equal @set.at(2), 2
equal @set.at(4), 4
test "at(index) returns undefined when there is no item at that index", ->
@set.add(true)
equal @set.at(0), true
equal @set.at(32), undefined
equal @set.at(-7), undefined
test "add(items...) adds the items to the set, such that has(item) returns true for each item, and increments the set's length accordingly", ->
deepEqual @set.add('foo', 'bar'), ['foo', 'bar']
equal @set.length, 2
equal @set.has('foo'), true
equal @set.has('bar'), true
test "add(items...) only increments length for items which weren't already there, and only returns items which weren't already there", ->
deepEqual @set.add('foo'), ['foo']
deepEqual @set.add('foo', 'bar'), ['bar']
deepEqual @set.add('baz', 'baz'), ['baz']
equal @set.length, 3
test "remove(items...) removes the items from the set, returning the item and not touching any others", ->
@set.add('foo', o1={}, o2={}, o3={})
equal @set.length, 4
deepEqual @set.remove(o2, o3), [o2, o3]
equal @set.length, 2
equal @set.has('foo'), true
equal @set.has(o1), true
equal @set.has(o2), false
equal @set.has(o3), false
test "remove(items...) returns an array of only the items that were there in the first place", ->
@set.add('foo')
@set.add('baz')
deepEqual @set.remove('foo', 'bar'), ['foo']
deepEqual @set.remove('foo'), []
test "remove(items...) only decrements length for items that are there to be removed", ->
@set.add('foo', 'bar', 'baz')
@set.remove('foo', 'qux')
@set.remove('bar', 'bar')
equal @set.length, 1
test "find(f) returns the first item for which f is true", 1, ->
@set.add(1, 2, 3, 5)
result = @set.find (n) -> n % 2 is 0
equal result, 2
test "find(f) returns undefined when f is false for all items", 1, ->
@set.add(1, 2)
result = @set.find -> false
equal result, undefined
test "find(f) works with booleans", 2, ->
@set.add(false, true)
result = @set.find (item) -> item is true
equal result, true
@set.clear()
@set.add(true, false)
result = @set.find (item) -> item is false
equal result, false
test "merge(other) returns a merged set without changing the original", ->
@set.add('foo', 'bar', 'baz')
other = new Batman.Set
other.add('qux', 'buzz')
merged = @set.merge(other)
for v in ['foo', 'bar', 'baz', 'qux', 'buzz']
ok merged.has(v)
equal merged.length, 5
ok !@set.has('qux')
ok !@set.has('buzz')
test "add(items...) fires length observers", ->
@set.observe 'length', spy = createSpy()
@set.add('foo')
deepEqual spy.lastCallArguments, [1, 0, 'length']
@set.add('baz', 'bar')
deepEqual spy.lastCallArguments, [3, 1, 'length']
equal spy.callCount, 2
@set.add('bar')
equal spy.callCount, 2
test "add(items...) fires itemsWereAdded handlers", ->
@set.on 'itemsWereAdded', spy = createSpy()
@set.add('foo')
deepEqual spy.lastCallArguments[0], ['foo']
@set.add('baz', 'bar')
deepEqual spy.lastCallArguments[0], ['baz', 'bar']
equal spy.callCount, 2
@set.add('bar')
equal spy.callCount, 2
test "remove(items...) fires length observers", ->
@set.observe 'length', spy = createSpy()
@set.add('foo')
@set.remove('foo')
deepEqual spy.lastCallArguments, [0, 1, 'length']
equal spy.callCount, 2
@set.remove('foo')
equal spy.callCount, 2
test "remove(items...) fires itemsWereRemoved handlers", ->
@set.on 'itemsWereRemoved', spy = createSpy()
@set.add('foo')
@set.remove('foo')
deepEqual spy.lastCallArguments[0], ['foo']
equal spy.callCount, 1
@set.remove('foo')
equal spy.callCount, 1
test "clear() fires length observers", ->
spy = createSpy()
@set.observe('length', spy)
@set.add('foo', 'bar')
@set.clear()
equal spy.callCount, 2, 'clear() fires length observers'
test "clear() fires itemsWereRemoved handlers", ->
spy = createSpy()
@set.on('itemsWereRemoved', spy)
@set.add('foo', 'bar')
@set.clear()
equal spy.callCount, 1, 'clear() fires itemsWereRemoved handlers'
test "replace() doesn't fire length observers if the size didn't change", ->
spy = createSpy()
other = new Batman.Set
other.add('baz', 'cux')
@set.add('foo', 'bar')
@set.observe('length', spy)
@set.replace(other)
equal spy.callCount, 0, 'replaces() fires length observers'
test "replace() fires length observers if the size has changed", ->
spy = createSpy()
other = new Batman.Set
other.add('baz', 'cux', 'cuux')
@set.add('foo', 'bar')
@set.observe('length', spy)
@set.replace(other)
equal spy.callCount, 1, 'replaces() fires length observers'
test "replace() fires item-based mutation events for Batman.Set", ->
addedSpy = createSpy()
removedSpy = createSpy()
other = new Batman.Set
other.add('baz', 'cux')
@set.add('foo', 'bar')
@set.on('itemsWereAdded', addedSpy)
@set.on('itemsWereRemoved', removedSpy)
@set.replace(other)
equal addedSpy.callCount, 1, 'replaces() fires itemsWereAdded observers'
equal removedSpy.callCount, 1, 'replaces() fires itemsWereRemoved observers'
test "replace() removes existing items", ->
spy = createSpy()
other = new Batman.Set
other.add('baz', 'cux')
@set.add('foo', 'bar')
@set.replace(other)
deepEqual @set.toArray(), other.toArray()
test "filter() returns a set", ->
@set.add 'foo', 'bar', 'baz'
@filtered = @set.filter (v) -> v.slice(0, 1) is 'b'
equal @filtered.length, 2
ok @filtered.has 'bar'
ok @filtered.has 'baz'
test "using .has(key) in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'hasFoo', => @set.has('foo')
obj.observe 'hasFoo', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 1
@set.remove('foo')
equal observer.callCount, 2
test ".observe('isEmpty') fires when the value actually changes", ->
@set.add('foo')
@set.observe 'isEmpty', observer = createSpy()
@set.add('bar')
equal observer.callCount, 0
@set.remove('bar')
equal observer.callCount, 0
@set.remove('foo')
equal observer.callCount, 1
@set.add('foo')
equal observer.callCount, 2
test "using .toArray() in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'array', => @set.toArray()
obj.observe 'array', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 2
test "using .forEach() in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'foreach', => @set.forEach(->); []
obj.observe 'foreach', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 2
test "using .merge() in an accessor registers the original and merged sets as sources of the property", ->
obj = new Batman.Object
otherSet = new Batman.Set
obj.accessor 'mergedWithOther', => @set.merge(otherSet)
obj.observe 'mergedWithOther', observer = createSpy()
@set.add('foo')
equal observer.callCount, 1
@set.add('bar')
equal observer.callCount, 2
otherSet.add('baz')
equal observer.callCount, 3
test "using .find() in an accessor registers the set as a source of the property", ->
obj = new Batman.Object
obj.accessor 'firstBiggerThan2', => @set.find (n) -> n > 2
obj.observe 'firstBiggerThan2', observer = createSpy()
@set.add(3)
equal observer.callCount, 1
strictEqual obj.get('firstBiggerThan2'), 3
@set.add(4)
equal observer.callCount, 1
strictEqual obj.get('firstBiggerThan2'), 3
@set.remove(3)
equal observer.callCount, 2
strictEqual obj.get('firstBiggerThan2'), 4
test "using .toJSON() returns a serializable array representation of the set", ->
set = new Batman.Set
set.add new Batman.Object foo: 'bar'
set.add new Batman.Object bar: 'baz'
deepEqual set.toJSON(), [{foo: 'bar'}, {bar: 'baz'}]
sortAndIndexSuite = ->
test "sortedBy(property, order) returns a cached SetSort", ->
ascendingFoo = @set.sortedBy('foo')
strictEqual @set.sortedBy('foo'), ascendingFoo
descendingFoo = @set.sortedBy('foo', 'desc')
strictEqual @set.sortedBy('foo', 'desc'), descendingFoo
notEqual ascendingFoo, descendingFoo
equal ascendingFoo.base, @base
equal ascendingFoo.key, 'foo'
equal ascendingFoo.descending, no
equal descendingFoo.base, @base
equal descendingFoo.key, 'foo'
equal descendingFoo.descending, yes
test "sortedBy(deepProperty, order) returns a cached SetSort", ->
ascendingFoo = @set.sortedBy('foo.bar')
strictEqual @set.sortedBy('foo.bar'), ascendingFoo
descendingFoo = @set.sortedBy('foo.bar', 'desc')
strictEqual @set.sortedBy('foo.bar', 'desc'), descendingFoo
notEqual ascendingFoo, descendingFoo
equal ascendingFoo.base, @base
equal ascendingFoo.key, 'PI:KEY:<KEY>END_PI'
equal ascendingFoo.descending, no
equal descendingFoo.base, @base
equal descendingFoo.key, 'PI:KEY:<KEY>END_PI'
equal descendingFoo.descending, yes
test "get('sortedBy.name') returns .sortedBy('name')", ->
strictEqual @set.get('sortedBy.name'), @set.sortedBy('name')
test "get('sortedByDescending.name') returns .sortedBy('name', 'desc')", ->
strictEqual @set.get('sortedByDescending.name'), @set.sortedBy('name', 'desc')
test "sortedBy(deepProperty) sorts by the deep property instead of traversing the keypath", ->
sort = @set.sortedBy('foo.bar')
deepEqual sort.toArray(), [@o1, @o2, @o3]
test "get('sortedBy').get(deepProperty) sorts by the deep property instead of traversing the keypath", ->
sort = @set.get('sortedBy').get('foo.bar')
deepEqual sort.toArray(), [@o1, @o2, @o3]
test "sortedBy(deepProperty, 'desc') sorts by the deep property instead of traversing the keypath", ->
sort = @set.sortedBy('foo.bar', 'desc')
deepEqual sort.toArray(), [@o3, @o2, @o1]
test "get('sortedByDescending').get(deepProperty) sorts by the deep property instead of traversing the keypath", ->
sort = @set.get('sortedByDescending').get('foo.bar')
deepEqual sort.toArray(), [@o3, @o2, @o1]
test "indexedBy(key) returns a memoized Batman.SetIndex for that key", ->
index = @set.indexedBy('length')
ok index instanceof Batman.SetIndex
equal index.base, @base
equal index.key, 'PI:KEY:<KEY>END_PI'
strictEqual @set.indexedBy('length'), index
test "get('indexedBy.someKey') returns the same index as indexedBy(key)", ->
strictEqual @set.get('indexedBy.length'), @set.indexedBy('length')
test "indexedBy(deepProperty) indexes by the deep property instead of traversing the keypath", ->
index = @set.indexedBy('foo.bar')
deepEqual index.get(2).toArray(), [@o2]
test "get('indexedBy').get(deepProperty) indexes by the deep property instead of traversing the keypath", ->
index = @set.get('indexedBy').get('foo.bar')
deepEqual index.get(2).toArray(), [@o2]
test "indexedByUnique(key) returns a memoized UniqueSetIndex for that key", ->
Batman.developer.suppress =>
index = @set.indexedByUnique('foo')
ok index instanceof Batman.UniqueSetIndex
equal index.base, @base
equal index.key, 'foo'
strictEqual @set.indexedByUnique('foo'), index
test "get('indexedByUnique.foo') returns a memoized UniqueSetIndex for the key 'foo'", ->
Batman.developer.suppress =>
strictEqual @set.get('indexedByUnique.foo'), @set.indexedByUnique('foo')
QUnit.module 'Batman.Set',
setup: ->
@set = new Batman.Set
basicSetTestSuite()
QUnit.module 'Batman.SetIntersection set polymorphism',
setup: ->
@set = new Batman.SetIntersection(new Batman.Set, new Batman.Set)
basicSetTestSuite()
QUnit.module 'Batman.SetUnion set polymorphism',
setup: ->
@set = new Batman.SetUnion(new Batman.Set, new Batman.Set)
basicSetTestSuite()
QUnit.module 'Batman.Set indexedBy and SortedBy' ,
setup: ->
@base = @set = new Batman.Set
@set.add @o3 =
foo:
bar: 3
@set.add @o1 =
foo:
bar: 1
@set.add @o2 =
foo:
bar: 2
sortAndIndexSuite()
QUnit.module "Batman.SetSort set polymorphism",
setup: ->
set = new Batman.Set
@set = set.sortedBy('')
basicSetTestSuite()
QUnit.module 'Batman.SetSort indexedBy and SortedBy' ,
setup: ->
@base = new Batman.Set
@set = @base.sortedBy('')
@set.add @o3 =
foo:
bar: 3
@set.add @o1 =
foo:
bar: 1
@set.add @o2 =
foo:
bar: 2
sortAndIndexSuite()
|
[
{
"context": "####################################\n#\n# Author: Cobe Greene\n# Date Created: 10 / 20 / 2017\n# Date Finish:",
"end": 70,
"score": 0.9998720288276672,
"start": 59,
"tag": "NAME",
"value": "Cobe Greene"
}
] | snippets/mips.cson | CobeGreene/mips-snippet | 0 | ############################################
#
# Author: Cobe Greene
# Date Created: 10 / 20 / 2017
# Date Finish: 10 / 25 / 2017
#
# Overview: Snippet For Mips Assembly Language
#
####
'.source.mips':
# Variables
'Variable':
'prefix': 'var'
'body': '${1:"name"}: .${2:"type"} ${3:"value"}'
'description': 'Allocate Memory For A Variable'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Adding
'Add':
'prefix': 'add'
'body': 'add ${1:"dest = "}, ${2:"source + "}, ${3:"source"}'
'description': 'Adds 32-bit integers. If overflow occurs, then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Add Unsigned':
'prefix': 'addu'
'body': 'addu ${1:"dest = "}, ${2:"source + "}, ${3:"source"}'
'description': 'To add 32-bit intgers'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Add Immediate':
'prefix': 'addi'
'body': 'addi ${1:"dest = "}, ${2:"source + "}, ${3:"value"}'
'description': 'To add a constant to a 32-bit integer. If overflow occurs, then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Add Imediate Unsigned':
'prefix': 'addiu'
'body': 'addiu ${1:"dest = "}, ${2:"source + "}, ${3:"value"}'
'description': 'To add a constant to a 32-bit integer'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Count Leading Binary
'Count Leading Ones':
'prefix': 'clo'
'body': 'clo ${1:"dest"}, ${2:"source"}'
'description': 'To count the number of leading ones in a word'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Count Leading Zeros':
'prefix': 'clz'
'body': '${1:"dest"}, ${2:"souurce"}'
'description': 'To count the number of leading zeros in a word'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Subtract
'Subtract':
'prefix': 'sub'
'body': 'sub ${1:"dest = "}, ${2:"source - "}, ${3:"source"}'
'description': 'To subtract 32-bit integers, if overflow then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Subtract Unsigned':
'prefix': 'subu'
'body': 'subu ${1:"dest = "}, ${2:"source - "}, ${3:"source"}'
'description': 'To subtract 32-bit integers'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Multiply
'Multiply':
'prefix': 'mul'
'body': 'mul ${1:"dest = "}, ${2:"source * "}, ${3:"source"}'
'description': 'To multiply two words'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply To Hi, Lo':
'prefix': 'mult'
'body': 'mult ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two words and stored the value into Hi and Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply Unsigned To Hi, Lo':
'prefix': 'multu'
'body': 'multu ${1:"source * "}, ${2:"source"}'
'description': 'To multiply 32-bit unsigned integers'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Dividing
'Divide To Hi, Lo':
'prefix': 'div'
'body': 'div ${1:"source /"}, ${2:"source"}'
'description': 'To divide a 32-bit signed integers. Quotient is placed into LO and Remainder is placed into Hi'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Divide Unsigned To Hi, Lo':
'prefix': 'divu'
'body': 'add ${1:"source /"}, ${2:"source"}'
'description': 'To divide a 32-bit unsigned integers. Quotient is placed into LO and Remainder is placed into Hi'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Multiple Operations
'Multiply And Add Word To Hi, Lo':
'prefix': 'madd'
'body': 'madd ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two words and add the result to Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply And Add Unsigned To Hi, Lo':
'prefix': 'maddu'
'body': 'maddu ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two unsigned words and add the result to Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply And Subtract Word To Hi, Lo':
'prefix': 'msub'
'body': 'msub ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two words and subtract the results from Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply And Subtract Unsigned To Hi, Lo':
'prefix': 'msubu'
'body': 'msubu ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two unsigned words and subtract the results from Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Jump
'Jump':
'prefix': 'j'
'body': 'j ${1:"target"}'
'description': 'To branch to desire location'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Jump And Link':
'prefix': 'jal'
'body': 'jal ${1:"target"}'
'description': 'To go to desire location, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Jump And Link Register':
'prefix': 'jalr'
'body': 'jalr ${1:"return dest"}, ${2:"target"}'
'description': 'To go to desire location, and pass the return address into $r'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Jump Register':
'prefix': 'jr'
'body': 'jr ${1:"target"}'
'description': 'To go to desire location in the register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Set On
'Set On Less Than':
'prefix': 'slt'
'body': 'slt ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"source"}'
'description': 'To record the result of a less-than comparision'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Set On Less Than Immediate':
'prefix': 'slti'
'body': 'slti ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"value"}'
'description': 'To record the result of a less-than comparision with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Set On Less Than Immediate Unsigned':
'prefix': 'sltiu'
'body': 'sltiu ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"value"}'
'description': 'To record the result of an unsigned less-than comparision with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Set On Less Than Unsigned':
'prefix': 'sltu'
'body': 'sltu ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"source"}'
'description': 'To record the result of an unsigned less-than comparision'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Bitwise Operations And Arithmetic Operration
'Or':
'prefix': 'or'
'body': 'or ${1:"dest = "}, ${2:"source OR "}, ${3:"source"}'
'description': 'To do a bitwise logical OR'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Or Immediate':
'prefix': 'ori'
'body': 'ori ${1:"dest = "}, ${2:"source OR "}, ${3:"value"}'
'description': 'To do a bitwise logical OR with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Not Or':
'prefix': 'nor'
'body': 'nor ${1:"dest = "}, ${2:"source NOR "}, ${3:"source"}'
'description': 'To do a bitwise logical NOT OR'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Exclusive Or':
'prefix': 'xor'
'body': 'xor ${1:"dest = "}, ${2:"source XOR"}, ${3:"source"}'
'description': 'To do a bitwise logical exclusive or'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Exclusive Or Immediate':
'prefix': 'xori'
'body': 'xori ${1:"dest = "}, ${2:"source XOR"}, ${3:"value"}'
'description': 'To do a bitwise logical exclusive or with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'And':
'prefix': 'and'
'body': 'and ${1:"dest = "}, ${2:"source AND "}, ${3:"source"}'
'description': 'To do a bitwise logical AND'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'And Immediate':
'prefix': 'andi'
'body': 'andi ${1:"dest = "}, ${2:"source AND "}, ${3:"value"}'
'description': 'To do a bitwise logical AND with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Left Logical':
'prefix': 'sll'
'body': 'sll ${1:"dest = "}, ${2:"source << "}, ${3:"value"}'
'description': 'To left-shift a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Left Variable':
'prefix': 'sllv'
'body': 'sllv ${1:"dest = "}, ${2:"source << "}, ${3:"source"}'
'description': 'To left-shift a word by a variable number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Right Logical':
'prefix': 'srl'
'body': 'srl ${1:"dest = "}, ${2:"source >> "}, ${3:"value"}'
'description': 'To execute a logical right-shift of a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Right Logical Variable':
'prefix': 'srlv'
'body': 'srlv ${1:"dest = "}, ${2:"source >> "}, ${3:"source"}'
'description': 'To execute a logical right-shift of a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Word Right Arithmetic':
'prefix': 'sra'
'body': 'sra ${1:"dest = "}, ${2:"source >> "}, ${3:"source"}'
'description': 'To execute an arithmetic right-shift of a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Word Right Arithmetic Variable':
'prefix': 'srav'
'body': 'srav ${1:"dest = "}, ${2:"source >> "}, ${3:"source"}'
'description': 'To execute an arithmetic right-shfit of a word by a variable number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Loading
'Load Byte':
'prefix': 'lb'
'body': 'lb ${1:"dest ="}, ${2:"byte"}'
'description': 'To load a byte from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Byte Unsigned':
'prefix': 'lbu'
'body': 'lb ${1:"dest ="}, ${2:"byte"}'
'description': 'To load a byte from memory as an unsigned value'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Halfword':
'prefix': 'lh'
'body': 'lh ${1:"dest = "}, ${2:"halfword"}'
'description': 'To load a halfbyte from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Halfword Unsigned':
'prefix': 'lhu'
'body': 'lhu ${1:"dest = "}, ${2:"halfword"}'
'description': 'To load a halfbyte from memory as an unsigned value'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Immediate':
'prefix': 'li'
'body': 'li ${1:"dest = "}, ${2:"value"}'
'description': 'To load a value into the register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Word':
'prefix': 'lw'
'body': 'lw ${1:"dest = "}, ${2:"source"}'
'description': 'To load word from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Address':
'prefix': 'la'
'body': 'la ${1:"dest = "}, ${2:"source"}'
'description': 'To load the address of a memory location into the register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Linked Word':
'prefix': 'll'
'body': 'll ${1:"dest = "}, ${2:"source"}'
'description': 'To load a word from memory for an atomic read-modify-write'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Word Right':
'prefix': 'lwr'
'body': 'lwr ${1:"dest = "}, ${2:"source"}'
'description': 'To load the least significant part of a word as a signed value from an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Word Left':
'prefix': 'lwl'
'body': 'lwl ${1:"dest = "}, ${2:"source"}'
'description': 'To load the most significant part of a word as a signed value from an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Upper Immediate':
'prefix': 'lui'
'body': 'lui ${1:"dest = "}, ${2:"value"}'
'description': 'To load a constant into the upper half of the word'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Store
'Store Byte':
'prefix': 'sb'
'body': 'sb ${1:"source"}, ${2:" = dest"}'
'description': 'To store a byte from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Halfword':
'prefix': 'sh'
'body': 'sh ${1:"source"}, ${2:" = dest"}'
'description': 'To store a halfword from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store':
'prefix': 'sw'
'body': 'sw ${1:"source"}, ${2:" = dest"}'
'description': 'To store a word into memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Word Right':
'prefix': 'swr'
'body': 'swr ${1:"source "}, ${2:" = dest"}'
'description': 'To store the least-significant part of a word to an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Conditional Word':
'prefix': 'sc'
'body': 'sc ${1:"source "}, ${2:" = dest"}'
'description': 'To store a word to memory to complete an atomic read-modify-write'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Word Left':
'prefix': 'swl'
'body': 'swl ${1:"source"}, ${2:" = dest"}'
'description': 'To store the most-significant part of a word to an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Move
'Move':
'prefix': 'move'
'body': 'move ${1:"dest = "}, ${2:"source"}'
'description': 'To copy the source register into the destination register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move From Hi Register':
'prefix': 'mfhi'
'body': 'mfhi ${1:"dest"}'
'description': 'To copy the special purpose Hi register to register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move From Lo Register':
'prefix': 'mflo'
'body': 'mflo ${1:"dest"}'
'description': 'To copy the special purpose Lo register to register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move To Hi Register':
'prefix': 'mthi'
'body': 'mthi ${1:"source"}'
'description': 'To copy from the register to the special purpose register Hi'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move To Lo Register':
'prefix': 'mtlo'
'body': 'mtlo ${1:"source"}'
'description': 'To copy from the register to the special purpose register Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move Conditional On Zero':
'prefix': 'movz'
'body': 'movz ${1:"dest = "}, ${2:"source"}, ${3:"source == 0"}'
'description': 'To move r2 to r1 if r3 equals 0'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move Conditional On Not Zero':
'prefix': 'movn'
'body': 'movn ${1:"dest = "}, ${2:"source"}, ${3:"source != 0"}'
'description': 'To move r2 to r1 if r3 doesn\'t equal 0'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Conditional
'Branch If Equal':
'prefix': 'beq'
'body': '''
beq ${1:"source == "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision r1 == r2 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Equal To Zero':
'prefix': 'beqz'
'body': '''
beqz ${1:"source == 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision r1 == 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Greater Than Or Equal To Zero':
'prefix': 'bgez'
'body': '''
bgez ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision r1 >= 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Greater Than Or Equal To Zero And Link':
'prefix': 'bgezal'
'body': '''
bgezal ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs >= 0 then do a PC-relative conditional branch, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Greater Than Zero':
'prefix': 'bgtz'
'body': '''
bgtz ${1:"source > 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs > 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Or Equal To Zero':
'prefix': 'blez'
'body': '''
blez ${1:"source <= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs <= 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Zero And Link':
'prefix': 'bltzal'
'body': '''
bltzal ${1:"source < 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Zero':
'prefix': 'bltz'
'body': '''
bltz ${1:"source < 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Not Equal':
'prefix': 'bne'
'body': '''
bne ${1:"source != "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs != 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Not Equal To Zero':
'prefix': 'bnez'
'body': '''
bnez ${1:"source != 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs != 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch':
'prefix': 'b'
'body': '''
b ${1:"target"}
nop
$2 '''
'description': 'To do an unconditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Zero Likely':
'prefix': 'bltzl'
'body': '''
bltzl ${1:"source < "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Less Than Zero And Link Likely':
'prefix': 'bltzall'
'body': '''
bltzall ${1:"source < "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Less Than Or Equal To Zero Likely':
'prefix': 'blezl'
'body': '''
blezl ${1:"source <= 0 "}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs <= 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Zero Likely':
'prefix': 'bgtzl'
'body': '''
bgtzl ${1:"source > 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs > 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken.'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Equal Likely':
'prefix': 'beql'
'body': '''
beql ${1:"source =="}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision r1 == r2 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Or Equal To Zero Likely':
'prefix': 'bgezl'
'body': '''
bgezal ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs >= 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch And Link':
'prefix': 'bal'
'body': '''
bal ${1:"move to label"}
nop
$2 '''
'description': 'To do an unconditional PC-relative procedure call, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Or Equal To Zero And Link Likely':
'prefix': 'bgezall'
'body': '''
bgezall ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs >= 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Not Equal Likely':
'prefix': 'bnel'
'body': '''
bnel ${1:"source != "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs != 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Or Equal To':
'prefix': 'bge'
'body': '''
bge ${1:"source >= "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs >= rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'Branch On Greater Than':
'prefix': 'bgt'
'body': '''
bgt ${1:"source > "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs > rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'Branch On Less Than Or Equal To':
'prefix': 'ble'
'body': '''
ble ${1:"source <= "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs <= rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'Branch On Less Than':
'prefix': 'blt'
'body': '''
blt ${1:"source < "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs < rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
# Trapping
'Trap If Equal':
'prefix': 'teq'
'body': 'teq ${1:"source == "}, ${2:"source"}'
'description': 'To run comparision r1 == r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Equal Immediate':
'prefix': 'teqi'
'body': 'teqi ${1:"source == "}, ${2:"value"}'
'description': 'To run comparision r1 == constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Than Or Equal To Immediate':
'prefix': 'tgei'
'body': 'tgei ${1:"source >= "}, ${2:"value"}'
'description': 'To run comparision r1 >= constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than Unsigned':
'prefix': 'tltu'
'body': 'tltu ${1:"source < "}, ${2:"source"}'
'description': 'To run comparision r1 < r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Or Equal':
'prefix': 'tge'
'body': 'tge ${1:"source >="}, ${2:"source"}'
'description': 'To run comparision r1 >= r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than Immediate Unsigned':
'prefix': 'tltiu'
'body': 'tltiu ${1:"source < "}, ${2:"value"}'
'description': 'To run comparision r1 < constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Not Equal':
'prefix': 'tne'
'body': 'tne ${1:"source != "}, ${2:"source"}'
'description': 'To run comparision r1 != r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Not Equal Immediate':
'prefix': 'tnei'
'body': 'tnei ${1:"source != "}, ${2:"value"}'
'description': 'To run comparision r1 != constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Or Equal Unsigned':
'prefix': 'tgeu'
'body': 'tgeu ${1:"source >= "}, ${2:"source"}'
'description': 'To run comparision r1 >= r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than':
'prefix': 'tlt'
'body': 'tlt ${1:"source < "}, ${2:"source"}'
'description': 'To run comparision r1 < r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than Immediate':
'prefix': 'tlti'
'body': 'tlti ${1:"source < "}, ${2:"valu"}'
'description': 'To run comparision r1 < constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Or Equal Immediate Unsigned':
'prefix': 'tgeiu'
'body': 'tgeiu ${1:"source >="}, ${2:"source"}'
'description': 'To run comparision r1 >= constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Other Commands
'Negate':
'prefix': 'neg'
'body': '${1:"source ="}, ${2:"-1 * source"}'
'description': 'The value is negated, and place into a register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'No Operation':
'prefix': 'nop'
'body': 'nop'
'description': 'To perform no operation'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Break':
'prefix': 'break'
'body': 'break'
'description': 'To cause a Breakpoint exeception'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Debug Exeception Return':
'prefix': 'deret'
'body': 'deret'
'description': 'To return from a debug exeception'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'System Call':
'prefix': 'syscall'
'body': 'syscall'
'description': 'To cause a system call'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Exeception Return':
'prefix': 'eret'
'body': 'eret'
'description': 'To return from interrupt, exeception, or error trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
| 59096 | ############################################
#
# Author: <NAME>
# Date Created: 10 / 20 / 2017
# Date Finish: 10 / 25 / 2017
#
# Overview: Snippet For Mips Assembly Language
#
####
'.source.mips':
# Variables
'Variable':
'prefix': 'var'
'body': '${1:"name"}: .${2:"type"} ${3:"value"}'
'description': 'Allocate Memory For A Variable'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Adding
'Add':
'prefix': 'add'
'body': 'add ${1:"dest = "}, ${2:"source + "}, ${3:"source"}'
'description': 'Adds 32-bit integers. If overflow occurs, then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Add Unsigned':
'prefix': 'addu'
'body': 'addu ${1:"dest = "}, ${2:"source + "}, ${3:"source"}'
'description': 'To add 32-bit intgers'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Add Immediate':
'prefix': 'addi'
'body': 'addi ${1:"dest = "}, ${2:"source + "}, ${3:"value"}'
'description': 'To add a constant to a 32-bit integer. If overflow occurs, then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Add Imediate Unsigned':
'prefix': 'addiu'
'body': 'addiu ${1:"dest = "}, ${2:"source + "}, ${3:"value"}'
'description': 'To add a constant to a 32-bit integer'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Count Leading Binary
'Count Leading Ones':
'prefix': 'clo'
'body': 'clo ${1:"dest"}, ${2:"source"}'
'description': 'To count the number of leading ones in a word'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Count Leading Zeros':
'prefix': 'clz'
'body': '${1:"dest"}, ${2:"souurce"}'
'description': 'To count the number of leading zeros in a word'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Subtract
'Subtract':
'prefix': 'sub'
'body': 'sub ${1:"dest = "}, ${2:"source - "}, ${3:"source"}'
'description': 'To subtract 32-bit integers, if overflow then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Subtract Unsigned':
'prefix': 'subu'
'body': 'subu ${1:"dest = "}, ${2:"source - "}, ${3:"source"}'
'description': 'To subtract 32-bit integers'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Multiply
'Multiply':
'prefix': 'mul'
'body': 'mul ${1:"dest = "}, ${2:"source * "}, ${3:"source"}'
'description': 'To multiply two words'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply To Hi, Lo':
'prefix': 'mult'
'body': 'mult ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two words and stored the value into Hi and Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply Unsigned To Hi, Lo':
'prefix': 'multu'
'body': 'multu ${1:"source * "}, ${2:"source"}'
'description': 'To multiply 32-bit unsigned integers'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Dividing
'Divide To Hi, Lo':
'prefix': 'div'
'body': 'div ${1:"source /"}, ${2:"source"}'
'description': 'To divide a 32-bit signed integers. Quotient is placed into LO and Remainder is placed into Hi'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Divide Unsigned To Hi, Lo':
'prefix': 'divu'
'body': 'add ${1:"source /"}, ${2:"source"}'
'description': 'To divide a 32-bit unsigned integers. Quotient is placed into LO and Remainder is placed into Hi'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Multiple Operations
'Multiply And Add Word To Hi, Lo':
'prefix': 'madd'
'body': 'madd ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two words and add the result to Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply And Add Unsigned To Hi, Lo':
'prefix': 'maddu'
'body': 'maddu ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two unsigned words and add the result to Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply And Subtract Word To Hi, Lo':
'prefix': 'msub'
'body': 'msub ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two words and subtract the results from Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply And Subtract Unsigned To Hi, Lo':
'prefix': 'msubu'
'body': 'msubu ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two unsigned words and subtract the results from Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Jump
'Jump':
'prefix': 'j'
'body': 'j ${1:"target"}'
'description': 'To branch to desire location'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Jump And Link':
'prefix': 'jal'
'body': 'jal ${1:"target"}'
'description': 'To go to desire location, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Jump And Link Register':
'prefix': 'jalr'
'body': 'jalr ${1:"return dest"}, ${2:"target"}'
'description': 'To go to desire location, and pass the return address into $r'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Jump Register':
'prefix': 'jr'
'body': 'jr ${1:"target"}'
'description': 'To go to desire location in the register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Set On
'Set On Less Than':
'prefix': 'slt'
'body': 'slt ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"source"}'
'description': 'To record the result of a less-than comparision'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Set On Less Than Immediate':
'prefix': 'slti'
'body': 'slti ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"value"}'
'description': 'To record the result of a less-than comparision with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Set On Less Than Immediate Unsigned':
'prefix': 'sltiu'
'body': 'sltiu ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"value"}'
'description': 'To record the result of an unsigned less-than comparision with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Set On Less Than Unsigned':
'prefix': 'sltu'
'body': 'sltu ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"source"}'
'description': 'To record the result of an unsigned less-than comparision'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Bitwise Operations And Arithmetic Operration
'Or':
'prefix': 'or'
'body': 'or ${1:"dest = "}, ${2:"source OR "}, ${3:"source"}'
'description': 'To do a bitwise logical OR'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Or Immediate':
'prefix': 'ori'
'body': 'ori ${1:"dest = "}, ${2:"source OR "}, ${3:"value"}'
'description': 'To do a bitwise logical OR with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Not Or':
'prefix': 'nor'
'body': 'nor ${1:"dest = "}, ${2:"source NOR "}, ${3:"source"}'
'description': 'To do a bitwise logical NOT OR'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Exclusive Or':
'prefix': 'xor'
'body': 'xor ${1:"dest = "}, ${2:"source XOR"}, ${3:"source"}'
'description': 'To do a bitwise logical exclusive or'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Exclusive Or Immediate':
'prefix': 'xori'
'body': 'xori ${1:"dest = "}, ${2:"source XOR"}, ${3:"value"}'
'description': 'To do a bitwise logical exclusive or with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'And':
'prefix': 'and'
'body': 'and ${1:"dest = "}, ${2:"source AND "}, ${3:"source"}'
'description': 'To do a bitwise logical AND'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'And Immediate':
'prefix': 'andi'
'body': 'andi ${1:"dest = "}, ${2:"source AND "}, ${3:"value"}'
'description': 'To do a bitwise logical AND with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Left Logical':
'prefix': 'sll'
'body': 'sll ${1:"dest = "}, ${2:"source << "}, ${3:"value"}'
'description': 'To left-shift a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Left Variable':
'prefix': 'sllv'
'body': 'sllv ${1:"dest = "}, ${2:"source << "}, ${3:"source"}'
'description': 'To left-shift a word by a variable number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Right Logical':
'prefix': 'srl'
'body': 'srl ${1:"dest = "}, ${2:"source >> "}, ${3:"value"}'
'description': 'To execute a logical right-shift of a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Right Logical Variable':
'prefix': 'srlv'
'body': 'srlv ${1:"dest = "}, ${2:"source >> "}, ${3:"source"}'
'description': 'To execute a logical right-shift of a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Word Right Arithmetic':
'prefix': 'sra'
'body': 'sra ${1:"dest = "}, ${2:"source >> "}, ${3:"source"}'
'description': 'To execute an arithmetic right-shift of a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Word Right Arithmetic Variable':
'prefix': 'srav'
'body': 'srav ${1:"dest = "}, ${2:"source >> "}, ${3:"source"}'
'description': 'To execute an arithmetic right-shfit of a word by a variable number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Loading
'Load Byte':
'prefix': 'lb'
'body': 'lb ${1:"dest ="}, ${2:"byte"}'
'description': 'To load a byte from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Byte Unsigned':
'prefix': 'lbu'
'body': 'lb ${1:"dest ="}, ${2:"byte"}'
'description': 'To load a byte from memory as an unsigned value'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Halfword':
'prefix': 'lh'
'body': 'lh ${1:"dest = "}, ${2:"halfword"}'
'description': 'To load a halfbyte from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Halfword Unsigned':
'prefix': 'lhu'
'body': 'lhu ${1:"dest = "}, ${2:"halfword"}'
'description': 'To load a halfbyte from memory as an unsigned value'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Immediate':
'prefix': 'li'
'body': 'li ${1:"dest = "}, ${2:"value"}'
'description': 'To load a value into the register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Word':
'prefix': 'lw'
'body': 'lw ${1:"dest = "}, ${2:"source"}'
'description': 'To load word from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Address':
'prefix': 'la'
'body': 'la ${1:"dest = "}, ${2:"source"}'
'description': 'To load the address of a memory location into the register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Linked Word':
'prefix': 'll'
'body': 'll ${1:"dest = "}, ${2:"source"}'
'description': 'To load a word from memory for an atomic read-modify-write'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Word Right':
'prefix': 'lwr'
'body': 'lwr ${1:"dest = "}, ${2:"source"}'
'description': 'To load the least significant part of a word as a signed value from an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Word Left':
'prefix': 'lwl'
'body': 'lwl ${1:"dest = "}, ${2:"source"}'
'description': 'To load the most significant part of a word as a signed value from an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Upper Immediate':
'prefix': 'lui'
'body': 'lui ${1:"dest = "}, ${2:"value"}'
'description': 'To load a constant into the upper half of the word'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Store
'Store Byte':
'prefix': 'sb'
'body': 'sb ${1:"source"}, ${2:" = dest"}'
'description': 'To store a byte from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Halfword':
'prefix': 'sh'
'body': 'sh ${1:"source"}, ${2:" = dest"}'
'description': 'To store a halfword from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store':
'prefix': 'sw'
'body': 'sw ${1:"source"}, ${2:" = dest"}'
'description': 'To store a word into memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Word Right':
'prefix': 'swr'
'body': 'swr ${1:"source "}, ${2:" = dest"}'
'description': 'To store the least-significant part of a word to an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Conditional Word':
'prefix': 'sc'
'body': 'sc ${1:"source "}, ${2:" = dest"}'
'description': 'To store a word to memory to complete an atomic read-modify-write'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Word Left':
'prefix': 'swl'
'body': 'swl ${1:"source"}, ${2:" = dest"}'
'description': 'To store the most-significant part of a word to an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Move
'Move':
'prefix': 'move'
'body': 'move ${1:"dest = "}, ${2:"source"}'
'description': 'To copy the source register into the destination register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move From Hi Register':
'prefix': 'mfhi'
'body': 'mfhi ${1:"dest"}'
'description': 'To copy the special purpose Hi register to register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move From Lo Register':
'prefix': 'mflo'
'body': 'mflo ${1:"dest"}'
'description': 'To copy the special purpose Lo register to register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move To Hi Register':
'prefix': 'mthi'
'body': 'mthi ${1:"source"}'
'description': 'To copy from the register to the special purpose register Hi'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move To Lo Register':
'prefix': 'mtlo'
'body': 'mtlo ${1:"source"}'
'description': 'To copy from the register to the special purpose register Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move Conditional On Zero':
'prefix': 'movz'
'body': 'movz ${1:"dest = "}, ${2:"source"}, ${3:"source == 0"}'
'description': 'To move r2 to r1 if r3 equals 0'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move Conditional On Not Zero':
'prefix': 'movn'
'body': 'movn ${1:"dest = "}, ${2:"source"}, ${3:"source != 0"}'
'description': 'To move r2 to r1 if r3 doesn\'t equal 0'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Conditional
'Branch If Equal':
'prefix': 'beq'
'body': '''
beq ${1:"source == "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision r1 == r2 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Equal To Zero':
'prefix': 'beqz'
'body': '''
beqz ${1:"source == 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision r1 == 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Greater Than Or Equal To Zero':
'prefix': 'bgez'
'body': '''
bgez ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision r1 >= 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Greater Than Or Equal To Zero And Link':
'prefix': 'bgezal'
'body': '''
bgezal ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs >= 0 then do a PC-relative conditional branch, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Greater Than Zero':
'prefix': 'bgtz'
'body': '''
bgtz ${1:"source > 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs > 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Or Equal To Zero':
'prefix': 'blez'
'body': '''
blez ${1:"source <= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs <= 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Zero And Link':
'prefix': 'bltzal'
'body': '''
bltzal ${1:"source < 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Zero':
'prefix': 'bltz'
'body': '''
bltz ${1:"source < 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Not Equal':
'prefix': 'bne'
'body': '''
bne ${1:"source != "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs != 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Not Equal To Zero':
'prefix': 'bnez'
'body': '''
bnez ${1:"source != 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs != 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch':
'prefix': 'b'
'body': '''
b ${1:"target"}
nop
$2 '''
'description': 'To do an unconditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Zero Likely':
'prefix': 'bltzl'
'body': '''
bltzl ${1:"source < "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Less Than Zero And Link Likely':
'prefix': 'bltzall'
'body': '''
bltzall ${1:"source < "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Less Than Or Equal To Zero Likely':
'prefix': 'blezl'
'body': '''
blezl ${1:"source <= 0 "}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs <= 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Zero Likely':
'prefix': 'bgtzl'
'body': '''
bgtzl ${1:"source > 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs > 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken.'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Equal Likely':
'prefix': 'beql'
'body': '''
beql ${1:"source =="}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision r1 == r2 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Or Equal To Zero Likely':
'prefix': 'bgezl'
'body': '''
bgezal ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs >= 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch And Link':
'prefix': 'bal'
'body': '''
bal ${1:"move to label"}
nop
$2 '''
'description': 'To do an unconditional PC-relative procedure call, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Or Equal To Zero And Link Likely':
'prefix': 'bgezall'
'body': '''
bgezall ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs >= 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Not Equal Likely':
'prefix': 'bnel'
'body': '''
bnel ${1:"source != "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs != 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Or Equal To':
'prefix': 'bge'
'body': '''
bge ${1:"source >= "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs >= rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'Branch On Greater Than':
'prefix': 'bgt'
'body': '''
bgt ${1:"source > "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs > rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'Branch On Less Than Or Equal To':
'prefix': 'ble'
'body': '''
ble ${1:"source <= "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs <= rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'Branch On Less Than':
'prefix': 'blt'
'body': '''
blt ${1:"source < "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs < rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
# Trapping
'Trap If Equal':
'prefix': 'teq'
'body': 'teq ${1:"source == "}, ${2:"source"}'
'description': 'To run comparision r1 == r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Equal Immediate':
'prefix': 'teqi'
'body': 'teqi ${1:"source == "}, ${2:"value"}'
'description': 'To run comparision r1 == constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Than Or Equal To Immediate':
'prefix': 'tgei'
'body': 'tgei ${1:"source >= "}, ${2:"value"}'
'description': 'To run comparision r1 >= constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than Unsigned':
'prefix': 'tltu'
'body': 'tltu ${1:"source < "}, ${2:"source"}'
'description': 'To run comparision r1 < r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Or Equal':
'prefix': 'tge'
'body': 'tge ${1:"source >="}, ${2:"source"}'
'description': 'To run comparision r1 >= r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than Immediate Unsigned':
'prefix': 'tltiu'
'body': 'tltiu ${1:"source < "}, ${2:"value"}'
'description': 'To run comparision r1 < constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Not Equal':
'prefix': 'tne'
'body': 'tne ${1:"source != "}, ${2:"source"}'
'description': 'To run comparision r1 != r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Not Equal Immediate':
'prefix': 'tnei'
'body': 'tnei ${1:"source != "}, ${2:"value"}'
'description': 'To run comparision r1 != constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Or Equal Unsigned':
'prefix': 'tgeu'
'body': 'tgeu ${1:"source >= "}, ${2:"source"}'
'description': 'To run comparision r1 >= r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than':
'prefix': 'tlt'
'body': 'tlt ${1:"source < "}, ${2:"source"}'
'description': 'To run comparision r1 < r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than Immediate':
'prefix': 'tlti'
'body': 'tlti ${1:"source < "}, ${2:"valu"}'
'description': 'To run comparision r1 < constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Or Equal Immediate Unsigned':
'prefix': 'tgeiu'
'body': 'tgeiu ${1:"source >="}, ${2:"source"}'
'description': 'To run comparision r1 >= constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Other Commands
'Negate':
'prefix': 'neg'
'body': '${1:"source ="}, ${2:"-1 * source"}'
'description': 'The value is negated, and place into a register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'No Operation':
'prefix': 'nop'
'body': 'nop'
'description': 'To perform no operation'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Break':
'prefix': 'break'
'body': 'break'
'description': 'To cause a Breakpoint exeception'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Debug Exeception Return':
'prefix': 'deret'
'body': 'deret'
'description': 'To return from a debug exeception'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'System Call':
'prefix': 'syscall'
'body': 'syscall'
'description': 'To cause a system call'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Exeception Return':
'prefix': 'eret'
'body': 'eret'
'description': 'To return from interrupt, exeception, or error trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
| true | ############################################
#
# Author: PI:NAME:<NAME>END_PI
# Date Created: 10 / 20 / 2017
# Date Finish: 10 / 25 / 2017
#
# Overview: Snippet For Mips Assembly Language
#
####
'.source.mips':
# Variables
'Variable':
'prefix': 'var'
'body': '${1:"name"}: .${2:"type"} ${3:"value"}'
'description': 'Allocate Memory For A Variable'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Adding
'Add':
'prefix': 'add'
'body': 'add ${1:"dest = "}, ${2:"source + "}, ${3:"source"}'
'description': 'Adds 32-bit integers. If overflow occurs, then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Add Unsigned':
'prefix': 'addu'
'body': 'addu ${1:"dest = "}, ${2:"source + "}, ${3:"source"}'
'description': 'To add 32-bit intgers'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Add Immediate':
'prefix': 'addi'
'body': 'addi ${1:"dest = "}, ${2:"source + "}, ${3:"value"}'
'description': 'To add a constant to a 32-bit integer. If overflow occurs, then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Add Imediate Unsigned':
'prefix': 'addiu'
'body': 'addiu ${1:"dest = "}, ${2:"source + "}, ${3:"value"}'
'description': 'To add a constant to a 32-bit integer'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Count Leading Binary
'Count Leading Ones':
'prefix': 'clo'
'body': 'clo ${1:"dest"}, ${2:"source"}'
'description': 'To count the number of leading ones in a word'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Count Leading Zeros':
'prefix': 'clz'
'body': '${1:"dest"}, ${2:"souurce"}'
'description': 'To count the number of leading zeros in a word'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Subtract
'Subtract':
'prefix': 'sub'
'body': 'sub ${1:"dest = "}, ${2:"source - "}, ${3:"source"}'
'description': 'To subtract 32-bit integers, if overflow then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Subtract Unsigned':
'prefix': 'subu'
'body': 'subu ${1:"dest = "}, ${2:"source - "}, ${3:"source"}'
'description': 'To subtract 32-bit integers'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Multiply
'Multiply':
'prefix': 'mul'
'body': 'mul ${1:"dest = "}, ${2:"source * "}, ${3:"source"}'
'description': 'To multiply two words'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply To Hi, Lo':
'prefix': 'mult'
'body': 'mult ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two words and stored the value into Hi and Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply Unsigned To Hi, Lo':
'prefix': 'multu'
'body': 'multu ${1:"source * "}, ${2:"source"}'
'description': 'To multiply 32-bit unsigned integers'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Dividing
'Divide To Hi, Lo':
'prefix': 'div'
'body': 'div ${1:"source /"}, ${2:"source"}'
'description': 'To divide a 32-bit signed integers. Quotient is placed into LO and Remainder is placed into Hi'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Divide Unsigned To Hi, Lo':
'prefix': 'divu'
'body': 'add ${1:"source /"}, ${2:"source"}'
'description': 'To divide a 32-bit unsigned integers. Quotient is placed into LO and Remainder is placed into Hi'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Multiple Operations
'Multiply And Add Word To Hi, Lo':
'prefix': 'madd'
'body': 'madd ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two words and add the result to Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply And Add Unsigned To Hi, Lo':
'prefix': 'maddu'
'body': 'maddu ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two unsigned words and add the result to Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply And Subtract Word To Hi, Lo':
'prefix': 'msub'
'body': 'msub ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two words and subtract the results from Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Multiply And Subtract Unsigned To Hi, Lo':
'prefix': 'msubu'
'body': 'msubu ${1:"source * "}, ${2:"source"}'
'description': 'To multiply two unsigned words and subtract the results from Hi, Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Jump
'Jump':
'prefix': 'j'
'body': 'j ${1:"target"}'
'description': 'To branch to desire location'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Jump And Link':
'prefix': 'jal'
'body': 'jal ${1:"target"}'
'description': 'To go to desire location, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Jump And Link Register':
'prefix': 'jalr'
'body': 'jalr ${1:"return dest"}, ${2:"target"}'
'description': 'To go to desire location, and pass the return address into $r'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Jump Register':
'prefix': 'jr'
'body': 'jr ${1:"target"}'
'description': 'To go to desire location in the register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Set On
'Set On Less Than':
'prefix': 'slt'
'body': 'slt ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"source"}'
'description': 'To record the result of a less-than comparision'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Set On Less Than Immediate':
'prefix': 'slti'
'body': 'slti ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"value"}'
'description': 'To record the result of a less-than comparision with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Set On Less Than Immediate Unsigned':
'prefix': 'sltiu'
'body': 'sltiu ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"value"}'
'description': 'To record the result of an unsigned less-than comparision with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Set On Less Than Unsigned':
'prefix': 'sltu'
'body': 'sltu ${1:"dest == 1/0"}, ${2:"source < "}, ${3:"source"}'
'description': 'To record the result of an unsigned less-than comparision'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Bitwise Operations And Arithmetic Operration
'Or':
'prefix': 'or'
'body': 'or ${1:"dest = "}, ${2:"source OR "}, ${3:"source"}'
'description': 'To do a bitwise logical OR'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Or Immediate':
'prefix': 'ori'
'body': 'ori ${1:"dest = "}, ${2:"source OR "}, ${3:"value"}'
'description': 'To do a bitwise logical OR with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Not Or':
'prefix': 'nor'
'body': 'nor ${1:"dest = "}, ${2:"source NOR "}, ${3:"source"}'
'description': 'To do a bitwise logical NOT OR'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Exclusive Or':
'prefix': 'xor'
'body': 'xor ${1:"dest = "}, ${2:"source XOR"}, ${3:"source"}'
'description': 'To do a bitwise logical exclusive or'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Exclusive Or Immediate':
'prefix': 'xori'
'body': 'xori ${1:"dest = "}, ${2:"source XOR"}, ${3:"value"}'
'description': 'To do a bitwise logical exclusive or with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'And':
'prefix': 'and'
'body': 'and ${1:"dest = "}, ${2:"source AND "}, ${3:"source"}'
'description': 'To do a bitwise logical AND'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'And Immediate':
'prefix': 'andi'
'body': 'andi ${1:"dest = "}, ${2:"source AND "}, ${3:"value"}'
'description': 'To do a bitwise logical AND with a constant'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Left Logical':
'prefix': 'sll'
'body': 'sll ${1:"dest = "}, ${2:"source << "}, ${3:"value"}'
'description': 'To left-shift a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Left Variable':
'prefix': 'sllv'
'body': 'sllv ${1:"dest = "}, ${2:"source << "}, ${3:"source"}'
'description': 'To left-shift a word by a variable number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Right Logical':
'prefix': 'srl'
'body': 'srl ${1:"dest = "}, ${2:"source >> "}, ${3:"value"}'
'description': 'To execute a logical right-shift of a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Right Logical Variable':
'prefix': 'srlv'
'body': 'srlv ${1:"dest = "}, ${2:"source >> "}, ${3:"source"}'
'description': 'To execute a logical right-shift of a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Word Right Arithmetic':
'prefix': 'sra'
'body': 'sra ${1:"dest = "}, ${2:"source >> "}, ${3:"source"}'
'description': 'To execute an arithmetic right-shift of a word by a fixed number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Shift Word Right Arithmetic Variable':
'prefix': 'srav'
'body': 'srav ${1:"dest = "}, ${2:"source >> "}, ${3:"source"}'
'description': 'To execute an arithmetic right-shfit of a word by a variable number of bits'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Loading
'Load Byte':
'prefix': 'lb'
'body': 'lb ${1:"dest ="}, ${2:"byte"}'
'description': 'To load a byte from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Byte Unsigned':
'prefix': 'lbu'
'body': 'lb ${1:"dest ="}, ${2:"byte"}'
'description': 'To load a byte from memory as an unsigned value'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Halfword':
'prefix': 'lh'
'body': 'lh ${1:"dest = "}, ${2:"halfword"}'
'description': 'To load a halfbyte from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Halfword Unsigned':
'prefix': 'lhu'
'body': 'lhu ${1:"dest = "}, ${2:"halfword"}'
'description': 'To load a halfbyte from memory as an unsigned value'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Immediate':
'prefix': 'li'
'body': 'li ${1:"dest = "}, ${2:"value"}'
'description': 'To load a value into the register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Word':
'prefix': 'lw'
'body': 'lw ${1:"dest = "}, ${2:"source"}'
'description': 'To load word from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Address':
'prefix': 'la'
'body': 'la ${1:"dest = "}, ${2:"source"}'
'description': 'To load the address of a memory location into the register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Linked Word':
'prefix': 'll'
'body': 'll ${1:"dest = "}, ${2:"source"}'
'description': 'To load a word from memory for an atomic read-modify-write'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Word Right':
'prefix': 'lwr'
'body': 'lwr ${1:"dest = "}, ${2:"source"}'
'description': 'To load the least significant part of a word as a signed value from an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Word Left':
'prefix': 'lwl'
'body': 'lwl ${1:"dest = "}, ${2:"source"}'
'description': 'To load the most significant part of a word as a signed value from an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Load Upper Immediate':
'prefix': 'lui'
'body': 'lui ${1:"dest = "}, ${2:"value"}'
'description': 'To load a constant into the upper half of the word'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Store
'Store Byte':
'prefix': 'sb'
'body': 'sb ${1:"source"}, ${2:" = dest"}'
'description': 'To store a byte from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Halfword':
'prefix': 'sh'
'body': 'sh ${1:"source"}, ${2:" = dest"}'
'description': 'To store a halfword from memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store':
'prefix': 'sw'
'body': 'sw ${1:"source"}, ${2:" = dest"}'
'description': 'To store a word into memory'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Word Right':
'prefix': 'swr'
'body': 'swr ${1:"source "}, ${2:" = dest"}'
'description': 'To store the least-significant part of a word to an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Conditional Word':
'prefix': 'sc'
'body': 'sc ${1:"source "}, ${2:" = dest"}'
'description': 'To store a word to memory to complete an atomic read-modify-write'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Store Word Left':
'prefix': 'swl'
'body': 'swl ${1:"source"}, ${2:" = dest"}'
'description': 'To store the most-significant part of a word to an unaligned memory address'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Move
'Move':
'prefix': 'move'
'body': 'move ${1:"dest = "}, ${2:"source"}'
'description': 'To copy the source register into the destination register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move From Hi Register':
'prefix': 'mfhi'
'body': 'mfhi ${1:"dest"}'
'description': 'To copy the special purpose Hi register to register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move From Lo Register':
'prefix': 'mflo'
'body': 'mflo ${1:"dest"}'
'description': 'To copy the special purpose Lo register to register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move To Hi Register':
'prefix': 'mthi'
'body': 'mthi ${1:"source"}'
'description': 'To copy from the register to the special purpose register Hi'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move To Lo Register':
'prefix': 'mtlo'
'body': 'mtlo ${1:"source"}'
'description': 'To copy from the register to the special purpose register Lo'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move Conditional On Zero':
'prefix': 'movz'
'body': 'movz ${1:"dest = "}, ${2:"source"}, ${3:"source == 0"}'
'description': 'To move r2 to r1 if r3 equals 0'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Move Conditional On Not Zero':
'prefix': 'movn'
'body': 'movn ${1:"dest = "}, ${2:"source"}, ${3:"source != 0"}'
'description': 'To move r2 to r1 if r3 doesn\'t equal 0'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Conditional
'Branch If Equal':
'prefix': 'beq'
'body': '''
beq ${1:"source == "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision r1 == r2 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Equal To Zero':
'prefix': 'beqz'
'body': '''
beqz ${1:"source == 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision r1 == 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Greater Than Or Equal To Zero':
'prefix': 'bgez'
'body': '''
bgez ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision r1 >= 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Greater Than Or Equal To Zero And Link':
'prefix': 'bgezal'
'body': '''
bgezal ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs >= 0 then do a PC-relative conditional branch, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Greater Than Zero':
'prefix': 'bgtz'
'body': '''
bgtz ${1:"source > 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs > 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Or Equal To Zero':
'prefix': 'blez'
'body': '''
blez ${1:"source <= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs <= 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Zero And Link':
'prefix': 'bltzal'
'body': '''
bltzal ${1:"source < 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Zero':
'prefix': 'bltz'
'body': '''
bltz ${1:"source < 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Not Equal':
'prefix': 'bne'
'body': '''
bne ${1:"source != "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs != 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Not Equal To Zero':
'prefix': 'bnez'
'body': '''
bnez ${1:"source != 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs != 0 then do a PC-relative conditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch':
'prefix': 'b'
'body': '''
b ${1:"target"}
nop
$2 '''
'description': 'To do an unconditional branch'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch If Less Than Zero Likely':
'prefix': 'bltzl'
'body': '''
bltzl ${1:"source < "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Less Than Zero And Link Likely':
'prefix': 'bltzall'
'body': '''
bltzall ${1:"source < "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs < 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Less Than Or Equal To Zero Likely':
'prefix': 'blezl'
'body': '''
blezl ${1:"source <= 0 "}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs <= 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Zero Likely':
'prefix': 'bgtzl'
'body': '''
bgtzl ${1:"source > 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs > 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken.'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Equal Likely':
'prefix': 'beql'
'body': '''
beql ${1:"source =="}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision r1 == r2 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Or Equal To Zero Likely':
'prefix': 'bgezl'
'body': '''
bgezal ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs >= 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch And Link':
'prefix': 'bal'
'body': '''
bal ${1:"move to label"}
nop
$2 '''
'description': 'To do an unconditional PC-relative procedure call, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Or Equal To Zero And Link Likely':
'prefix': 'bgezall'
'body': '''
bgezall ${1:"source >= 0"}, ${2:"move to label"}
nop
$3 '''
'description': 'To run comparision rs >= 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken, and pass the return address into $ra'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Not Equal Likely':
'prefix': 'bnel'
'body': '''
bnel ${1:"source != "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs != 0 then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Branch On Greater Than Or Equal To':
'prefix': 'bge'
'body': '''
bge ${1:"source >= "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs >= rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'Branch On Greater Than':
'prefix': 'bgt'
'body': '''
bgt ${1:"source > "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs > rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'Branch On Less Than Or Equal To':
'prefix': 'ble'
'body': '''
ble ${1:"source <= "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs <= rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'Branch On Less Than':
'prefix': 'blt'
'body': '''
blt ${1:"source < "}, ${2:"source"}, ${3:"move to label"}
nop
$4 '''
'description': 'To run comparision rs < rs then do a PC-relative conditional branch; execute the delay slot only if the branch is taken'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
# Trapping
'Trap If Equal':
'prefix': 'teq'
'body': 'teq ${1:"source == "}, ${2:"source"}'
'description': 'To run comparision r1 == r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Equal Immediate':
'prefix': 'teqi'
'body': 'teqi ${1:"source == "}, ${2:"value"}'
'description': 'To run comparision r1 == constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Than Or Equal To Immediate':
'prefix': 'tgei'
'body': 'tgei ${1:"source >= "}, ${2:"value"}'
'description': 'To run comparision r1 >= constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than Unsigned':
'prefix': 'tltu'
'body': 'tltu ${1:"source < "}, ${2:"source"}'
'description': 'To run comparision r1 < r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Or Equal':
'prefix': 'tge'
'body': 'tge ${1:"source >="}, ${2:"source"}'
'description': 'To run comparision r1 >= r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than Immediate Unsigned':
'prefix': 'tltiu'
'body': 'tltiu ${1:"source < "}, ${2:"value"}'
'description': 'To run comparision r1 < constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Not Equal':
'prefix': 'tne'
'body': 'tne ${1:"source != "}, ${2:"source"}'
'description': 'To run comparision r1 != r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Not Equal Immediate':
'prefix': 'tnei'
'body': 'tnei ${1:"source != "}, ${2:"value"}'
'description': 'To run comparision r1 != constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Or Equal Unsigned':
'prefix': 'tgeu'
'body': 'tgeu ${1:"source >= "}, ${2:"source"}'
'description': 'To run comparision r1 >= r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than':
'prefix': 'tlt'
'body': 'tlt ${1:"source < "}, ${2:"source"}'
'description': 'To run comparision r1 < r2, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Less Than Immediate':
'prefix': 'tlti'
'body': 'tlti ${1:"source < "}, ${2:"valu"}'
'description': 'To run comparision r1 < constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Trap If Greater Or Equal Immediate Unsigned':
'prefix': 'tgeiu'
'body': 'tgeiu ${1:"source >="}, ${2:"source"}'
'description': 'To run comparision r1 >= constant, if true then trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
# Other Commands
'Negate':
'prefix': 'neg'
'body': '${1:"source ="}, ${2:"-1 * source"}'
'description': 'The value is negated, and place into a register'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'No Operation':
'prefix': 'nop'
'body': 'nop'
'description': 'To perform no operation'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Break':
'prefix': 'break'
'body': 'break'
'description': 'To cause a Breakpoint exeception'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Debug Exeception Return':
'prefix': 'deret'
'body': 'deret'
'description': 'To return from a debug exeception'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'System Call':
'prefix': 'syscall'
'body': 'syscall'
'description': 'To cause a system call'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
'Exeception Return':
'prefix': 'eret'
'body': 'eret'
'description': 'To return from interrupt, exeception, or error trap'
'leftLabelHTML': '<span style="font-weight: bold; color:#038c7d">MIPS</span>'
'descriptionMoreURL': 'https://www.cs.cornell.edu/courses/cs3410/2008fa/MIPS_Vol2.pdf'
|
[
{
"context": "###\n@Author: Kristinita\n@Date:\t 2017-04-09 09:17:06\n@Last Modified time: ",
"end": 23,
"score": 0.9997648596763611,
"start": 13,
"tag": "NAME",
"value": "Kristinita"
}
] | themes/sashapelican/static/coffee/Clipboard-js/Clipboard.coffee | Kristinita/KristinitaPelicanCI | 0 | ###
@Author: Kristinita
@Date: 2017-04-09 09:17:06
@Last Modified time: 2018-05-04 08:57:40
###
################
# Clipboard.js #
################
###
Activate Clipboard.js for .SashaButton class
[DEPRECATED] Works without DOM initialization
http://ru.stackoverflow.com/a/582520/199934
[DEPRECATED] For Rainbow: http://stackoverflow.com/a/33758293/5951529
[NEW] For SuperFences: https://stackoverflow.com/a/33758435/5951529
###
new Clipboard('.SashaButton', text: (trigger) ->
$(trigger).closest('.SashaBlockHighlight').find('pre').text()
)
| 192580 | ###
@Author: <NAME>
@Date: 2017-04-09 09:17:06
@Last Modified time: 2018-05-04 08:57:40
###
################
# Clipboard.js #
################
###
Activate Clipboard.js for .SashaButton class
[DEPRECATED] Works without DOM initialization
http://ru.stackoverflow.com/a/582520/199934
[DEPRECATED] For Rainbow: http://stackoverflow.com/a/33758293/5951529
[NEW] For SuperFences: https://stackoverflow.com/a/33758435/5951529
###
new Clipboard('.SashaButton', text: (trigger) ->
$(trigger).closest('.SashaBlockHighlight').find('pre').text()
)
| true | ###
@Author: PI:NAME:<NAME>END_PI
@Date: 2017-04-09 09:17:06
@Last Modified time: 2018-05-04 08:57:40
###
################
# Clipboard.js #
################
###
Activate Clipboard.js for .SashaButton class
[DEPRECATED] Works without DOM initialization
http://ru.stackoverflow.com/a/582520/199934
[DEPRECATED] For Rainbow: http://stackoverflow.com/a/33758293/5951529
[NEW] For SuperFences: https://stackoverflow.com/a/33758435/5951529
###
new Clipboard('.SashaButton', text: (trigger) ->
$(trigger).closest('.SashaBlockHighlight').find('pre').text()
)
|
[
{
"context": " db', (done) ->\n user1 = new User\n name: 'Dummy'\n mail: 'dummy@example.org'\n user1.save (",
"end": 271,
"score": 0.8685647249221802,
"start": 266,
"tag": "NAME",
"value": "Dummy"
},
{
"context": "user1 = new User\n name: 'Dummy'\n mail: 'dummy@example.org'\n user1.save (err, doc) ->\n should.not.ex",
"end": 303,
"score": 0.9999256134033203,
"start": 286,
"tag": "EMAIL",
"value": "dummy@example.org"
},
{
"context": "ame', (done) ->\n user2 = new User\n name: 'Dummy'\n mail: 'dummy@example.org'\n user2.save (",
"end": 514,
"score": 0.9088159799575806,
"start": 509,
"tag": "NAME",
"value": "Dummy"
},
{
"context": "user2 = new User\n name: 'Dummy'\n mail: 'dummy@example.org'\n user2.save (err, doc) ->\n should.exist(",
"end": 546,
"score": 0.999926745891571,
"start": 529,
"tag": "EMAIL",
"value": "dummy@example.org"
}
] | src/spec/models/user_models_test.coffee | henvo/express-dummy | 0 | should = require 'should'
mongoose = require 'mongoose'
User = mongoose.model('User')
describe 'User Model Test', ->
after (done) ->
User.remove {}, (err) ->
done() unless err
it 'should save user to db', (done) ->
user1 = new User
name: 'Dummy'
mail: 'dummy@example.org'
user1.save (err, doc) ->
should.not.exist(err)
should(doc).be.exactly(user1)
done()
it 'should not save user with same email or name', (done) ->
user2 = new User
name: 'Dummy'
mail: 'dummy@example.org'
user2.save (err, doc) ->
should.exist(err)
done()
| 222663 | should = require 'should'
mongoose = require 'mongoose'
User = mongoose.model('User')
describe 'User Model Test', ->
after (done) ->
User.remove {}, (err) ->
done() unless err
it 'should save user to db', (done) ->
user1 = new User
name: '<NAME>'
mail: '<EMAIL>'
user1.save (err, doc) ->
should.not.exist(err)
should(doc).be.exactly(user1)
done()
it 'should not save user with same email or name', (done) ->
user2 = new User
name: '<NAME>'
mail: '<EMAIL>'
user2.save (err, doc) ->
should.exist(err)
done()
| true | should = require 'should'
mongoose = require 'mongoose'
User = mongoose.model('User')
describe 'User Model Test', ->
after (done) ->
User.remove {}, (err) ->
done() unless err
it 'should save user to db', (done) ->
user1 = new User
name: 'PI:NAME:<NAME>END_PI'
mail: 'PI:EMAIL:<EMAIL>END_PI'
user1.save (err, doc) ->
should.not.exist(err)
should(doc).be.exactly(user1)
done()
it 'should not save user with same email or name', (done) ->
user2 = new User
name: 'PI:NAME:<NAME>END_PI'
mail: 'PI:EMAIL:<EMAIL>END_PI'
user2.save (err, doc) ->
should.exist(err)
done()
|
[
{
"context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'PlLd'\n\n constructor: (layer, length) ->\n super(lay",
"end": 210,
"score": 0.9950593709945679,
"start": 206,
"tag": "KEY",
"value": "PlLd"
}
] | src/psd/layer_info/placed_layer.coffee | taofei-pro/psd.js | 0 | LayerInfo = require '../layer_info.coffee'
Util = require '../util.coffee'
Descriptor = require '../descriptor.coffee'
module.exports = class UnicodeName extends LayerInfo
@shouldParse: (key) -> key is 'PlLd'
constructor: (layer, length) ->
super(layer, length)
@Trnf = []
parse: ->
@identifier = @file.readString()
@version = @file.readInt()
len = Util.pad2 @file.readByte()
@Idnt = @file.readString(len)
@PgNm = @file.parseInt();
@totalPages = @file.parseInt();
@Annt = @file.readInt();
@Type = @file.readInt();
@parseTransformInfo()
@warpValue = @file.readInt()
@file.seek 4, true
@warpData = new Descriptor(@file).parse()
return @
parseTransformInfo: ->
count = 8
for i in [0...count]
@Trnf.push @file.readDouble() | 113836 | LayerInfo = require '../layer_info.coffee'
Util = require '../util.coffee'
Descriptor = require '../descriptor.coffee'
module.exports = class UnicodeName extends LayerInfo
@shouldParse: (key) -> key is '<KEY>'
constructor: (layer, length) ->
super(layer, length)
@Trnf = []
parse: ->
@identifier = @file.readString()
@version = @file.readInt()
len = Util.pad2 @file.readByte()
@Idnt = @file.readString(len)
@PgNm = @file.parseInt();
@totalPages = @file.parseInt();
@Annt = @file.readInt();
@Type = @file.readInt();
@parseTransformInfo()
@warpValue = @file.readInt()
@file.seek 4, true
@warpData = new Descriptor(@file).parse()
return @
parseTransformInfo: ->
count = 8
for i in [0...count]
@Trnf.push @file.readDouble() | true | LayerInfo = require '../layer_info.coffee'
Util = require '../util.coffee'
Descriptor = require '../descriptor.coffee'
module.exports = class UnicodeName extends LayerInfo
@shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI'
constructor: (layer, length) ->
super(layer, length)
@Trnf = []
parse: ->
@identifier = @file.readString()
@version = @file.readInt()
len = Util.pad2 @file.readByte()
@Idnt = @file.readString(len)
@PgNm = @file.parseInt();
@totalPages = @file.parseInt();
@Annt = @file.readInt();
@Type = @file.readInt();
@parseTransformInfo()
@warpValue = @file.readInt()
@file.seek 4, true
@warpData = new Descriptor(@file).parse()
return @
parseTransformInfo: ->
count = 8
for i in [0...count]
@Trnf.push @file.readDouble() |
[
{
"context": "onfig: meshbluConfig\n mongoDbUri: 'mongodb://127.0.0.1/test-uuid-alias-service'\n\n @server = new Serve",
"end": 564,
"score": 0.9875825047492981,
"start": 555,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " new Datastore\n database: mongojs 'mongodb://127.0.0.1/test-uuid-alias-service'\n collection",
"end": 932,
"score": 0.7644376158714294,
"start": 931,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "w Datastore\n database: mongojs 'mongodb://127.0.0.1/test-uuid-alias-service'\n collection: 'alias",
"end": 940,
"score": 0.7425282597541809,
"start": 935,
"tag": "IP_ADDRESS",
"value": "0.0.1"
},
{
"context": "(done) ->\n auth =\n username: '899801b3-e877-4c69-93db-89bd9787ceea'\n password: 'us",
"end": 1533,
"score": 0.9697843194007874,
"start": 1520,
"tag": "PASSWORD",
"value": "899801b3-e877"
},
{
"context": " auth =\n username: '899801b3-e877-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n al",
"end": 1556,
"score": 0.999459981918335,
"start": 1534,
"tag": "PASSWORD",
"value": "4c69-93db-89bd9787ceea"
},
{
"context": "77-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n alias =\n name: 'undeterred",
"end": 1591,
"score": 0.9994142651557922,
"start": 1581,
"tag": "PASSWORD",
"value": "user-token"
},
{
"context": "(done) ->\n auth =\n username: '899801b3-e877-4c69-93db-89bd9787ceea'\n password:",
"end": 2531,
"score": 0.9464840292930603,
"start": 2523,
"tag": "USERNAME",
"value": "899801b3"
},
{
"context": "\n auth =\n username: '899801b3-e877-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n al",
"end": 2559,
"score": 0.8975123763084412,
"start": 2532,
"tag": "PASSWORD",
"value": "e877-4c69-93db-89bd9787ceea"
},
{
"context": "77-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n alias =\n name: '☃.💩'\n ",
"end": 2594,
"score": 0.9994549751281738,
"start": 2584,
"tag": "PASSWORD",
"value": "user-token"
},
{
"context": "e) ->\n auth =\n username: '899801b3-e877-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n ",
"end": 3581,
"score": 0.9972537755966187,
"start": 3545,
"tag": "PASSWORD",
"value": "899801b3-e877-4c69-93db-89bd9787ceea"
},
{
"context": "-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n alias =\n name: 'c38b94",
"end": 3618,
"score": 0.999401867389679,
"start": 3608,
"tag": "PASSWORD",
"value": "user-token"
},
{
"context": "e) ->\n auth =\n username: '899801b3-e877-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n ",
"end": 4619,
"score": 0.9911900758743286,
"start": 4583,
"tag": "PASSWORD",
"value": "899801b3-e877-4c69-93db-89bd9787ceea"
},
{
"context": "-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n alias =\n name: undefin",
"end": 4656,
"score": 0.9993829727172852,
"start": 4646,
"tag": "PASSWORD",
"value": "user-token"
},
{
"context": "e) ->\n auth =\n username: '899801b3-e877-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n ",
"end": 5599,
"score": 0.999403178691864,
"start": 5563,
"tag": "PASSWORD",
"value": "899801b3-e877-4c69-93db-89bd9787ceea"
},
{
"context": "-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n alias =\n name: 'burlap",
"end": 5636,
"score": 0.9994290471076965,
"start": 5626,
"tag": "PASSWORD",
"value": "user-token"
},
{
"context": "e) ->\n auth =\n username: '899801b3-e877-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n ",
"end": 6565,
"score": 0.9984672665596008,
"start": 6529,
"tag": "PASSWORD",
"value": "899801b3-e877-4c69-93db-89bd9787ceea"
},
{
"context": "-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n alias =\n name: 'burlap",
"end": 6602,
"score": 0.9994432330131531,
"start": 6592,
"tag": "PASSWORD",
"value": "user-token"
},
{
"context": "(done) ->\n auth =\n username: '899801b3-e877-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n al",
"end": 7601,
"score": 0.9994503259658813,
"start": 7565,
"tag": "PASSWORD",
"value": "899801b3-e877-4c69-93db-89bd9787ceea"
},
{
"context": "77-4c69-93db-89bd9787ceea'\n password: 'user-token'\n\n alias =\n name: 'undeterred",
"end": 7636,
"score": 0.9993460774421692,
"start": 7626,
"tag": "PASSWORD",
"value": "user-token"
},
{
"context": "ach (done) ->\n auth =\n username: 'd9233797-95e5-44f8-9f33-4f3af80d436d'\n password:",
"end": 8549,
"score": 0.6075710654258728,
"start": 8542,
"tag": "USERNAME",
"value": "d923379"
},
{
"context": "ne) ->\n auth =\n username: 'd9233797-95e5-44f8-9f33-4f3af80d436d'\n password: 'other-user-token'\n\n ",
"end": 8578,
"score": 0.9013441205024719,
"start": 8549,
"tag": "PASSWORD",
"value": "7-95e5-44f8-9f33-4f3af80d436d"
},
{
"context": "95e5-44f8-9f33-4f3af80d436d'\n password: 'other-user-token'\n\n alias =\n name: 'accident'\n ",
"end": 8617,
"score": 0.9993869066238403,
"start": 8601,
"tag": "PASSWORD",
"value": "other-user-token"
}
] | test/integration/sub-aliases/create-subalias-integration-spec.coffee | joaoaneto/uuid-alias-service | 0 | http = require 'http'
request = require 'request'
shmock = require 'shmock'
Server = require '../../../src/server'
mongojs = require 'mongojs'
Datastore = require 'meshblu-core-datastore'
describe 'POST /aliases/chloroform', ->
beforeEach ->
@meshblu = shmock 0xd00d
afterEach (done) ->
@meshblu.close => done()
beforeEach (done) ->
meshbluConfig =
server: 'localhost'
port: 0xd00d
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig: meshbluConfig
mongoDbUri: 'mongodb://127.0.0.1/test-uuid-alias-service'
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
beforeEach ->
@whoamiHandler = @meshblu.get('/v2/whoami')
.reply(200, '{"uuid": "899801b3-e877-4c69-93db-89bd9787ceea"}')
beforeEach (done) ->
@datastore = new Datastore
database: mongojs 'mongodb://127.0.0.1/test-uuid-alias-service'
collection: 'aliases'
@datastore.remove {}, (error) => done() # delete everything
afterEach (done) ->
@server.stop => done()
context 'when given a valid sub alias', ->
context 'when the alias exists', ->
beforeEach (done) ->
@datastore.insert name: 'chloroform', uuid: '21560426-7338-450d-ab10-e477ef1908a6', owner: '899801b3-e877-4c69-93db-89bd9787ceea', subaliases: [], (error, @alias) =>
done error
context 'an ascii name', ->
beforeEach (done) ->
auth =
username: '899801b3-e877-4c69-93db-89bd9787ceea'
password: 'user-token'
alias =
name: 'undeterred.by.lack.of.training'
uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'create an alias in mongo', ->
expect(@alias.subaliases).to.contain name: 'undeterred.by.lack.of.training', uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
context 'a unicode name', ->
beforeEach (done) ->
auth =
username: '899801b3-e877-4c69-93db-89bd9787ceea'
password: 'user-token'
alias =
name: '☃.💩'
uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'create an alias in mongo', ->
expect(@alias.subaliases).to.contain name: '☃.💩', uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
context 'when given an invalid sub-alias', ->
context 'when given a UUID as a name', ->
beforeEach (done) ->
auth =
username: '899801b3-e877-4c69-93db-89bd9787ceea'
password: 'user-token'
alias =
name: 'c38b942c-f851-4ef8-a5a0-65b0ea960a4c'
uuid: '48162884-d42f-4110-bdb2-9d17db996993'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'c38b942c-f851-4ef8-a5a0-65b0ea960a4c'
context 'when given an empty name', ->
beforeEach (done) ->
auth =
username: '899801b3-e877-4c69-93db-89bd9787ceea'
password: 'user-token'
alias =
name: undefined
uuid: 'ecca684d-68ba-47d9-bb93-5124f20936cc'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: undefined
context 'when given an empty uuid', ->
beforeEach (done) ->
auth =
username: '899801b3-e877-4c69-93db-89bd9787ceea'
password: 'user-token'
alias =
name: 'burlap-sack'
uuid: undefined
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'burlap-sack'
context 'when given non-uuid as the uuid', ->
beforeEach (done) ->
auth =
username: '899801b3-e877-4c69-93db-89bd9787ceea'
password: 'user-token'
alias =
name: 'burlap-sack'
uuid: 'billy-club'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'burlap-sack'
context 'when given a valid sub alias', ->
context 'when the alias does not exist', ->
context 'an ascii name', ->
beforeEach (done) ->
auth =
username: '899801b3-e877-4c69-93db-89bd9787ceea'
password: 'user-token'
alias =
name: 'undeterred.by.lack.of.training'
uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/velocity", options, (error, @response, @body) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 404', ->
expect(@response.statusCode).to.equal 404
context 'when a different user', ->
context 'when the alias exists', ->
beforeEach (done) ->
@datastore.insert name: 'poor-trunk-ventilation', uuid: '21560426-7338-450d-ab10-e477ef1908a6', owner: '899801b3-e877-4c69-93db-89bd9787ceea', subaliases: [], (error, @alias) =>
done error
beforeEach (done) ->
auth =
username: 'd9233797-95e5-44f8-9f33-4f3af80d436d'
password: 'other-user-token'
alias =
name: 'accident'
uuid: '65255089-6ed8-4a75-853a-90825a6525c3'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/poor-trunk-ventilation", options, (error, @response, @body) =>
done error
it 'should authenticate with meshblu', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with 403', ->
expect(@response.statusCode).to.equal 403
beforeEach (done) ->
@datastore.findOne name: 'poor-trunk-ventilation', (error, @alias) =>
done error
it 'should not add a subalias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'accident', uuid: '65255089-6ed8-4a75-853a-90825a6525c3'
| 189545 | http = require 'http'
request = require 'request'
shmock = require 'shmock'
Server = require '../../../src/server'
mongojs = require 'mongojs'
Datastore = require 'meshblu-core-datastore'
describe 'POST /aliases/chloroform', ->
beforeEach ->
@meshblu = shmock 0xd00d
afterEach (done) ->
@meshblu.close => done()
beforeEach (done) ->
meshbluConfig =
server: 'localhost'
port: 0xd00d
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig: meshbluConfig
mongoDbUri: 'mongodb://127.0.0.1/test-uuid-alias-service'
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
beforeEach ->
@whoamiHandler = @meshblu.get('/v2/whoami')
.reply(200, '{"uuid": "899801b3-e877-4c69-93db-89bd9787ceea"}')
beforeEach (done) ->
@datastore = new Datastore
database: mongojs 'mongodb://127.0.0.1/test-uuid-alias-service'
collection: 'aliases'
@datastore.remove {}, (error) => done() # delete everything
afterEach (done) ->
@server.stop => done()
context 'when given a valid sub alias', ->
context 'when the alias exists', ->
beforeEach (done) ->
@datastore.insert name: 'chloroform', uuid: '21560426-7338-450d-ab10-e477ef1908a6', owner: '899801b3-e877-4c69-93db-89bd9787ceea', subaliases: [], (error, @alias) =>
done error
context 'an ascii name', ->
beforeEach (done) ->
auth =
username: '<PASSWORD>-<PASSWORD>'
password: '<PASSWORD>'
alias =
name: 'undeterred.by.lack.of.training'
uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'create an alias in mongo', ->
expect(@alias.subaliases).to.contain name: 'undeterred.by.lack.of.training', uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
context 'a unicode name', ->
beforeEach (done) ->
auth =
username: '899801b3-<PASSWORD>'
password: '<PASSWORD>'
alias =
name: '☃.💩'
uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'create an alias in mongo', ->
expect(@alias.subaliases).to.contain name: '☃.💩', uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
context 'when given an invalid sub-alias', ->
context 'when given a UUID as a name', ->
beforeEach (done) ->
auth =
username: '<PASSWORD>'
password: '<PASSWORD>'
alias =
name: 'c38b942c-f851-4ef8-a5a0-65b0ea960a4c'
uuid: '48162884-d42f-4110-bdb2-9d17db996993'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'c38b942c-f851-4ef8-a5a0-65b0ea960a4c'
context 'when given an empty name', ->
beforeEach (done) ->
auth =
username: '<PASSWORD>'
password: '<PASSWORD>'
alias =
name: undefined
uuid: 'ecca684d-68ba-47d9-bb93-5124f20936cc'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: undefined
context 'when given an empty uuid', ->
beforeEach (done) ->
auth =
username: '<PASSWORD>'
password: '<PASSWORD>'
alias =
name: 'burlap-sack'
uuid: undefined
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'burlap-sack'
context 'when given non-uuid as the uuid', ->
beforeEach (done) ->
auth =
username: '<PASSWORD>'
password: '<PASSWORD>'
alias =
name: 'burlap-sack'
uuid: 'billy-club'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'burlap-sack'
context 'when given a valid sub alias', ->
context 'when the alias does not exist', ->
context 'an ascii name', ->
beforeEach (done) ->
auth =
username: '<PASSWORD>'
password: '<PASSWORD>'
alias =
name: 'undeterred.by.lack.of.training'
uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/velocity", options, (error, @response, @body) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 404', ->
expect(@response.statusCode).to.equal 404
context 'when a different user', ->
context 'when the alias exists', ->
beforeEach (done) ->
@datastore.insert name: 'poor-trunk-ventilation', uuid: '21560426-7338-450d-ab10-e477ef1908a6', owner: '899801b3-e877-4c69-93db-89bd9787ceea', subaliases: [], (error, @alias) =>
done error
beforeEach (done) ->
auth =
username: 'd923379<PASSWORD>'
password: '<PASSWORD>'
alias =
name: 'accident'
uuid: '65255089-6ed8-4a75-853a-90825a6525c3'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/poor-trunk-ventilation", options, (error, @response, @body) =>
done error
it 'should authenticate with meshblu', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with 403', ->
expect(@response.statusCode).to.equal 403
beforeEach (done) ->
@datastore.findOne name: 'poor-trunk-ventilation', (error, @alias) =>
done error
it 'should not add a subalias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'accident', uuid: '65255089-6ed8-4a75-853a-90825a6525c3'
| true | http = require 'http'
request = require 'request'
shmock = require 'shmock'
Server = require '../../../src/server'
mongojs = require 'mongojs'
Datastore = require 'meshblu-core-datastore'
describe 'POST /aliases/chloroform', ->
beforeEach ->
@meshblu = shmock 0xd00d
afterEach (done) ->
@meshblu.close => done()
beforeEach (done) ->
meshbluConfig =
server: 'localhost'
port: 0xd00d
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig: meshbluConfig
mongoDbUri: 'mongodb://127.0.0.1/test-uuid-alias-service'
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
beforeEach ->
@whoamiHandler = @meshblu.get('/v2/whoami')
.reply(200, '{"uuid": "899801b3-e877-4c69-93db-89bd9787ceea"}')
beforeEach (done) ->
@datastore = new Datastore
database: mongojs 'mongodb://127.0.0.1/test-uuid-alias-service'
collection: 'aliases'
@datastore.remove {}, (error) => done() # delete everything
afterEach (done) ->
@server.stop => done()
context 'when given a valid sub alias', ->
context 'when the alias exists', ->
beforeEach (done) ->
@datastore.insert name: 'chloroform', uuid: '21560426-7338-450d-ab10-e477ef1908a6', owner: '899801b3-e877-4c69-93db-89bd9787ceea', subaliases: [], (error, @alias) =>
done error
context 'an ascii name', ->
beforeEach (done) ->
auth =
username: 'PI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
alias =
name: 'undeterred.by.lack.of.training'
uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'create an alias in mongo', ->
expect(@alias.subaliases).to.contain name: 'undeterred.by.lack.of.training', uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
context 'a unicode name', ->
beforeEach (done) ->
auth =
username: '899801b3-PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
alias =
name: '☃.💩'
uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 201', ->
expect(@response.statusCode).to.equal 201
it 'create an alias in mongo', ->
expect(@alias.subaliases).to.contain name: '☃.💩', uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
context 'when given an invalid sub-alias', ->
context 'when given a UUID as a name', ->
beforeEach (done) ->
auth =
username: 'PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
alias =
name: 'c38b942c-f851-4ef8-a5a0-65b0ea960a4c'
uuid: '48162884-d42f-4110-bdb2-9d17db996993'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'c38b942c-f851-4ef8-a5a0-65b0ea960a4c'
context 'when given an empty name', ->
beforeEach (done) ->
auth =
username: 'PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
alias =
name: undefined
uuid: 'ecca684d-68ba-47d9-bb93-5124f20936cc'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: undefined
context 'when given an empty uuid', ->
beforeEach (done) ->
auth =
username: 'PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
alias =
name: 'burlap-sack'
uuid: undefined
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'burlap-sack'
context 'when given non-uuid as the uuid', ->
beforeEach (done) ->
auth =
username: 'PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
alias =
name: 'burlap-sack'
uuid: 'billy-club'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/chloroform", options, (error, @response, @body) =>
done error
beforeEach (done) ->
@datastore.findOne name: 'chloroform', (error, @alias) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 422', ->
expect(@response.statusCode).to.equal 422
it 'should not create an alias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'burlap-sack'
context 'when given a valid sub alias', ->
context 'when the alias does not exist', ->
context 'an ascii name', ->
beforeEach (done) ->
auth =
username: 'PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
alias =
name: 'undeterred.by.lack.of.training'
uuid: 'b38d4757-6f91-4aee-8ffb-ff53abc796a2'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/velocity", options, (error, @response, @body) =>
done error
it 'should call the whoamiHandler', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with a 404', ->
expect(@response.statusCode).to.equal 404
context 'when a different user', ->
context 'when the alias exists', ->
beforeEach (done) ->
@datastore.insert name: 'poor-trunk-ventilation', uuid: '21560426-7338-450d-ab10-e477ef1908a6', owner: '899801b3-e877-4c69-93db-89bd9787ceea', subaliases: [], (error, @alias) =>
done error
beforeEach (done) ->
auth =
username: 'd923379PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
alias =
name: 'accident'
uuid: '65255089-6ed8-4a75-853a-90825a6525c3'
options =
auth: auth
json: alias
request.post "http://localhost:#{@serverPort}/aliases/poor-trunk-ventilation", options, (error, @response, @body) =>
done error
it 'should authenticate with meshblu', ->
expect(@whoamiHandler.isDone).to.be.true
it 'should respond with 403', ->
expect(@response.statusCode).to.equal 403
beforeEach (done) ->
@datastore.findOne name: 'poor-trunk-ventilation', (error, @alias) =>
done error
it 'should not add a subalias in mongo', ->
expect(@alias.subaliases).to.not.contain name: 'accident', uuid: '65255089-6ed8-4a75-853a-90825a6525c3'
|
[
{
"context": " 0, 0, 1\n 1, 1, 0\n]\nkids =\n brother:\n name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: ",
"end": 601,
"score": 0.9998713731765747,
"start": 598,
"tag": "NAME",
"value": "Max"
},
{
"context": " name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: 9\n\nouter = 1\nchangeNumbers = ->\n inne",
"end": 640,
"score": 0.9998502731323242,
"start": 637,
"tag": "NAME",
"value": "Ida"
},
{
"context": "lver = second\n rest = others\ncontenders = [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"",
"end": 897,
"score": 0.999815821647644,
"start": 883,
"tag": "NAME",
"value": "Michael Phelps"
},
{
"context": "t = others\ncontenders = [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"",
"end": 911,
"score": 0.9997791647911072,
"start": 902,
"tag": "NAME",
"value": "Liu Xiang"
},
{
"context": "ontenders = [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Seb",
"end": 924,
"score": 0.9998114705085754,
"start": 916,
"tag": "NAME",
"value": "Yao Ming"
},
{
"context": "\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingji",
"end": 942,
"score": 0.9998499751091003,
"start": 929,
"tag": "NAME",
"value": "Allyson Felix"
},
{
"context": "\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n",
"end": 960,
"score": 0.9998174905776978,
"start": 947,
"tag": "NAME",
"value": "Shawn Johnson"
},
{
"context": "\"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n",
"end": 977,
"score": 0.9998506307601929,
"start": 965,
"tag": "NAME",
"value": "Roman Sebrle"
},
{
"context": "yson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\n",
"end": 994,
"score": 0.9998672008514404,
"start": 982,
"tag": "NAME",
"value": "Guo Jingjing"
},
{
"context": "awn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\nawardMedals co",
"end": 1008,
"score": 0.9998302459716797,
"start": 999,
"tag": "NAME",
"value": "Tyson Gay"
},
{
"context": " \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\nawardMedals contenders...\nconso",
"end": 1025,
"score": 0.9998458027839661,
"start": 1013,
"tag": "NAME",
"value": "Asafa Powell"
},
{
"context": " \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\nawardMedals contenders...\nconsole.log \"Gold: \"",
"end": 1040,
"score": 0.9998524188995361,
"start": 1030,
"tag": "NAME",
"value": "Usain Bolt"
},
{
"context": "ert \"Galloping...\"\n super 45\n\nsam = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\nsam.move()\n",
"end": 2777,
"score": 0.9185106158256531,
"start": 2761,
"tag": "NAME",
"value": "Sammy the Python"
},
{
"context": "m = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\nsam.move()\ntom.move()\n\nString::dasherize = ->\n ",
"end": 2814,
"score": 0.9309378266334534,
"start": 2796,
"tag": "NAME",
"value": "Tommy the Palomino"
},
{
"context": "erReport \"Berkeley, CA\"\n\nfuturists =\n sculptor: \"Umberto Boccioni\"\n painter: \"Vladimir Burliuk\"\n poet:\n name:",
"end": 3147,
"score": 0.9998894929885864,
"start": 3131,
"tag": "NAME",
"value": "Umberto Boccioni"
},
{
"context": "sts =\n sculptor: \"Umberto Boccioni\"\n painter: \"Vladimir Burliuk\"\n poet:\n name: \"F.T. Marinetti\"\n address",
"end": 3178,
"score": 0.999889075756073,
"start": 3162,
"tag": "NAME",
"value": "Vladimir Burliuk"
},
{
"context": "painter: \"Vladimir Burliuk\"\n poet:\n name: \"F.T. Marinetti\"\n address: [\n \"Via Roma 42R\"\n \"Bella",
"end": 3215,
"score": 0.999890923500061,
"start": 3201,
"tag": "NAME",
"value": "F.T. Marinetti"
},
{
"context": "> cholesterol > 60\nconsole.log healthy\n\nauthor = \"Wittgenstein\"\nquote = \"A picture is a fact. -- #{ author }\"\ns",
"end": 4528,
"score": 0.9995108842849731,
"start": 4516,
"tag": "NAME",
"value": "Wittgenstein"
},
{
"context": " a decent approximation of π\"\n\nmobyDick = \"Call me Ishmael. Some years ago --\n never mind how long precisel",
"end": 4661,
"score": 0.8357759714126587,
"start": 4654,
"tag": "NAME",
"value": "Ishmael"
}
] | testcoffee/simple.coffee | quchunguang/test | 1 | # [Ref]: http://coffee-script.org/
number = 42
opposite = true
number = -42 if opposite
square = (x) -> x * x
list = [1, 2, 3, 4, 5]
math =
root: Math.sqrt
square: square
cube: (x) -> x * square(x)
race = (winner, runner) -> console.log winner, runner
race number, opposite
alert "I new it" if elvis?
cubs = (math.cube num for num in list)
console.log "number = " + square(number)
fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
console.log fill 'OK'
bitlist = [
1, 0, 1
0, 0, 1
1, 1, 0
]
kids =
brother:
name: "Max"
age: 11
sister:
name: "Ida"
age: 9
outer = 1
changeNumbers = ->
inner = -1
outer = 10
inner = changeNumbers()
gold = silver = rest = "unknown"
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
"Michael Phelps"
"Liu Xiang"
"Yao Ming"
"Allyson Felix"
"Shawn Johnson"
"Roman Sebrle"
"Guo Jingjing"
"Tyson Gay"
"Asafa Powell"
"Usain Bolt"
]
awardMedals contenders...
console.log "Gold: " + gold
console.log "Silver: " + silver
console.log "The Field: " + rest
eat = console.log
menu = (s...) -> console.log "*", s
# 吃午饭.
eat food for food in ['toast', 'cheese', 'wine']
# 精致的五道菜.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses
# 注重健康的一餐.
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
countdown = (num for num in [10..1] by -2)
console.log countdown
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
console.log ages
# 摇篮曲
num = 6
lyrics = while num -= 1
"#{num} little monkeys, jumping on the bed.
One fell out and bumped his head."
console.log lyrics
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
grade = (student) ->
if student.excellentWork
"A+"
else if student.okayStuff
if student.triedHard then "B" else "B-"
else
"C"
eldest = if 24 > 21 then "Liz" else "Ike"
six = (one = 1) + (two = 2) + (three = 3)
# 前十个全局属性(变量).
window = {'a':1, 'b':2, 'c':3, 'd':4}
globals = (name for name of window)[0...2]
console.log globals
alert = console.log
alert(
try
nonexistent / undefined
catch error
"And the error is ... #{error}"
)
solipsism = true if mind? and not world?
speed = 1
speed ?= 15
footprints = yeti ? "bear"
# zip = lottery.drawWinner?().address?.zipcode
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
sam.move()
tom.move()
String::dasherize = ->
this.replace /_/g, "-"
theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [theSwitch, theBait]
weatherReport = (location) ->
# 发起一个 Ajax 请求获取天气...
[location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
futurists =
sculptor: "Umberto Boccioni"
painter: "Vladimir Burliuk"
poet:
name: "F.T. Marinetti"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{poet: {name, address: [street, city]}} = futurists
tag = "<impossible>"
[open, contents..., close] = tag.split("")
# text = "Every literary critic believes he will outwit history and have the last word"
# [first, ..., last] = text.split " "
class Person
constructor: (options) ->
{@name, @age, @height} = options
tim = new Person age: 4
Account = (customer, cart) ->
@customer = customer
@cart = cart
$('.shopping_cart').bind 'click', (event) =>
@customer.purchase @cart
hi = `function() {
return [document.title, "Hello JavaScript"].join(": ");
}`
day = "Tue"
go = (work) -> console.log ("go " + work)
switch day
when "Mon" then go "work"
when "Tue" then go "relax"
when "Thu" then go "iceFishing"
when "Fri", "Sat"
if day is bingoDay
go "bingo"
go "dancing"
when "Sun" then go "church"
else go "work"
score = 76
grade = switch
when score < 60 then 'F'
when score < 70 then 'D'
when score < 80 then 'C'
when score < 90 then 'B'
else 'A'
# grade == 'C'
try
allHellBreaksLoose()
catsAndDogsLivingTogether()
catch error
console.log error
finally
console.log "cleanUp()"
cholesterol = 127
healthy = 200 > cholesterol > 60
console.log healthy
author = "Wittgenstein"
quote = "A picture is a fact. -- #{ author }"
sentence = "#{ 22 / 7 } is a decent approximation of π"
mobyDick = "Call me Ishmael. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
html = """
<strong>
cup of coffeescript
</strong>
"""
###
SkinnyMochaHalfCaffScript Compiler v1.0
Released under the MIT License
###
OPERATOR = /// ^ (
?: [-=]> # 函数
| [-+*/%<>&|^!?=]= # 复合赋值 / 比较
| >>>=? # 补 0 右移
| ([-+:])\1 # 双写
| ([&|<>])\2=? # 逻辑 / 移位
| \?\. # soak 访问
| \.{2,3} # 范围或者 splat
) ///
| 91741 | # [Ref]: http://coffee-script.org/
number = 42
opposite = true
number = -42 if opposite
square = (x) -> x * x
list = [1, 2, 3, 4, 5]
math =
root: Math.sqrt
square: square
cube: (x) -> x * square(x)
race = (winner, runner) -> console.log winner, runner
race number, opposite
alert "I new it" if elvis?
cubs = (math.cube num for num in list)
console.log "number = " + square(number)
fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
console.log fill 'OK'
bitlist = [
1, 0, 1
0, 0, 1
1, 1, 0
]
kids =
brother:
name: "<NAME>"
age: 11
sister:
name: "<NAME>"
age: 9
outer = 1
changeNumbers = ->
inner = -1
outer = 10
inner = changeNumbers()
gold = silver = rest = "unknown"
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
awardMedals contenders...
console.log "Gold: " + gold
console.log "Silver: " + silver
console.log "The Field: " + rest
eat = console.log
menu = (s...) -> console.log "*", s
# 吃午饭.
eat food for food in ['toast', 'cheese', 'wine']
# 精致的五道菜.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses
# 注重健康的一餐.
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
countdown = (num for num in [10..1] by -2)
console.log countdown
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
console.log ages
# 摇篮曲
num = 6
lyrics = while num -= 1
"#{num} little monkeys, jumping on the bed.
One fell out and bumped his head."
console.log lyrics
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
grade = (student) ->
if student.excellentWork
"A+"
else if student.okayStuff
if student.triedHard then "B" else "B-"
else
"C"
eldest = if 24 > 21 then "Liz" else "Ike"
six = (one = 1) + (two = 2) + (three = 3)
# 前十个全局属性(变量).
window = {'a':1, 'b':2, 'c':3, 'd':4}
globals = (name for name of window)[0...2]
console.log globals
alert = console.log
alert(
try
nonexistent / undefined
catch error
"And the error is ... #{error}"
)
solipsism = true if mind? and not world?
speed = 1
speed ?= 15
footprints = yeti ? "bear"
# zip = lottery.drawWinner?().address?.zipcode
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
sam = new Snake "<NAME>"
tom = new Horse "<NAME>"
sam.move()
tom.move()
String::dasherize = ->
this.replace /_/g, "-"
theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [theSwitch, theBait]
weatherReport = (location) ->
# 发起一个 Ajax 请求获取天气...
[location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
futurists =
sculptor: "<NAME>"
painter: "<NAME>"
poet:
name: "<NAME>"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{poet: {name, address: [street, city]}} = futurists
tag = "<impossible>"
[open, contents..., close] = tag.split("")
# text = "Every literary critic believes he will outwit history and have the last word"
# [first, ..., last] = text.split " "
class Person
constructor: (options) ->
{@name, @age, @height} = options
tim = new Person age: 4
Account = (customer, cart) ->
@customer = customer
@cart = cart
$('.shopping_cart').bind 'click', (event) =>
@customer.purchase @cart
hi = `function() {
return [document.title, "Hello JavaScript"].join(": ");
}`
day = "Tue"
go = (work) -> console.log ("go " + work)
switch day
when "Mon" then go "work"
when "Tue" then go "relax"
when "Thu" then go "iceFishing"
when "Fri", "Sat"
if day is bingoDay
go "bingo"
go "dancing"
when "Sun" then go "church"
else go "work"
score = 76
grade = switch
when score < 60 then 'F'
when score < 70 then 'D'
when score < 80 then 'C'
when score < 90 then 'B'
else 'A'
# grade == 'C'
try
allHellBreaksLoose()
catsAndDogsLivingTogether()
catch error
console.log error
finally
console.log "cleanUp()"
cholesterol = 127
healthy = 200 > cholesterol > 60
console.log healthy
author = "<NAME>"
quote = "A picture is a fact. -- #{ author }"
sentence = "#{ 22 / 7 } is a decent approximation of π"
mobyDick = "Call me <NAME>. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
html = """
<strong>
cup of coffeescript
</strong>
"""
###
SkinnyMochaHalfCaffScript Compiler v1.0
Released under the MIT License
###
OPERATOR = /// ^ (
?: [-=]> # 函数
| [-+*/%<>&|^!?=]= # 复合赋值 / 比较
| >>>=? # 补 0 右移
| ([-+:])\1 # 双写
| ([&|<>])\2=? # 逻辑 / 移位
| \?\. # soak 访问
| \.{2,3} # 范围或者 splat
) ///
| true | # [Ref]: http://coffee-script.org/
number = 42
opposite = true
number = -42 if opposite
square = (x) -> x * x
list = [1, 2, 3, 4, 5]
math =
root: Math.sqrt
square: square
cube: (x) -> x * square(x)
race = (winner, runner) -> console.log winner, runner
race number, opposite
alert "I new it" if elvis?
cubs = (math.cube num for num in list)
console.log "number = " + square(number)
fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
console.log fill 'OK'
bitlist = [
1, 0, 1
0, 0, 1
1, 1, 0
]
kids =
brother:
name: "PI:NAME:<NAME>END_PI"
age: 11
sister:
name: "PI:NAME:<NAME>END_PI"
age: 9
outer = 1
changeNumbers = ->
inner = -1
outer = 10
inner = changeNumbers()
gold = silver = rest = "unknown"
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
awardMedals contenders...
console.log "Gold: " + gold
console.log "Silver: " + silver
console.log "The Field: " + rest
eat = console.log
menu = (s...) -> console.log "*", s
# 吃午饭.
eat food for food in ['toast', 'cheese', 'wine']
# 精致的五道菜.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses
# 注重健康的一餐.
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
countdown = (num for num in [10..1] by -2)
console.log countdown
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
console.log ages
# 摇篮曲
num = 6
lyrics = while num -= 1
"#{num} little monkeys, jumping on the bed.
One fell out and bumped his head."
console.log lyrics
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
grade = (student) ->
if student.excellentWork
"A+"
else if student.okayStuff
if student.triedHard then "B" else "B-"
else
"C"
eldest = if 24 > 21 then "Liz" else "Ike"
six = (one = 1) + (two = 2) + (three = 3)
# 前十个全局属性(变量).
window = {'a':1, 'b':2, 'c':3, 'd':4}
globals = (name for name of window)[0...2]
console.log globals
alert = console.log
alert(
try
nonexistent / undefined
catch error
"And the error is ... #{error}"
)
solipsism = true if mind? and not world?
speed = 1
speed ?= 15
footprints = yeti ? "bear"
# zip = lottery.drawWinner?().address?.zipcode
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
sam = new Snake "PI:NAME:<NAME>END_PI"
tom = new Horse "PI:NAME:<NAME>END_PI"
sam.move()
tom.move()
String::dasherize = ->
this.replace /_/g, "-"
theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [theSwitch, theBait]
weatherReport = (location) ->
# 发起一个 Ajax 请求获取天气...
[location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
futurists =
sculptor: "PI:NAME:<NAME>END_PI"
painter: "PI:NAME:<NAME>END_PI"
poet:
name: "PI:NAME:<NAME>END_PI"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{poet: {name, address: [street, city]}} = futurists
tag = "<impossible>"
[open, contents..., close] = tag.split("")
# text = "Every literary critic believes he will outwit history and have the last word"
# [first, ..., last] = text.split " "
class Person
constructor: (options) ->
{@name, @age, @height} = options
tim = new Person age: 4
Account = (customer, cart) ->
@customer = customer
@cart = cart
$('.shopping_cart').bind 'click', (event) =>
@customer.purchase @cart
hi = `function() {
return [document.title, "Hello JavaScript"].join(": ");
}`
day = "Tue"
go = (work) -> console.log ("go " + work)
switch day
when "Mon" then go "work"
when "Tue" then go "relax"
when "Thu" then go "iceFishing"
when "Fri", "Sat"
if day is bingoDay
go "bingo"
go "dancing"
when "Sun" then go "church"
else go "work"
score = 76
grade = switch
when score < 60 then 'F'
when score < 70 then 'D'
when score < 80 then 'C'
when score < 90 then 'B'
else 'A'
# grade == 'C'
try
allHellBreaksLoose()
catsAndDogsLivingTogether()
catch error
console.log error
finally
console.log "cleanUp()"
cholesterol = 127
healthy = 200 > cholesterol > 60
console.log healthy
author = "PI:NAME:<NAME>END_PI"
quote = "A picture is a fact. -- #{ author }"
sentence = "#{ 22 / 7 } is a decent approximation of π"
mobyDick = "Call me PI:NAME:<NAME>END_PI. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
html = """
<strong>
cup of coffeescript
</strong>
"""
###
SkinnyMochaHalfCaffScript Compiler v1.0
Released under the MIT License
###
OPERATOR = /// ^ (
?: [-=]> # 函数
| [-+*/%<>&|^!?=]= # 复合赋值 / 比较
| >>>=? # 补 0 右移
| ([-+:])\1 # 双写
| ([&|<>])\2=? # 逻辑 / 移位
| \?\. # soak 访问
| \.{2,3} # 范围或者 splat
) ///
|
[
{
"context": "inCtrl', ($scope) ->\n $scope.data = {\n name: 'Gulangco Plate'\n }",
"end": 109,
"score": 0.9998499751091003,
"start": 95,
"tag": "NAME",
"value": "Gulangco Plate"
}
] | src/app/main/mainCtrl.coffee | SteefTheBeef/ng-gulp | 0 | angular.module('mainCtrl', []).controller 'mainCtrl', ($scope) ->
$scope.data = {
name: 'Gulangco Plate'
} | 167016 | angular.module('mainCtrl', []).controller 'mainCtrl', ($scope) ->
$scope.data = {
name: '<NAME>'
} | true | angular.module('mainCtrl', []).controller 'mainCtrl', ($scope) ->
$scope.data = {
name: 'PI:NAME:<NAME>END_PI'
} |
[
{
"context": "0 mins\n }\n redisStore: redisStore\n key: 'rememberme'\n secret: 'secret'\n}\n\ndescribe 'Remember me te",
"end": 584,
"score": 0.9153887033462524,
"start": 574,
"tag": "KEY",
"value": "rememberme"
},
{
"context": " before ->\n req.cookies.rememberme = 'stupidvalue'\n req.session = {}\n\n it 'should",
"end": 2029,
"score": 0.693118155002594,
"start": 2018,
"tag": "PASSWORD",
"value": "stupidvalue"
},
{
"context": "234'\n res.rememberme = {userid: '1234'}\n res.end()\n\n \n\n\n\n\n\n\n",
"end": 15452,
"score": 0.5530538558959961,
"start": 15450,
"tag": "USERNAME",
"value": "34"
}
] | test/rememberme-test.coffee | jamessharp/redis-rememberme | 1 | should = require 'should'
connect = require 'connect'
RedisStore = require('connect-redis')(connect)
RememberMe = require '../'
winston = require 'winston'
sinon = require 'sinon'
# Setup fake timers
clock = sinon.useFakeTimers('setInterval', 'Date')
# Remove the logging
winston.remove winston.transports.Console
# Get the cookie parser middleware
cookieParser = connect.middleware.cookieParser()
redisStore = new RedisStore {
db: 15
}
rememberMe = new RememberMe {
cookie: {
maxAge: 40 * 60 * 1000 # 40 mins
}
redisStore: redisStore
key: 'rememberme'
secret: 'secret'
}
describe 'Remember me tests', ->
req = {}
res = {}
resetMocks = ->
# Basic mock req, res
req = {
cookies: {}
headers: {}
connection: {}
session: {}
}
res = {
headers: {}
setHeader: (header, val) ->
this.headers[header] = val
}
before (done) ->
redisStore.client.flushall done
after ->
clock.restore()
beforeEach ->
resetMocks()
describe 'requests with no cookie', ->
it 'should not be given a user if no user is on the session', (done) ->
rememberMe req, res, ->
should.not.exist req.session.userid
done()
it 'should not remove the user if a user is on the session', (done) ->
req.session = {userid: '1234'}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
done()
it 'should not set a cookie', (done) ->
req.session = {userid: '1234'}
res.end = ->
should.not.exist res.headers['Set-Cookie']
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.end()
describe 'requests with bad cookie', ->
before ->
req.cookies.rememberme = 'stupidvalue'
req.session = {}
it 'should not be given a user if no user is on the session', (done) ->
rememberMe req, res, ->
should.not.exist req.session.userid
done()
it 'should not remove the user if a user is on the session', (done) ->
req.session = {userid: '1234'}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
done()
it 'should not set a cookie', (done) ->
req.session = {userid: '1234'}
res.end = ->
should.not.exist res.headers['Set-Cookie']
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.end()
describe 'setting the cookie', ->
it 'should set the cookie when res.rememberme is set', (done) ->
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should not set the cookie when res.remember me is set to a different userid than the session', (done) ->
req.session = {userid: '1234'}
res.end = ->
should.not.exist res.headers['Set-Cookie']
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '4567'}
res.end()
describe 'requests with correct cookie', ->
cookie = null
beforeEach (done) ->
# Set a remember me cookie
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie = res.headers['Set-Cookie'].split(';')[0] + ';'
resetMocks()
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should put a userid on the session if the correct cookie is present', (done) ->
req.headers.cookie = cookie
req.session = {}
req.cookies = null
res.end = ->
# Should get a new cookie
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
newcookie = res.headers['Set-Cookie'].split(';')[0] + ';'
newcookie.should.not.equal cookie
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
req.session.rememberme.should.be.true
res.end()
it 'shouldn\'t set a cookie if there is already a user on the session', (done) ->
req.headers.cookie = cookie
res.headers = {}
req.session = { userid: '1234' }
req.cookies = null
res.end = ->
# Should get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
it 'should authenticate after there has been a user on the session', (done) ->
this.timeout(0)
req.headers.cookie = cookie
res.headers = {}
req.session = { userid: '1234' }
req.cookies = null
res.end = ->
# Should get a new cookie
should.not.exist res.headers['Set-Cookie']
# Now log in with no session but a rememberme cookie
resetMocks()
req.headers.cookie = cookie
req.cookies = null
res.end = ->
# Should get a new cookie
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
newcookie = res.headers['Set-Cookie'].split(';')[0] + ';'
newcookie.should.not.equal cookie
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
describe 'request with stolen cookie', ->
stolenCookie = null
newcookie = null
before (done) ->
# Set a remember me cookie
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
stolenCookie = res.headers['Set-Cookie'].split(';')[0] + ';'
req.headers.cookie = stolenCookie
req.session = {}
req.cookies = null
res.end = ->
# Should get a new cookie
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
newcookie = res.headers['Set-Cookie'].split(';')[0] + ';'
newcookie.should.not.equal stolenCookie
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should not be possible to use a cookie twice', (done) ->
req.headers.cookie = stolenCookie
req.session = {}
req.cookies = null
res.headers = {}
res.end = ->
# Should not get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.not.exist req.session.userid
req.rememberme.stolen.should.be.true
res.end()
it 'should now have invalidated the use of all other remember me cookies as well', (done) ->
req.headers.cookie = newcookie
req.session = {}
req.cookies = null
res.headers = {}
res.end = ->
# Should not get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.not.exist req.session.userid
res.end()
describe 'destroying the cookie', ->
cookie1 = null
cookie2 = null
before (done) ->
# Create two remember me cookies
req.session = {userid: '1234'}
res.headers = {}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie1 = res.headers['Set-Cookie'].split(';')[0] + ';'
req.session = {userid: '1234'}
res.headers = {}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie2 = res.headers['Set-Cookie'].split(';')[0] + ';'
cookie2.should.not.equal cookie1
done()
it 'should not set a new cookie once destroyed', (done) ->
req.headers.cookie = cookie1
req.session = {}
req.cookies = null
res.headers = {}
res.end = ->
# Should not get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
req.rememberme.destroy()
res.end()
it 'should not be possible to log in with cookie1', (done) ->
req.headers.cookie = cookie1
req.session = {}
req.cookies = null
res.headers = {}
cookieParser req, res, ->
rememberMe req, res, ->
should.not.exist req.session.userid
done()
it 'should still be possible to log in with cookie2', (done) ->
req.headers.cookie = cookie2
req.session = {}
req.cookies = null
res.headers = {}
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
done()
describe 'expiry', ->
beforeEach (done) ->
# Create a cookie
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie = res.headers['Set-Cookie'].split(';')[0] + ';'
resetMocks()
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should expire everything after an hour (thats the runtime of the scheduled task)', (done) ->
clock.tick(3601 * 1000)
# Wait for the cleaned event and check that its all worked
rememberMe.worker.once 'cleaned', ->
# Now check the database and make sure everything has gone
redisStore.client.keys 'remme*', (err, replies) ->
should.not.exist err
replies.should.have.length 0
done()
it 'should not remove unexpired details though', (done) ->
# Tick the clock on 30 mins then create a new cookie
clock.tick(30 * 60 * 1000)
resetMocks()
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie = res.headers['Set-Cookie'].split(';')[0] + ';'
resetMocks()
# Tick the clock over the hour (forcing the cleanup to happen)
clock.tick 31 * 60 * 1000
rememberMe.worker.once 'cleaned', ->
# There should be one series and token left in the sets
multi = redisStore.client.multi()
multi.scard 'remme:1234:token'
multi.scard 'remme:1234:series'
multi.exec (err, replies) ->
should.not.exist err
replies[0].should.equal 1
replies[1].should.equal 1
# Now tick the clock on another hour (causing a fresh clean up)
# There should then be nothing left
clock.tick 60 * 60 * 1000
rememberMe.worker.once 'cleaned', ->
# Now check the database and make sure everything has gone
redisStore.client.keys 'remme*', (err, replies) ->
should.not.exist err
replies.should.have.length 0
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
| 133251 | should = require 'should'
connect = require 'connect'
RedisStore = require('connect-redis')(connect)
RememberMe = require '../'
winston = require 'winston'
sinon = require 'sinon'
# Setup fake timers
clock = sinon.useFakeTimers('setInterval', 'Date')
# Remove the logging
winston.remove winston.transports.Console
# Get the cookie parser middleware
cookieParser = connect.middleware.cookieParser()
redisStore = new RedisStore {
db: 15
}
rememberMe = new RememberMe {
cookie: {
maxAge: 40 * 60 * 1000 # 40 mins
}
redisStore: redisStore
key: '<KEY>'
secret: 'secret'
}
describe 'Remember me tests', ->
req = {}
res = {}
resetMocks = ->
# Basic mock req, res
req = {
cookies: {}
headers: {}
connection: {}
session: {}
}
res = {
headers: {}
setHeader: (header, val) ->
this.headers[header] = val
}
before (done) ->
redisStore.client.flushall done
after ->
clock.restore()
beforeEach ->
resetMocks()
describe 'requests with no cookie', ->
it 'should not be given a user if no user is on the session', (done) ->
rememberMe req, res, ->
should.not.exist req.session.userid
done()
it 'should not remove the user if a user is on the session', (done) ->
req.session = {userid: '1234'}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
done()
it 'should not set a cookie', (done) ->
req.session = {userid: '1234'}
res.end = ->
should.not.exist res.headers['Set-Cookie']
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.end()
describe 'requests with bad cookie', ->
before ->
req.cookies.rememberme = '<PASSWORD>'
req.session = {}
it 'should not be given a user if no user is on the session', (done) ->
rememberMe req, res, ->
should.not.exist req.session.userid
done()
it 'should not remove the user if a user is on the session', (done) ->
req.session = {userid: '1234'}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
done()
it 'should not set a cookie', (done) ->
req.session = {userid: '1234'}
res.end = ->
should.not.exist res.headers['Set-Cookie']
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.end()
describe 'setting the cookie', ->
it 'should set the cookie when res.rememberme is set', (done) ->
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should not set the cookie when res.remember me is set to a different userid than the session', (done) ->
req.session = {userid: '1234'}
res.end = ->
should.not.exist res.headers['Set-Cookie']
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '4567'}
res.end()
describe 'requests with correct cookie', ->
cookie = null
beforeEach (done) ->
# Set a remember me cookie
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie = res.headers['Set-Cookie'].split(';')[0] + ';'
resetMocks()
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should put a userid on the session if the correct cookie is present', (done) ->
req.headers.cookie = cookie
req.session = {}
req.cookies = null
res.end = ->
# Should get a new cookie
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
newcookie = res.headers['Set-Cookie'].split(';')[0] + ';'
newcookie.should.not.equal cookie
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
req.session.rememberme.should.be.true
res.end()
it 'shouldn\'t set a cookie if there is already a user on the session', (done) ->
req.headers.cookie = cookie
res.headers = {}
req.session = { userid: '1234' }
req.cookies = null
res.end = ->
# Should get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
it 'should authenticate after there has been a user on the session', (done) ->
this.timeout(0)
req.headers.cookie = cookie
res.headers = {}
req.session = { userid: '1234' }
req.cookies = null
res.end = ->
# Should get a new cookie
should.not.exist res.headers['Set-Cookie']
# Now log in with no session but a rememberme cookie
resetMocks()
req.headers.cookie = cookie
req.cookies = null
res.end = ->
# Should get a new cookie
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
newcookie = res.headers['Set-Cookie'].split(';')[0] + ';'
newcookie.should.not.equal cookie
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
describe 'request with stolen cookie', ->
stolenCookie = null
newcookie = null
before (done) ->
# Set a remember me cookie
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
stolenCookie = res.headers['Set-Cookie'].split(';')[0] + ';'
req.headers.cookie = stolenCookie
req.session = {}
req.cookies = null
res.end = ->
# Should get a new cookie
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
newcookie = res.headers['Set-Cookie'].split(';')[0] + ';'
newcookie.should.not.equal stolenCookie
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should not be possible to use a cookie twice', (done) ->
req.headers.cookie = stolenCookie
req.session = {}
req.cookies = null
res.headers = {}
res.end = ->
# Should not get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.not.exist req.session.userid
req.rememberme.stolen.should.be.true
res.end()
it 'should now have invalidated the use of all other remember me cookies as well', (done) ->
req.headers.cookie = newcookie
req.session = {}
req.cookies = null
res.headers = {}
res.end = ->
# Should not get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.not.exist req.session.userid
res.end()
describe 'destroying the cookie', ->
cookie1 = null
cookie2 = null
before (done) ->
# Create two remember me cookies
req.session = {userid: '1234'}
res.headers = {}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie1 = res.headers['Set-Cookie'].split(';')[0] + ';'
req.session = {userid: '1234'}
res.headers = {}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie2 = res.headers['Set-Cookie'].split(';')[0] + ';'
cookie2.should.not.equal cookie1
done()
it 'should not set a new cookie once destroyed', (done) ->
req.headers.cookie = cookie1
req.session = {}
req.cookies = null
res.headers = {}
res.end = ->
# Should not get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
req.rememberme.destroy()
res.end()
it 'should not be possible to log in with cookie1', (done) ->
req.headers.cookie = cookie1
req.session = {}
req.cookies = null
res.headers = {}
cookieParser req, res, ->
rememberMe req, res, ->
should.not.exist req.session.userid
done()
it 'should still be possible to log in with cookie2', (done) ->
req.headers.cookie = cookie2
req.session = {}
req.cookies = null
res.headers = {}
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
done()
describe 'expiry', ->
beforeEach (done) ->
# Create a cookie
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie = res.headers['Set-Cookie'].split(';')[0] + ';'
resetMocks()
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should expire everything after an hour (thats the runtime of the scheduled task)', (done) ->
clock.tick(3601 * 1000)
# Wait for the cleaned event and check that its all worked
rememberMe.worker.once 'cleaned', ->
# Now check the database and make sure everything has gone
redisStore.client.keys 'remme*', (err, replies) ->
should.not.exist err
replies.should.have.length 0
done()
it 'should not remove unexpired details though', (done) ->
# Tick the clock on 30 mins then create a new cookie
clock.tick(30 * 60 * 1000)
resetMocks()
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie = res.headers['Set-Cookie'].split(';')[0] + ';'
resetMocks()
# Tick the clock over the hour (forcing the cleanup to happen)
clock.tick 31 * 60 * 1000
rememberMe.worker.once 'cleaned', ->
# There should be one series and token left in the sets
multi = redisStore.client.multi()
multi.scard 'remme:1234:token'
multi.scard 'remme:1234:series'
multi.exec (err, replies) ->
should.not.exist err
replies[0].should.equal 1
replies[1].should.equal 1
# Now tick the clock on another hour (causing a fresh clean up)
# There should then be nothing left
clock.tick 60 * 60 * 1000
rememberMe.worker.once 'cleaned', ->
# Now check the database and make sure everything has gone
redisStore.client.keys 'remme*', (err, replies) ->
should.not.exist err
replies.should.have.length 0
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
| true | should = require 'should'
connect = require 'connect'
RedisStore = require('connect-redis')(connect)
RememberMe = require '../'
winston = require 'winston'
sinon = require 'sinon'
# Setup fake timers
clock = sinon.useFakeTimers('setInterval', 'Date')
# Remove the logging
winston.remove winston.transports.Console
# Get the cookie parser middleware
cookieParser = connect.middleware.cookieParser()
redisStore = new RedisStore {
db: 15
}
rememberMe = new RememberMe {
cookie: {
maxAge: 40 * 60 * 1000 # 40 mins
}
redisStore: redisStore
key: 'PI:KEY:<KEY>END_PI'
secret: 'secret'
}
describe 'Remember me tests', ->
req = {}
res = {}
resetMocks = ->
# Basic mock req, res
req = {
cookies: {}
headers: {}
connection: {}
session: {}
}
res = {
headers: {}
setHeader: (header, val) ->
this.headers[header] = val
}
before (done) ->
redisStore.client.flushall done
after ->
clock.restore()
beforeEach ->
resetMocks()
describe 'requests with no cookie', ->
it 'should not be given a user if no user is on the session', (done) ->
rememberMe req, res, ->
should.not.exist req.session.userid
done()
it 'should not remove the user if a user is on the session', (done) ->
req.session = {userid: '1234'}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
done()
it 'should not set a cookie', (done) ->
req.session = {userid: '1234'}
res.end = ->
should.not.exist res.headers['Set-Cookie']
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.end()
describe 'requests with bad cookie', ->
before ->
req.cookies.rememberme = 'PI:PASSWORD:<PASSWORD>END_PI'
req.session = {}
it 'should not be given a user if no user is on the session', (done) ->
rememberMe req, res, ->
should.not.exist req.session.userid
done()
it 'should not remove the user if a user is on the session', (done) ->
req.session = {userid: '1234'}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
done()
it 'should not set a cookie', (done) ->
req.session = {userid: '1234'}
res.end = ->
should.not.exist res.headers['Set-Cookie']
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.end()
describe 'setting the cookie', ->
it 'should set the cookie when res.rememberme is set', (done) ->
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should not set the cookie when res.remember me is set to a different userid than the session', (done) ->
req.session = {userid: '1234'}
res.end = ->
should.not.exist res.headers['Set-Cookie']
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '4567'}
res.end()
describe 'requests with correct cookie', ->
cookie = null
beforeEach (done) ->
# Set a remember me cookie
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie = res.headers['Set-Cookie'].split(';')[0] + ';'
resetMocks()
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should put a userid on the session if the correct cookie is present', (done) ->
req.headers.cookie = cookie
req.session = {}
req.cookies = null
res.end = ->
# Should get a new cookie
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
newcookie = res.headers['Set-Cookie'].split(';')[0] + ';'
newcookie.should.not.equal cookie
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
req.session.rememberme.should.be.true
res.end()
it 'shouldn\'t set a cookie if there is already a user on the session', (done) ->
req.headers.cookie = cookie
res.headers = {}
req.session = { userid: '1234' }
req.cookies = null
res.end = ->
# Should get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
it 'should authenticate after there has been a user on the session', (done) ->
this.timeout(0)
req.headers.cookie = cookie
res.headers = {}
req.session = { userid: '1234' }
req.cookies = null
res.end = ->
# Should get a new cookie
should.not.exist res.headers['Set-Cookie']
# Now log in with no session but a rememberme cookie
resetMocks()
req.headers.cookie = cookie
req.cookies = null
res.end = ->
# Should get a new cookie
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
newcookie = res.headers['Set-Cookie'].split(';')[0] + ';'
newcookie.should.not.equal cookie
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
describe 'request with stolen cookie', ->
stolenCookie = null
newcookie = null
before (done) ->
# Set a remember me cookie
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
stolenCookie = res.headers['Set-Cookie'].split(';')[0] + ';'
req.headers.cookie = stolenCookie
req.session = {}
req.cookies = null
res.end = ->
# Should get a new cookie
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
newcookie = res.headers['Set-Cookie'].split(';')[0] + ';'
newcookie.should.not.equal stolenCookie
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
res.end()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should not be possible to use a cookie twice', (done) ->
req.headers.cookie = stolenCookie
req.session = {}
req.cookies = null
res.headers = {}
res.end = ->
# Should not get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.not.exist req.session.userid
req.rememberme.stolen.should.be.true
res.end()
it 'should now have invalidated the use of all other remember me cookies as well', (done) ->
req.headers.cookie = newcookie
req.session = {}
req.cookies = null
res.headers = {}
res.end = ->
# Should not get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.not.exist req.session.userid
res.end()
describe 'destroying the cookie', ->
cookie1 = null
cookie2 = null
before (done) ->
# Create two remember me cookies
req.session = {userid: '1234'}
res.headers = {}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie1 = res.headers['Set-Cookie'].split(';')[0] + ';'
req.session = {userid: '1234'}
res.headers = {}
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie2 = res.headers['Set-Cookie'].split(';')[0] + ';'
cookie2.should.not.equal cookie1
done()
it 'should not set a new cookie once destroyed', (done) ->
req.headers.cookie = cookie1
req.session = {}
req.cookies = null
res.headers = {}
res.end = ->
# Should not get a new cookie
should.not.exist res.headers['Set-Cookie']
done()
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
req.rememberme.destroy()
res.end()
it 'should not be possible to log in with cookie1', (done) ->
req.headers.cookie = cookie1
req.session = {}
req.cookies = null
res.headers = {}
cookieParser req, res, ->
rememberMe req, res, ->
should.not.exist req.session.userid
done()
it 'should still be possible to log in with cookie2', (done) ->
req.headers.cookie = cookie2
req.session = {}
req.cookies = null
res.headers = {}
cookieParser req, res, ->
rememberMe req, res, ->
should.exist req.session.userid
req.session.userid.should.equal '1234'
done()
describe 'expiry', ->
beforeEach (done) ->
# Create a cookie
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie = res.headers['Set-Cookie'].split(';')[0] + ';'
resetMocks()
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
it 'should expire everything after an hour (thats the runtime of the scheduled task)', (done) ->
clock.tick(3601 * 1000)
# Wait for the cleaned event and check that its all worked
rememberMe.worker.once 'cleaned', ->
# Now check the database and make sure everything has gone
redisStore.client.keys 'remme*', (err, replies) ->
should.not.exist err
replies.should.have.length 0
done()
it 'should not remove unexpired details though', (done) ->
# Tick the clock on 30 mins then create a new cookie
clock.tick(30 * 60 * 1000)
resetMocks()
req.session = {userid: '1234'}
res.headers = {}
res.end = ->
should.exist res.headers['Set-Cookie']
res.headers['Set-Cookie'].indexOf('rememberme=').should.equal 0
cookie = res.headers['Set-Cookie'].split(';')[0] + ';'
resetMocks()
# Tick the clock over the hour (forcing the cleanup to happen)
clock.tick 31 * 60 * 1000
rememberMe.worker.once 'cleaned', ->
# There should be one series and token left in the sets
multi = redisStore.client.multi()
multi.scard 'remme:1234:token'
multi.scard 'remme:1234:series'
multi.exec (err, replies) ->
should.not.exist err
replies[0].should.equal 1
replies[1].should.equal 1
# Now tick the clock on another hour (causing a fresh clean up)
# There should then be nothing left
clock.tick 60 * 60 * 1000
rememberMe.worker.once 'cleaned', ->
# Now check the database and make sure everything has gone
redisStore.client.keys 'remme*', (err, replies) ->
should.not.exist err
replies.should.have.length 0
done()
rememberMe req, res, ->
req.session.userid.should.equal '1234'
res.rememberme = {userid: '1234'}
res.end()
|
[
{
"context": "Utility function tests\n#\n# Copyright (C) 2011-2013 Nikolay Nemshilov\n#\nutil = require('util')\n{Test,should} = requir",
"end": 72,
"score": 0.9998874068260193,
"start": 55,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/core/test/util_test.coffee | lovely-io/lovely.io-stl | 2 | #
# Utility function tests
#
# Copyright (C) 2011-2013 Nikolay Nemshilov
#
util = require('util')
{Test,should} = require('lovely')
eval(Test.build)
Lovely = this.Lovely
#
# A shortcut for the type check functions mass-testing
#
# @param {String} function name
# @param {Object} okays and fails
# @return void
#
assertTypeCheck = (name, options) ->
->
for value in options.ok
do (value) ->
it "should return 'true' for: "+ util.inspect(value), ->
Lovely[name](value).should.be.true
for value in options.fail
do (value) ->
it "should return 'false' for: "+ util.inspect(value), ->
Lovely[name](value).should.be.false
describe 'Core Utils', ->
describe "ext(a,b)", ->
ext = Lovely.ext
it 'should extend one object with another', ->
a = a: 1
b = b: 2
c = ext(a, b)
c.should.eql {a:1, b:2}
c.should.be.equal a
it "should accept 'null' as the second argument", ->
ext({a: 1}, null).should.eql {a: 1}
it "should accept 'undefined' as the second argument", ->
ext({a: 1}, undefined).should.eql {a: 1}
it "should skip the prototype values", ->
o1 = ->
o2 = ->
ext(o1, o2)
o1.prototype.should.not.be.equal o2.prototype
describe "bind", ->
bind = Lovely.bind
result = {}
original = ->
result.context = this
result.args = Lovely.A(arguments)
describe '\b(context)', ->
callback = bind(original, context = {})
it "should execute the original in the prebinded context", ->
callback()
result.context.should.be.equal context
result.args.should.eql []
it "should execute the original even when called in a different context", ->
callback.apply other: 'context'
result.context.should.be.equal context
result.args.should.eql []
it "should bypass the arguments to the original function", ->
callback(1,2,3)
result.context.should.be.equal context
result.args.should.eql [1,2,3]
describe '\b(context, arg1, arg2,..)', ->
callback = bind(original, context = {}, 1,2,3)
it "should pass the prebinded arguments into the original function", ->
callback()
result.context.should.be.equal context
result.args.should.eql [1,2,3]
it "should handle additional arguments if specified", ->
callback(4,5,6)
result.context.should.be.equal context
result.args.should.eql [1,2,3,4,5,6]
describe 'trim(string)', ->
string = Lovely.trim(" boo hoo!\n\t ")
it "should trim the excessive spaces out", ->
string.should.be.equal "boo hoo!"
describe "isString(value)", assertTypeCheck('isString',
ok: ['']
fail: [1, 2.2, true, false, null, undefined, [], {}, ->])
describe "isNumber(value)", assertTypeCheck('isNumber',
ok: [1, 2.2]
fail: ['11', '2.2', true, false, null, undefined, [], {}, NaN, ->])
describe "isFunction(value)", assertTypeCheck('isFunction',
ok: [`function(){}`, new Function('return 1')]
fail: ['', 1, 2.2, true, false, null, undefined, [], {}, /\s/])
describe "isArray(value)", assertTypeCheck('isArray',
ok: [[], new Lovely.List()]
fail: ['', 1, 2.2, true, false, null, undefined, {}, ->])
describe "isObject(value)", assertTypeCheck('isObject',
ok: [{}]
fail: ['', 1, 2.2, true, false, null, undefined, [], ->])
describe "A(iterable)", ->
A = Lovely.A
it "should convert arguments into arrays", ->
dummy = -> arguments
array = A(dummy(1,2,3))
array.should.be.instanceOf Array
array.should.eql [1,2,3]
describe "L(iterable)", ->
L = Lovely.L
it "should make a List", ->
l = L([1,2,3])
l.should.be.instanceOf Lovely.List
l.toArray().should.eql [1,2,3]
describe "H(object)", ->
H = Lovely.H
it "should make a Hash", ->
hash = H(a:1)
hash.should.be.instanceOf Lovely.Hash
hash.toObject().should.eql a:1
| 109701 | #
# Utility function tests
#
# Copyright (C) 2011-2013 <NAME>
#
util = require('util')
{Test,should} = require('lovely')
eval(Test.build)
Lovely = this.Lovely
#
# A shortcut for the type check functions mass-testing
#
# @param {String} function name
# @param {Object} okays and fails
# @return void
#
assertTypeCheck = (name, options) ->
->
for value in options.ok
do (value) ->
it "should return 'true' for: "+ util.inspect(value), ->
Lovely[name](value).should.be.true
for value in options.fail
do (value) ->
it "should return 'false' for: "+ util.inspect(value), ->
Lovely[name](value).should.be.false
describe 'Core Utils', ->
describe "ext(a,b)", ->
ext = Lovely.ext
it 'should extend one object with another', ->
a = a: 1
b = b: 2
c = ext(a, b)
c.should.eql {a:1, b:2}
c.should.be.equal a
it "should accept 'null' as the second argument", ->
ext({a: 1}, null).should.eql {a: 1}
it "should accept 'undefined' as the second argument", ->
ext({a: 1}, undefined).should.eql {a: 1}
it "should skip the prototype values", ->
o1 = ->
o2 = ->
ext(o1, o2)
o1.prototype.should.not.be.equal o2.prototype
describe "bind", ->
bind = Lovely.bind
result = {}
original = ->
result.context = this
result.args = Lovely.A(arguments)
describe '\b(context)', ->
callback = bind(original, context = {})
it "should execute the original in the prebinded context", ->
callback()
result.context.should.be.equal context
result.args.should.eql []
it "should execute the original even when called in a different context", ->
callback.apply other: 'context'
result.context.should.be.equal context
result.args.should.eql []
it "should bypass the arguments to the original function", ->
callback(1,2,3)
result.context.should.be.equal context
result.args.should.eql [1,2,3]
describe '\b(context, arg1, arg2,..)', ->
callback = bind(original, context = {}, 1,2,3)
it "should pass the prebinded arguments into the original function", ->
callback()
result.context.should.be.equal context
result.args.should.eql [1,2,3]
it "should handle additional arguments if specified", ->
callback(4,5,6)
result.context.should.be.equal context
result.args.should.eql [1,2,3,4,5,6]
describe 'trim(string)', ->
string = Lovely.trim(" boo hoo!\n\t ")
it "should trim the excessive spaces out", ->
string.should.be.equal "boo hoo!"
describe "isString(value)", assertTypeCheck('isString',
ok: ['']
fail: [1, 2.2, true, false, null, undefined, [], {}, ->])
describe "isNumber(value)", assertTypeCheck('isNumber',
ok: [1, 2.2]
fail: ['11', '2.2', true, false, null, undefined, [], {}, NaN, ->])
describe "isFunction(value)", assertTypeCheck('isFunction',
ok: [`function(){}`, new Function('return 1')]
fail: ['', 1, 2.2, true, false, null, undefined, [], {}, /\s/])
describe "isArray(value)", assertTypeCheck('isArray',
ok: [[], new Lovely.List()]
fail: ['', 1, 2.2, true, false, null, undefined, {}, ->])
describe "isObject(value)", assertTypeCheck('isObject',
ok: [{}]
fail: ['', 1, 2.2, true, false, null, undefined, [], ->])
describe "A(iterable)", ->
A = Lovely.A
it "should convert arguments into arrays", ->
dummy = -> arguments
array = A(dummy(1,2,3))
array.should.be.instanceOf Array
array.should.eql [1,2,3]
describe "L(iterable)", ->
L = Lovely.L
it "should make a List", ->
l = L([1,2,3])
l.should.be.instanceOf Lovely.List
l.toArray().should.eql [1,2,3]
describe "H(object)", ->
H = Lovely.H
it "should make a Hash", ->
hash = H(a:1)
hash.should.be.instanceOf Lovely.Hash
hash.toObject().should.eql a:1
| true | #
# Utility function tests
#
# Copyright (C) 2011-2013 PI:NAME:<NAME>END_PI
#
util = require('util')
{Test,should} = require('lovely')
eval(Test.build)
Lovely = this.Lovely
#
# A shortcut for the type check functions mass-testing
#
# @param {String} function name
# @param {Object} okays and fails
# @return void
#
assertTypeCheck = (name, options) ->
->
for value in options.ok
do (value) ->
it "should return 'true' for: "+ util.inspect(value), ->
Lovely[name](value).should.be.true
for value in options.fail
do (value) ->
it "should return 'false' for: "+ util.inspect(value), ->
Lovely[name](value).should.be.false
describe 'Core Utils', ->
describe "ext(a,b)", ->
ext = Lovely.ext
it 'should extend one object with another', ->
a = a: 1
b = b: 2
c = ext(a, b)
c.should.eql {a:1, b:2}
c.should.be.equal a
it "should accept 'null' as the second argument", ->
ext({a: 1}, null).should.eql {a: 1}
it "should accept 'undefined' as the second argument", ->
ext({a: 1}, undefined).should.eql {a: 1}
it "should skip the prototype values", ->
o1 = ->
o2 = ->
ext(o1, o2)
o1.prototype.should.not.be.equal o2.prototype
describe "bind", ->
bind = Lovely.bind
result = {}
original = ->
result.context = this
result.args = Lovely.A(arguments)
describe '\b(context)', ->
callback = bind(original, context = {})
it "should execute the original in the prebinded context", ->
callback()
result.context.should.be.equal context
result.args.should.eql []
it "should execute the original even when called in a different context", ->
callback.apply other: 'context'
result.context.should.be.equal context
result.args.should.eql []
it "should bypass the arguments to the original function", ->
callback(1,2,3)
result.context.should.be.equal context
result.args.should.eql [1,2,3]
describe '\b(context, arg1, arg2,..)', ->
callback = bind(original, context = {}, 1,2,3)
it "should pass the prebinded arguments into the original function", ->
callback()
result.context.should.be.equal context
result.args.should.eql [1,2,3]
it "should handle additional arguments if specified", ->
callback(4,5,6)
result.context.should.be.equal context
result.args.should.eql [1,2,3,4,5,6]
describe 'trim(string)', ->
string = Lovely.trim(" boo hoo!\n\t ")
it "should trim the excessive spaces out", ->
string.should.be.equal "boo hoo!"
describe "isString(value)", assertTypeCheck('isString',
ok: ['']
fail: [1, 2.2, true, false, null, undefined, [], {}, ->])
describe "isNumber(value)", assertTypeCheck('isNumber',
ok: [1, 2.2]
fail: ['11', '2.2', true, false, null, undefined, [], {}, NaN, ->])
describe "isFunction(value)", assertTypeCheck('isFunction',
ok: [`function(){}`, new Function('return 1')]
fail: ['', 1, 2.2, true, false, null, undefined, [], {}, /\s/])
describe "isArray(value)", assertTypeCheck('isArray',
ok: [[], new Lovely.List()]
fail: ['', 1, 2.2, true, false, null, undefined, {}, ->])
describe "isObject(value)", assertTypeCheck('isObject',
ok: [{}]
fail: ['', 1, 2.2, true, false, null, undefined, [], ->])
describe "A(iterable)", ->
A = Lovely.A
it "should convert arguments into arrays", ->
dummy = -> arguments
array = A(dummy(1,2,3))
array.should.be.instanceOf Array
array.should.eql [1,2,3]
describe "L(iterable)", ->
L = Lovely.L
it "should make a List", ->
l = L([1,2,3])
l.should.be.instanceOf Lovely.List
l.toArray().should.eql [1,2,3]
describe "H(object)", ->
H = Lovely.H
it "should make a Hash", ->
hash = H(a:1)
hash.should.be.instanceOf Lovely.Hash
hash.toObject().should.eql a:1
|
[
{
"context": " 'username': 'String'\n 'password': 'String'\n 'email': 'String'\n 'created_dt': ",
"end": 262,
"score": 0.9758886694908142,
"start": 256,
"tag": "PASSWORD",
"value": "String"
}
] | src/models/internal_storage/user.coffee | RaghavendhraK/daily_sales | 0 | InternalStorageModel = require './index'
Encrypt = require '../../lib/encrypt'
Token = require '../../lib/token'
class User extends InternalStorageModel
getSchema: ()->
@schema = {
fields: {
'username': 'String'
'password': 'String'
'email': 'String'
'created_dt': 'Date'
'updated_dt': 'Date'
}
table: 'users'
id: '_id'
} unless @schema?
return @schema
create: (params, cb)->
params['password'] = Encrypt.encrypt(params['password'])
super params, cb
deleteById: (id, cb)->
super id, (e)=>
return cb.apply @, [e] if e?
Token.clearUserTokens id, (e)=>
return cb.apply @, [e]
getByUsername: (username, cb)->
filters = {'username': username}
@getOne filters, cb
module.exports = User | 163700 | InternalStorageModel = require './index'
Encrypt = require '../../lib/encrypt'
Token = require '../../lib/token'
class User extends InternalStorageModel
getSchema: ()->
@schema = {
fields: {
'username': 'String'
'password': '<PASSWORD>'
'email': 'String'
'created_dt': 'Date'
'updated_dt': 'Date'
}
table: 'users'
id: '_id'
} unless @schema?
return @schema
create: (params, cb)->
params['password'] = Encrypt.encrypt(params['password'])
super params, cb
deleteById: (id, cb)->
super id, (e)=>
return cb.apply @, [e] if e?
Token.clearUserTokens id, (e)=>
return cb.apply @, [e]
getByUsername: (username, cb)->
filters = {'username': username}
@getOne filters, cb
module.exports = User | true | InternalStorageModel = require './index'
Encrypt = require '../../lib/encrypt'
Token = require '../../lib/token'
class User extends InternalStorageModel
getSchema: ()->
@schema = {
fields: {
'username': 'String'
'password': 'PI:PASSWORD:<PASSWORD>END_PI'
'email': 'String'
'created_dt': 'Date'
'updated_dt': 'Date'
}
table: 'users'
id: '_id'
} unless @schema?
return @schema
create: (params, cb)->
params['password'] = Encrypt.encrypt(params['password'])
super params, cb
deleteById: (id, cb)->
super id, (e)=>
return cb.apply @, [e] if e?
Token.clearUserTokens id, (e)=>
return cb.apply @, [e]
getByUsername: (username, cb)->
filters = {'username': username}
@getOne filters, cb
module.exports = User |
[
{
"context": "jector](http://neocotic.com/injector)\n#\n# (c) 2014 Alasdair Mercer\n#\n# Freely distributable under the MIT license\n\n#",
"end": 71,
"score": 0.9998756647109985,
"start": 56,
"tag": "NAME",
"value": "Alasdair Mercer"
}
] | src/coffee/install.coffee | SlinkySalmon633/injector-chrome | 33 | # [Injector](http://neocotic.com/injector)
#
# (c) 2014 Alasdair Mercer
#
# Freely distributable under the MIT license
# Inline installation
# -------------------
# Injector's extension ID is currently using.
id = chrome.i18n.getMessage('@@extension_id')
# Names of the classes to be added to the targeted elements.
newClasses = [ 'disabled' ]
# Names of the classes to be removed from the targeted elements.
oldClasses = [ 'chrome_install_button' ]
# Disable all "Install" links on the homepage for Template.
links = document.querySelectorAll("a.#{oldClasses[0]}[href$=#{id}]")
for link in links
link.innerHTML = link.innerHTML.replace('Install', 'Installed')
link.classList.add(cls) for cls in newClasses
link.classList.remove(cls) for cls in oldClasses
| 28455 | # [Injector](http://neocotic.com/injector)
#
# (c) 2014 <NAME>
#
# Freely distributable under the MIT license
# Inline installation
# -------------------
# Injector's extension ID is currently using.
id = chrome.i18n.getMessage('@@extension_id')
# Names of the classes to be added to the targeted elements.
newClasses = [ 'disabled' ]
# Names of the classes to be removed from the targeted elements.
oldClasses = [ 'chrome_install_button' ]
# Disable all "Install" links on the homepage for Template.
links = document.querySelectorAll("a.#{oldClasses[0]}[href$=#{id}]")
for link in links
link.innerHTML = link.innerHTML.replace('Install', 'Installed')
link.classList.add(cls) for cls in newClasses
link.classList.remove(cls) for cls in oldClasses
| true | # [Injector](http://neocotic.com/injector)
#
# (c) 2014 PI:NAME:<NAME>END_PI
#
# Freely distributable under the MIT license
# Inline installation
# -------------------
# Injector's extension ID is currently using.
id = chrome.i18n.getMessage('@@extension_id')
# Names of the classes to be added to the targeted elements.
newClasses = [ 'disabled' ]
# Names of the classes to be removed from the targeted elements.
oldClasses = [ 'chrome_install_button' ]
# Disable all "Install" links on the homepage for Template.
links = document.querySelectorAll("a.#{oldClasses[0]}[href$=#{id}]")
for link in links
link.innerHTML = link.innerHTML.replace('Install', 'Installed')
link.classList.add(cls) for cls in newClasses
link.classList.remove(cls) for cls in oldClasses
|
[
{
"context": "llapsible Component Script\n# -----\n# Copyright (c) Kiruse 2021. Licensed under MIT License\nimport anime fro",
"end": 132,
"score": 0.9911298155784607,
"start": 126,
"tag": "NAME",
"value": "Kiruse"
}
] | dapp/src/components/collapsible.coffee | Kiruse/WotD.sol | 0 | ######################################################################
# Collapsible Component Script
# -----
# Copyright (c) Kiruse 2021. Licensed under MIT License
import anime from 'animejs'
animDuration = 300
export default
data: ->
expanded: !!this.open
animtarget: {height: 0}
props: ['label', 'open']
computed:
collapsed: -> not this.expanded
collapseClass: -> if this.collapsed then 'collapsed'
_label: -> if this.expanded then 'collapse' else 'expand'
_style: ->
height = this.animtarget.height
if typeof height is 'number'
height += 'px'
return {height}
methods:
show: ->
this.$emit 'beforeExpand'
await this.animateOpen()
this.expanded = true
this.$emit 'expand'
null
hide: ->
this.$emit 'beforeCollapse'
await this.animateClose()
this.expanded = false
this.$emit 'collapse'
null
toggle: -> if this.expanded then this.hide() else this.show()
animateOpen: ->
cnt = this.$refs.content
cnt.style.height = 'auto'
targetHeight = innerHeight(cnt)
cnt.style.height = 0
await anime(
targets: this.animtarget
height: [0, targetHeight]
easing: 'easeOutQuad'
duration: animDuration
).finished
this.animtarget.height = 'auto'
animateClose: ->
sourceHeight = innerHeight(this.$refs.content)
await anime(
targets: this.animtarget
height: [sourceHeight, 0]
easing: 'easeOutQuad'
duration: animDuration
).finished
innerHeight = (el) ->
styles = getComputedStyle(el)
return el.clientHeight - parseFloat(styles.paddingTop) - parseFloat(styles.paddingBottom)
innerWidth = (el) ->
styles = getComputedStyle(el)
return el.clientWidth - parseFloat(styles.paddingLeft) - parseFloat(styles.paddingRight)
| 156511 | ######################################################################
# Collapsible Component Script
# -----
# Copyright (c) <NAME> 2021. Licensed under MIT License
import anime from 'animejs'
animDuration = 300
export default
data: ->
expanded: !!this.open
animtarget: {height: 0}
props: ['label', 'open']
computed:
collapsed: -> not this.expanded
collapseClass: -> if this.collapsed then 'collapsed'
_label: -> if this.expanded then 'collapse' else 'expand'
_style: ->
height = this.animtarget.height
if typeof height is 'number'
height += 'px'
return {height}
methods:
show: ->
this.$emit 'beforeExpand'
await this.animateOpen()
this.expanded = true
this.$emit 'expand'
null
hide: ->
this.$emit 'beforeCollapse'
await this.animateClose()
this.expanded = false
this.$emit 'collapse'
null
toggle: -> if this.expanded then this.hide() else this.show()
animateOpen: ->
cnt = this.$refs.content
cnt.style.height = 'auto'
targetHeight = innerHeight(cnt)
cnt.style.height = 0
await anime(
targets: this.animtarget
height: [0, targetHeight]
easing: 'easeOutQuad'
duration: animDuration
).finished
this.animtarget.height = 'auto'
animateClose: ->
sourceHeight = innerHeight(this.$refs.content)
await anime(
targets: this.animtarget
height: [sourceHeight, 0]
easing: 'easeOutQuad'
duration: animDuration
).finished
innerHeight = (el) ->
styles = getComputedStyle(el)
return el.clientHeight - parseFloat(styles.paddingTop) - parseFloat(styles.paddingBottom)
innerWidth = (el) ->
styles = getComputedStyle(el)
return el.clientWidth - parseFloat(styles.paddingLeft) - parseFloat(styles.paddingRight)
| true | ######################################################################
# Collapsible Component Script
# -----
# Copyright (c) PI:NAME:<NAME>END_PI 2021. Licensed under MIT License
import anime from 'animejs'
animDuration = 300
export default
data: ->
expanded: !!this.open
animtarget: {height: 0}
props: ['label', 'open']
computed:
collapsed: -> not this.expanded
collapseClass: -> if this.collapsed then 'collapsed'
_label: -> if this.expanded then 'collapse' else 'expand'
_style: ->
height = this.animtarget.height
if typeof height is 'number'
height += 'px'
return {height}
methods:
show: ->
this.$emit 'beforeExpand'
await this.animateOpen()
this.expanded = true
this.$emit 'expand'
null
hide: ->
this.$emit 'beforeCollapse'
await this.animateClose()
this.expanded = false
this.$emit 'collapse'
null
toggle: -> if this.expanded then this.hide() else this.show()
animateOpen: ->
cnt = this.$refs.content
cnt.style.height = 'auto'
targetHeight = innerHeight(cnt)
cnt.style.height = 0
await anime(
targets: this.animtarget
height: [0, targetHeight]
easing: 'easeOutQuad'
duration: animDuration
).finished
this.animtarget.height = 'auto'
animateClose: ->
sourceHeight = innerHeight(this.$refs.content)
await anime(
targets: this.animtarget
height: [sourceHeight, 0]
easing: 'easeOutQuad'
duration: animDuration
).finished
innerHeight = (el) ->
styles = getComputedStyle(el)
return el.clientHeight - parseFloat(styles.paddingTop) - parseFloat(styles.paddingBottom)
innerWidth = (el) ->
styles = getComputedStyle(el)
return el.clientWidth - parseFloat(styles.paddingLeft) - parseFloat(styles.paddingRight)
|
[
{
"context": "]\n key = VALIDATION_PHASES_SINGULAR[phase].toLowerCase()\n if names.length is 1\n key +=",
"end": 4327,
"score": 0.6216108202934265,
"start": 4316,
"tag": "KEY",
"value": "toLowerCase"
},
{
"context": " if names.length is 1\n key += \"_singular\"\n prefix_key = \"#{key}_prefix\"\n suf",
"end": 4388,
"score": 0.5752695798873901,
"start": 4380,
"tag": "KEY",
"value": "singular"
},
{
"context": " key += \"_singular\"\n prefix_key = \"#{key}_prefix\"\n suffix_key = \"#{key}_suffix\"\n par",
"end": 4425,
"score": 0.656769335269928,
"start": 4419,
"tag": "KEY",
"value": "prefix"
},
{
"context": "_key = \"#{key}_prefix\"\n suffix_key = \"#{key}_suffix\"\n parts = ({message: \"'#{name}'\", prefix: ",
"end": 4462,
"score": 0.7797603607177734,
"start": 4456,
"tag": "KEY",
"value": "suffix"
},
{
"context": "ix_key]} for name in names)\n else\n key = \"#{VALIDATION_PHASES_SINGULAR[phase].toLowerCase()}_general\"\n parts = []\n return {parts}\n # retu",
"end": 4667,
"score": 0.8874176144599915,
"start": 4608,
"tag": "KEY",
"value": "\"#{VALIDATION_PHASES_SINGULAR[phase].toLowerCase()}_general"
},
{
"context": "er the normal type\n error = errors[0]\n key = \"#{VALIDATION_PHASES_SINGULAR[phase].toLowerCase()}_#{error.error_message_type or error.type}\"\n # her",
"end": 5112,
"score": 0.9638515710830688,
"start": 5058,
"tag": "KEY",
"value": "\"#{VALIDATION_PHASES_SINGULAR[phase].toLowerCase()}_#{"
},
{
"context": "erCase()}_#{error.error_message_type or error.type}\"\n # here only 1 error is in the 'errors' list =",
"end": 5150,
"score": 0.9234182238578796,
"start": 5150,
"tag": "KEY",
"value": ""
},
{
"context": "ype may use a special locale key)\n key_prefix = \"#{phase_singular}_\"\n default_prefix = locales[locale][",
"end": 6446,
"score": 0.8037514686584473,
"start": 6438,
"tag": "KEY",
"value": "\"#{phase"
},
{
"context": "e a special locale key)\n key_prefix = \"#{phase_singular}_\"\n default_prefix = locales[locale][\"#{phase_si",
"end": 6457,
"score": 0.9228106737136841,
"start": 6447,
"tag": "KEY",
"value": "singular}_"
},
{
"context": " keys.push option\n\n key = get_combined_key(keys, locale, key_prefix)\n if key?\n ",
"end": 7075,
"score": 0.6607263684272766,
"start": 7067,
"tag": "KEY",
"value": "combined"
},
{
"context": "g. '#{key_prefix}#{keys.join(\"_\")}')!\")\n\n key = \"#{phase_singular}_#{build_mode.toLowerCase()}\"\n # replace {{value}} with the actual value\n ",
"end": 7834,
"score": 0.9981224536895752,
"start": 7787,
"tag": "KEY",
"value": "\"#{phase_singular}_#{build_mode.toLowerCase()}\""
}
] | error_message_builders.coffee | jneuendorf/FormValidator | 0 | #########################################################################################################
# WORKFLOW: error_message_builders[VALIDATION_PHASE] -> message builder
locale_message_builders =
de: {}
en: {}
locale_message_builders.de[BUILD_MODES.ENUMERATE] = null
locale_message_builders.de[BUILD_MODES.SENTENCE] = null
locale_message_builders.de[BUILD_MODES.LIST] = null
locale_message_builders.en[BUILD_MODES.ENUMERATE] = null
locale_message_builders.en[BUILD_MODES.SENTENCE] = null
locale_message_builders.en[BUILD_MODES.LIST] = null
message_builders = {}
message_data_creators = {}
# NOTE: This class structure overhead was made mainly for structuring/API reasons. If this causes preformance problems this should be simplified
class Maker
# CONSTRUCTOR
constructor: (namespace, key, func) ->
if arguments.length is 3
@func = func
namespace[key] = @
else
@func = arguments[0]
make: () ->
return @func(arguments...)
# This class'es instance's method is used to create the "raw" message data from the error data
class MessageDataCreator extends Maker
# CONSTRUCTOR
constructor: (name, func) ->
super(message_data_creators, name, func)
create_data: (errors, phase, build_mode, locale) ->
return @make(errors, phase, build_mode, locale)
# This class'es instance's method is used to transform the "raw" message data from the ErrorMessageBuilder
class MessageBuilder extends Maker
# CONSTRUCTOR
constructor: (name, func) ->
super(message_builders, name, func)
build_message: (parts, locale, phase, build_mode, error_data) ->
return @make(parts, locale, phase, build_mode, error_data)
class OrderedDict
# CONSTRUCTOR
constructor: () ->
@_dict = {}
@_order = []
put: (key, val, idx) ->
@_dict[key] = val
if not idx?
if key not in @_order
@_order.push key
else
i = @_order.indexOf(key)
# == key in @_order => remove it first
if i >= 0
@_order.splice(i, 1)
@_order.splice(idx, 0, key)
return @
get: (key) ->
return @_dict[key]
remove: (key) ->
delete @_dict[key]
@_order = (item for item in @_order when item isnt key)
return @
join: (str = "") ->
return (@_dict[key].join?(str) or @_dict[key] for key in @_order).join(str)
each: (callback) ->
for key, i in @_order
if callback.call(@, key, @_dict[key], i) is false
return @
return @
to_array: () ->
return (@_dict[key] for key in @_order)
to_object: () ->
res = {}
for key, val of @_dict
res[key] = val
return res
get_object: () ->
return @_dict
get_order: () ->
return @_order
# this function parses and replaces mustache-like strings or evaluate functions
part_evaluator = (part, values...) ->
if values.length is 1
values = values[0]
else
values = $.extend(values...)
# string => mustache-like
if typeof part is "string"
for key, val of values
substr = "{{#{key}}}"
if part.indexOf(substr) >= 0
regex = new RegExp(substr, "g")
part = part.replace(regex, val)
return part
if part instanceof Function
return part(values)
throw new Error("FormValidator: Error while building an error message. Expected mustache-like string or function but was given:", part, values)
################################################################################################
# DEFINE MESSAGE BUILDERS (FOR EACH VALIDATION PHASE)
new MessageDataCreator VALIDATION_PHASES.DEPENDENCIES, (errors, phase, build_mode, locale) ->
names = (error.name for error in errors when error.name?)
# if all errors have a name property (<=> all dependencies are named)
if names.length is errors.length
# sentence does not make sense in this case => fallback to enumerate
# if build_mode is BUILD_MODES.SENTENCE
# build_mode = BUILD_MODES.ENUMERATE
lang_data = locales[locale]
key = VALIDATION_PHASES_SINGULAR[phase].toLowerCase()
if names.length is 1
key += "_singular"
prefix_key = "#{key}_prefix"
suffix_key = "#{key}_suffix"
parts = ({message: "'#{name}'", prefix: lang_data[prefix_key], suffix: lang_data[suffix_key]} for name in names)
else
key = "#{VALIDATION_PHASES_SINGULAR[phase].toLowerCase()}_general"
parts = []
return {parts}
# return locales[locale]["#{VALIDATION_PHASES_SINGULAR[phase].toLowerCase()}_general"]
new MessageDataCreator VALIDATION_PHASES.VALUE, (errors, phase, build_mode, locale) ->
# NOTE each error in errors (exactly 1 because of the phase) contains an error_message_type. that type is prefered over the normal type
error = errors[0]
key = "#{VALIDATION_PHASES_SINGULAR[phase].toLowerCase()}_#{error.error_message_type or error.type}"
# here only 1 error is in the 'errors' list => therefore we just use the simplest build mode
part =
message: part_evaluator(locales[locale][key], error)
prefix: ""
suffix: ""
# return message_builders[build_mode.toLowerCase()](key, phase, build_mode, locale, [part])
return {key, parts: [part]}
new MessageDataCreator VALIDATION_PHASES.CONSTRAINTS, (errors, phase, build_mode, locale) ->
parts = []
# group by error.type as defined in constraint_validator_groups (if an error is in no group it implicitely creates an own group)
grouped_errors = []
ungrouped_errors = []
for error in errors
error_in_group = false
for group, i in constraint_validator_groups
if error.type in group
error_in_group = true
if grouped_errors[i]?
grouped_errors[i].push(error)
else
grouped_errors[i] = [error]
if not error_in_group
ungrouped_errors.push error
for error in ungrouped_errors
grouped_errors.push [error]
phase_singular = VALIDATION_PHASES_SINGULAR[phase].toLowerCase()
# find combinable locale keys (errors with the same type may use a special locale key)
key_prefix = "#{phase_singular}_"
default_prefix = locales[locale]["#{phase_singular}_#{build_mode}_prefix".toLowerCase()] or ""
default_suffix = locales[locale]["#{phase_singular}_#{build_mode}_suffix".toLowerCase()] or ""
# go through groups of errors (and skip empty entries caused in the above loop)
for errors in grouped_errors when errors?
keys = []
for error in errors
keys.push error.type
if error.options?
for option, val of error.options when include_constraint_option_in_locale_key(option, val, locale)
keys.push option
key = get_combined_key(keys, locale, key_prefix)
if key?
parts.push {
message: part_evaluator(locales[locale][key], errors...)
prefix: part_evaluator(locales[locale]["#{key}_prefix"], error) or default_prefix
suffix: part_evaluator(locales[locale]["#{key}_suffix"], error) or default_suffix
}
else if DEBUG
throw new Error("Could not find a translation for key while trying to create an error message during the constraint validation phase. The keys that were retrieved from the generated errors are: #{JSON.stringify(keys)}. Define an according key in the 'locales' variable (e.g. '#{key_prefix}#{keys.join("_")}')!")
key = "#{phase_singular}_#{build_mode.toLowerCase()}"
# replace {{value}} with the actual value
prefix = part_evaluator("#{locales[locale]["#{key}_prefix"]}", errors[0])
error_data = $.extend([{}].concat(errors)...)
return {key, parts, error_data, prefix}
# this function concatenates the prefix, mid part (== joined parts), and the suffix (used in the error message builders)
# key = locale key used to find pre- and suffix
message_builder_helper = new Maker (data, phase, build_mode, locale, prefix, suffix, prefix_delimiter = " ", suffix_delimiter = " ") ->
# unpack data and set defaults
{key, parts, error_data = {}} = data
prefix = prefix or data.prefix or locales[locale]["#{key}_prefix"] or ""
suffix = suffix or data.suffix or locales[locale]["#{key}_suffix"] or ""
data.prefix = prefix?() or prefix
data.suffix = suffix?() or suffix
for part, i in parts
dict = new OrderedDict()
# if prefix instanceof Function
# prefix = prefix()
if part.prefix
dict.put("prefix", part.prefix)
dict.put("prefix_delimiter", part.prefix_delimiter or prefix_delimiter)
dict.put("message", part.message)
# if suffix instanceof Function
# suffix = suffix()
if part.suffix
dict.put("suffix_delimiter", part.suffix_delimiter or suffix_delimiter)
dict.put("suffix", part.suffix)
parts[i] = dict
new_parts = new OrderedDict()
for part, i in parts
new_parts.put(i, part)
data.parts = new_parts
return data
new MessageBuilder BUILD_MODES.ENUMERATE, (data, phase, build_mode, locale) ->
data = message_builder_helper.make(data, phase, build_mode, locale)
parts = data.parts.to_array()
lang_data = locales[locale]
parts_grouped_by_suffix = group_arr_by parts, (part) ->
return part.get("suffix") or ""
parts = []
for suffix, suffix_group of parts_grouped_by_suffix
parts_grouped_by_prefix = group_arr_by suffix_group, (part) ->
return part.get("prefix") or ""
# let the common prefix remain only in 1st part of the group
for prefix, prefix_group of parts_grouped_by_prefix
for p, i in prefix_group when i > 0
p.remove("prefix")
p.remove("prefix_delimiter")
# let the common suffix remain only in the last part of the group
for p, i in suffix_group when i < suffix_group.length - 1
p.remove("suffix_delimiter")
p.remove("suffix")
parts = parts.concat suffix_group
new_parts = new OrderedDict()
for part, i in parts
# prepend "and" to last part (if it's not the only part)
if i is parts.length - 1 and i > 0
part.put("prefix", " #{locales[locale]["and"]} #{part.get("prefix") or ""}", 0)
part.put("prefix_delimiter", " ", 1)
new_parts.put(i, part)
data.parts = new_parts
return "#{data.prefix or ""} #{new_parts.join("")} #{data.suffix or ""}".replace(/\s+/g, " ")
new MessageBuilder BUILD_MODES.SENTENCE, (data, phase, build_mode, locale) ->
data = message_builder_helper.make(data, phase, build_mode, locale)
data.parts.each (idx, part) ->
part.put("prefix", " #{data.prefix or ""} #{part.get("prefix") or ""}".trim(), 0)
part.put("prefix_delimiter", " ", 1)
part.put("suffix_delimiter", (if part.get("suffix") then part.get("suffix_delimiter") else ""), 3)
part.put("suffix", " #{data.suffix or ""} #{part.get("suffix") or ""}.".trim(), 4)
return true
parts = []
for part in data.parts.to_array()
parts.push part.join()
return parts.join(" ").replace(/\s+/g, " ").trim()
new MessageBuilder BUILD_MODES.LIST, (data, phase, build_mode, locale) ->
sentences = message_builders[BUILD_MODES.SENTENCE].build_message(data, phase, build_mode, locale)
if sentences[sentences.length - 1] is "."
sentences += " "
return "<ul><li>#{("#{sentence}." for sentence in sentences.split(". ") when sentence).join("</li><li>")}</li></ul>"
| 104588 | #########################################################################################################
# WORKFLOW: error_message_builders[VALIDATION_PHASE] -> message builder
locale_message_builders =
de: {}
en: {}
locale_message_builders.de[BUILD_MODES.ENUMERATE] = null
locale_message_builders.de[BUILD_MODES.SENTENCE] = null
locale_message_builders.de[BUILD_MODES.LIST] = null
locale_message_builders.en[BUILD_MODES.ENUMERATE] = null
locale_message_builders.en[BUILD_MODES.SENTENCE] = null
locale_message_builders.en[BUILD_MODES.LIST] = null
message_builders = {}
message_data_creators = {}
# NOTE: This class structure overhead was made mainly for structuring/API reasons. If this causes preformance problems this should be simplified
class Maker
# CONSTRUCTOR
constructor: (namespace, key, func) ->
if arguments.length is 3
@func = func
namespace[key] = @
else
@func = arguments[0]
make: () ->
return @func(arguments...)
# This class'es instance's method is used to create the "raw" message data from the error data
class MessageDataCreator extends Maker
# CONSTRUCTOR
constructor: (name, func) ->
super(message_data_creators, name, func)
create_data: (errors, phase, build_mode, locale) ->
return @make(errors, phase, build_mode, locale)
# This class'es instance's method is used to transform the "raw" message data from the ErrorMessageBuilder
class MessageBuilder extends Maker
# CONSTRUCTOR
constructor: (name, func) ->
super(message_builders, name, func)
build_message: (parts, locale, phase, build_mode, error_data) ->
return @make(parts, locale, phase, build_mode, error_data)
class OrderedDict
# CONSTRUCTOR
constructor: () ->
@_dict = {}
@_order = []
put: (key, val, idx) ->
@_dict[key] = val
if not idx?
if key not in @_order
@_order.push key
else
i = @_order.indexOf(key)
# == key in @_order => remove it first
if i >= 0
@_order.splice(i, 1)
@_order.splice(idx, 0, key)
return @
get: (key) ->
return @_dict[key]
remove: (key) ->
delete @_dict[key]
@_order = (item for item in @_order when item isnt key)
return @
join: (str = "") ->
return (@_dict[key].join?(str) or @_dict[key] for key in @_order).join(str)
each: (callback) ->
for key, i in @_order
if callback.call(@, key, @_dict[key], i) is false
return @
return @
to_array: () ->
return (@_dict[key] for key in @_order)
to_object: () ->
res = {}
for key, val of @_dict
res[key] = val
return res
get_object: () ->
return @_dict
get_order: () ->
return @_order
# this function parses and replaces mustache-like strings or evaluate functions
part_evaluator = (part, values...) ->
if values.length is 1
values = values[0]
else
values = $.extend(values...)
# string => mustache-like
if typeof part is "string"
for key, val of values
substr = "{{#{key}}}"
if part.indexOf(substr) >= 0
regex = new RegExp(substr, "g")
part = part.replace(regex, val)
return part
if part instanceof Function
return part(values)
throw new Error("FormValidator: Error while building an error message. Expected mustache-like string or function but was given:", part, values)
################################################################################################
# DEFINE MESSAGE BUILDERS (FOR EACH VALIDATION PHASE)
new MessageDataCreator VALIDATION_PHASES.DEPENDENCIES, (errors, phase, build_mode, locale) ->
names = (error.name for error in errors when error.name?)
# if all errors have a name property (<=> all dependencies are named)
if names.length is errors.length
# sentence does not make sense in this case => fallback to enumerate
# if build_mode is BUILD_MODES.SENTENCE
# build_mode = BUILD_MODES.ENUMERATE
lang_data = locales[locale]
key = VALIDATION_PHASES_SINGULAR[phase].<KEY>()
if names.length is 1
key += "_<KEY>"
prefix_key = "#{key}_<KEY>"
suffix_key = "#{key}_<KEY>"
parts = ({message: "'#{name}'", prefix: lang_data[prefix_key], suffix: lang_data[suffix_key]} for name in names)
else
key = <KEY>"
parts = []
return {parts}
# return locales[locale]["#{VALIDATION_PHASES_SINGULAR[phase].toLowerCase()}_general"]
new MessageDataCreator VALIDATION_PHASES.VALUE, (errors, phase, build_mode, locale) ->
# NOTE each error in errors (exactly 1 because of the phase) contains an error_message_type. that type is prefered over the normal type
error = errors[0]
key = <KEY>error.error_message_type or error.type<KEY>}"
# here only 1 error is in the 'errors' list => therefore we just use the simplest build mode
part =
message: part_evaluator(locales[locale][key], error)
prefix: ""
suffix: ""
# return message_builders[build_mode.toLowerCase()](key, phase, build_mode, locale, [part])
return {key, parts: [part]}
new MessageDataCreator VALIDATION_PHASES.CONSTRAINTS, (errors, phase, build_mode, locale) ->
parts = []
# group by error.type as defined in constraint_validator_groups (if an error is in no group it implicitely creates an own group)
grouped_errors = []
ungrouped_errors = []
for error in errors
error_in_group = false
for group, i in constraint_validator_groups
if error.type in group
error_in_group = true
if grouped_errors[i]?
grouped_errors[i].push(error)
else
grouped_errors[i] = [error]
if not error_in_group
ungrouped_errors.push error
for error in ungrouped_errors
grouped_errors.push [error]
phase_singular = VALIDATION_PHASES_SINGULAR[phase].toLowerCase()
# find combinable locale keys (errors with the same type may use a special locale key)
key_prefix = <KEY>_<KEY>"
default_prefix = locales[locale]["#{phase_singular}_#{build_mode}_prefix".toLowerCase()] or ""
default_suffix = locales[locale]["#{phase_singular}_#{build_mode}_suffix".toLowerCase()] or ""
# go through groups of errors (and skip empty entries caused in the above loop)
for errors in grouped_errors when errors?
keys = []
for error in errors
keys.push error.type
if error.options?
for option, val of error.options when include_constraint_option_in_locale_key(option, val, locale)
keys.push option
key = get_<KEY>_key(keys, locale, key_prefix)
if key?
parts.push {
message: part_evaluator(locales[locale][key], errors...)
prefix: part_evaluator(locales[locale]["#{key}_prefix"], error) or default_prefix
suffix: part_evaluator(locales[locale]["#{key}_suffix"], error) or default_suffix
}
else if DEBUG
throw new Error("Could not find a translation for key while trying to create an error message during the constraint validation phase. The keys that were retrieved from the generated errors are: #{JSON.stringify(keys)}. Define an according key in the 'locales' variable (e.g. '#{key_prefix}#{keys.join("_")}')!")
key = <KEY>
# replace {{value}} with the actual value
prefix = part_evaluator("#{locales[locale]["#{key}_prefix"]}", errors[0])
error_data = $.extend([{}].concat(errors)...)
return {key, parts, error_data, prefix}
# this function concatenates the prefix, mid part (== joined parts), and the suffix (used in the error message builders)
# key = locale key used to find pre- and suffix
message_builder_helper = new Maker (data, phase, build_mode, locale, prefix, suffix, prefix_delimiter = " ", suffix_delimiter = " ") ->
# unpack data and set defaults
{key, parts, error_data = {}} = data
prefix = prefix or data.prefix or locales[locale]["#{key}_prefix"] or ""
suffix = suffix or data.suffix or locales[locale]["#{key}_suffix"] or ""
data.prefix = prefix?() or prefix
data.suffix = suffix?() or suffix
for part, i in parts
dict = new OrderedDict()
# if prefix instanceof Function
# prefix = prefix()
if part.prefix
dict.put("prefix", part.prefix)
dict.put("prefix_delimiter", part.prefix_delimiter or prefix_delimiter)
dict.put("message", part.message)
# if suffix instanceof Function
# suffix = suffix()
if part.suffix
dict.put("suffix_delimiter", part.suffix_delimiter or suffix_delimiter)
dict.put("suffix", part.suffix)
parts[i] = dict
new_parts = new OrderedDict()
for part, i in parts
new_parts.put(i, part)
data.parts = new_parts
return data
new MessageBuilder BUILD_MODES.ENUMERATE, (data, phase, build_mode, locale) ->
data = message_builder_helper.make(data, phase, build_mode, locale)
parts = data.parts.to_array()
lang_data = locales[locale]
parts_grouped_by_suffix = group_arr_by parts, (part) ->
return part.get("suffix") or ""
parts = []
for suffix, suffix_group of parts_grouped_by_suffix
parts_grouped_by_prefix = group_arr_by suffix_group, (part) ->
return part.get("prefix") or ""
# let the common prefix remain only in 1st part of the group
for prefix, prefix_group of parts_grouped_by_prefix
for p, i in prefix_group when i > 0
p.remove("prefix")
p.remove("prefix_delimiter")
# let the common suffix remain only in the last part of the group
for p, i in suffix_group when i < suffix_group.length - 1
p.remove("suffix_delimiter")
p.remove("suffix")
parts = parts.concat suffix_group
new_parts = new OrderedDict()
for part, i in parts
# prepend "and" to last part (if it's not the only part)
if i is parts.length - 1 and i > 0
part.put("prefix", " #{locales[locale]["and"]} #{part.get("prefix") or ""}", 0)
part.put("prefix_delimiter", " ", 1)
new_parts.put(i, part)
data.parts = new_parts
return "#{data.prefix or ""} #{new_parts.join("")} #{data.suffix or ""}".replace(/\s+/g, " ")
new MessageBuilder BUILD_MODES.SENTENCE, (data, phase, build_mode, locale) ->
data = message_builder_helper.make(data, phase, build_mode, locale)
data.parts.each (idx, part) ->
part.put("prefix", " #{data.prefix or ""} #{part.get("prefix") or ""}".trim(), 0)
part.put("prefix_delimiter", " ", 1)
part.put("suffix_delimiter", (if part.get("suffix") then part.get("suffix_delimiter") else ""), 3)
part.put("suffix", " #{data.suffix or ""} #{part.get("suffix") or ""}.".trim(), 4)
return true
parts = []
for part in data.parts.to_array()
parts.push part.join()
return parts.join(" ").replace(/\s+/g, " ").trim()
new MessageBuilder BUILD_MODES.LIST, (data, phase, build_mode, locale) ->
sentences = message_builders[BUILD_MODES.SENTENCE].build_message(data, phase, build_mode, locale)
if sentences[sentences.length - 1] is "."
sentences += " "
return "<ul><li>#{("#{sentence}." for sentence in sentences.split(". ") when sentence).join("</li><li>")}</li></ul>"
| true | #########################################################################################################
# WORKFLOW: error_message_builders[VALIDATION_PHASE] -> message builder
locale_message_builders =
de: {}
en: {}
locale_message_builders.de[BUILD_MODES.ENUMERATE] = null
locale_message_builders.de[BUILD_MODES.SENTENCE] = null
locale_message_builders.de[BUILD_MODES.LIST] = null
locale_message_builders.en[BUILD_MODES.ENUMERATE] = null
locale_message_builders.en[BUILD_MODES.SENTENCE] = null
locale_message_builders.en[BUILD_MODES.LIST] = null
message_builders = {}
message_data_creators = {}
# NOTE: This class structure overhead was made mainly for structuring/API reasons. If this causes preformance problems this should be simplified
class Maker
# CONSTRUCTOR
constructor: (namespace, key, func) ->
if arguments.length is 3
@func = func
namespace[key] = @
else
@func = arguments[0]
make: () ->
return @func(arguments...)
# This class'es instance's method is used to create the "raw" message data from the error data
class MessageDataCreator extends Maker
# CONSTRUCTOR
constructor: (name, func) ->
super(message_data_creators, name, func)
create_data: (errors, phase, build_mode, locale) ->
return @make(errors, phase, build_mode, locale)
# This class'es instance's method is used to transform the "raw" message data from the ErrorMessageBuilder
class MessageBuilder extends Maker
# CONSTRUCTOR
constructor: (name, func) ->
super(message_builders, name, func)
build_message: (parts, locale, phase, build_mode, error_data) ->
return @make(parts, locale, phase, build_mode, error_data)
class OrderedDict
# CONSTRUCTOR
constructor: () ->
@_dict = {}
@_order = []
put: (key, val, idx) ->
@_dict[key] = val
if not idx?
if key not in @_order
@_order.push key
else
i = @_order.indexOf(key)
# == key in @_order => remove it first
if i >= 0
@_order.splice(i, 1)
@_order.splice(idx, 0, key)
return @
get: (key) ->
return @_dict[key]
remove: (key) ->
delete @_dict[key]
@_order = (item for item in @_order when item isnt key)
return @
join: (str = "") ->
return (@_dict[key].join?(str) or @_dict[key] for key in @_order).join(str)
each: (callback) ->
for key, i in @_order
if callback.call(@, key, @_dict[key], i) is false
return @
return @
to_array: () ->
return (@_dict[key] for key in @_order)
to_object: () ->
res = {}
for key, val of @_dict
res[key] = val
return res
get_object: () ->
return @_dict
get_order: () ->
return @_order
# this function parses and replaces mustache-like strings or evaluate functions
part_evaluator = (part, values...) ->
if values.length is 1
values = values[0]
else
values = $.extend(values...)
# string => mustache-like
if typeof part is "string"
for key, val of values
substr = "{{#{key}}}"
if part.indexOf(substr) >= 0
regex = new RegExp(substr, "g")
part = part.replace(regex, val)
return part
if part instanceof Function
return part(values)
throw new Error("FormValidator: Error while building an error message. Expected mustache-like string or function but was given:", part, values)
################################################################################################
# DEFINE MESSAGE BUILDERS (FOR EACH VALIDATION PHASE)
new MessageDataCreator VALIDATION_PHASES.DEPENDENCIES, (errors, phase, build_mode, locale) ->
names = (error.name for error in errors when error.name?)
# if all errors have a name property (<=> all dependencies are named)
if names.length is errors.length
# sentence does not make sense in this case => fallback to enumerate
# if build_mode is BUILD_MODES.SENTENCE
# build_mode = BUILD_MODES.ENUMERATE
lang_data = locales[locale]
key = VALIDATION_PHASES_SINGULAR[phase].PI:KEY:<KEY>END_PI()
if names.length is 1
key += "_PI:KEY:<KEY>END_PI"
prefix_key = "#{key}_PI:KEY:<KEY>END_PI"
suffix_key = "#{key}_PI:KEY:<KEY>END_PI"
parts = ({message: "'#{name}'", prefix: lang_data[prefix_key], suffix: lang_data[suffix_key]} for name in names)
else
key = PI:KEY:<KEY>END_PI"
parts = []
return {parts}
# return locales[locale]["#{VALIDATION_PHASES_SINGULAR[phase].toLowerCase()}_general"]
new MessageDataCreator VALIDATION_PHASES.VALUE, (errors, phase, build_mode, locale) ->
# NOTE each error in errors (exactly 1 because of the phase) contains an error_message_type. that type is prefered over the normal type
error = errors[0]
key = PI:KEY:<KEY>END_PIerror.error_message_type or error.typePI:KEY:<KEY>END_PI}"
# here only 1 error is in the 'errors' list => therefore we just use the simplest build mode
part =
message: part_evaluator(locales[locale][key], error)
prefix: ""
suffix: ""
# return message_builders[build_mode.toLowerCase()](key, phase, build_mode, locale, [part])
return {key, parts: [part]}
new MessageDataCreator VALIDATION_PHASES.CONSTRAINTS, (errors, phase, build_mode, locale) ->
parts = []
# group by error.type as defined in constraint_validator_groups (if an error is in no group it implicitely creates an own group)
grouped_errors = []
ungrouped_errors = []
for error in errors
error_in_group = false
for group, i in constraint_validator_groups
if error.type in group
error_in_group = true
if grouped_errors[i]?
grouped_errors[i].push(error)
else
grouped_errors[i] = [error]
if not error_in_group
ungrouped_errors.push error
for error in ungrouped_errors
grouped_errors.push [error]
phase_singular = VALIDATION_PHASES_SINGULAR[phase].toLowerCase()
# find combinable locale keys (errors with the same type may use a special locale key)
key_prefix = PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI"
default_prefix = locales[locale]["#{phase_singular}_#{build_mode}_prefix".toLowerCase()] or ""
default_suffix = locales[locale]["#{phase_singular}_#{build_mode}_suffix".toLowerCase()] or ""
# go through groups of errors (and skip empty entries caused in the above loop)
for errors in grouped_errors when errors?
keys = []
for error in errors
keys.push error.type
if error.options?
for option, val of error.options when include_constraint_option_in_locale_key(option, val, locale)
keys.push option
key = get_PI:KEY:<KEY>END_PI_key(keys, locale, key_prefix)
if key?
parts.push {
message: part_evaluator(locales[locale][key], errors...)
prefix: part_evaluator(locales[locale]["#{key}_prefix"], error) or default_prefix
suffix: part_evaluator(locales[locale]["#{key}_suffix"], error) or default_suffix
}
else if DEBUG
throw new Error("Could not find a translation for key while trying to create an error message during the constraint validation phase. The keys that were retrieved from the generated errors are: #{JSON.stringify(keys)}. Define an according key in the 'locales' variable (e.g. '#{key_prefix}#{keys.join("_")}')!")
key = PI:KEY:<KEY>END_PI
# replace {{value}} with the actual value
prefix = part_evaluator("#{locales[locale]["#{key}_prefix"]}", errors[0])
error_data = $.extend([{}].concat(errors)...)
return {key, parts, error_data, prefix}
# this function concatenates the prefix, mid part (== joined parts), and the suffix (used in the error message builders)
# key = locale key used to find pre- and suffix
message_builder_helper = new Maker (data, phase, build_mode, locale, prefix, suffix, prefix_delimiter = " ", suffix_delimiter = " ") ->
# unpack data and set defaults
{key, parts, error_data = {}} = data
prefix = prefix or data.prefix or locales[locale]["#{key}_prefix"] or ""
suffix = suffix or data.suffix or locales[locale]["#{key}_suffix"] or ""
data.prefix = prefix?() or prefix
data.suffix = suffix?() or suffix
for part, i in parts
dict = new OrderedDict()
# if prefix instanceof Function
# prefix = prefix()
if part.prefix
dict.put("prefix", part.prefix)
dict.put("prefix_delimiter", part.prefix_delimiter or prefix_delimiter)
dict.put("message", part.message)
# if suffix instanceof Function
# suffix = suffix()
if part.suffix
dict.put("suffix_delimiter", part.suffix_delimiter or suffix_delimiter)
dict.put("suffix", part.suffix)
parts[i] = dict
new_parts = new OrderedDict()
for part, i in parts
new_parts.put(i, part)
data.parts = new_parts
return data
new MessageBuilder BUILD_MODES.ENUMERATE, (data, phase, build_mode, locale) ->
data = message_builder_helper.make(data, phase, build_mode, locale)
parts = data.parts.to_array()
lang_data = locales[locale]
parts_grouped_by_suffix = group_arr_by parts, (part) ->
return part.get("suffix") or ""
parts = []
for suffix, suffix_group of parts_grouped_by_suffix
parts_grouped_by_prefix = group_arr_by suffix_group, (part) ->
return part.get("prefix") or ""
# let the common prefix remain only in 1st part of the group
for prefix, prefix_group of parts_grouped_by_prefix
for p, i in prefix_group when i > 0
p.remove("prefix")
p.remove("prefix_delimiter")
# let the common suffix remain only in the last part of the group
for p, i in suffix_group when i < suffix_group.length - 1
p.remove("suffix_delimiter")
p.remove("suffix")
parts = parts.concat suffix_group
new_parts = new OrderedDict()
for part, i in parts
# prepend "and" to last part (if it's not the only part)
if i is parts.length - 1 and i > 0
part.put("prefix", " #{locales[locale]["and"]} #{part.get("prefix") or ""}", 0)
part.put("prefix_delimiter", " ", 1)
new_parts.put(i, part)
data.parts = new_parts
return "#{data.prefix or ""} #{new_parts.join("")} #{data.suffix or ""}".replace(/\s+/g, " ")
new MessageBuilder BUILD_MODES.SENTENCE, (data, phase, build_mode, locale) ->
data = message_builder_helper.make(data, phase, build_mode, locale)
data.parts.each (idx, part) ->
part.put("prefix", " #{data.prefix or ""} #{part.get("prefix") or ""}".trim(), 0)
part.put("prefix_delimiter", " ", 1)
part.put("suffix_delimiter", (if part.get("suffix") then part.get("suffix_delimiter") else ""), 3)
part.put("suffix", " #{data.suffix or ""} #{part.get("suffix") or ""}.".trim(), 4)
return true
parts = []
for part in data.parts.to_array()
parts.push part.join()
return parts.join(" ").replace(/\s+/g, " ").trim()
new MessageBuilder BUILD_MODES.LIST, (data, phase, build_mode, locale) ->
sentences = message_builders[BUILD_MODES.SENTENCE].build_message(data, phase, build_mode, locale)
if sentences[sentences.length - 1] is "."
sentences += " "
return "<ul><li>#{("#{sentence}." for sentence in sentences.split(". ") when sentence).join("</li><li>")}</li></ul>"
|
[
{
"context": " hubot XXX [<args>] - DESCRIPTION\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nmodule.exports = (robot) ->\n r",
"end": 152,
"score": 0.9997252821922302,
"start": 145,
"tag": "USERNAME",
"value": "bouzuya"
},
{
"context": "X [<args>] - DESCRIPTION\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nmodule.exports = (robot) ->\n robot.respond /h",
"end": 167,
"score": 0.9999259114265442,
"start": 154,
"tag": "EMAIL",
"value": "m@bouzuya.net"
}
] | src/scripts/hello.coffee | bouzuya/hubot-script-boilerplate | 4 | # Description
# A Hubot script that DESCRIPTION
#
# Configuration:
# None
#
# Commands:
# hubot XXX [<args>] - DESCRIPTION
#
# Author:
# bouzuya <m@bouzuya.net>
#
module.exports = (robot) ->
robot.respond /h(?:ello|i)$/i, (res) ->
res.send 'hello!'
| 121771 | # Description
# A Hubot script that DESCRIPTION
#
# Configuration:
# None
#
# Commands:
# hubot XXX [<args>] - DESCRIPTION
#
# Author:
# bouzuya <<EMAIL>>
#
module.exports = (robot) ->
robot.respond /h(?:ello|i)$/i, (res) ->
res.send 'hello!'
| true | # Description
# A Hubot script that DESCRIPTION
#
# Configuration:
# None
#
# Commands:
# hubot XXX [<args>] - DESCRIPTION
#
# Author:
# bouzuya <PI:EMAIL:<EMAIL>END_PI>
#
module.exports = (robot) ->
robot.respond /h(?:ello|i)$/i, (res) ->
res.send 'hello!'
|
[
{
"context": "blesorter.com\n###\n\nlast_name_options =\n id: 'last_name' # the parser na",
"end": 173,
"score": 0.8212679028511047,
"start": 169,
"tag": "NAME",
"value": "last"
},
{
"context": "rter.com\n###\n\nlast_name_options =\n id: 'last_name' # the parser name\n ",
"end": 178,
"score": 0.5095197558403015,
"start": 174,
"tag": "NAME",
"value": "name"
}
] | app/assets/javascripts/unit_certs/unit_certs_table.js.coffee | andyl/BAMRU-Private | 1 | ###
This is jQuery code that manages the
table sorting on the unit_certs/index page.
Table sorter plugin at: http://tablesorter.com
###
last_name_options =
id: 'last_name' # the parser name
is: (s) -> false # disable standard parser
type: 'text' # either text or numeric
format: (s) -> (new MemberName(s)).last_name() # the sort key (last name)
role_score_options =
id: 'role_score' # the parser name
is: (s) -> false # disable standard parser
type: 'numeric' # either text or numeric
format: (s) -> (new RoleScore(s)).score() # the sort key (role score)
sort_opts =
headers:
0: {sorter: 'role_score'} # sort col 0 using role_score options
1: {sorter: 'last_name'} # sort col 3 using last_name options
filter_params =
filterContainer: "#filter-box"
filterClearContainer: "#filter-clear-button"
filterColumns: [0,1,2,3,4,5,6,7,8,9,10,11]
columns: ["role", "name", "med", "cpr", "ham", "tracking", "avy", "rigging", "ics", "search", "driver", "bkgrnd"]
save_cert_sort_to_cookie = (sort_spec) ->
spec_string = JSON.stringify(sort_spec)
createCookie("cert_sort", spec_string)
read_cert_sort_from_cookie = ->
string = readCookie("cert_sort")
if (string == null) then null else JSON.parse(string)
$(document).ready ->
$.tablesorter.addParser last_name_options
$.tablesorter.addParser role_score_options
sort_spec = read_cert_sort_from_cookie()
sort_opts['sortList'] = sort_spec unless sort_spec == null
$("#myTable").tablesorter(sort_opts).bind "sortEnd", (sorter) ->
save_cert_sort_to_cookie(sorter.target.config.sortList)
$("#myTable").tablesorterFilter(filter_params)
$("#filter-box").focus()
$(document).ready ->
$('#clearsort').click ->
eraseCookie("cert_sort")
refresh_url = window.location.href.split(/[?#]/, 1)
window.location.assign(refresh_url) | 35722 | ###
This is jQuery code that manages the
table sorting on the unit_certs/index page.
Table sorter plugin at: http://tablesorter.com
###
last_name_options =
id: '<NAME>_<NAME>' # the parser name
is: (s) -> false # disable standard parser
type: 'text' # either text or numeric
format: (s) -> (new MemberName(s)).last_name() # the sort key (last name)
role_score_options =
id: 'role_score' # the parser name
is: (s) -> false # disable standard parser
type: 'numeric' # either text or numeric
format: (s) -> (new RoleScore(s)).score() # the sort key (role score)
sort_opts =
headers:
0: {sorter: 'role_score'} # sort col 0 using role_score options
1: {sorter: 'last_name'} # sort col 3 using last_name options
filter_params =
filterContainer: "#filter-box"
filterClearContainer: "#filter-clear-button"
filterColumns: [0,1,2,3,4,5,6,7,8,9,10,11]
columns: ["role", "name", "med", "cpr", "ham", "tracking", "avy", "rigging", "ics", "search", "driver", "bkgrnd"]
save_cert_sort_to_cookie = (sort_spec) ->
spec_string = JSON.stringify(sort_spec)
createCookie("cert_sort", spec_string)
read_cert_sort_from_cookie = ->
string = readCookie("cert_sort")
if (string == null) then null else JSON.parse(string)
$(document).ready ->
$.tablesorter.addParser last_name_options
$.tablesorter.addParser role_score_options
sort_spec = read_cert_sort_from_cookie()
sort_opts['sortList'] = sort_spec unless sort_spec == null
$("#myTable").tablesorter(sort_opts).bind "sortEnd", (sorter) ->
save_cert_sort_to_cookie(sorter.target.config.sortList)
$("#myTable").tablesorterFilter(filter_params)
$("#filter-box").focus()
$(document).ready ->
$('#clearsort').click ->
eraseCookie("cert_sort")
refresh_url = window.location.href.split(/[?#]/, 1)
window.location.assign(refresh_url) | true | ###
This is jQuery code that manages the
table sorting on the unit_certs/index page.
Table sorter plugin at: http://tablesorter.com
###
last_name_options =
id: 'PI:NAME:<NAME>END_PI_PI:NAME:<NAME>END_PI' # the parser name
is: (s) -> false # disable standard parser
type: 'text' # either text or numeric
format: (s) -> (new MemberName(s)).last_name() # the sort key (last name)
role_score_options =
id: 'role_score' # the parser name
is: (s) -> false # disable standard parser
type: 'numeric' # either text or numeric
format: (s) -> (new RoleScore(s)).score() # the sort key (role score)
sort_opts =
headers:
0: {sorter: 'role_score'} # sort col 0 using role_score options
1: {sorter: 'last_name'} # sort col 3 using last_name options
filter_params =
filterContainer: "#filter-box"
filterClearContainer: "#filter-clear-button"
filterColumns: [0,1,2,3,4,5,6,7,8,9,10,11]
columns: ["role", "name", "med", "cpr", "ham", "tracking", "avy", "rigging", "ics", "search", "driver", "bkgrnd"]
save_cert_sort_to_cookie = (sort_spec) ->
spec_string = JSON.stringify(sort_spec)
createCookie("cert_sort", spec_string)
read_cert_sort_from_cookie = ->
string = readCookie("cert_sort")
if (string == null) then null else JSON.parse(string)
$(document).ready ->
$.tablesorter.addParser last_name_options
$.tablesorter.addParser role_score_options
sort_spec = read_cert_sort_from_cookie()
sort_opts['sortList'] = sort_spec unless sort_spec == null
$("#myTable").tablesorter(sort_opts).bind "sortEnd", (sorter) ->
save_cert_sort_to_cookie(sorter.target.config.sortList)
$("#myTable").tablesorterFilter(filter_params)
$("#filter-box").focus()
$(document).ready ->
$('#clearsort').click ->
eraseCookie("cert_sort")
refresh_url = window.location.href.split(/[?#]/, 1)
window.location.assign(refresh_url) |
[
{
"context": " throw new Error(\"InvalidStateError\")\n key = \"#{header}\".toLowerCase()\n if @requestHeaders[key]\n @requestHeaders",
"end": 2017,
"score": 0.9899927973747253,
"start": 1992,
"tag": "KEY",
"value": "\"#{header}\".toLowerCase()"
},
{
"context": "ED\n return null if @errorFlag == true\n key = \"#{header}\".toLowerCase()\n return @responseHeaders[key] if @responseHead",
"end": 5174,
"score": 0.9980186223983765,
"start": 5149,
"tag": "KEY",
"value": "\"#{header}\".toLowerCase()"
},
{
"context": "[name, value] = line.split(\":\", 2)\n key = name.toLowerCase()\n @responseHeaders[key] = [name, value.tr",
"end": 9923,
"score": 0.9969635605812073,
"start": 9905,
"tag": "KEY",
"value": "name.toLowerCase()"
}
] | src/board/memhttprequest.coffee | kimushu/rubic-chrome | 1 | "use strict"
module.exports = class MemHttpRequest
DEBUG = 0
# XMLHttpRequest compatible constants
@UNSENT: XMLHttpRequest.UNSENT
@OPENED: XMLHttpRequest.OPENED
@HEADERS_RECEIVED: XMLHttpRequest.HEADERS_RECEIVED
@LOADING: XMLHttpRequest.LOADING
@DONE: XMLHttpRequest.DONE
UNSENT: @UNSENT
OPENED: @OPENED
HEADERS_RECEIVED: @HEADERS_RECEIVED
LOADING: @LOADING
DONE: @DONE
#------------------------------------------------
# XMLHttpRequest compatible members
#
onloadstart: null
onprogress: null
onabort: null
onerror: null
onload: null
ontimeout: null
onloadend: null
onreadystatechange: null
###*
@property {Number} readyState
@readonly
Attribute for XMLHttpRequest compatibility.
###
readyState: @UNSENT
###*
@method open
@param {String} method Request method (GET/POST/etc.)
@param {String} url Request URL (http://xx/yy/zz?query)
@return {void}
Method for XMLHttpRequest compatibility.
But no sync mode and no user authentication.
###
open: (method, url) ->
parser = document.createElement("a")
parser.href = url
throw new TypeError("Unsupported protocol") unless parser.protocol == "http:"
@requestMethod = "#{method}".toUpperCase()
@requestStartLine = "\
#{@requestMethod} #{encodeURI(parser.pathname + parser.search)} HTTP/1.1\r\n\
"
@requestHeaders = {host: ["Host", encodeURI(parser.hostname)]}
App.log.verbose({"MemHttpRequest#open": this}) if DEBUG > 0
@sendFlag = false
@changeState(@OPENED)
null
###*
@method setRequestHeader
@param {String} header Header string (ex: User-Agent)
@param {String} value Value string
@return {void}
Method for XMLHttpRequest compatibility.
###
setRequestHeader: (header, value) ->
unless @readyState == @OPENED and @sendFlag == false
throw new Error("InvalidStateError")
key = "#{header}".toLowerCase()
if @requestHeaders[key]
@requestHeaders[key][1] = "#{value}"
else
@requestHeaders[key] = ["#{header}", "#{value}"]
null
###*
@property {Number} timeout
Attribute for XMLHttpRequest compatibility.
###
timeout: 0
###*
@property {Boolean} withCredentials
Attribute for XMLHttpRequest compatibility. But not supported.
###
withCredentials: false # not supported
###*
@property {Object} upload
Attribute for XMLHttpRequest compatibility. But not supported.
###
upload: null # not supported
###*
@method send
@param {Uint8Array/String} data Request body
@return {void}
Method for XMLHttpRequest compatibility.
Supported type of data are Uint8Array and String only.
###
send: (data) ->
unless @readyState == @OPENED and @sendFlag == false
throw new Error("InvalidStateError")
data = null if @requestMethod == "GET" or @requestMethod == "HEAD"
if data instanceof Uint8Array
contentType = "application/octet-stream"
else if data instanceof String
contentType = "text/plain;charset=UTF-8"
else unless data?
contentType = null
else
throw new TypeError("Unsupported data type")
@sendFlag = true
@requestHeaders["content-type"] or= ["Content-Type", contentType] if contentType?
sendArrayBuffer = (buffer) =>
dataLength = if buffer? then buffer.byteLength else 0
@requestHeaders["content-length"] or= ["Content-Length", "#{dataLength}"]
request = @requestStartLine
request += "#{pair[0]}: #{pair[1]}\r\n" for key, pair of @requestHeaders
request += "\r\n"
reader = new FileReader()
reader.onload = =>
App.log.verbose({"request-header": request})
App.log.verbose({"request-body": new Uint8Array(buffer)})
array = new Uint8Array(reader.result.byteLength + dataLength)
array.set(new Uint8Array(reader.result), 0)
array.set(new Uint8Array(buffer), reader.result.byteLength) if buffer?
@requestBuffer = array.buffer
@requestOffset = 0
@responseOffset = 0
@clearTimeStamp()
@transmitMessage()
reader.readAsArrayBuffer(new Blob([request]))
if data instanceof String
reader = new FileReader()
reader.onload = -> sendArrayBuffer(reader.result)
reader.readAsArrayBuffer(new Blob([data]))
else
sendArrayBuffer(data or new ArrayBuffer(0))
null
###*
@method abort
@return {void}
Method for XMLHttpRequest compatibility. But not supported.
###
abort: () ->
throw new Error("NotSupportedError")
###*
@property {Number} status
@readonly
Attribute for XMLHttpRequest compatibility.
###
status: 0
###*
@property {String} statusText
@readonly
Attribute for XMLHttpRequest compatibility.
###
statusText: ""
###*
@method getResponseHeader
@param {String} header Response header
@return {void/String}
Method for XMLHttpRequest compatibility.
###
getResponseHeader: (header) ->
return null if @readyState == UNSENT or @readyState == OPENED
return null if @errorFlag == true
key = "#{header}".toLowerCase()
return @responseHeaders[key] if @responseHeaders[key][1]
null
###*
@method getAllResponseHeaders
@return {String}
Method for XMLHttpRequest compatibility.
###
getAllResponseHeaders: () ->
return "" if @readyState == UNSENT or @readyState == OPENED
return "" if @errorFlag == true
result = ""
for key, pair of @responseHeaders
result += "#{pair[0]}: #{pair[1]}\r\n"
result
###*
@method overrideMimeType
@return {void}
Method for XMLHttpRequest compatibility. But not supported.
###
overrideMimeType: (mime) ->
throw new Error("NotSupportedError")
###*
@property {String} responseType
Attribute for XMLHttpRequest compatibility.
###
responseType: ""
###*
@property {Object} response
@readonly
Attribute for XMLHttpRequest compatibility.
###
response: null
###*
@property {Object} responseXML
@readonly
Attribute for XMLHttpRequest compatibility. But not supported.
###
responseXML: null # not supported
#------------------------------------------------
# Private member
#
TX_RETRY_MS = 100
RX_RETRY_MS = 100
###*
Constructor of MemHttpRequest
@param {Object} datalink Object with data-link (getTxPacket/getRxPacket)
###
constructor: (@datalink) -> null
###*
@private
@method changeState
@param {Integer} newState
Update state and invoke callbacks
###
changeState: (newState) ->
return if @readyState == newState
App.log.verbose({
"MemHttpRequest#changeState": this
oldState: @readyState
newState: newState
}) if DEBUG > 0
@readyState = newState
@onreadystatechange and @onreadystatechange() if newState != @UNSENT
###*
@private
@method failed
@param {String} message
@param {Function} callback
Set error flag and update state to DONE
###
failed: (message, callback) ->
App.log.verbose({"MemHttpRequest#failed": this, message: message})
@errorFlag = true
@changeState(@DONE)
callback?()
###*
@private
@method transmitMessage
Transmit a request message
###
transmitMessage: () ->
@datalink.getTxPacket((packet) =>
return @isTimedOut("Transmit") or \
setTimeout((=> @transmitMessage()), TX_RETRY_MS) unless packet?
offset = @requestOffset
packet.length = Math.min(@requestBuffer.byteLength - offset, packet.capacity)
@requestOffset += packet.length
packet.buffer = @requestBuffer.slice(offset, offset + packet.length)
App.log.verbose({
"MemHttpRequest#transmitMessage": this
packet: packet
array: new Uint8Array(packet.buffer)
}) if DEBUG > 0
packet.startOfMessage = (offset == 0)
if @requestOffset >= @requestBuffer.byteLength
packet.endOfMessage = true
packet.transmit((result) =>
return @failed("Transmitting last packet") unless result
@clearTimeStamp()
@receiveMessage()
)
else
packet.endOfMessag = false
packet.transmit((result) =>
return @failed("Transmitting packet") unless result
@clearTimeStamp()
@transmitMessage()
)
null
)
###*
@private
@method receiveMessage
Receive a response message
###
receiveMessage: () ->
@datalink.getRxPacket((packet) =>
return @isTimedOut("Receive") or \
setTimeout((=> @receiveMessage()), RX_RETRY_MS) unless packet?
App.log.verbose({
"MemHttpRequest#receiveMessage": this
packet: packet
data: new Uint8Array(packet.buffer)
}) if DEBUG > 0
failed = (message) => @failed(message, packet.discard)
if @responseOffset == 0
return failed("Received invalid first packet") unless packet.startOfMessage
headerLength = null
array = new Uint8Array(packet.buffer)
for i in [0..packet.length-4]
if array[i+0] == 0xd and array[i+1] == 0xa and \
array[i+2] == 0xd and array[i+3] == 0xa
headerLength = i
break
return failed("No splitter in first packet") unless headerLength
resp = String.fromCharCode.apply(null, new Uint8Array(array.buffer, 0, headerLength))
headerLength += 4
lines = resp.split("\r\n")
[http, @statusText] = lines.shift().split(" ", 2)
unless http == "HTTP/1.0" or http == "HTTP/1.1"
return failed("Invalid response start line")
@status = parseInt(@statusText)
if DEBUG > 0
App.log.verbose({"response-status": @status})
App.log.verbose({"response-header": "#{resp}\r\n\r\n"})
@responseHeaders = {}
for line in lines
[name, value] = line.split(":", 2)
key = name.toLowerCase()
@responseHeaders[key] = [name, value.trim()]
@responseLength = parseInt((@responseHeaders["content-length"] or [null, "0"])[1])
@responseBuffer = new ArrayBuffer(@responseLength)
else
headerLength = 0
if @responseBuffer.byteLength > 0
copyLength = Math.min(@responseLength - @responseOffset,
packet.length - headerLength)
if copyLength > 0
array = new Uint8Array(@responseBuffer, @responseOffset, copyLength)
array.set(new Uint8Array(array.buffer, headerLength, copyLength))
@responseOffset += copyLength
return packet.discard(=>
@clearTimeStamp()
@receiveMessage()
) unless packet.endOfMessage
return failed("Broken message") unless @responseOffset >= @responseLength
switch @responseType
when "", "string"
@response = String.fromCharCode.apply(null, new Uint8Array(@responseBuffer))
when "arraybuffer"
@response = @responseBuffer
else
throw new TypeError("Unsupported responseType")
App.log.verbose({"response-body": @response}) if DEBUG > 0
packet.discard(=> @changeState(@DONE))
)
###*
@private
@method clearTimeStamp
@return {Boolean} Always true
###
clearTimeStamp: () ->
@timeStamp = +new Date()
true
###*
@private
@method isTimedOut
@retval true Timed out
@retval false Not timed out
###
isTimedOut: (message) ->
duration = (new Date() - @timeStamp)
return false if @timeout == 0 or duration < @timeout
@failed(message)
true
App = require("app/app")
| 72762 | "use strict"
module.exports = class MemHttpRequest
DEBUG = 0
# XMLHttpRequest compatible constants
@UNSENT: XMLHttpRequest.UNSENT
@OPENED: XMLHttpRequest.OPENED
@HEADERS_RECEIVED: XMLHttpRequest.HEADERS_RECEIVED
@LOADING: XMLHttpRequest.LOADING
@DONE: XMLHttpRequest.DONE
UNSENT: @UNSENT
OPENED: @OPENED
HEADERS_RECEIVED: @HEADERS_RECEIVED
LOADING: @LOADING
DONE: @DONE
#------------------------------------------------
# XMLHttpRequest compatible members
#
onloadstart: null
onprogress: null
onabort: null
onerror: null
onload: null
ontimeout: null
onloadend: null
onreadystatechange: null
###*
@property {Number} readyState
@readonly
Attribute for XMLHttpRequest compatibility.
###
readyState: @UNSENT
###*
@method open
@param {String} method Request method (GET/POST/etc.)
@param {String} url Request URL (http://xx/yy/zz?query)
@return {void}
Method for XMLHttpRequest compatibility.
But no sync mode and no user authentication.
###
open: (method, url) ->
parser = document.createElement("a")
parser.href = url
throw new TypeError("Unsupported protocol") unless parser.protocol == "http:"
@requestMethod = "#{method}".toUpperCase()
@requestStartLine = "\
#{@requestMethod} #{encodeURI(parser.pathname + parser.search)} HTTP/1.1\r\n\
"
@requestHeaders = {host: ["Host", encodeURI(parser.hostname)]}
App.log.verbose({"MemHttpRequest#open": this}) if DEBUG > 0
@sendFlag = false
@changeState(@OPENED)
null
###*
@method setRequestHeader
@param {String} header Header string (ex: User-Agent)
@param {String} value Value string
@return {void}
Method for XMLHttpRequest compatibility.
###
setRequestHeader: (header, value) ->
unless @readyState == @OPENED and @sendFlag == false
throw new Error("InvalidStateError")
key = <KEY>
if @requestHeaders[key]
@requestHeaders[key][1] = "#{value}"
else
@requestHeaders[key] = ["#{header}", "#{value}"]
null
###*
@property {Number} timeout
Attribute for XMLHttpRequest compatibility.
###
timeout: 0
###*
@property {Boolean} withCredentials
Attribute for XMLHttpRequest compatibility. But not supported.
###
withCredentials: false # not supported
###*
@property {Object} upload
Attribute for XMLHttpRequest compatibility. But not supported.
###
upload: null # not supported
###*
@method send
@param {Uint8Array/String} data Request body
@return {void}
Method for XMLHttpRequest compatibility.
Supported type of data are Uint8Array and String only.
###
send: (data) ->
unless @readyState == @OPENED and @sendFlag == false
throw new Error("InvalidStateError")
data = null if @requestMethod == "GET" or @requestMethod == "HEAD"
if data instanceof Uint8Array
contentType = "application/octet-stream"
else if data instanceof String
contentType = "text/plain;charset=UTF-8"
else unless data?
contentType = null
else
throw new TypeError("Unsupported data type")
@sendFlag = true
@requestHeaders["content-type"] or= ["Content-Type", contentType] if contentType?
sendArrayBuffer = (buffer) =>
dataLength = if buffer? then buffer.byteLength else 0
@requestHeaders["content-length"] or= ["Content-Length", "#{dataLength}"]
request = @requestStartLine
request += "#{pair[0]}: #{pair[1]}\r\n" for key, pair of @requestHeaders
request += "\r\n"
reader = new FileReader()
reader.onload = =>
App.log.verbose({"request-header": request})
App.log.verbose({"request-body": new Uint8Array(buffer)})
array = new Uint8Array(reader.result.byteLength + dataLength)
array.set(new Uint8Array(reader.result), 0)
array.set(new Uint8Array(buffer), reader.result.byteLength) if buffer?
@requestBuffer = array.buffer
@requestOffset = 0
@responseOffset = 0
@clearTimeStamp()
@transmitMessage()
reader.readAsArrayBuffer(new Blob([request]))
if data instanceof String
reader = new FileReader()
reader.onload = -> sendArrayBuffer(reader.result)
reader.readAsArrayBuffer(new Blob([data]))
else
sendArrayBuffer(data or new ArrayBuffer(0))
null
###*
@method abort
@return {void}
Method for XMLHttpRequest compatibility. But not supported.
###
abort: () ->
throw new Error("NotSupportedError")
###*
@property {Number} status
@readonly
Attribute for XMLHttpRequest compatibility.
###
status: 0
###*
@property {String} statusText
@readonly
Attribute for XMLHttpRequest compatibility.
###
statusText: ""
###*
@method getResponseHeader
@param {String} header Response header
@return {void/String}
Method for XMLHttpRequest compatibility.
###
getResponseHeader: (header) ->
return null if @readyState == UNSENT or @readyState == OPENED
return null if @errorFlag == true
key = <KEY>
return @responseHeaders[key] if @responseHeaders[key][1]
null
###*
@method getAllResponseHeaders
@return {String}
Method for XMLHttpRequest compatibility.
###
getAllResponseHeaders: () ->
return "" if @readyState == UNSENT or @readyState == OPENED
return "" if @errorFlag == true
result = ""
for key, pair of @responseHeaders
result += "#{pair[0]}: #{pair[1]}\r\n"
result
###*
@method overrideMimeType
@return {void}
Method for XMLHttpRequest compatibility. But not supported.
###
overrideMimeType: (mime) ->
throw new Error("NotSupportedError")
###*
@property {String} responseType
Attribute for XMLHttpRequest compatibility.
###
responseType: ""
###*
@property {Object} response
@readonly
Attribute for XMLHttpRequest compatibility.
###
response: null
###*
@property {Object} responseXML
@readonly
Attribute for XMLHttpRequest compatibility. But not supported.
###
responseXML: null # not supported
#------------------------------------------------
# Private member
#
TX_RETRY_MS = 100
RX_RETRY_MS = 100
###*
Constructor of MemHttpRequest
@param {Object} datalink Object with data-link (getTxPacket/getRxPacket)
###
constructor: (@datalink) -> null
###*
@private
@method changeState
@param {Integer} newState
Update state and invoke callbacks
###
changeState: (newState) ->
return if @readyState == newState
App.log.verbose({
"MemHttpRequest#changeState": this
oldState: @readyState
newState: newState
}) if DEBUG > 0
@readyState = newState
@onreadystatechange and @onreadystatechange() if newState != @UNSENT
###*
@private
@method failed
@param {String} message
@param {Function} callback
Set error flag and update state to DONE
###
failed: (message, callback) ->
App.log.verbose({"MemHttpRequest#failed": this, message: message})
@errorFlag = true
@changeState(@DONE)
callback?()
###*
@private
@method transmitMessage
Transmit a request message
###
transmitMessage: () ->
@datalink.getTxPacket((packet) =>
return @isTimedOut("Transmit") or \
setTimeout((=> @transmitMessage()), TX_RETRY_MS) unless packet?
offset = @requestOffset
packet.length = Math.min(@requestBuffer.byteLength - offset, packet.capacity)
@requestOffset += packet.length
packet.buffer = @requestBuffer.slice(offset, offset + packet.length)
App.log.verbose({
"MemHttpRequest#transmitMessage": this
packet: packet
array: new Uint8Array(packet.buffer)
}) if DEBUG > 0
packet.startOfMessage = (offset == 0)
if @requestOffset >= @requestBuffer.byteLength
packet.endOfMessage = true
packet.transmit((result) =>
return @failed("Transmitting last packet") unless result
@clearTimeStamp()
@receiveMessage()
)
else
packet.endOfMessag = false
packet.transmit((result) =>
return @failed("Transmitting packet") unless result
@clearTimeStamp()
@transmitMessage()
)
null
)
###*
@private
@method receiveMessage
Receive a response message
###
receiveMessage: () ->
@datalink.getRxPacket((packet) =>
return @isTimedOut("Receive") or \
setTimeout((=> @receiveMessage()), RX_RETRY_MS) unless packet?
App.log.verbose({
"MemHttpRequest#receiveMessage": this
packet: packet
data: new Uint8Array(packet.buffer)
}) if DEBUG > 0
failed = (message) => @failed(message, packet.discard)
if @responseOffset == 0
return failed("Received invalid first packet") unless packet.startOfMessage
headerLength = null
array = new Uint8Array(packet.buffer)
for i in [0..packet.length-4]
if array[i+0] == 0xd and array[i+1] == 0xa and \
array[i+2] == 0xd and array[i+3] == 0xa
headerLength = i
break
return failed("No splitter in first packet") unless headerLength
resp = String.fromCharCode.apply(null, new Uint8Array(array.buffer, 0, headerLength))
headerLength += 4
lines = resp.split("\r\n")
[http, @statusText] = lines.shift().split(" ", 2)
unless http == "HTTP/1.0" or http == "HTTP/1.1"
return failed("Invalid response start line")
@status = parseInt(@statusText)
if DEBUG > 0
App.log.verbose({"response-status": @status})
App.log.verbose({"response-header": "#{resp}\r\n\r\n"})
@responseHeaders = {}
for line in lines
[name, value] = line.split(":", 2)
key = <KEY>
@responseHeaders[key] = [name, value.trim()]
@responseLength = parseInt((@responseHeaders["content-length"] or [null, "0"])[1])
@responseBuffer = new ArrayBuffer(@responseLength)
else
headerLength = 0
if @responseBuffer.byteLength > 0
copyLength = Math.min(@responseLength - @responseOffset,
packet.length - headerLength)
if copyLength > 0
array = new Uint8Array(@responseBuffer, @responseOffset, copyLength)
array.set(new Uint8Array(array.buffer, headerLength, copyLength))
@responseOffset += copyLength
return packet.discard(=>
@clearTimeStamp()
@receiveMessage()
) unless packet.endOfMessage
return failed("Broken message") unless @responseOffset >= @responseLength
switch @responseType
when "", "string"
@response = String.fromCharCode.apply(null, new Uint8Array(@responseBuffer))
when "arraybuffer"
@response = @responseBuffer
else
throw new TypeError("Unsupported responseType")
App.log.verbose({"response-body": @response}) if DEBUG > 0
packet.discard(=> @changeState(@DONE))
)
###*
@private
@method clearTimeStamp
@return {Boolean} Always true
###
clearTimeStamp: () ->
@timeStamp = +new Date()
true
###*
@private
@method isTimedOut
@retval true Timed out
@retval false Not timed out
###
isTimedOut: (message) ->
duration = (new Date() - @timeStamp)
return false if @timeout == 0 or duration < @timeout
@failed(message)
true
App = require("app/app")
| true | "use strict"
module.exports = class MemHttpRequest
DEBUG = 0
# XMLHttpRequest compatible constants
@UNSENT: XMLHttpRequest.UNSENT
@OPENED: XMLHttpRequest.OPENED
@HEADERS_RECEIVED: XMLHttpRequest.HEADERS_RECEIVED
@LOADING: XMLHttpRequest.LOADING
@DONE: XMLHttpRequest.DONE
UNSENT: @UNSENT
OPENED: @OPENED
HEADERS_RECEIVED: @HEADERS_RECEIVED
LOADING: @LOADING
DONE: @DONE
#------------------------------------------------
# XMLHttpRequest compatible members
#
onloadstart: null
onprogress: null
onabort: null
onerror: null
onload: null
ontimeout: null
onloadend: null
onreadystatechange: null
###*
@property {Number} readyState
@readonly
Attribute for XMLHttpRequest compatibility.
###
readyState: @UNSENT
###*
@method open
@param {String} method Request method (GET/POST/etc.)
@param {String} url Request URL (http://xx/yy/zz?query)
@return {void}
Method for XMLHttpRequest compatibility.
But no sync mode and no user authentication.
###
open: (method, url) ->
parser = document.createElement("a")
parser.href = url
throw new TypeError("Unsupported protocol") unless parser.protocol == "http:"
@requestMethod = "#{method}".toUpperCase()
@requestStartLine = "\
#{@requestMethod} #{encodeURI(parser.pathname + parser.search)} HTTP/1.1\r\n\
"
@requestHeaders = {host: ["Host", encodeURI(parser.hostname)]}
App.log.verbose({"MemHttpRequest#open": this}) if DEBUG > 0
@sendFlag = false
@changeState(@OPENED)
null
###*
@method setRequestHeader
@param {String} header Header string (ex: User-Agent)
@param {String} value Value string
@return {void}
Method for XMLHttpRequest compatibility.
###
setRequestHeader: (header, value) ->
unless @readyState == @OPENED and @sendFlag == false
throw new Error("InvalidStateError")
key = PI:KEY:<KEY>END_PI
if @requestHeaders[key]
@requestHeaders[key][1] = "#{value}"
else
@requestHeaders[key] = ["#{header}", "#{value}"]
null
###*
@property {Number} timeout
Attribute for XMLHttpRequest compatibility.
###
timeout: 0
###*
@property {Boolean} withCredentials
Attribute for XMLHttpRequest compatibility. But not supported.
###
withCredentials: false # not supported
###*
@property {Object} upload
Attribute for XMLHttpRequest compatibility. But not supported.
###
upload: null # not supported
###*
@method send
@param {Uint8Array/String} data Request body
@return {void}
Method for XMLHttpRequest compatibility.
Supported type of data are Uint8Array and String only.
###
send: (data) ->
unless @readyState == @OPENED and @sendFlag == false
throw new Error("InvalidStateError")
data = null if @requestMethod == "GET" or @requestMethod == "HEAD"
if data instanceof Uint8Array
contentType = "application/octet-stream"
else if data instanceof String
contentType = "text/plain;charset=UTF-8"
else unless data?
contentType = null
else
throw new TypeError("Unsupported data type")
@sendFlag = true
@requestHeaders["content-type"] or= ["Content-Type", contentType] if contentType?
sendArrayBuffer = (buffer) =>
dataLength = if buffer? then buffer.byteLength else 0
@requestHeaders["content-length"] or= ["Content-Length", "#{dataLength}"]
request = @requestStartLine
request += "#{pair[0]}: #{pair[1]}\r\n" for key, pair of @requestHeaders
request += "\r\n"
reader = new FileReader()
reader.onload = =>
App.log.verbose({"request-header": request})
App.log.verbose({"request-body": new Uint8Array(buffer)})
array = new Uint8Array(reader.result.byteLength + dataLength)
array.set(new Uint8Array(reader.result), 0)
array.set(new Uint8Array(buffer), reader.result.byteLength) if buffer?
@requestBuffer = array.buffer
@requestOffset = 0
@responseOffset = 0
@clearTimeStamp()
@transmitMessage()
reader.readAsArrayBuffer(new Blob([request]))
if data instanceof String
reader = new FileReader()
reader.onload = -> sendArrayBuffer(reader.result)
reader.readAsArrayBuffer(new Blob([data]))
else
sendArrayBuffer(data or new ArrayBuffer(0))
null
###*
@method abort
@return {void}
Method for XMLHttpRequest compatibility. But not supported.
###
abort: () ->
throw new Error("NotSupportedError")
###*
@property {Number} status
@readonly
Attribute for XMLHttpRequest compatibility.
###
status: 0
###*
@property {String} statusText
@readonly
Attribute for XMLHttpRequest compatibility.
###
statusText: ""
###*
@method getResponseHeader
@param {String} header Response header
@return {void/String}
Method for XMLHttpRequest compatibility.
###
getResponseHeader: (header) ->
return null if @readyState == UNSENT or @readyState == OPENED
return null if @errorFlag == true
key = PI:KEY:<KEY>END_PI
return @responseHeaders[key] if @responseHeaders[key][1]
null
###*
@method getAllResponseHeaders
@return {String}
Method for XMLHttpRequest compatibility.
###
getAllResponseHeaders: () ->
return "" if @readyState == UNSENT or @readyState == OPENED
return "" if @errorFlag == true
result = ""
for key, pair of @responseHeaders
result += "#{pair[0]}: #{pair[1]}\r\n"
result
###*
@method overrideMimeType
@return {void}
Method for XMLHttpRequest compatibility. But not supported.
###
overrideMimeType: (mime) ->
throw new Error("NotSupportedError")
###*
@property {String} responseType
Attribute for XMLHttpRequest compatibility.
###
responseType: ""
###*
@property {Object} response
@readonly
Attribute for XMLHttpRequest compatibility.
###
response: null
###*
@property {Object} responseXML
@readonly
Attribute for XMLHttpRequest compatibility. But not supported.
###
responseXML: null # not supported
#------------------------------------------------
# Private member
#
TX_RETRY_MS = 100
RX_RETRY_MS = 100
###*
Constructor of MemHttpRequest
@param {Object} datalink Object with data-link (getTxPacket/getRxPacket)
###
constructor: (@datalink) -> null
###*
@private
@method changeState
@param {Integer} newState
Update state and invoke callbacks
###
changeState: (newState) ->
return if @readyState == newState
App.log.verbose({
"MemHttpRequest#changeState": this
oldState: @readyState
newState: newState
}) if DEBUG > 0
@readyState = newState
@onreadystatechange and @onreadystatechange() if newState != @UNSENT
###*
@private
@method failed
@param {String} message
@param {Function} callback
Set error flag and update state to DONE
###
failed: (message, callback) ->
App.log.verbose({"MemHttpRequest#failed": this, message: message})
@errorFlag = true
@changeState(@DONE)
callback?()
###*
@private
@method transmitMessage
Transmit a request message
###
transmitMessage: () ->
@datalink.getTxPacket((packet) =>
return @isTimedOut("Transmit") or \
setTimeout((=> @transmitMessage()), TX_RETRY_MS) unless packet?
offset = @requestOffset
packet.length = Math.min(@requestBuffer.byteLength - offset, packet.capacity)
@requestOffset += packet.length
packet.buffer = @requestBuffer.slice(offset, offset + packet.length)
App.log.verbose({
"MemHttpRequest#transmitMessage": this
packet: packet
array: new Uint8Array(packet.buffer)
}) if DEBUG > 0
packet.startOfMessage = (offset == 0)
if @requestOffset >= @requestBuffer.byteLength
packet.endOfMessage = true
packet.transmit((result) =>
return @failed("Transmitting last packet") unless result
@clearTimeStamp()
@receiveMessage()
)
else
packet.endOfMessag = false
packet.transmit((result) =>
return @failed("Transmitting packet") unless result
@clearTimeStamp()
@transmitMessage()
)
null
)
###*
@private
@method receiveMessage
Receive a response message
###
receiveMessage: () ->
@datalink.getRxPacket((packet) =>
return @isTimedOut("Receive") or \
setTimeout((=> @receiveMessage()), RX_RETRY_MS) unless packet?
App.log.verbose({
"MemHttpRequest#receiveMessage": this
packet: packet
data: new Uint8Array(packet.buffer)
}) if DEBUG > 0
failed = (message) => @failed(message, packet.discard)
if @responseOffset == 0
return failed("Received invalid first packet") unless packet.startOfMessage
headerLength = null
array = new Uint8Array(packet.buffer)
for i in [0..packet.length-4]
if array[i+0] == 0xd and array[i+1] == 0xa and \
array[i+2] == 0xd and array[i+3] == 0xa
headerLength = i
break
return failed("No splitter in first packet") unless headerLength
resp = String.fromCharCode.apply(null, new Uint8Array(array.buffer, 0, headerLength))
headerLength += 4
lines = resp.split("\r\n")
[http, @statusText] = lines.shift().split(" ", 2)
unless http == "HTTP/1.0" or http == "HTTP/1.1"
return failed("Invalid response start line")
@status = parseInt(@statusText)
if DEBUG > 0
App.log.verbose({"response-status": @status})
App.log.verbose({"response-header": "#{resp}\r\n\r\n"})
@responseHeaders = {}
for line in lines
[name, value] = line.split(":", 2)
key = PI:KEY:<KEY>END_PI
@responseHeaders[key] = [name, value.trim()]
@responseLength = parseInt((@responseHeaders["content-length"] or [null, "0"])[1])
@responseBuffer = new ArrayBuffer(@responseLength)
else
headerLength = 0
if @responseBuffer.byteLength > 0
copyLength = Math.min(@responseLength - @responseOffset,
packet.length - headerLength)
if copyLength > 0
array = new Uint8Array(@responseBuffer, @responseOffset, copyLength)
array.set(new Uint8Array(array.buffer, headerLength, copyLength))
@responseOffset += copyLength
return packet.discard(=>
@clearTimeStamp()
@receiveMessage()
) unless packet.endOfMessage
return failed("Broken message") unless @responseOffset >= @responseLength
switch @responseType
when "", "string"
@response = String.fromCharCode.apply(null, new Uint8Array(@responseBuffer))
when "arraybuffer"
@response = @responseBuffer
else
throw new TypeError("Unsupported responseType")
App.log.verbose({"response-body": @response}) if DEBUG > 0
packet.discard(=> @changeState(@DONE))
)
###*
@private
@method clearTimeStamp
@return {Boolean} Always true
###
clearTimeStamp: () ->
@timeStamp = +new Date()
true
###*
@private
@method isTimedOut
@retval true Timed out
@retval false Not timed out
###
isTimedOut: (message) ->
duration = (new Date() - @timeStamp)
return false if @timeout == 0 or duration < @timeout
@failed(message)
true
App = require("app/app")
|
[
{
"context": " auth:\n user: @clientId\n pass: @clientSecret\n\n @request req, (error, response, body) =>\n ",
"end": 805,
"score": 0.8435720205307007,
"start": 793,
"tag": "PASSWORD",
"value": "clientSecret"
}
] | src/Client.coffee | eibbors/domonodo | 1 | request = require 'request'
class DomoClient
constructor: (options={}) ->
@clientId = options.clientId ? null
@clientSecret = options.clientSecret ? null
@accessToken = options.accessToken ? null
@scope = options.scope ? null
# Request an access token for making calls to Domo APIs
getToken: (options={}, callback) ->
# If the clientId / clientSecret are provided, then update stored values
if options.clientId? then @clientId = clientId
if options.clientSecret? then @clientSecret = clientSecret
# Set up our token request options
req =
method: 'GET'
uri: 'https://api.domo.com/oauth/token'
qs:
grant_type: 'client_credentials'
scope: options.scope ? @scope
auth:
user: @clientId
pass: @clientSecret
@request req, (error, response, body) =>
if error then return callback error, response, body
if body?.access_token?
@accessToken = body.access_token
else
error = body
callback error, response, body
# Simple wrapper function providing basic response parsing and auth configuration
request: (options={}, callback) ->
# Allow passing in a URI as a string to options parameter
if typeof options is 'string'
options =
method: 'GET'
uri: options
# If we have an access token and the user hasn't set the auth option, then configure it to use our token
if @accessToken
options.auth ?= { bearer: @accessToken }
# Submit the request
request options, (error, response, body) =>
if error then return callback error, response, body
if options.headers?.accept is 'text/csv' then
# Parse CSV files?
else
try
body = JSON.parse(body)
# Some HTTP errors come in as parsable objects, so check for that
if body.toe? then return callback body, response, body
catch e
# Handle JSON parsing error?
callback null, response, body
module.exports = DomoClient | 215165 | request = require 'request'
class DomoClient
constructor: (options={}) ->
@clientId = options.clientId ? null
@clientSecret = options.clientSecret ? null
@accessToken = options.accessToken ? null
@scope = options.scope ? null
# Request an access token for making calls to Domo APIs
getToken: (options={}, callback) ->
# If the clientId / clientSecret are provided, then update stored values
if options.clientId? then @clientId = clientId
if options.clientSecret? then @clientSecret = clientSecret
# Set up our token request options
req =
method: 'GET'
uri: 'https://api.domo.com/oauth/token'
qs:
grant_type: 'client_credentials'
scope: options.scope ? @scope
auth:
user: @clientId
pass: @<PASSWORD>
@request req, (error, response, body) =>
if error then return callback error, response, body
if body?.access_token?
@accessToken = body.access_token
else
error = body
callback error, response, body
# Simple wrapper function providing basic response parsing and auth configuration
request: (options={}, callback) ->
# Allow passing in a URI as a string to options parameter
if typeof options is 'string'
options =
method: 'GET'
uri: options
# If we have an access token and the user hasn't set the auth option, then configure it to use our token
if @accessToken
options.auth ?= { bearer: @accessToken }
# Submit the request
request options, (error, response, body) =>
if error then return callback error, response, body
if options.headers?.accept is 'text/csv' then
# Parse CSV files?
else
try
body = JSON.parse(body)
# Some HTTP errors come in as parsable objects, so check for that
if body.toe? then return callback body, response, body
catch e
# Handle JSON parsing error?
callback null, response, body
module.exports = DomoClient | true | request = require 'request'
class DomoClient
constructor: (options={}) ->
@clientId = options.clientId ? null
@clientSecret = options.clientSecret ? null
@accessToken = options.accessToken ? null
@scope = options.scope ? null
# Request an access token for making calls to Domo APIs
getToken: (options={}, callback) ->
# If the clientId / clientSecret are provided, then update stored values
if options.clientId? then @clientId = clientId
if options.clientSecret? then @clientSecret = clientSecret
# Set up our token request options
req =
method: 'GET'
uri: 'https://api.domo.com/oauth/token'
qs:
grant_type: 'client_credentials'
scope: options.scope ? @scope
auth:
user: @clientId
pass: @PI:PASSWORD:<PASSWORD>END_PI
@request req, (error, response, body) =>
if error then return callback error, response, body
if body?.access_token?
@accessToken = body.access_token
else
error = body
callback error, response, body
# Simple wrapper function providing basic response parsing and auth configuration
request: (options={}, callback) ->
# Allow passing in a URI as a string to options parameter
if typeof options is 'string'
options =
method: 'GET'
uri: options
# If we have an access token and the user hasn't set the auth option, then configure it to use our token
if @accessToken
options.auth ?= { bearer: @accessToken }
# Submit the request
request options, (error, response, body) =>
if error then return callback error, response, body
if options.headers?.accept is 'text/csv' then
# Parse CSV files?
else
try
body = JSON.parse(body)
# Some HTTP errors come in as parsable objects, so check for that
if body.toe? then return callback body, response, body
catch e
# Handle JSON parsing error?
callback null, response, body
module.exports = DomoClient |
[
{
"context": "!= 0)\n\n test.done()\n )\n\n debug.token({name: 'test'})\n\nexports.payloadNotEnabled = (test) ->\n debug",
"end": 1317,
"score": 0.5270657539367676,
"start": 1313,
"tag": "KEY",
"value": "test"
}
] | test/unit/debug-test.coffee | calebTomlinson/tedious | 2 | Debug = require('../../src/debug')
payload = 'payload'
class Packet
headerToString: ->
'header'
dataToString: ->
'data'
exports.packet = (test) ->
emitCount = 0;
debug = new Debug({packet: true})
debug.on('debug', (text) ->
emitCount++
switch emitCount
when 2
test.ok(/dir/.test(text))
when 3
test.ok(/header/.test(text))
test.done()
)
debug.packet('dir', new Packet())
exports.payloadEnabled = (test) ->
debug = new Debug({payload: true})
debug.on('debug', (text) ->
test.strictEqual(text, payload)
test.done()
)
debug.payload(->
payload
)
exports.payloadNotEnabled = (test) ->
debug = new Debug()
debug.on('debug', (text) ->
test.ok(false)
)
debug.payload(payload)
test.done()
exports.dataEnable = (test) ->
debug = new Debug({data: true})
debug.on('debug', (text) ->
test.strictEqual(text, 'data')
test.done()
)
debug.data(new Packet())
exports.dataNotEnabled = (test) ->
debug = new Debug()
debug.on('debug', (text) ->
test.ok(false)
)
debug.data(new Packet())
test.done()
exports.tokenEnabled = (test) ->
debug = new Debug({token: true})
debug.on('debug', (token) ->
test.ok(token.indexOf('test') != 0)
test.done()
)
debug.token({name: 'test'})
exports.payloadNotEnabled = (test) ->
debug = new Debug()
debug.on('debug', (token) ->
test.ok(false)
)
debug.token({name: 'test'})
test.done()
| 120219 | Debug = require('../../src/debug')
payload = 'payload'
class Packet
headerToString: ->
'header'
dataToString: ->
'data'
exports.packet = (test) ->
emitCount = 0;
debug = new Debug({packet: true})
debug.on('debug', (text) ->
emitCount++
switch emitCount
when 2
test.ok(/dir/.test(text))
when 3
test.ok(/header/.test(text))
test.done()
)
debug.packet('dir', new Packet())
exports.payloadEnabled = (test) ->
debug = new Debug({payload: true})
debug.on('debug', (text) ->
test.strictEqual(text, payload)
test.done()
)
debug.payload(->
payload
)
exports.payloadNotEnabled = (test) ->
debug = new Debug()
debug.on('debug', (text) ->
test.ok(false)
)
debug.payload(payload)
test.done()
exports.dataEnable = (test) ->
debug = new Debug({data: true})
debug.on('debug', (text) ->
test.strictEqual(text, 'data')
test.done()
)
debug.data(new Packet())
exports.dataNotEnabled = (test) ->
debug = new Debug()
debug.on('debug', (text) ->
test.ok(false)
)
debug.data(new Packet())
test.done()
exports.tokenEnabled = (test) ->
debug = new Debug({token: true})
debug.on('debug', (token) ->
test.ok(token.indexOf('test') != 0)
test.done()
)
debug.token({name: '<KEY>'})
exports.payloadNotEnabled = (test) ->
debug = new Debug()
debug.on('debug', (token) ->
test.ok(false)
)
debug.token({name: 'test'})
test.done()
| true | Debug = require('../../src/debug')
payload = 'payload'
class Packet
headerToString: ->
'header'
dataToString: ->
'data'
exports.packet = (test) ->
emitCount = 0;
debug = new Debug({packet: true})
debug.on('debug', (text) ->
emitCount++
switch emitCount
when 2
test.ok(/dir/.test(text))
when 3
test.ok(/header/.test(text))
test.done()
)
debug.packet('dir', new Packet())
exports.payloadEnabled = (test) ->
debug = new Debug({payload: true})
debug.on('debug', (text) ->
test.strictEqual(text, payload)
test.done()
)
debug.payload(->
payload
)
exports.payloadNotEnabled = (test) ->
debug = new Debug()
debug.on('debug', (text) ->
test.ok(false)
)
debug.payload(payload)
test.done()
exports.dataEnable = (test) ->
debug = new Debug({data: true})
debug.on('debug', (text) ->
test.strictEqual(text, 'data')
test.done()
)
debug.data(new Packet())
exports.dataNotEnabled = (test) ->
debug = new Debug()
debug.on('debug', (text) ->
test.ok(false)
)
debug.data(new Packet())
test.done()
exports.tokenEnabled = (test) ->
debug = new Debug({token: true})
debug.on('debug', (token) ->
test.ok(token.indexOf('test') != 0)
test.done()
)
debug.token({name: 'PI:KEY:<KEY>END_PI'})
exports.payloadNotEnabled = (test) ->
debug = new Debug()
debug.on('debug', (token) ->
test.ok(false)
)
debug.token({name: 'test'})
test.done()
|
[
{
"context": "n unless Batman.acceptData(elem)\n internalKey = Batman.expando\n isNode = elem.nodeType\n # non DOM-nodes ha",
"end": 2801,
"score": 0.852504551410675,
"start": 2787,
"tag": "KEY",
"value": "Batman.expando"
}
] | src/view/data.coffee | Shipow/batman | 1 | isEmptyDataObject = (obj) ->
for name of obj
return false
return true
Batman.extend Batman,
cache: {}
uuid: 0
expando: "batman" + Math.random().toString().replace(/\D/g, '')
# Test to see if it's possible to delete an expando from an element
# Fails in Internet Explorer
canDeleteExpando: do ->
try
div = document.createElement 'div'
delete div.test
catch e
Batman.canDeleteExpando = false
noData: # these throw exceptions if you attempt to add expandos to them
"embed": true,
# Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
hasData: (elem) ->
elem = (if elem.nodeType then Batman.cache[elem[Batman.expando]] else elem[Batman.expando])
!!elem and !isEmptyDataObject(elem)
data: (elem, name, data, pvt) -> # pvt is for internal use only
return unless Batman.acceptData(elem)
internalKey = Batman.expando
getByName = typeof name == "string"
cache = Batman.cache
# Only defining an ID for JS objects if its cache already exists allows
# the code to shortcut on the same path as a DOM node with no cache
id = elem[Batman.expando]
# Avoid doing any more work than we need to when trying to get data on an
# object that has no data at all
if (not id or (pvt and id and (cache[id] and not cache[id][internalKey]))) and getByName and data == undefined
return
unless id
# Also check that it's not a text node; IE can't set expandos on them
if elem.nodeType isnt 3
elem[Batman.expando] = id = ++Batman.uuid
else
id = Batman.expando
cache[id] = {} unless cache[id]
# An object can be passed to Batman._data instead of a key/value pair; this gets
# shallow copied over onto the existing cache
if typeof name == "object" or typeof name == "function"
if pvt
cache[id][internalKey] = Batman.extend(cache[id][internalKey], name)
else
cache[id] = Batman.extend(cache[id], name)
thisCache = cache[id]
# Internal Batman data is stored in a separate object inside the object's data
# cache in order to avoid key collisions between internal data and user-defined
# data
if pvt
thisCache[internalKey] ||= {}
thisCache = thisCache[internalKey]
if data != undefined
thisCache[name] = data
# Check for both converted-to-camel and non-converted data property names
# If a data property was specified
if getByName
# First try to find as-is property data
ret = thisCache[name]
else
ret = thisCache
return ret
removeData: (elem, name, pvt) -> # pvt is for internal use only
return unless Batman.acceptData(elem)
internalKey = Batman.expando
isNode = elem.nodeType
# non DOM-nodes have their data attached directly
cache = Batman.cache
id = elem[Batman.expando]
# If there is already no cache entry for this object, there is no
# purpose in continuing
return unless cache[id]
if name
thisCache = if pvt then cache[id][internalKey] else cache[id]
if thisCache
# Support interoperable removal of hyphenated or camelcased keys
delete thisCache[name]
# If there is no data left in the cache, we want to continue
# and let the cache object itself get destroyed
return unless isEmptyDataObject(thisCache)
if pvt
delete cache[id][internalKey]
# Don't destroy the parent cache unless the internal data object
# had been the only thing left in it
return unless isEmptyDataObject(cache[id])
internalCache = cache[id][internalKey]
# Browsers that fail expando deletion also refuse to delete expandos on
# the window, but it will allow it on all other JS objects; other browsers
# don't care
# Ensure that `cache` is not a window object
if Batman.canDeleteExpando or !cache.setInterval
delete cache[id]
else
cache[id] = null
# We destroyed the entire user cache at once because it's faster than
# iterating through each key, but we need to continue to persist internal
# data if it existed
if internalCache
cache[id] = {}
cache[id][internalKey] = internalCache
# Otherwise, we need to eliminate the expando on the node to avoid
# false lookups in the cache for entries that no longer exist
else
if Batman.canDeleteExpando
delete elem[Batman.expando]
else if elem.removeAttribute
elem.removeAttribute Batman.expando
else
elem[Batman.expando] = null
# For internal use only
_data: (elem, name, data) ->
Batman.data elem, name, data, true
# A method for determining if a DOM node can handle the data expando
acceptData: (elem) ->
if elem.nodeName
match = Batman.noData[elem.nodeName.toLowerCase()]
if match
return !(match == true or elem.getAttribute("classid") != match)
return true
| 77242 | isEmptyDataObject = (obj) ->
for name of obj
return false
return true
Batman.extend Batman,
cache: {}
uuid: 0
expando: "batman" + Math.random().toString().replace(/\D/g, '')
# Test to see if it's possible to delete an expando from an element
# Fails in Internet Explorer
canDeleteExpando: do ->
try
div = document.createElement 'div'
delete div.test
catch e
Batman.canDeleteExpando = false
noData: # these throw exceptions if you attempt to add expandos to them
"embed": true,
# Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
hasData: (elem) ->
elem = (if elem.nodeType then Batman.cache[elem[Batman.expando]] else elem[Batman.expando])
!!elem and !isEmptyDataObject(elem)
data: (elem, name, data, pvt) -> # pvt is for internal use only
return unless Batman.acceptData(elem)
internalKey = Batman.expando
getByName = typeof name == "string"
cache = Batman.cache
# Only defining an ID for JS objects if its cache already exists allows
# the code to shortcut on the same path as a DOM node with no cache
id = elem[Batman.expando]
# Avoid doing any more work than we need to when trying to get data on an
# object that has no data at all
if (not id or (pvt and id and (cache[id] and not cache[id][internalKey]))) and getByName and data == undefined
return
unless id
# Also check that it's not a text node; IE can't set expandos on them
if elem.nodeType isnt 3
elem[Batman.expando] = id = ++Batman.uuid
else
id = Batman.expando
cache[id] = {} unless cache[id]
# An object can be passed to Batman._data instead of a key/value pair; this gets
# shallow copied over onto the existing cache
if typeof name == "object" or typeof name == "function"
if pvt
cache[id][internalKey] = Batman.extend(cache[id][internalKey], name)
else
cache[id] = Batman.extend(cache[id], name)
thisCache = cache[id]
# Internal Batman data is stored in a separate object inside the object's data
# cache in order to avoid key collisions between internal data and user-defined
# data
if pvt
thisCache[internalKey] ||= {}
thisCache = thisCache[internalKey]
if data != undefined
thisCache[name] = data
# Check for both converted-to-camel and non-converted data property names
# If a data property was specified
if getByName
# First try to find as-is property data
ret = thisCache[name]
else
ret = thisCache
return ret
removeData: (elem, name, pvt) -> # pvt is for internal use only
return unless Batman.acceptData(elem)
internalKey = <KEY>
isNode = elem.nodeType
# non DOM-nodes have their data attached directly
cache = Batman.cache
id = elem[Batman.expando]
# If there is already no cache entry for this object, there is no
# purpose in continuing
return unless cache[id]
if name
thisCache = if pvt then cache[id][internalKey] else cache[id]
if thisCache
# Support interoperable removal of hyphenated or camelcased keys
delete thisCache[name]
# If there is no data left in the cache, we want to continue
# and let the cache object itself get destroyed
return unless isEmptyDataObject(thisCache)
if pvt
delete cache[id][internalKey]
# Don't destroy the parent cache unless the internal data object
# had been the only thing left in it
return unless isEmptyDataObject(cache[id])
internalCache = cache[id][internalKey]
# Browsers that fail expando deletion also refuse to delete expandos on
# the window, but it will allow it on all other JS objects; other browsers
# don't care
# Ensure that `cache` is not a window object
if Batman.canDeleteExpando or !cache.setInterval
delete cache[id]
else
cache[id] = null
# We destroyed the entire user cache at once because it's faster than
# iterating through each key, but we need to continue to persist internal
# data if it existed
if internalCache
cache[id] = {}
cache[id][internalKey] = internalCache
# Otherwise, we need to eliminate the expando on the node to avoid
# false lookups in the cache for entries that no longer exist
else
if Batman.canDeleteExpando
delete elem[Batman.expando]
else if elem.removeAttribute
elem.removeAttribute Batman.expando
else
elem[Batman.expando] = null
# For internal use only
_data: (elem, name, data) ->
Batman.data elem, name, data, true
# A method for determining if a DOM node can handle the data expando
acceptData: (elem) ->
if elem.nodeName
match = Batman.noData[elem.nodeName.toLowerCase()]
if match
return !(match == true or elem.getAttribute("classid") != match)
return true
| true | isEmptyDataObject = (obj) ->
for name of obj
return false
return true
Batman.extend Batman,
cache: {}
uuid: 0
expando: "batman" + Math.random().toString().replace(/\D/g, '')
# Test to see if it's possible to delete an expando from an element
# Fails in Internet Explorer
canDeleteExpando: do ->
try
div = document.createElement 'div'
delete div.test
catch e
Batman.canDeleteExpando = false
noData: # these throw exceptions if you attempt to add expandos to them
"embed": true,
# Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
hasData: (elem) ->
elem = (if elem.nodeType then Batman.cache[elem[Batman.expando]] else elem[Batman.expando])
!!elem and !isEmptyDataObject(elem)
data: (elem, name, data, pvt) -> # pvt is for internal use only
return unless Batman.acceptData(elem)
internalKey = Batman.expando
getByName = typeof name == "string"
cache = Batman.cache
# Only defining an ID for JS objects if its cache already exists allows
# the code to shortcut on the same path as a DOM node with no cache
id = elem[Batman.expando]
# Avoid doing any more work than we need to when trying to get data on an
# object that has no data at all
if (not id or (pvt and id and (cache[id] and not cache[id][internalKey]))) and getByName and data == undefined
return
unless id
# Also check that it's not a text node; IE can't set expandos on them
if elem.nodeType isnt 3
elem[Batman.expando] = id = ++Batman.uuid
else
id = Batman.expando
cache[id] = {} unless cache[id]
# An object can be passed to Batman._data instead of a key/value pair; this gets
# shallow copied over onto the existing cache
if typeof name == "object" or typeof name == "function"
if pvt
cache[id][internalKey] = Batman.extend(cache[id][internalKey], name)
else
cache[id] = Batman.extend(cache[id], name)
thisCache = cache[id]
# Internal Batman data is stored in a separate object inside the object's data
# cache in order to avoid key collisions between internal data and user-defined
# data
if pvt
thisCache[internalKey] ||= {}
thisCache = thisCache[internalKey]
if data != undefined
thisCache[name] = data
# Check for both converted-to-camel and non-converted data property names
# If a data property was specified
if getByName
# First try to find as-is property data
ret = thisCache[name]
else
ret = thisCache
return ret
removeData: (elem, name, pvt) -> # pvt is for internal use only
return unless Batman.acceptData(elem)
internalKey = PI:KEY:<KEY>END_PI
isNode = elem.nodeType
# non DOM-nodes have their data attached directly
cache = Batman.cache
id = elem[Batman.expando]
# If there is already no cache entry for this object, there is no
# purpose in continuing
return unless cache[id]
if name
thisCache = if pvt then cache[id][internalKey] else cache[id]
if thisCache
# Support interoperable removal of hyphenated or camelcased keys
delete thisCache[name]
# If there is no data left in the cache, we want to continue
# and let the cache object itself get destroyed
return unless isEmptyDataObject(thisCache)
if pvt
delete cache[id][internalKey]
# Don't destroy the parent cache unless the internal data object
# had been the only thing left in it
return unless isEmptyDataObject(cache[id])
internalCache = cache[id][internalKey]
# Browsers that fail expando deletion also refuse to delete expandos on
# the window, but it will allow it on all other JS objects; other browsers
# don't care
# Ensure that `cache` is not a window object
if Batman.canDeleteExpando or !cache.setInterval
delete cache[id]
else
cache[id] = null
# We destroyed the entire user cache at once because it's faster than
# iterating through each key, but we need to continue to persist internal
# data if it existed
if internalCache
cache[id] = {}
cache[id][internalKey] = internalCache
# Otherwise, we need to eliminate the expando on the node to avoid
# false lookups in the cache for entries that no longer exist
else
if Batman.canDeleteExpando
delete elem[Batman.expando]
else if elem.removeAttribute
elem.removeAttribute Batman.expando
else
elem[Batman.expando] = null
# For internal use only
_data: (elem, name, data) ->
Batman.data elem, name, data, true
# A method for determining if a DOM node can handle the data expando
acceptData: (elem) ->
if elem.nodeName
match = Batman.noData[elem.nodeName.toLowerCase()]
if match
return !(match == true or elem.getAttribute("classid") != match)
return true
|
[
{
"context": ", key) ->\n if key isnt 'factory' and key isnt 'makeSubNameSpace' and key isnt 'constants'\n count += 1\n quni",
"end": 257,
"score": 0.9576725959777832,
"start": 241,
"tag": "KEY",
"value": "makeSubNameSpace"
},
{
"context": ", key) ->\n if key isnt 'factory' and key isnt 'makeSubNameSpace' and key isnt 'constants'\n node = OJ.body.ma",
"end": 432,
"score": 0.8966246247291565,
"start": 416,
"tag": "KEY",
"value": "makeSubNameSpace"
}
] | test/controls/test.allControls.coffee | ahamid/oj | 2 | qunit = require 'qunit'
qunit.module 'all controls', setup: ->
OJ['GENERATE_UNIQUE_IDS'] = true
qunit.test 'Test all controls', ->
count = 0
OJ.each OJ.controls.members, (val, key) ->
if key isnt 'factory' and key isnt 'makeSubNameSpace' and key isnt 'constants'
count += 1
qunit.expect count * 7
OJ.each OJ.controls.members, (val, key) ->
if key isnt 'factory' and key isnt 'makeSubNameSpace' and key isnt 'constants'
node = OJ.body.make key
node.text 'Hi I\'m some text'
# Test 1: tagName is div
qunit.deepEqual node.controlName, val, 'Control is a ' + key.toUpperCase()
nodeId = node.getId()
dNode = document.getElementById nodeId
# Test 2: node is in the DOM
qunit.ok dNode, 'Node is in the DOM'
# Test 3: IDs are equal
qunit.deepEqual nodeId, dNode.id, 'Element IDs are equal'
# Test 4: chaining works
child = node.make key
childId = child.getId()
qunit.deepEqual child.controlName, val, 'Control is a ' + key.toUpperCase()
# Test 5: chained node is in the DOM
cNode = document.getElementById childId
qunit.deepEqual cNode.id, childId, 'Element IDs are equal'
node.remove()
# Test 6: node is removed
qunit.equal `undefined`, document.getElementById(nodeId), 'Node has been removed'
# Test 7: child is removed
qunit.equal `undefined`, document.getElementById(childId), 'Child has been removed' | 176098 | qunit = require 'qunit'
qunit.module 'all controls', setup: ->
OJ['GENERATE_UNIQUE_IDS'] = true
qunit.test 'Test all controls', ->
count = 0
OJ.each OJ.controls.members, (val, key) ->
if key isnt 'factory' and key isnt '<KEY>' and key isnt 'constants'
count += 1
qunit.expect count * 7
OJ.each OJ.controls.members, (val, key) ->
if key isnt 'factory' and key isnt '<KEY>' and key isnt 'constants'
node = OJ.body.make key
node.text 'Hi I\'m some text'
# Test 1: tagName is div
qunit.deepEqual node.controlName, val, 'Control is a ' + key.toUpperCase()
nodeId = node.getId()
dNode = document.getElementById nodeId
# Test 2: node is in the DOM
qunit.ok dNode, 'Node is in the DOM'
# Test 3: IDs are equal
qunit.deepEqual nodeId, dNode.id, 'Element IDs are equal'
# Test 4: chaining works
child = node.make key
childId = child.getId()
qunit.deepEqual child.controlName, val, 'Control is a ' + key.toUpperCase()
# Test 5: chained node is in the DOM
cNode = document.getElementById childId
qunit.deepEqual cNode.id, childId, 'Element IDs are equal'
node.remove()
# Test 6: node is removed
qunit.equal `undefined`, document.getElementById(nodeId), 'Node has been removed'
# Test 7: child is removed
qunit.equal `undefined`, document.getElementById(childId), 'Child has been removed' | true | qunit = require 'qunit'
qunit.module 'all controls', setup: ->
OJ['GENERATE_UNIQUE_IDS'] = true
qunit.test 'Test all controls', ->
count = 0
OJ.each OJ.controls.members, (val, key) ->
if key isnt 'factory' and key isnt 'PI:KEY:<KEY>END_PI' and key isnt 'constants'
count += 1
qunit.expect count * 7
OJ.each OJ.controls.members, (val, key) ->
if key isnt 'factory' and key isnt 'PI:KEY:<KEY>END_PI' and key isnt 'constants'
node = OJ.body.make key
node.text 'Hi I\'m some text'
# Test 1: tagName is div
qunit.deepEqual node.controlName, val, 'Control is a ' + key.toUpperCase()
nodeId = node.getId()
dNode = document.getElementById nodeId
# Test 2: node is in the DOM
qunit.ok dNode, 'Node is in the DOM'
# Test 3: IDs are equal
qunit.deepEqual nodeId, dNode.id, 'Element IDs are equal'
# Test 4: chaining works
child = node.make key
childId = child.getId()
qunit.deepEqual child.controlName, val, 'Control is a ' + key.toUpperCase()
# Test 5: chained node is in the DOM
cNode = document.getElementById childId
qunit.deepEqual cNode.id, childId, 'Element IDs are equal'
node.remove()
# Test 6: node is removed
qunit.equal `undefined`, document.getElementById(nodeId), 'Node has been removed'
# Test 7: child is removed
qunit.equal `undefined`, document.getElementById(childId), 'Child has been removed' |
[
{
"context": "\n res.json bugs:\n url: \"http://github.com/example/sample/issues\"\n email: \"sample@example.com\"\n",
"end": 326,
"score": 0.9994714260101318,
"start": 319,
"tag": "USERNAME",
"value": "example"
},
{
"context": "//github.com/example/sample/issues\"\n email: \"sample@example.com\"\n\n return\n\n client.bugs \"http://localhost:133",
"end": 374,
"score": 0.9999229311943054,
"start": 356,
"tag": "EMAIL",
"value": "sample@example.com"
}
] | deps/npm/node_modules/npm-registry-client/test/bugs.coffee | lxe/io.coffee | 0 | tap = require("tap")
server = require("./lib/server.js")
common = require("./lib/common.js")
client = common.freshClient()
tap.test "get the URL for the bugs page on a package", (t) ->
server.expect "GET", "/sample/latest", (req, res) ->
t.equal req.method, "GET"
res.json bugs:
url: "http://github.com/example/sample/issues"
email: "sample@example.com"
return
client.bugs "http://localhost:1337/sample", (error, info) ->
t.ifError error
t.ok info.url, "got the URL"
t.ok info.email, "got the email address"
t.end()
return
return
| 134094 | tap = require("tap")
server = require("./lib/server.js")
common = require("./lib/common.js")
client = common.freshClient()
tap.test "get the URL for the bugs page on a package", (t) ->
server.expect "GET", "/sample/latest", (req, res) ->
t.equal req.method, "GET"
res.json bugs:
url: "http://github.com/example/sample/issues"
email: "<EMAIL>"
return
client.bugs "http://localhost:1337/sample", (error, info) ->
t.ifError error
t.ok info.url, "got the URL"
t.ok info.email, "got the email address"
t.end()
return
return
| true | tap = require("tap")
server = require("./lib/server.js")
common = require("./lib/common.js")
client = common.freshClient()
tap.test "get the URL for the bugs page on a package", (t) ->
server.expect "GET", "/sample/latest", (req, res) ->
t.equal req.method, "GET"
res.json bugs:
url: "http://github.com/example/sample/issues"
email: "PI:EMAIL:<EMAIL>END_PI"
return
client.bugs "http://localhost:1337/sample", (error, info) ->
t.ifError error
t.ok info.url, "got the URL"
t.ok info.email, "got the email address"
t.end()
return
return
|
[
{
"context": "\n # Destroy the old guest when attaching.\n key = \"#{embedder.getId()}-#{elementInstanceId}\"\n oldGuestInstanceId = embedderElementsMap[key]\n ",
"end": 2954,
"score": 0.9983947277069092,
"start": 2912,
"tag": "KEY",
"value": "\"#{embedder.getId()}-#{elementInstanceId}\""
}
] | atom/browser/lib/guest-view-manager.coffee | otmanerhazi/electron | 1 | ipc = require 'ipc'
webContents = require 'web-contents'
webViewManager = null # Doesn't exist in early initialization.
supportedWebViewEvents = [
'did-finish-load'
'did-fail-load'
'did-frame-finish-load'
'did-start-loading'
'did-stop-loading'
'did-get-response-details'
'did-get-redirect-request'
'dom-ready'
'console-message'
'new-window'
'close'
'crashed'
'gpu-crashed'
'plugin-crashed'
'destroyed'
'page-title-set'
'page-favicon-updated'
'enter-html-full-screen'
'leave-html-full-screen'
]
nextInstanceId = 0
guestInstances = {}
embedderElementsMap = {}
reverseEmbedderElementsMap = {}
# Generate guestInstanceId.
getNextInstanceId = (webContents) ->
++nextInstanceId
# Create a new guest instance.
createGuest = (embedder, params) ->
webViewManager ?= process.atomBinding 'web_view_manager'
id = getNextInstanceId embedder
guest = webContents.create
isGuest: true
guestInstanceId: id
guestInstances[id] = {guest, embedder}
# Destroy guest when the embedder is gone or navigated.
destroyEvents = ['destroyed', 'crashed', 'did-navigate-to-different-page']
destroy = ->
destroyGuest embedder, id if guestInstances[id]?
embedder.once event, destroy for event in destroyEvents
guest.once 'destroyed', ->
embedder.removeListener event, destroy for event in destroyEvents
# Init guest web view after attached.
guest.once 'did-attach', ->
params = @attachParams
delete @attachParams
@viewInstanceId = params.instanceId
@setSize
normal:
width: params.elementWidth, height: params.elementHeight
enableAutoSize: params.autosize
min:
width: params.minwidth, height: params.minheight
max:
width: params.maxwidth, height: params.maxheight
if params.src
opts = {}
opts.httpreferrer = params.httpreferrer if params.httpreferrer
opts.useragent = params.useragent if params.useragent
@loadUrl params.src, opts
if params.allowtransparency?
@setAllowTransparency params.allowtransparency
# Dispatch events to embedder.
for event in supportedWebViewEvents
do (event) ->
guest.on event, (_, args...) ->
embedder.send "ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-#{guest.viewInstanceId}", event, args...
# Dispatch guest's IPC messages to embedder.
guest.on 'ipc-message-host', (_, packed) ->
[channel, args...] = packed
embedder.send "ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-#{guest.viewInstanceId}", channel, args...
# Autosize.
guest.on 'size-changed', (_, args...) ->
embedder.send "ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-#{guest.viewInstanceId}", args...
id
# Attach the guest to an element of embedder.
attachGuest = (embedder, elementInstanceId, guestInstanceId, params) ->
guest = guestInstances[guestInstanceId].guest
# Destroy the old guest when attaching.
key = "#{embedder.getId()}-#{elementInstanceId}"
oldGuestInstanceId = embedderElementsMap[key]
if oldGuestInstanceId?
# Reattachment to the same guest is not currently supported.
return unless oldGuestInstanceId != guestInstanceId
return unless guestInstances[oldGuestInstanceId]?
destroyGuest embedder, oldGuestInstanceId
webViewManager.addGuest guestInstanceId, elementInstanceId, embedder, guest,
nodeIntegration: params.nodeintegration
plugins: params.plugins
disableWebSecurity: params.disablewebsecurity
preloadUrl: params.preload ? ''
guest.attachParams = params
embedderElementsMap[key] = guestInstanceId
reverseEmbedderElementsMap[guestInstanceId] = key
# Destroy an existing guest instance.
destroyGuest = (embedder, id) ->
webViewManager.removeGuest embedder, id
guestInstances[id].guest.destroy()
delete guestInstances[id]
key = reverseEmbedderElementsMap[id]
if key?
delete reverseEmbedderElementsMap[id]
delete embedderElementsMap[key]
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', (event, params, requestId) ->
event.sender.send "ATOM_SHELL_RESPONSE_#{requestId}", createGuest(event.sender, params)
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', (event, elementInstanceId, guestInstanceId, params) ->
attachGuest event.sender, elementInstanceId, guestInstanceId, params
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', (event, id) ->
destroyGuest event.sender, id
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', (event, id, params) ->
guestInstances[id]?.guest.setSize params
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', (event, id, allowtransparency) ->
guestInstances[id]?.guest.setAllowTransparency allowtransparency
# Returns WebContents from its guest id.
exports.getGuest = (id) ->
guestInstances[id]?.guest
# Returns the embedder of the guest.
exports.getEmbedder = (id) ->
guestInstances[id]?.embedder
| 5682 | ipc = require 'ipc'
webContents = require 'web-contents'
webViewManager = null # Doesn't exist in early initialization.
supportedWebViewEvents = [
'did-finish-load'
'did-fail-load'
'did-frame-finish-load'
'did-start-loading'
'did-stop-loading'
'did-get-response-details'
'did-get-redirect-request'
'dom-ready'
'console-message'
'new-window'
'close'
'crashed'
'gpu-crashed'
'plugin-crashed'
'destroyed'
'page-title-set'
'page-favicon-updated'
'enter-html-full-screen'
'leave-html-full-screen'
]
nextInstanceId = 0
guestInstances = {}
embedderElementsMap = {}
reverseEmbedderElementsMap = {}
# Generate guestInstanceId.
getNextInstanceId = (webContents) ->
++nextInstanceId
# Create a new guest instance.
createGuest = (embedder, params) ->
webViewManager ?= process.atomBinding 'web_view_manager'
id = getNextInstanceId embedder
guest = webContents.create
isGuest: true
guestInstanceId: id
guestInstances[id] = {guest, embedder}
# Destroy guest when the embedder is gone or navigated.
destroyEvents = ['destroyed', 'crashed', 'did-navigate-to-different-page']
destroy = ->
destroyGuest embedder, id if guestInstances[id]?
embedder.once event, destroy for event in destroyEvents
guest.once 'destroyed', ->
embedder.removeListener event, destroy for event in destroyEvents
# Init guest web view after attached.
guest.once 'did-attach', ->
params = @attachParams
delete @attachParams
@viewInstanceId = params.instanceId
@setSize
normal:
width: params.elementWidth, height: params.elementHeight
enableAutoSize: params.autosize
min:
width: params.minwidth, height: params.minheight
max:
width: params.maxwidth, height: params.maxheight
if params.src
opts = {}
opts.httpreferrer = params.httpreferrer if params.httpreferrer
opts.useragent = params.useragent if params.useragent
@loadUrl params.src, opts
if params.allowtransparency?
@setAllowTransparency params.allowtransparency
# Dispatch events to embedder.
for event in supportedWebViewEvents
do (event) ->
guest.on event, (_, args...) ->
embedder.send "ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-#{guest.viewInstanceId}", event, args...
# Dispatch guest's IPC messages to embedder.
guest.on 'ipc-message-host', (_, packed) ->
[channel, args...] = packed
embedder.send "ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-#{guest.viewInstanceId}", channel, args...
# Autosize.
guest.on 'size-changed', (_, args...) ->
embedder.send "ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-#{guest.viewInstanceId}", args...
id
# Attach the guest to an element of embedder.
attachGuest = (embedder, elementInstanceId, guestInstanceId, params) ->
guest = guestInstances[guestInstanceId].guest
# Destroy the old guest when attaching.
key = <KEY>
oldGuestInstanceId = embedderElementsMap[key]
if oldGuestInstanceId?
# Reattachment to the same guest is not currently supported.
return unless oldGuestInstanceId != guestInstanceId
return unless guestInstances[oldGuestInstanceId]?
destroyGuest embedder, oldGuestInstanceId
webViewManager.addGuest guestInstanceId, elementInstanceId, embedder, guest,
nodeIntegration: params.nodeintegration
plugins: params.plugins
disableWebSecurity: params.disablewebsecurity
preloadUrl: params.preload ? ''
guest.attachParams = params
embedderElementsMap[key] = guestInstanceId
reverseEmbedderElementsMap[guestInstanceId] = key
# Destroy an existing guest instance.
destroyGuest = (embedder, id) ->
webViewManager.removeGuest embedder, id
guestInstances[id].guest.destroy()
delete guestInstances[id]
key = reverseEmbedderElementsMap[id]
if key?
delete reverseEmbedderElementsMap[id]
delete embedderElementsMap[key]
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', (event, params, requestId) ->
event.sender.send "ATOM_SHELL_RESPONSE_#{requestId}", createGuest(event.sender, params)
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', (event, elementInstanceId, guestInstanceId, params) ->
attachGuest event.sender, elementInstanceId, guestInstanceId, params
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', (event, id) ->
destroyGuest event.sender, id
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', (event, id, params) ->
guestInstances[id]?.guest.setSize params
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', (event, id, allowtransparency) ->
guestInstances[id]?.guest.setAllowTransparency allowtransparency
# Returns WebContents from its guest id.
exports.getGuest = (id) ->
guestInstances[id]?.guest
# Returns the embedder of the guest.
exports.getEmbedder = (id) ->
guestInstances[id]?.embedder
| true | ipc = require 'ipc'
webContents = require 'web-contents'
webViewManager = null # Doesn't exist in early initialization.
supportedWebViewEvents = [
'did-finish-load'
'did-fail-load'
'did-frame-finish-load'
'did-start-loading'
'did-stop-loading'
'did-get-response-details'
'did-get-redirect-request'
'dom-ready'
'console-message'
'new-window'
'close'
'crashed'
'gpu-crashed'
'plugin-crashed'
'destroyed'
'page-title-set'
'page-favicon-updated'
'enter-html-full-screen'
'leave-html-full-screen'
]
nextInstanceId = 0
guestInstances = {}
embedderElementsMap = {}
reverseEmbedderElementsMap = {}
# Generate guestInstanceId.
getNextInstanceId = (webContents) ->
++nextInstanceId
# Create a new guest instance.
createGuest = (embedder, params) ->
webViewManager ?= process.atomBinding 'web_view_manager'
id = getNextInstanceId embedder
guest = webContents.create
isGuest: true
guestInstanceId: id
guestInstances[id] = {guest, embedder}
# Destroy guest when the embedder is gone or navigated.
destroyEvents = ['destroyed', 'crashed', 'did-navigate-to-different-page']
destroy = ->
destroyGuest embedder, id if guestInstances[id]?
embedder.once event, destroy for event in destroyEvents
guest.once 'destroyed', ->
embedder.removeListener event, destroy for event in destroyEvents
# Init guest web view after attached.
guest.once 'did-attach', ->
params = @attachParams
delete @attachParams
@viewInstanceId = params.instanceId
@setSize
normal:
width: params.elementWidth, height: params.elementHeight
enableAutoSize: params.autosize
min:
width: params.minwidth, height: params.minheight
max:
width: params.maxwidth, height: params.maxheight
if params.src
opts = {}
opts.httpreferrer = params.httpreferrer if params.httpreferrer
opts.useragent = params.useragent if params.useragent
@loadUrl params.src, opts
if params.allowtransparency?
@setAllowTransparency params.allowtransparency
# Dispatch events to embedder.
for event in supportedWebViewEvents
do (event) ->
guest.on event, (_, args...) ->
embedder.send "ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-#{guest.viewInstanceId}", event, args...
# Dispatch guest's IPC messages to embedder.
guest.on 'ipc-message-host', (_, packed) ->
[channel, args...] = packed
embedder.send "ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-#{guest.viewInstanceId}", channel, args...
# Autosize.
guest.on 'size-changed', (_, args...) ->
embedder.send "ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-#{guest.viewInstanceId}", args...
id
# Attach the guest to an element of embedder.
attachGuest = (embedder, elementInstanceId, guestInstanceId, params) ->
guest = guestInstances[guestInstanceId].guest
# Destroy the old guest when attaching.
key = PI:KEY:<KEY>END_PI
oldGuestInstanceId = embedderElementsMap[key]
if oldGuestInstanceId?
# Reattachment to the same guest is not currently supported.
return unless oldGuestInstanceId != guestInstanceId
return unless guestInstances[oldGuestInstanceId]?
destroyGuest embedder, oldGuestInstanceId
webViewManager.addGuest guestInstanceId, elementInstanceId, embedder, guest,
nodeIntegration: params.nodeintegration
plugins: params.plugins
disableWebSecurity: params.disablewebsecurity
preloadUrl: params.preload ? ''
guest.attachParams = params
embedderElementsMap[key] = guestInstanceId
reverseEmbedderElementsMap[guestInstanceId] = key
# Destroy an existing guest instance.
destroyGuest = (embedder, id) ->
webViewManager.removeGuest embedder, id
guestInstances[id].guest.destroy()
delete guestInstances[id]
key = reverseEmbedderElementsMap[id]
if key?
delete reverseEmbedderElementsMap[id]
delete embedderElementsMap[key]
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', (event, params, requestId) ->
event.sender.send "ATOM_SHELL_RESPONSE_#{requestId}", createGuest(event.sender, params)
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', (event, elementInstanceId, guestInstanceId, params) ->
attachGuest event.sender, elementInstanceId, guestInstanceId, params
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', (event, id) ->
destroyGuest event.sender, id
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', (event, id, params) ->
guestInstances[id]?.guest.setSize params
ipc.on 'ATOM_SHELL_GUEST_VIEW_MANAGER_SET_ALLOW_TRANSPARENCY', (event, id, allowtransparency) ->
guestInstances[id]?.guest.setAllowTransparency allowtransparency
# Returns WebContents from its guest id.
exports.getGuest = (id) ->
guestInstances[id]?.guest
# Returns the embedder of the guest.
exports.getEmbedder = (id) ->
guestInstances[id]?.embedder
|
[
{
"context": "x'\nfs = require 'fs'\ndata = fdf.generate\n name: 'Clark'\n type: 'superhero'\n\nfs.writeFileSync('document.",
"end": 78,
"score": 0.998387336730957,
"start": 73,
"tag": "NAME",
"value": "Clark"
}
] | node_modules/fdf/test/test.coffee | 3cola/fillpdf | 0 |
fdf = require '../index'
fs = require 'fs'
data = fdf.generate
name: 'Clark'
type: 'superhero'
fs.writeFileSync('document.fdf', data)
| 9660 |
fdf = require '../index'
fs = require 'fs'
data = fdf.generate
name: '<NAME>'
type: 'superhero'
fs.writeFileSync('document.fdf', data)
| true |
fdf = require '../index'
fs = require 'fs'
data = fdf.generate
name: 'PI:NAME:<NAME>END_PI'
type: 'superhero'
fs.writeFileSync('document.fdf', data)
|
[
{
"context": "ER DEALINGS IN THE SOFTWARE.\n\n# Copyright (c) 2015 Lu Wang\n\nKeyboardEventModifiers = new Set\nKeyboardEventMo",
"end": 1124,
"score": 0.9996331930160522,
"start": 1117,
"tag": "NAME",
"value": "Lu Wang"
}
] | src/nvim/key_handler.coffee | coolwanglu/neovim-e | 252 | # helper.coffee from atom-keymap
#
# Copyright (c) 2014 GitHub Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Copyright (c) 2015 Lu Wang
KeyboardEventModifiers = new Set
KeyboardEventModifiers.add(modifier) for modifier in ['Control', 'Alt', 'Shift', 'Meta']
SpecificityCache = {}
WindowsAndLinuxKeyIdentifierTranslations =
'U+00A0': 'Shift'
'U+00A1': 'Shift'
'U+00A2': 'Control'
'U+00A3': 'Control'
'U+00A4': 'Alt'
'U+00A5': 'Alt'
'Win': 'Meta'
WindowsAndLinuxCharCodeTranslations =
48:
shifted: 41 # ")"
unshifted: 48 # "0"
49:
shifted: 33 # "!"
unshifted: 49 # "1"
50:
shifted: 64 # "@"
unshifted: 50 # "2"
51:
shifted: 35 # "#"
unshifted: 51 # "3"
52:
shifted: 36 # "$"
unshifted: 52 # "4"
53:
shifted: 37 # "%"
unshifted: 53 # "5"
54:
shifted: 94 # "^"
unshifted: 54 # "6"
55:
shifted: 38 # "&"
unshifted: 55 # "7"
56:
shifted: 42 # "*"
unshifted: 56 # "8"
57:
shifted: 40 # "("
unshifted: 57 # "9"
186:
shifted: 58 # ":"
unshifted: 59 # ";"
187:
shifted: 43 # "+"
unshifted: 61 # "="
188:
shifted: 60 # "<"
unshifted: 44 # ","
189:
shifted: 95 # "_"
unshifted: 45 # "-"
190:
shifted: 62 # ">"
unshifted: 46 # "."
191:
shifted: 63 # "?"
unshifted: 47 # "/"
192:
shifted: 126 # "~"
unshifted: 96 # "`"
219:
shifted: 123 # "{"
unshifted: 91 # "["
220:
shifted: 124 # "|"
unshifted: 92 # "\"
221:
shifted: 125 # "}"
unshifted: 93 # "]"
222:
shifted: 34 # '"'
unshifted: 39 # "'"
NumPadToASCII =
79: 47 # "/"
74: 42 # "*"
77: 45 # "-"
75: 43 # "+"
78: 46 # "."
96: 48 # "0"
65: 49 # "1"
66: 50 # "2"
67: 51 # "3"
68: 52 # "4"
69: 53 # "5"
70: 54 # "6"
71: 55 # "7"
72: 56 # "8"
73: 57 # "9"
exports.keystrokeForKeyboardEvent = (event) ->
keyIdentifier = event.keyIdentifier
if process.platform is 'linux' or process.platform is 'win32'
keyIdentifier = translateKeyIdentifierForWindowsAndLinuxChromiumBug(keyIdentifier)
unless KeyboardEventModifiers.has(keyIdentifier)
charCode = charCodeFromKeyIdentifier(keyIdentifier)
if charCode?
if process.platform is 'linux' or process.platform is 'win32'
charCode = translateCharCodeForWindowsAndLinuxChromiumBug(charCode, event.shiftKey)
if event.location is KeyboardEvent.DOM_KEY_LOCATION_NUMPAD
# This is a numpad number
charCode = numpadToASCII(charCode)
charCode = event.which if not isASCII(charCode) and isASCII(event.keyCode)
key = keyFromCharCode(charCode)
else
key = if keyIdentifier.length == 1 then keyIdentifier.toLowerCase() else keyIdentifier
if not key?
''
else
keystroke = ''
keystroke += 'C-' if event.ctrlKey
keystroke += 'A-' if event.altKey
if event.shiftKey
# Don't push 'shift' when modifying symbolic characters like '{'
keystroke += 'S-' if key.length > 1
# Only upper case alphabetic characters like 'a'
key = key.toUpperCase() if /^[a-z]$/.test(key)
else
key = key.toLowerCase() if /^[A-Z]$/.test(key)
keystroke += 'D-' if event.metaKey
key = "lt" if key == "<" and not keystroke.length
keystroke += key
if keystroke.length == 1 then keystroke else '<' + keystroke + '>'
charCodeFromKeyIdentifier = (keyIdentifier) ->
parseInt(keyIdentifier[2..], 16) if keyIdentifier.indexOf('U+') is 0
# Chromium includes incorrect keyIdentifier values on keypress events for
# certain symbols keys on Window and Linux.
#
# See https://code.google.com/p/chromium/issues/detail?id=51024
# See https://bugs.webkit.org/show_bug.cgi?id=19906
translateKeyIdentifierForWindowsAndLinuxChromiumBug = (keyIdentifier) ->
WindowsAndLinuxKeyIdentifierTranslations[keyIdentifier] ? keyIdentifier
translateCharCodeForWindowsAndLinuxChromiumBug = (charCode, shift) ->
if translation = WindowsAndLinuxCharCodeTranslations[charCode]
if shift then translation.shifted else translation.unshifted
else
charCode
keyFromCharCode = (charCode) ->
# See :help key-notation
switch charCode
when 0 then 'Nul'
when 8 then 'BS'
when 9 then 'Tab'
when 10 then 'NL'
when 12 then 'FF'
when 13 then 'Enter'
when 27 then 'Esc'
when 32 then 'Space'
when 92 then 'Bslash'
when 124 then 'Bar'
when 127 then 'Del'
else String.fromCharCode(charCode)
isASCII = (charCode) ->
0 <= charCode <= 127
numpadToASCII = (charCode) ->
NumPadToASCII[charCode] ? charCode
| 66111 | # helper.coffee from atom-keymap
#
# Copyright (c) 2014 GitHub Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Copyright (c) 2015 <NAME>
KeyboardEventModifiers = new Set
KeyboardEventModifiers.add(modifier) for modifier in ['Control', 'Alt', 'Shift', 'Meta']
SpecificityCache = {}
WindowsAndLinuxKeyIdentifierTranslations =
'U+00A0': 'Shift'
'U+00A1': 'Shift'
'U+00A2': 'Control'
'U+00A3': 'Control'
'U+00A4': 'Alt'
'U+00A5': 'Alt'
'Win': 'Meta'
WindowsAndLinuxCharCodeTranslations =
48:
shifted: 41 # ")"
unshifted: 48 # "0"
49:
shifted: 33 # "!"
unshifted: 49 # "1"
50:
shifted: 64 # "@"
unshifted: 50 # "2"
51:
shifted: 35 # "#"
unshifted: 51 # "3"
52:
shifted: 36 # "$"
unshifted: 52 # "4"
53:
shifted: 37 # "%"
unshifted: 53 # "5"
54:
shifted: 94 # "^"
unshifted: 54 # "6"
55:
shifted: 38 # "&"
unshifted: 55 # "7"
56:
shifted: 42 # "*"
unshifted: 56 # "8"
57:
shifted: 40 # "("
unshifted: 57 # "9"
186:
shifted: 58 # ":"
unshifted: 59 # ";"
187:
shifted: 43 # "+"
unshifted: 61 # "="
188:
shifted: 60 # "<"
unshifted: 44 # ","
189:
shifted: 95 # "_"
unshifted: 45 # "-"
190:
shifted: 62 # ">"
unshifted: 46 # "."
191:
shifted: 63 # "?"
unshifted: 47 # "/"
192:
shifted: 126 # "~"
unshifted: 96 # "`"
219:
shifted: 123 # "{"
unshifted: 91 # "["
220:
shifted: 124 # "|"
unshifted: 92 # "\"
221:
shifted: 125 # "}"
unshifted: 93 # "]"
222:
shifted: 34 # '"'
unshifted: 39 # "'"
NumPadToASCII =
79: 47 # "/"
74: 42 # "*"
77: 45 # "-"
75: 43 # "+"
78: 46 # "."
96: 48 # "0"
65: 49 # "1"
66: 50 # "2"
67: 51 # "3"
68: 52 # "4"
69: 53 # "5"
70: 54 # "6"
71: 55 # "7"
72: 56 # "8"
73: 57 # "9"
exports.keystrokeForKeyboardEvent = (event) ->
keyIdentifier = event.keyIdentifier
if process.platform is 'linux' or process.platform is 'win32'
keyIdentifier = translateKeyIdentifierForWindowsAndLinuxChromiumBug(keyIdentifier)
unless KeyboardEventModifiers.has(keyIdentifier)
charCode = charCodeFromKeyIdentifier(keyIdentifier)
if charCode?
if process.platform is 'linux' or process.platform is 'win32'
charCode = translateCharCodeForWindowsAndLinuxChromiumBug(charCode, event.shiftKey)
if event.location is KeyboardEvent.DOM_KEY_LOCATION_NUMPAD
# This is a numpad number
charCode = numpadToASCII(charCode)
charCode = event.which if not isASCII(charCode) and isASCII(event.keyCode)
key = keyFromCharCode(charCode)
else
key = if keyIdentifier.length == 1 then keyIdentifier.toLowerCase() else keyIdentifier
if not key?
''
else
keystroke = ''
keystroke += 'C-' if event.ctrlKey
keystroke += 'A-' if event.altKey
if event.shiftKey
# Don't push 'shift' when modifying symbolic characters like '{'
keystroke += 'S-' if key.length > 1
# Only upper case alphabetic characters like 'a'
key = key.toUpperCase() if /^[a-z]$/.test(key)
else
key = key.toLowerCase() if /^[A-Z]$/.test(key)
keystroke += 'D-' if event.metaKey
key = "lt" if key == "<" and not keystroke.length
keystroke += key
if keystroke.length == 1 then keystroke else '<' + keystroke + '>'
charCodeFromKeyIdentifier = (keyIdentifier) ->
parseInt(keyIdentifier[2..], 16) if keyIdentifier.indexOf('U+') is 0
# Chromium includes incorrect keyIdentifier values on keypress events for
# certain symbols keys on Window and Linux.
#
# See https://code.google.com/p/chromium/issues/detail?id=51024
# See https://bugs.webkit.org/show_bug.cgi?id=19906
translateKeyIdentifierForWindowsAndLinuxChromiumBug = (keyIdentifier) ->
WindowsAndLinuxKeyIdentifierTranslations[keyIdentifier] ? keyIdentifier
translateCharCodeForWindowsAndLinuxChromiumBug = (charCode, shift) ->
if translation = WindowsAndLinuxCharCodeTranslations[charCode]
if shift then translation.shifted else translation.unshifted
else
charCode
keyFromCharCode = (charCode) ->
# See :help key-notation
switch charCode
when 0 then 'Nul'
when 8 then 'BS'
when 9 then 'Tab'
when 10 then 'NL'
when 12 then 'FF'
when 13 then 'Enter'
when 27 then 'Esc'
when 32 then 'Space'
when 92 then 'Bslash'
when 124 then 'Bar'
when 127 then 'Del'
else String.fromCharCode(charCode)
isASCII = (charCode) ->
0 <= charCode <= 127
numpadToASCII = (charCode) ->
NumPadToASCII[charCode] ? charCode
| true | # helper.coffee from atom-keymap
#
# Copyright (c) 2014 GitHub Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Copyright (c) 2015 PI:NAME:<NAME>END_PI
KeyboardEventModifiers = new Set
KeyboardEventModifiers.add(modifier) for modifier in ['Control', 'Alt', 'Shift', 'Meta']
SpecificityCache = {}
WindowsAndLinuxKeyIdentifierTranslations =
'U+00A0': 'Shift'
'U+00A1': 'Shift'
'U+00A2': 'Control'
'U+00A3': 'Control'
'U+00A4': 'Alt'
'U+00A5': 'Alt'
'Win': 'Meta'
WindowsAndLinuxCharCodeTranslations =
48:
shifted: 41 # ")"
unshifted: 48 # "0"
49:
shifted: 33 # "!"
unshifted: 49 # "1"
50:
shifted: 64 # "@"
unshifted: 50 # "2"
51:
shifted: 35 # "#"
unshifted: 51 # "3"
52:
shifted: 36 # "$"
unshifted: 52 # "4"
53:
shifted: 37 # "%"
unshifted: 53 # "5"
54:
shifted: 94 # "^"
unshifted: 54 # "6"
55:
shifted: 38 # "&"
unshifted: 55 # "7"
56:
shifted: 42 # "*"
unshifted: 56 # "8"
57:
shifted: 40 # "("
unshifted: 57 # "9"
186:
shifted: 58 # ":"
unshifted: 59 # ";"
187:
shifted: 43 # "+"
unshifted: 61 # "="
188:
shifted: 60 # "<"
unshifted: 44 # ","
189:
shifted: 95 # "_"
unshifted: 45 # "-"
190:
shifted: 62 # ">"
unshifted: 46 # "."
191:
shifted: 63 # "?"
unshifted: 47 # "/"
192:
shifted: 126 # "~"
unshifted: 96 # "`"
219:
shifted: 123 # "{"
unshifted: 91 # "["
220:
shifted: 124 # "|"
unshifted: 92 # "\"
221:
shifted: 125 # "}"
unshifted: 93 # "]"
222:
shifted: 34 # '"'
unshifted: 39 # "'"
NumPadToASCII =
79: 47 # "/"
74: 42 # "*"
77: 45 # "-"
75: 43 # "+"
78: 46 # "."
96: 48 # "0"
65: 49 # "1"
66: 50 # "2"
67: 51 # "3"
68: 52 # "4"
69: 53 # "5"
70: 54 # "6"
71: 55 # "7"
72: 56 # "8"
73: 57 # "9"
exports.keystrokeForKeyboardEvent = (event) ->
keyIdentifier = event.keyIdentifier
if process.platform is 'linux' or process.platform is 'win32'
keyIdentifier = translateKeyIdentifierForWindowsAndLinuxChromiumBug(keyIdentifier)
unless KeyboardEventModifiers.has(keyIdentifier)
charCode = charCodeFromKeyIdentifier(keyIdentifier)
if charCode?
if process.platform is 'linux' or process.platform is 'win32'
charCode = translateCharCodeForWindowsAndLinuxChromiumBug(charCode, event.shiftKey)
if event.location is KeyboardEvent.DOM_KEY_LOCATION_NUMPAD
# This is a numpad number
charCode = numpadToASCII(charCode)
charCode = event.which if not isASCII(charCode) and isASCII(event.keyCode)
key = keyFromCharCode(charCode)
else
key = if keyIdentifier.length == 1 then keyIdentifier.toLowerCase() else keyIdentifier
if not key?
''
else
keystroke = ''
keystroke += 'C-' if event.ctrlKey
keystroke += 'A-' if event.altKey
if event.shiftKey
# Don't push 'shift' when modifying symbolic characters like '{'
keystroke += 'S-' if key.length > 1
# Only upper case alphabetic characters like 'a'
key = key.toUpperCase() if /^[a-z]$/.test(key)
else
key = key.toLowerCase() if /^[A-Z]$/.test(key)
keystroke += 'D-' if event.metaKey
key = "lt" if key == "<" and not keystroke.length
keystroke += key
if keystroke.length == 1 then keystroke else '<' + keystroke + '>'
charCodeFromKeyIdentifier = (keyIdentifier) ->
parseInt(keyIdentifier[2..], 16) if keyIdentifier.indexOf('U+') is 0
# Chromium includes incorrect keyIdentifier values on keypress events for
# certain symbols keys on Window and Linux.
#
# See https://code.google.com/p/chromium/issues/detail?id=51024
# See https://bugs.webkit.org/show_bug.cgi?id=19906
translateKeyIdentifierForWindowsAndLinuxChromiumBug = (keyIdentifier) ->
WindowsAndLinuxKeyIdentifierTranslations[keyIdentifier] ? keyIdentifier
translateCharCodeForWindowsAndLinuxChromiumBug = (charCode, shift) ->
if translation = WindowsAndLinuxCharCodeTranslations[charCode]
if shift then translation.shifted else translation.unshifted
else
charCode
keyFromCharCode = (charCode) ->
# See :help key-notation
switch charCode
when 0 then 'Nul'
when 8 then 'BS'
when 9 then 'Tab'
when 10 then 'NL'
when 12 then 'FF'
when 13 then 'Enter'
when 27 then 'Esc'
when 32 then 'Space'
when 92 then 'Bslash'
when 124 then 'Bar'
when 127 then 'Del'
else String.fromCharCode(charCode)
isASCII = (charCode) ->
0 <= charCode <= 127
numpadToASCII = (charCode) ->
NumPadToASCII[charCode] ? charCode
|
[
{
"context": "fcgi?db=pubmed&query_key=1&WebEnv=NCID_1_54953983_165.112.9.28_9001_1461227951_1012752855_0MetA0_S_MegaStore_F_1",
"end": 791,
"score": 0.9432511925697327,
"start": 779,
"tag": "IP_ADDRESS",
"value": "165.112.9.28"
},
{
"context": "\",\n \"AuthorList\": [\n {\n \"Author\": \"Jackson M\"\n }\n ],\n \"LastAuthor\": \"Jackson M\",\n ",
"end": 10722,
"score": 0.9997444748878479,
"start": 10713,
"tag": "NAME",
"value": "Jackson M"
},
{
"context": "r\": \"Jackson M\"\n }\n ],\n \"LastAuthor\": \"Jackson M\",\n \"Title\": \"The pursuit of happiness: The soc",
"end": 10767,
"score": 0.9997517466545105,
"start": 10758,
"tag": "NAME",
"value": "Jackson M"
}
] | server/use/pubmed.coffee | leviathanindustries/noddy | 2 |
_decodeEntities = (str) ->
re = /&(nbsp|amp|quot|lt|gt);/g
translate = "nbsp" : " ", "amp" : "&", "quot" : "\"", "lt" : "<", "gt" : ">"
return str.replace(re, (match, entity) ->
return translate[entity];
).replace(/&#(\d+);/gi, (match, numStr) ->
return String.fromCharCode parseInt numStr, 10
)
# pubmed API http://www.ncbi.nlm.nih.gov/books/NBK25497/
# examples http://www.ncbi.nlm.nih.gov/books/NBK25498/#chapter3.ESearch__ESummaryEFetch
# get a pmid - need first to issue a query to get some IDs...
# http://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi?id=21999661&db=pubmed
# then scrape the QueryKey and WebEnv values from it and use like so:
# http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&query_key=1&WebEnv=NCID_1_54953983_165.112.9.28_9001_1461227951_1012752855_0MetA0_S_MegaStore_F_1
API.use ?= {}
API.use.pubmed = {}
API.add 'use/pubmed/search/:q', get: () -> return API.use.pubmed.search this.urlParams.q, this.queryParams.full?, this.queryParams.size, this.queryParams.ids?
API.add 'use/pubmed/:pmid', get: () -> return API.use.pubmed.pmid this.urlParams.pmid
API.add 'use/pubmed/summary/:pmid',
get: () ->
res = API.use.pubmed.entrez.summary undefined, undefined, this.urlParams.pmid
return if this.queryParams.format then API.use.pubmed.format(res) else res
API.use.pubmed.entrez = {}
API.use.pubmed.entrez.summary = (qk,webenv,id) ->
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed'
if id?
id = id.join(',') if _.isArray id
url += '&id=' + id # can be a comma separated list as well
else
url += '&query_key=' + qk + '&WebEnv=' + webenv
API.log 'Using pubmed entrez summary for ' + url
if 1 is 1 #try
res = HTTP.call 'GET', url
md = API.convert.xml2json res.content, undefined, false
recs = []
for rec in md.eSummaryResult.DocSum
frec = {id:rec.Id[0]}
for ii in rec.Item
if ii.$.Type is 'List'
frec[ii.$.Name] = []
if ii.Item?
for si in ii.Item
sio = {}
sio[si.$.Name] = si._
frec[ii.$.Name].push sio
else
frec[ii.$.Name] = ii._
recs.push frec
if not id? or id.indexOf(',') is -1
return recs[0]
break
return recs
#catch
# return undefined
API.use.pubmed.entrez.pmid = (pmid) ->
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi?db=pubmed&id=' + pmid
API.log 'Using pubmed entrez post for ' + url
try
res = HTTP.call 'GET', url
result = API.convert.xml2json res.content, undefined, false
return API.use.pubmed.entrez.summary result.ePostResult.QueryKey[0], result.ePostResult.WebEnv[0]
catch
return undefined
API.use.pubmed.search = (str,full,size=10,ids=false) ->
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmax=' + size + '&sort=pub date&term=' + str
API.log 'Using pubmed entrez search for ' + url
try
ids = ids.split(',') if typeof ids is 'string'
if _.isArray ids
res = {total: ids.length, data: []}
else
res = HTTP.call 'GET', url
result = API.convert.xml2json res.content, undefined, false
res = {total: result.eSearchResult.Count[0], data: []}
if ids is true
res.data = result.eSearchResult.IdList[0].Id
return res
else
ids = result.eSearchResult.IdList[0].Id
if full # may need a rate limiter on this
for uid in ids
pg = API.job.limit 300, 'API.use.pubmed.pmid', [uid], "PUBMED_EUTILS"
res.data.push pg
break if res.data.length is size
else
urlids = []
for id in ids
break if res.data.length is size
urlids.push id
if urlids.length is 40
#summaries = API.job.limit 300, 'API.use.pubmed.entrez.summary', [undefined,undefined,urlids], "PUBMED_EUTILS"
for rec in API.use.pubmed.entrez.summary undefined, undefined, urlids
res.data.push API.use.pubmed.format rec
break if res.data.length is size
urlids = []
if urlids.length
#remains = API.job.limit 300, 'API.use.pubmed.entrez.summary', [undefined,undefined,urlids], "PUBMED_EUTILS"
for rec in API.use.pubmed.entrez.summary undefined, undefined, urlids
res.data.push API.use.pubmed.format rec
break if res.data.length is size
return res
catch err
return {status:'error', error: err.toString()}
API.use.pubmed.pmid = (pmid) ->
try
url = 'https://www.ncbi.nlm.nih.gov/pubmed/' + pmid + '?report=xml'
res = HTTP.call 'GET', url
if res?.content? and res.content.indexOf('<') is 0
return API.use.pubmed.format _decodeEntities res.content.split('<pre>')[1].split('</pre>')[0].replace('\n','')
try
return API.use.pubmed.format API.use.pubmed.entrez.pmid pmid
return undefined
API.use.pubmed.aheadofprint = (pmid) ->
try
res = HTTP.call 'GET', 'https://www.ncbi.nlm.nih.gov/pubmed/' + pmid + '?report=xml'
return res.content?.indexOf('PublicationStatus>aheadofprint</PublicationStatus') isnt -1
catch
return false
API.use.pubmed.format = (rec, metadata={}) ->
if typeof rec is 'string' and rec.indexOf('<') is 0
rec = API.convert.xml2json rec, undefined, false
if rec.eSummaryResult?.DocSum? or rec.ArticleIds
frec = {}
if rec.eSummaryResult?.DocSum?
rec = md.eSummaryResult.DocSum[0]
for ii in rec.Item
if ii.$.Type is 'List'
frec[ii.$.Name] = []
if ii.Item?
for si in ii.Item
sio = {}
sio[si.$.Name] = si._
frec[ii.$.Name].push sio
else
frec[ii.$.Name] = ii._
else
frec = rec
try metadata.pmid ?= rec.Id[0]
try metadata.pmid ?= rec.id
try metadata.title ?= frec.Title
try metadata.issn ?= frec.ISSN
try metadata.essn ?= frec.ESSN
try metadata.doi ?= frec.DOI
try metadata.journal ?= frec.FullJournalName
try metadata.journal_short ?= frec.Source
try metadata.volume ?= frec.Volume
try metadata.issue ?= frec.Issue
try metadata.page ?= frec.Pages #like 13-29 how to handle this
try metadata.year ?= frec[if frec.PubDate then 'PubDate' else 'EPubDate'].split(' ')[0]
try
p = frec[if frec.PubDate then 'PubDate' else 'EPubDate'].split ' '
metadata.published ?= p[0] + '-' + (['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf(p[1].toLowerCase()) + 1) + '-' + (if p.length is 3 then p[2] else '01')
if frec.AuthorList?
metadata.author ?= []
for a in frec.AuthorList
try
a.family = a.Author.split(' ')[0]
a.given = a.Author.replace(a.family + ' ','')
a.name = a.given + ' ' + a.family
metadata.author.push a
if frec.ArticleIds? and not metadata.pmcid?
for ai in frec.ArticleIds
if ai.pmc # pmcid or pmc? replace PMC in the value? it will be present
metadata.pmcid ?= ai.pmc
break
else if rec.PubmedArticle?
rec = rec.PubmedArticle
mc = rec.MedlineCitation[0]
try metadata.pmid ?= mc.PMID[0]._
try metadata.title ?= mc.Article[0].ArticleTitle[0]
try metadata.issn ?= mc.Article[0].Journal[0].ISSN[0]._
try metadata.journal ?= mc.Article[0].Journal[0].Title[0]
try metadata.journal_short ?= mc.Article[0].Journal[0].ISOAbbreviation[0]
try
pd = mc.Article[0].Journal[0].JournalIssue[0].PubDate[0]
try metadata.year ?= pd.Year[0]
try metadata.published ?= pd.Year[0] + '-' + (if pd.Month then (['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf(pd.Month[0].toLowerCase()) + 1) else '01') + '-' + (if pd.Day then pd.Day[0] else '01')
try
metadata.author ?= []
for ar in mc.Article[0].AuthorList[0].Author
a = {}
a.family = ar.LastName[0]
a.given = ar.ForeName[0]
a.name = if a.Author then a.Author else a.given + ' ' + a.family
try a.affiliation = ar.AffiliationInfo[0].Affiliation[0]
if a.affiliation?
a.affiliation = a.affiliation[0] if _.isArray a.affiliation
a.affiliation = {name: a.affiliation} if typeof a.affiliation is 'string'
metadata.author.push a
try
for pid in rec.PubmedData[0].ArticleIdList[0].ArticleId
if pid.$.IdType is 'doi'
metadata.doi ?= pid._
break
try
metadata.reference ?= []
for ref in rec.PubmedData[0].ReferenceList[0].Reference
rc = ref.Citation[0]
rf = {}
rf.doi = rc.split('doi.org/')[1].trim() if rc.indexOf('doi.org/') isnt -1
try
rf.author = []
rf.author.push({name: an}) for an in rc.split('. ')[0].split(', ')
try rf.title = rc.split('. ')[1].split('?')[0].trim()
try rf.journal = rc.replace(/\?/g,'.').split('. ')[2].trim()
try
rf.url = 'http' + rc.split('http')[1].split(' ')[0]
delete rf.url if rf.url.indexOf('doi.org') isnt -1
metadata.reference.push(rf) if not _.isEmpty rf
try metadata.pdf ?= rec.pdf
try metadata.url ?= rec.url
try metadata.open ?= rec.open
try metadata.redirect ?= rec.redirect
return metadata
API.use.pubmed.status = () ->
try
return HTTP.call('GET', 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi', {timeout: API.settings.use?.europepmc?.timeout ? API.settings.use?._timeout ? 4000}).statusCode is 200
catch err
return err.toString()
API.use.pubmed.test = (verbose) ->
console.log('Starting pubmed test') if API.settings.dev
result = {passed:[],failed:[]}
tests = [
#() -> the below example is no longer accurate to the output of the function
# result.record = API.use.pubmed.pmid '23908565'
# delete result.record.EPubDate # don't know what happens to these, so just remove them...
# delete result.record.ELocationID
# return _.isEqual result.record, API.use.pubmed.test._examples.record
() ->
result.aheadofprint = API.use.pubmed.aheadofprint '23908565'
return result.aheadofprint is false # TODO add one that is true
]
(if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests
result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0
result = {passed:result.passed} if result.failed.length is 0 and not verbose
console.log('Ending pubmed test') if API.settings.dev
return result
API.use.pubmed.test._examples = {
record: {
"id": "23908565",
"PubDate": "2012 Dec",
"Source": "Hist Human Sci",
"AuthorList": [
{
"Author": "Jackson M"
}
],
"LastAuthor": "Jackson M",
"Title": "The pursuit of happiness: The social and scientific origins of Hans Selye's natural philosophy of life.",
"Volume": "25",
"Issue": "5",
"Pages": "13-29",
"LangList": [
{
"Lang": "English"
}
],
"NlmUniqueID": "100967737",
"ISSN": "0952-6951",
"ESSN": "1461-720X",
"PubTypeList": [
{
"PubType": "Journal Article"
}
],
"RecordStatus": "PubMed",
"PubStatus": "ppublish",
"ArticleIds": [
{
"pubmed": "23908565"
},
{
"doi": "10.1177/0952695112468526"
},
{
"pii": "10.1177_0952695112468526"
},
{
"pmc": "PMC3724273"
},
{
"rid": "23908565"
},
{
"eid": "23908565"
},
{
"pmcid": "pmc-id: PMC3724273;"
}
],
"DOI": "10.1177/0952695112468526",
"History": [
{
"entrez": "2013/08/03 06:00"
},
{
"pubmed": "2013/08/03 06:00"
},
{
"medline": "2013/08/03 06:00"
}
],
"References": [],
"HasAbstract": "1",
"PmcRefCount": "0",
"FullJournalName": "History of the human sciences",
"SO": "2012 Dec;25(5):13-29"
}
} | 146060 |
_decodeEntities = (str) ->
re = /&(nbsp|amp|quot|lt|gt);/g
translate = "nbsp" : " ", "amp" : "&", "quot" : "\"", "lt" : "<", "gt" : ">"
return str.replace(re, (match, entity) ->
return translate[entity];
).replace(/&#(\d+);/gi, (match, numStr) ->
return String.fromCharCode parseInt numStr, 10
)
# pubmed API http://www.ncbi.nlm.nih.gov/books/NBK25497/
# examples http://www.ncbi.nlm.nih.gov/books/NBK25498/#chapter3.ESearch__ESummaryEFetch
# get a pmid - need first to issue a query to get some IDs...
# http://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi?id=21999661&db=pubmed
# then scrape the QueryKey and WebEnv values from it and use like so:
# http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&query_key=1&WebEnv=NCID_1_54953983_172.16.58.3_9001_1461227951_1012752855_0MetA0_S_MegaStore_F_1
API.use ?= {}
API.use.pubmed = {}
API.add 'use/pubmed/search/:q', get: () -> return API.use.pubmed.search this.urlParams.q, this.queryParams.full?, this.queryParams.size, this.queryParams.ids?
API.add 'use/pubmed/:pmid', get: () -> return API.use.pubmed.pmid this.urlParams.pmid
API.add 'use/pubmed/summary/:pmid',
get: () ->
res = API.use.pubmed.entrez.summary undefined, undefined, this.urlParams.pmid
return if this.queryParams.format then API.use.pubmed.format(res) else res
API.use.pubmed.entrez = {}
API.use.pubmed.entrez.summary = (qk,webenv,id) ->
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed'
if id?
id = id.join(',') if _.isArray id
url += '&id=' + id # can be a comma separated list as well
else
url += '&query_key=' + qk + '&WebEnv=' + webenv
API.log 'Using pubmed entrez summary for ' + url
if 1 is 1 #try
res = HTTP.call 'GET', url
md = API.convert.xml2json res.content, undefined, false
recs = []
for rec in md.eSummaryResult.DocSum
frec = {id:rec.Id[0]}
for ii in rec.Item
if ii.$.Type is 'List'
frec[ii.$.Name] = []
if ii.Item?
for si in ii.Item
sio = {}
sio[si.$.Name] = si._
frec[ii.$.Name].push sio
else
frec[ii.$.Name] = ii._
recs.push frec
if not id? or id.indexOf(',') is -1
return recs[0]
break
return recs
#catch
# return undefined
API.use.pubmed.entrez.pmid = (pmid) ->
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi?db=pubmed&id=' + pmid
API.log 'Using pubmed entrez post for ' + url
try
res = HTTP.call 'GET', url
result = API.convert.xml2json res.content, undefined, false
return API.use.pubmed.entrez.summary result.ePostResult.QueryKey[0], result.ePostResult.WebEnv[0]
catch
return undefined
API.use.pubmed.search = (str,full,size=10,ids=false) ->
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmax=' + size + '&sort=pub date&term=' + str
API.log 'Using pubmed entrez search for ' + url
try
ids = ids.split(',') if typeof ids is 'string'
if _.isArray ids
res = {total: ids.length, data: []}
else
res = HTTP.call 'GET', url
result = API.convert.xml2json res.content, undefined, false
res = {total: result.eSearchResult.Count[0], data: []}
if ids is true
res.data = result.eSearchResult.IdList[0].Id
return res
else
ids = result.eSearchResult.IdList[0].Id
if full # may need a rate limiter on this
for uid in ids
pg = API.job.limit 300, 'API.use.pubmed.pmid', [uid], "PUBMED_EUTILS"
res.data.push pg
break if res.data.length is size
else
urlids = []
for id in ids
break if res.data.length is size
urlids.push id
if urlids.length is 40
#summaries = API.job.limit 300, 'API.use.pubmed.entrez.summary', [undefined,undefined,urlids], "PUBMED_EUTILS"
for rec in API.use.pubmed.entrez.summary undefined, undefined, urlids
res.data.push API.use.pubmed.format rec
break if res.data.length is size
urlids = []
if urlids.length
#remains = API.job.limit 300, 'API.use.pubmed.entrez.summary', [undefined,undefined,urlids], "PUBMED_EUTILS"
for rec in API.use.pubmed.entrez.summary undefined, undefined, urlids
res.data.push API.use.pubmed.format rec
break if res.data.length is size
return res
catch err
return {status:'error', error: err.toString()}
API.use.pubmed.pmid = (pmid) ->
try
url = 'https://www.ncbi.nlm.nih.gov/pubmed/' + pmid + '?report=xml'
res = HTTP.call 'GET', url
if res?.content? and res.content.indexOf('<') is 0
return API.use.pubmed.format _decodeEntities res.content.split('<pre>')[1].split('</pre>')[0].replace('\n','')
try
return API.use.pubmed.format API.use.pubmed.entrez.pmid pmid
return undefined
API.use.pubmed.aheadofprint = (pmid) ->
try
res = HTTP.call 'GET', 'https://www.ncbi.nlm.nih.gov/pubmed/' + pmid + '?report=xml'
return res.content?.indexOf('PublicationStatus>aheadofprint</PublicationStatus') isnt -1
catch
return false
API.use.pubmed.format = (rec, metadata={}) ->
if typeof rec is 'string' and rec.indexOf('<') is 0
rec = API.convert.xml2json rec, undefined, false
if rec.eSummaryResult?.DocSum? or rec.ArticleIds
frec = {}
if rec.eSummaryResult?.DocSum?
rec = md.eSummaryResult.DocSum[0]
for ii in rec.Item
if ii.$.Type is 'List'
frec[ii.$.Name] = []
if ii.Item?
for si in ii.Item
sio = {}
sio[si.$.Name] = si._
frec[ii.$.Name].push sio
else
frec[ii.$.Name] = ii._
else
frec = rec
try metadata.pmid ?= rec.Id[0]
try metadata.pmid ?= rec.id
try metadata.title ?= frec.Title
try metadata.issn ?= frec.ISSN
try metadata.essn ?= frec.ESSN
try metadata.doi ?= frec.DOI
try metadata.journal ?= frec.FullJournalName
try metadata.journal_short ?= frec.Source
try metadata.volume ?= frec.Volume
try metadata.issue ?= frec.Issue
try metadata.page ?= frec.Pages #like 13-29 how to handle this
try metadata.year ?= frec[if frec.PubDate then 'PubDate' else 'EPubDate'].split(' ')[0]
try
p = frec[if frec.PubDate then 'PubDate' else 'EPubDate'].split ' '
metadata.published ?= p[0] + '-' + (['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf(p[1].toLowerCase()) + 1) + '-' + (if p.length is 3 then p[2] else '01')
if frec.AuthorList?
metadata.author ?= []
for a in frec.AuthorList
try
a.family = a.Author.split(' ')[0]
a.given = a.Author.replace(a.family + ' ','')
a.name = a.given + ' ' + a.family
metadata.author.push a
if frec.ArticleIds? and not metadata.pmcid?
for ai in frec.ArticleIds
if ai.pmc # pmcid or pmc? replace PMC in the value? it will be present
metadata.pmcid ?= ai.pmc
break
else if rec.PubmedArticle?
rec = rec.PubmedArticle
mc = rec.MedlineCitation[0]
try metadata.pmid ?= mc.PMID[0]._
try metadata.title ?= mc.Article[0].ArticleTitle[0]
try metadata.issn ?= mc.Article[0].Journal[0].ISSN[0]._
try metadata.journal ?= mc.Article[0].Journal[0].Title[0]
try metadata.journal_short ?= mc.Article[0].Journal[0].ISOAbbreviation[0]
try
pd = mc.Article[0].Journal[0].JournalIssue[0].PubDate[0]
try metadata.year ?= pd.Year[0]
try metadata.published ?= pd.Year[0] + '-' + (if pd.Month then (['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf(pd.Month[0].toLowerCase()) + 1) else '01') + '-' + (if pd.Day then pd.Day[0] else '01')
try
metadata.author ?= []
for ar in mc.Article[0].AuthorList[0].Author
a = {}
a.family = ar.LastName[0]
a.given = ar.ForeName[0]
a.name = if a.Author then a.Author else a.given + ' ' + a.family
try a.affiliation = ar.AffiliationInfo[0].Affiliation[0]
if a.affiliation?
a.affiliation = a.affiliation[0] if _.isArray a.affiliation
a.affiliation = {name: a.affiliation} if typeof a.affiliation is 'string'
metadata.author.push a
try
for pid in rec.PubmedData[0].ArticleIdList[0].ArticleId
if pid.$.IdType is 'doi'
metadata.doi ?= pid._
break
try
metadata.reference ?= []
for ref in rec.PubmedData[0].ReferenceList[0].Reference
rc = ref.Citation[0]
rf = {}
rf.doi = rc.split('doi.org/')[1].trim() if rc.indexOf('doi.org/') isnt -1
try
rf.author = []
rf.author.push({name: an}) for an in rc.split('. ')[0].split(', ')
try rf.title = rc.split('. ')[1].split('?')[0].trim()
try rf.journal = rc.replace(/\?/g,'.').split('. ')[2].trim()
try
rf.url = 'http' + rc.split('http')[1].split(' ')[0]
delete rf.url if rf.url.indexOf('doi.org') isnt -1
metadata.reference.push(rf) if not _.isEmpty rf
try metadata.pdf ?= rec.pdf
try metadata.url ?= rec.url
try metadata.open ?= rec.open
try metadata.redirect ?= rec.redirect
return metadata
API.use.pubmed.status = () ->
try
return HTTP.call('GET', 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi', {timeout: API.settings.use?.europepmc?.timeout ? API.settings.use?._timeout ? 4000}).statusCode is 200
catch err
return err.toString()
API.use.pubmed.test = (verbose) ->
console.log('Starting pubmed test') if API.settings.dev
result = {passed:[],failed:[]}
tests = [
#() -> the below example is no longer accurate to the output of the function
# result.record = API.use.pubmed.pmid '23908565'
# delete result.record.EPubDate # don't know what happens to these, so just remove them...
# delete result.record.ELocationID
# return _.isEqual result.record, API.use.pubmed.test._examples.record
() ->
result.aheadofprint = API.use.pubmed.aheadofprint '23908565'
return result.aheadofprint is false # TODO add one that is true
]
(if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests
result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0
result = {passed:result.passed} if result.failed.length is 0 and not verbose
console.log('Ending pubmed test') if API.settings.dev
return result
API.use.pubmed.test._examples = {
record: {
"id": "23908565",
"PubDate": "2012 Dec",
"Source": "Hist Human Sci",
"AuthorList": [
{
"Author": "<NAME>"
}
],
"LastAuthor": "<NAME>",
"Title": "The pursuit of happiness: The social and scientific origins of Hans Selye's natural philosophy of life.",
"Volume": "25",
"Issue": "5",
"Pages": "13-29",
"LangList": [
{
"Lang": "English"
}
],
"NlmUniqueID": "100967737",
"ISSN": "0952-6951",
"ESSN": "1461-720X",
"PubTypeList": [
{
"PubType": "Journal Article"
}
],
"RecordStatus": "PubMed",
"PubStatus": "ppublish",
"ArticleIds": [
{
"pubmed": "23908565"
},
{
"doi": "10.1177/0952695112468526"
},
{
"pii": "10.1177_0952695112468526"
},
{
"pmc": "PMC3724273"
},
{
"rid": "23908565"
},
{
"eid": "23908565"
},
{
"pmcid": "pmc-id: PMC3724273;"
}
],
"DOI": "10.1177/0952695112468526",
"History": [
{
"entrez": "2013/08/03 06:00"
},
{
"pubmed": "2013/08/03 06:00"
},
{
"medline": "2013/08/03 06:00"
}
],
"References": [],
"HasAbstract": "1",
"PmcRefCount": "0",
"FullJournalName": "History of the human sciences",
"SO": "2012 Dec;25(5):13-29"
}
} | true |
_decodeEntities = (str) ->
re = /&(nbsp|amp|quot|lt|gt);/g
translate = "nbsp" : " ", "amp" : "&", "quot" : "\"", "lt" : "<", "gt" : ">"
return str.replace(re, (match, entity) ->
return translate[entity];
).replace(/&#(\d+);/gi, (match, numStr) ->
return String.fromCharCode parseInt numStr, 10
)
# pubmed API http://www.ncbi.nlm.nih.gov/books/NBK25497/
# examples http://www.ncbi.nlm.nih.gov/books/NBK25498/#chapter3.ESearch__ESummaryEFetch
# get a pmid - need first to issue a query to get some IDs...
# http://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi?id=21999661&db=pubmed
# then scrape the QueryKey and WebEnv values from it and use like so:
# http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&query_key=1&WebEnv=NCID_1_54953983_PI:IP_ADDRESS:172.16.58.3END_PI_9001_1461227951_1012752855_0MetA0_S_MegaStore_F_1
API.use ?= {}
API.use.pubmed = {}
API.add 'use/pubmed/search/:q', get: () -> return API.use.pubmed.search this.urlParams.q, this.queryParams.full?, this.queryParams.size, this.queryParams.ids?
API.add 'use/pubmed/:pmid', get: () -> return API.use.pubmed.pmid this.urlParams.pmid
API.add 'use/pubmed/summary/:pmid',
get: () ->
res = API.use.pubmed.entrez.summary undefined, undefined, this.urlParams.pmid
return if this.queryParams.format then API.use.pubmed.format(res) else res
API.use.pubmed.entrez = {}
API.use.pubmed.entrez.summary = (qk,webenv,id) ->
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed'
if id?
id = id.join(',') if _.isArray id
url += '&id=' + id # can be a comma separated list as well
else
url += '&query_key=' + qk + '&WebEnv=' + webenv
API.log 'Using pubmed entrez summary for ' + url
if 1 is 1 #try
res = HTTP.call 'GET', url
md = API.convert.xml2json res.content, undefined, false
recs = []
for rec in md.eSummaryResult.DocSum
frec = {id:rec.Id[0]}
for ii in rec.Item
if ii.$.Type is 'List'
frec[ii.$.Name] = []
if ii.Item?
for si in ii.Item
sio = {}
sio[si.$.Name] = si._
frec[ii.$.Name].push sio
else
frec[ii.$.Name] = ii._
recs.push frec
if not id? or id.indexOf(',') is -1
return recs[0]
break
return recs
#catch
# return undefined
API.use.pubmed.entrez.pmid = (pmid) ->
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi?db=pubmed&id=' + pmid
API.log 'Using pubmed entrez post for ' + url
try
res = HTTP.call 'GET', url
result = API.convert.xml2json res.content, undefined, false
return API.use.pubmed.entrez.summary result.ePostResult.QueryKey[0], result.ePostResult.WebEnv[0]
catch
return undefined
API.use.pubmed.search = (str,full,size=10,ids=false) ->
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&retmax=' + size + '&sort=pub date&term=' + str
API.log 'Using pubmed entrez search for ' + url
try
ids = ids.split(',') if typeof ids is 'string'
if _.isArray ids
res = {total: ids.length, data: []}
else
res = HTTP.call 'GET', url
result = API.convert.xml2json res.content, undefined, false
res = {total: result.eSearchResult.Count[0], data: []}
if ids is true
res.data = result.eSearchResult.IdList[0].Id
return res
else
ids = result.eSearchResult.IdList[0].Id
if full # may need a rate limiter on this
for uid in ids
pg = API.job.limit 300, 'API.use.pubmed.pmid', [uid], "PUBMED_EUTILS"
res.data.push pg
break if res.data.length is size
else
urlids = []
for id in ids
break if res.data.length is size
urlids.push id
if urlids.length is 40
#summaries = API.job.limit 300, 'API.use.pubmed.entrez.summary', [undefined,undefined,urlids], "PUBMED_EUTILS"
for rec in API.use.pubmed.entrez.summary undefined, undefined, urlids
res.data.push API.use.pubmed.format rec
break if res.data.length is size
urlids = []
if urlids.length
#remains = API.job.limit 300, 'API.use.pubmed.entrez.summary', [undefined,undefined,urlids], "PUBMED_EUTILS"
for rec in API.use.pubmed.entrez.summary undefined, undefined, urlids
res.data.push API.use.pubmed.format rec
break if res.data.length is size
return res
catch err
return {status:'error', error: err.toString()}
API.use.pubmed.pmid = (pmid) ->
try
url = 'https://www.ncbi.nlm.nih.gov/pubmed/' + pmid + '?report=xml'
res = HTTP.call 'GET', url
if res?.content? and res.content.indexOf('<') is 0
return API.use.pubmed.format _decodeEntities res.content.split('<pre>')[1].split('</pre>')[0].replace('\n','')
try
return API.use.pubmed.format API.use.pubmed.entrez.pmid pmid
return undefined
API.use.pubmed.aheadofprint = (pmid) ->
try
res = HTTP.call 'GET', 'https://www.ncbi.nlm.nih.gov/pubmed/' + pmid + '?report=xml'
return res.content?.indexOf('PublicationStatus>aheadofprint</PublicationStatus') isnt -1
catch
return false
API.use.pubmed.format = (rec, metadata={}) ->
if typeof rec is 'string' and rec.indexOf('<') is 0
rec = API.convert.xml2json rec, undefined, false
if rec.eSummaryResult?.DocSum? or rec.ArticleIds
frec = {}
if rec.eSummaryResult?.DocSum?
rec = md.eSummaryResult.DocSum[0]
for ii in rec.Item
if ii.$.Type is 'List'
frec[ii.$.Name] = []
if ii.Item?
for si in ii.Item
sio = {}
sio[si.$.Name] = si._
frec[ii.$.Name].push sio
else
frec[ii.$.Name] = ii._
else
frec = rec
try metadata.pmid ?= rec.Id[0]
try metadata.pmid ?= rec.id
try metadata.title ?= frec.Title
try metadata.issn ?= frec.ISSN
try metadata.essn ?= frec.ESSN
try metadata.doi ?= frec.DOI
try metadata.journal ?= frec.FullJournalName
try metadata.journal_short ?= frec.Source
try metadata.volume ?= frec.Volume
try metadata.issue ?= frec.Issue
try metadata.page ?= frec.Pages #like 13-29 how to handle this
try metadata.year ?= frec[if frec.PubDate then 'PubDate' else 'EPubDate'].split(' ')[0]
try
p = frec[if frec.PubDate then 'PubDate' else 'EPubDate'].split ' '
metadata.published ?= p[0] + '-' + (['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf(p[1].toLowerCase()) + 1) + '-' + (if p.length is 3 then p[2] else '01')
if frec.AuthorList?
metadata.author ?= []
for a in frec.AuthorList
try
a.family = a.Author.split(' ')[0]
a.given = a.Author.replace(a.family + ' ','')
a.name = a.given + ' ' + a.family
metadata.author.push a
if frec.ArticleIds? and not metadata.pmcid?
for ai in frec.ArticleIds
if ai.pmc # pmcid or pmc? replace PMC in the value? it will be present
metadata.pmcid ?= ai.pmc
break
else if rec.PubmedArticle?
rec = rec.PubmedArticle
mc = rec.MedlineCitation[0]
try metadata.pmid ?= mc.PMID[0]._
try metadata.title ?= mc.Article[0].ArticleTitle[0]
try metadata.issn ?= mc.Article[0].Journal[0].ISSN[0]._
try metadata.journal ?= mc.Article[0].Journal[0].Title[0]
try metadata.journal_short ?= mc.Article[0].Journal[0].ISOAbbreviation[0]
try
pd = mc.Article[0].Journal[0].JournalIssue[0].PubDate[0]
try metadata.year ?= pd.Year[0]
try metadata.published ?= pd.Year[0] + '-' + (if pd.Month then (['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf(pd.Month[0].toLowerCase()) + 1) else '01') + '-' + (if pd.Day then pd.Day[0] else '01')
try
metadata.author ?= []
for ar in mc.Article[0].AuthorList[0].Author
a = {}
a.family = ar.LastName[0]
a.given = ar.ForeName[0]
a.name = if a.Author then a.Author else a.given + ' ' + a.family
try a.affiliation = ar.AffiliationInfo[0].Affiliation[0]
if a.affiliation?
a.affiliation = a.affiliation[0] if _.isArray a.affiliation
a.affiliation = {name: a.affiliation} if typeof a.affiliation is 'string'
metadata.author.push a
try
for pid in rec.PubmedData[0].ArticleIdList[0].ArticleId
if pid.$.IdType is 'doi'
metadata.doi ?= pid._
break
try
metadata.reference ?= []
for ref in rec.PubmedData[0].ReferenceList[0].Reference
rc = ref.Citation[0]
rf = {}
rf.doi = rc.split('doi.org/')[1].trim() if rc.indexOf('doi.org/') isnt -1
try
rf.author = []
rf.author.push({name: an}) for an in rc.split('. ')[0].split(', ')
try rf.title = rc.split('. ')[1].split('?')[0].trim()
try rf.journal = rc.replace(/\?/g,'.').split('. ')[2].trim()
try
rf.url = 'http' + rc.split('http')[1].split(' ')[0]
delete rf.url if rf.url.indexOf('doi.org') isnt -1
metadata.reference.push(rf) if not _.isEmpty rf
try metadata.pdf ?= rec.pdf
try metadata.url ?= rec.url
try metadata.open ?= rec.open
try metadata.redirect ?= rec.redirect
return metadata
API.use.pubmed.status = () ->
try
return HTTP.call('GET', 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi', {timeout: API.settings.use?.europepmc?.timeout ? API.settings.use?._timeout ? 4000}).statusCode is 200
catch err
return err.toString()
API.use.pubmed.test = (verbose) ->
console.log('Starting pubmed test') if API.settings.dev
result = {passed:[],failed:[]}
tests = [
#() -> the below example is no longer accurate to the output of the function
# result.record = API.use.pubmed.pmid '23908565'
# delete result.record.EPubDate # don't know what happens to these, so just remove them...
# delete result.record.ELocationID
# return _.isEqual result.record, API.use.pubmed.test._examples.record
() ->
result.aheadofprint = API.use.pubmed.aheadofprint '23908565'
return result.aheadofprint is false # TODO add one that is true
]
(if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests
result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0
result = {passed:result.passed} if result.failed.length is 0 and not verbose
console.log('Ending pubmed test') if API.settings.dev
return result
API.use.pubmed.test._examples = {
record: {
"id": "23908565",
"PubDate": "2012 Dec",
"Source": "Hist Human Sci",
"AuthorList": [
{
"Author": "PI:NAME:<NAME>END_PI"
}
],
"LastAuthor": "PI:NAME:<NAME>END_PI",
"Title": "The pursuit of happiness: The social and scientific origins of Hans Selye's natural philosophy of life.",
"Volume": "25",
"Issue": "5",
"Pages": "13-29",
"LangList": [
{
"Lang": "English"
}
],
"NlmUniqueID": "100967737",
"ISSN": "0952-6951",
"ESSN": "1461-720X",
"PubTypeList": [
{
"PubType": "Journal Article"
}
],
"RecordStatus": "PubMed",
"PubStatus": "ppublish",
"ArticleIds": [
{
"pubmed": "23908565"
},
{
"doi": "10.1177/0952695112468526"
},
{
"pii": "10.1177_0952695112468526"
},
{
"pmc": "PMC3724273"
},
{
"rid": "23908565"
},
{
"eid": "23908565"
},
{
"pmcid": "pmc-id: PMC3724273;"
}
],
"DOI": "10.1177/0952695112468526",
"History": [
{
"entrez": "2013/08/03 06:00"
},
{
"pubmed": "2013/08/03 06:00"
},
{
"medline": "2013/08/03 06:00"
}
],
"References": [],
"HasAbstract": "1",
"PmcRefCount": "0",
"FullJournalName": "History of the human sciences",
"SO": "2012 Dec;25(5):13-29"
}
} |
[
{
"context": "d55224b15ff07ef'\n type: 'bulldozer'\n name: 'willy'\n response = [machine]\n res.send 200, response\n",
"end": 493,
"score": 0.9985742568969727,
"start": 488,
"tag": "NAME",
"value": "willy"
}
] | test/server.coffee | stekycz/cucumber-4-api-blueprint | 3 | require 'coffee-errors'
express = require 'express'
PORT = '3333'
app = express()
app.post '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
res.setHeader 'Content-Encoding', 'none'
response =
message: "Accepted"
res.send 202, response
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
res.setHeader 'Content-Encoding', 'none'
machine =
_id: '52341870ed55224b15ff07ef'
type: 'bulldozer'
name: 'willy'
response = [machine]
res.send 200, response
server = app.listen PORT
| 32649 | require 'coffee-errors'
express = require 'express'
PORT = '3333'
app = express()
app.post '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
res.setHeader 'Content-Encoding', 'none'
response =
message: "Accepted"
res.send 202, response
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
res.setHeader 'Content-Encoding', 'none'
machine =
_id: '52341870ed55224b15ff07ef'
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.send 200, response
server = app.listen PORT
| true | require 'coffee-errors'
express = require 'express'
PORT = '3333'
app = express()
app.post '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
res.setHeader 'Content-Encoding', 'none'
response =
message: "Accepted"
res.send 202, response
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
res.setHeader 'Content-Encoding', 'none'
machine =
_id: '52341870ed55224b15ff07ef'
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.send 200, response
server = app.listen PORT
|
[
{
"context": "###\n * grunt-statistiks\n * https://github.com/leny/grunt-statistiks\n *\n * Copyright (c) 2014 Leny\n *",
"end": 50,
"score": 0.9992215633392334,
"start": 46,
"tag": "USERNAME",
"value": "leny"
},
{
"context": "com/leny/grunt-statistiks\n *\n * Copyright (c) 2014 Leny\n * Licensed under the MIT license.\n###\n\n\"use stri",
"end": 97,
"score": 0.998692512512207,
"start": 93,
"tag": "NAME",
"value": "Leny"
}
] | src/statistiks.coffee | leny/grunt-statistiks | 0 | ###
* grunt-statistiks
* https://github.com/leny/grunt-statistiks
*
* Copyright (c) 2014 Leny
* Licensed under the MIT license.
###
"use strict"
chalk = require "chalk"
table = require "text-table"
( spinner = require "simple-spinner" )
.change_sequence [
"◓"
"◑"
"◒"
"◐"
]
module.exports = ( grunt ) ->
statistiksTask = ->
spinner.start 50
oOptions = @options
countEmptyLines: no
trimLines: yes
countFolders: no
iFoldersCount = 0
iFilesCount = 0
iLinesCount = 0
iCharsCount = 0
( if @filesSrc?.length then @filesSrc else grunt.file.expand [ "**", "!node_modules/**" ] )
.forEach ( sFilePath ) ->
return unless grunt.file.exists sFilePath
if oOptions.countFolders and grunt.file.isDir sFilePath
++iFoldersCount
return
if grunt.file.isFile sFilePath
++iFilesCount
grunt.file
.read sFilePath
.split /\r*\n/
.map ( sLine ) ->
return if oOptions.countEmptyLines is no and sLine.trim().length is 0
++iLinesCount
iCharsCount += if oOptions.trimLines then sLine.trim().length else sLine.length
spinner.stop()
grunt.log.write "#{ iFoldersCount } folder#{ if iFoldersCount > 1 then 's' else '' }, " if oOptions.countFolders
grunt.log.write "#{ iFilesCount } file#{ if iFilesCount > 1 then 's' else '' }, "
grunt.log.write "#{ iLinesCount } line#{ if iLinesCount > 1 then 's' else '' }, "
grunt.log.write "#{ iCharsCount } character#{ if iCharsCount > 1 then 's' else '' }"
if grunt.config.data.statistiks
grunt.registerMultiTask "statistiks", "Get statistics about files in project (lines, characters, …)", statistiksTask
else
grunt.registerTask "statistiks", "Get statistics about files in project (lines, characters, …)", statistiksTask
| 25202 | ###
* grunt-statistiks
* https://github.com/leny/grunt-statistiks
*
* Copyright (c) 2014 <NAME>
* Licensed under the MIT license.
###
"use strict"
chalk = require "chalk"
table = require "text-table"
( spinner = require "simple-spinner" )
.change_sequence [
"◓"
"◑"
"◒"
"◐"
]
module.exports = ( grunt ) ->
statistiksTask = ->
spinner.start 50
oOptions = @options
countEmptyLines: no
trimLines: yes
countFolders: no
iFoldersCount = 0
iFilesCount = 0
iLinesCount = 0
iCharsCount = 0
( if @filesSrc?.length then @filesSrc else grunt.file.expand [ "**", "!node_modules/**" ] )
.forEach ( sFilePath ) ->
return unless grunt.file.exists sFilePath
if oOptions.countFolders and grunt.file.isDir sFilePath
++iFoldersCount
return
if grunt.file.isFile sFilePath
++iFilesCount
grunt.file
.read sFilePath
.split /\r*\n/
.map ( sLine ) ->
return if oOptions.countEmptyLines is no and sLine.trim().length is 0
++iLinesCount
iCharsCount += if oOptions.trimLines then sLine.trim().length else sLine.length
spinner.stop()
grunt.log.write "#{ iFoldersCount } folder#{ if iFoldersCount > 1 then 's' else '' }, " if oOptions.countFolders
grunt.log.write "#{ iFilesCount } file#{ if iFilesCount > 1 then 's' else '' }, "
grunt.log.write "#{ iLinesCount } line#{ if iLinesCount > 1 then 's' else '' }, "
grunt.log.write "#{ iCharsCount } character#{ if iCharsCount > 1 then 's' else '' }"
if grunt.config.data.statistiks
grunt.registerMultiTask "statistiks", "Get statistics about files in project (lines, characters, …)", statistiksTask
else
grunt.registerTask "statistiks", "Get statistics about files in project (lines, characters, …)", statistiksTask
| true | ###
* grunt-statistiks
* https://github.com/leny/grunt-statistiks
*
* Copyright (c) 2014 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
"use strict"
chalk = require "chalk"
table = require "text-table"
( spinner = require "simple-spinner" )
.change_sequence [
"◓"
"◑"
"◒"
"◐"
]
module.exports = ( grunt ) ->
statistiksTask = ->
spinner.start 50
oOptions = @options
countEmptyLines: no
trimLines: yes
countFolders: no
iFoldersCount = 0
iFilesCount = 0
iLinesCount = 0
iCharsCount = 0
( if @filesSrc?.length then @filesSrc else grunt.file.expand [ "**", "!node_modules/**" ] )
.forEach ( sFilePath ) ->
return unless grunt.file.exists sFilePath
if oOptions.countFolders and grunt.file.isDir sFilePath
++iFoldersCount
return
if grunt.file.isFile sFilePath
++iFilesCount
grunt.file
.read sFilePath
.split /\r*\n/
.map ( sLine ) ->
return if oOptions.countEmptyLines is no and sLine.trim().length is 0
++iLinesCount
iCharsCount += if oOptions.trimLines then sLine.trim().length else sLine.length
spinner.stop()
grunt.log.write "#{ iFoldersCount } folder#{ if iFoldersCount > 1 then 's' else '' }, " if oOptions.countFolders
grunt.log.write "#{ iFilesCount } file#{ if iFilesCount > 1 then 's' else '' }, "
grunt.log.write "#{ iLinesCount } line#{ if iLinesCount > 1 then 's' else '' }, "
grunt.log.write "#{ iCharsCount } character#{ if iCharsCount > 1 then 's' else '' }"
if grunt.config.data.statistiks
grunt.registerMultiTask "statistiks", "Get statistics about files in project (lines, characters, …)", statistiksTask
else
grunt.registerTask "statistiks", "Get statistics about files in project (lines, characters, …)", statistiksTask
|
[
{
"context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#",
"end": 166,
"score": 0.9837273955345154,
"start": 152,
"tag": "USERNAME",
"value": "programmfabrik"
},
{
"context": "\t@__reader = new FileReader()\n\n\t\tfor key in [\n\t\t\t\"loadStart\"\n\t\t\t\"progress\"\n\t\t\t\"abort\"\n\t\t\t\"error\"\n\t\t\t\"load\"\n\t\t",
"end": 511,
"score": 0.9728743433952332,
"start": 502,
"tag": "KEY",
"value": "loadStart"
},
{
"context": "w FileReader()\n\n\t\tfor key in [\n\t\t\t\"loadStart\"\n\t\t\t\"progress\"\n\t\t\t\"abort\"\n\t\t\t\"error\"\n\t\t\t\"load\"\n\t\t\t\"loadend\"\n\t\t]",
"end": 525,
"score": 0.8573233485221863,
"start": 517,
"tag": "KEY",
"value": "progress"
},
{
"context": "\t\t\t\"progress\"\n\t\t\t\"abort\"\n\t\t\t\"error\"\n\t\t\t\"load\"\n\t\t\t\"loadend\"\n\t\t]\n\t\t\tdo (key) =>\n\t\t\t\t@__reader.addEventListene",
"end": 570,
"score": 0.8415589332580566,
"start": 563,
"tag": "KEY",
"value": "loadend"
}
] | src/elements/FileUpload/FileReaderFile.coffee | programmfabrik/coffeescript-ui | 10 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
class CUI.FileReaderFile extends CUI.FileUploadFile
initOpts: ->
super()
@addOpts
format:
mandatory: true
default: "Text"
check: ["ArrayBuffer", "Text"]
upload: (file) ->
# console.debug "upload file", file
@__reader = new FileReader()
for key in [
"loadStart"
"progress"
"abort"
"error"
"load"
"loadend"
]
do (key) =>
@__reader.addEventListener key.toLowerCase(), (ev) =>
# console.debug "caught event", key, @__reader
@["__event_"+key](ev)
switch @_format
when "Text"
@__reader.readAsText(@_file)
when "ArrayBuffer"
@__reader.readAsArrayBuffer(@_file)
return
getResult: ->
@__reader.result
__event_loadStart: ->
@__progress.status = "STARTED"
@__progress.percent = 0
@__dfr.notify(@)
return
__event_progress: (ev) ->
total = ev.total
loaded = ev.loaded
if ev.lengthComputable
percent = Math.floor(ev.loaded / ev.total * 100)
else
percent = -1
if loaded == total
@__progress.status = "COMPLETED"
else
@__progress.status = "PROGRESS"
@__progress.loaded = loaded
@__progress.total = total
@__progress.percent = percent
# console.debug @, @getProgress()
@__dfr.notify(@)
return
__event_abort: ->
__event_error: ->
__event_load: ->
__event_loadend: ->
# console.debug @_file.name, "result:", @__reader.result.length, @__reader.result.byteLength
@__progress.data = @__reader.result
@__progress.status = "DONE"
@__upload = null
@__dfr.resolve(@)
abort: ->
@__reader.abort()
| 32989 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
class CUI.FileReaderFile extends CUI.FileUploadFile
initOpts: ->
super()
@addOpts
format:
mandatory: true
default: "Text"
check: ["ArrayBuffer", "Text"]
upload: (file) ->
# console.debug "upload file", file
@__reader = new FileReader()
for key in [
"<KEY>"
"<KEY>"
"abort"
"error"
"load"
"<KEY>"
]
do (key) =>
@__reader.addEventListener key.toLowerCase(), (ev) =>
# console.debug "caught event", key, @__reader
@["__event_"+key](ev)
switch @_format
when "Text"
@__reader.readAsText(@_file)
when "ArrayBuffer"
@__reader.readAsArrayBuffer(@_file)
return
getResult: ->
@__reader.result
__event_loadStart: ->
@__progress.status = "STARTED"
@__progress.percent = 0
@__dfr.notify(@)
return
__event_progress: (ev) ->
total = ev.total
loaded = ev.loaded
if ev.lengthComputable
percent = Math.floor(ev.loaded / ev.total * 100)
else
percent = -1
if loaded == total
@__progress.status = "COMPLETED"
else
@__progress.status = "PROGRESS"
@__progress.loaded = loaded
@__progress.total = total
@__progress.percent = percent
# console.debug @, @getProgress()
@__dfr.notify(@)
return
__event_abort: ->
__event_error: ->
__event_load: ->
__event_loadend: ->
# console.debug @_file.name, "result:", @__reader.result.length, @__reader.result.byteLength
@__progress.data = @__reader.result
@__progress.status = "DONE"
@__upload = null
@__dfr.resolve(@)
abort: ->
@__reader.abort()
| true | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
class CUI.FileReaderFile extends CUI.FileUploadFile
initOpts: ->
super()
@addOpts
format:
mandatory: true
default: "Text"
check: ["ArrayBuffer", "Text"]
upload: (file) ->
# console.debug "upload file", file
@__reader = new FileReader()
for key in [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"abort"
"error"
"load"
"PI:KEY:<KEY>END_PI"
]
do (key) =>
@__reader.addEventListener key.toLowerCase(), (ev) =>
# console.debug "caught event", key, @__reader
@["__event_"+key](ev)
switch @_format
when "Text"
@__reader.readAsText(@_file)
when "ArrayBuffer"
@__reader.readAsArrayBuffer(@_file)
return
getResult: ->
@__reader.result
__event_loadStart: ->
@__progress.status = "STARTED"
@__progress.percent = 0
@__dfr.notify(@)
return
__event_progress: (ev) ->
total = ev.total
loaded = ev.loaded
if ev.lengthComputable
percent = Math.floor(ev.loaded / ev.total * 100)
else
percent = -1
if loaded == total
@__progress.status = "COMPLETED"
else
@__progress.status = "PROGRESS"
@__progress.loaded = loaded
@__progress.total = total
@__progress.percent = percent
# console.debug @, @getProgress()
@__dfr.notify(@)
return
__event_abort: ->
__event_error: ->
__event_load: ->
__event_loadend: ->
# console.debug @_file.name, "result:", @__reader.result.length, @__reader.result.byteLength
@__progress.data = @__reader.result
@__progress.status = "DONE"
@__upload = null
@__dfr.resolve(@)
abort: ->
@__reader.abort()
|
[
{
"context": "T.DB.spillDocToLocalStorage = (db, doc) ->\n key = \"/#{db}/#{doc._id}\"\n\n # most docs don't have a merge functi",
"end": 4543,
"score": 0.9877891540527344,
"start": 4533,
"tag": "KEY",
"value": "\"/#{db}/#{"
},
{
"context": "oLocalStorage = (db, doc) ->\n key = \"/#{db}/#{doc._id}\"\n\n # most docs don't have a merge function, so sa",
"end": 4552,
"score": 0.859041154384613,
"start": 4548,
"tag": "KEY",
"value": "id}\""
}
] | core/js/tabcat/db.coffee | davidmarin/tabcat | 1 | ###
Copyright (c) 2013, Regents of the University of California
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
# a thin layer over CouchDB that handles auto-merging conflicting documents
# and spilling to localStorage on network errors.
@TabCAT ?= {}
TabCAT.DB = {}
# so we don't have to type window.localStorage in functions
localStorage = @localStorage
# Promise (can't fail): upload a document to CouchDB, auto-resolving conflicts,
# and spilling to localStorage on any error.
#
# This will update the _rev field of doc, or, if we spill it to
# localStorage, _rev will be deleted.
#
# If options.expectConflict is true, we always try to GET the old version of
# the doc before we PUT the new one. This is just an optimization.
#
# options:
# - now: timeout is relative to this time (set this to $.now())
# - timeout: timeout in milliseconds
TabCAT.DB.putDoc = (db, doc, options) ->
# force timeout to be relative to now
if options?.timeout? and not options.now?
options = _.extend(options, now: $.now())
# don't even try if the user isn't authenticated; it'll cause 401s.
# also don't bother if we're offline (this is an optimization)
if not TabCAT.User.isAuthenticated() or navigator.onLine is false
TabCAT.DB.spillDocToLocalStorage(db, doc)
$.Deferred().resolve()
else
putDocIntoCouchDB(db, doc, options).then(
null,
->
TabCAT.DB.spillDocToLocalStorage(db, doc)
$.Deferred().resolve()
)
# Promise: putDoc() minus handling of offline/network errors. This can fail.
putDocIntoCouchDB = (db, doc, options) ->
if options?.expectConflict
resolvePutConflict(db, doc, options)
else
TabCAT.Couch.putDoc(db, doc, _.pick(options ? {}, 'now', 'timeout')).then(
null,
(xhr) -> switch xhr.status
when 409
resolvePutConflict(db, doc, options)
else
xhr
)
# helper for TabCAT.DB.forcePutDoc()
resolvePutConflict = (db, doc, options) ->
# make sure to putDoc() first when retrying
if options?
options = _.omit(options, 'expectConflict')
TabCAT.Couch.getDoc(
db, doc._id, _.pick(options ? {}, 'now', 'timeout')).then(
((oldDoc) ->
# resolve conflict
TabCAT.DB.merge(doc, oldDoc)
doc._rev = oldDoc._rev
# recursively call putDoc(), in the unlikely event
# that the old doc was changed since calling TabCAT.Couch.getDoc()
TabCAT.DB.putDoc(db, doc, options)
),
(xhr) -> switch xhr.status
# catch new docs with bad _rev field (and very rare race conditions)
when 404
if doc._rev?
delete doc._rev
TabCAT.DB.putDoc(db, doc, options)
else
xhr
)
# Merge oldDoc into doc, inferring the method to use from doc.
#
# Currently, we only handle docs with type 'patient'.
TabCAT.DB.merge = (doc, oldDoc) ->
merge = pickMergeFunc(doc)
if merge?
merge(doc, oldDoc)
# helper for TabCAT.Couch.merge() and TabCAT.DB.putDocOffline
pickMergeFunc = (doc) ->
switch doc.type
when 'patient'
TabCAT.Patient.merge
# Put a document into localStorage for safe-keeping, possibly
# merging with a previously stored version of the document.
#
# If doc._rev is set, delete it; we don't track revisions in localStorage.
TabCAT.DB.spillDocToLocalStorage = (db, doc) ->
key = "/#{db}/#{doc._id}"
# most docs don't have a merge function, so save decoding the JSON
# if there's no merging to do
if localStorage[key]?
merge = pickMergeFunc(doc)
if merge?
oldDoc = try JSON.parse(localStorage[key])
if oldDoc?
merge(doc, oldDoc)
if doc._rev?
delete doc._rev
localStorage[key] = JSON.stringify(doc)
# keep track of this as a doc the current user can vouch for
TabCAT.User.addDocSpilled(key)
# activate sync callback if it's not already running
TabCAT.DB.startSpilledDocSync()
return
# are we attempting to sync spilled docs?
spilledDocsSyncIsActive = false
# are we actually succeeding in syncing spilled docs?
syncingSpilledDocs = false
# are we currently syncing spilled docs? (for status bar)
TabCAT.DB.syncingSpilledDocs = ->
syncingSpilledDocs
# are there any spilled docs left to sync?
TabCAT.DB.spilledDocsRemain = ->
!!getNextDocPathToSync()
# Kick off syncing of spilled docs. You can pretty much call this anywhere
# (e.g. on page load)
TabCAT.DB.startSpilledDocSync = ->
if not spilledDocSyncIsActive
spilledDocSyncIsActive = true
syncSpilledDocs()
return
SYNC_SPILLED_DOCS_WAIT_TIME = 5000
syncSpilledDocs = ->
# if we're not really logged in, there's nothing to do
if not TabCAT.User.isAuthenticated()
spilledDocSyncIsActive = false
return
# if offline, wait until we're back online
if navigator.onLine is false
# not going to use 'online' event; it doesn't seem to be
# well synced with navigator.onLine
syncingSpilledDocs = false
callSyncSpilledDocsAgainIn(SYNC_SPILLED_DOCS_WAIT_TIME)
return
# pick a document to upload
# start with docs spilled by this user
docPath = TabCAT.User.getNextDocSpilled()
vouchForDoc = !!docPath
# if there aren't any, grab any doc
if not docPath?
docPath = getNextDocPathToSync()
if not docPath?
# no more docs; we are done!
localStorage.removeItem('dbSpillSyncLastDoc')
spilledDocSyncIsActive = false
syncingSpilledDocs = false
return
localStorage.dbSpillSyncLastDoc = docPath
doc = try JSON.parse(localStorage[docPath])
[__, db, docId] = docPath.split('/')
# whoops, something wrong with this doc, remove it
if not (doc? and db? and doc._id is docId)
localStorage.removeItem(docPath)
TabCAT.User.removeDocSpilled(docPath)
callSyncSpilledDocsAgainIn(0)
return
# respect security policy
user = TabCAT.User.get()
if doc.user? and not (vouchForDoc and doc.user is user)
if doc.user.slice(-1) isnt '?'
doc.user += '?'
doc.uploadedBy = user
# try syncing the doc
putDocIntoCouchDB(db, doc).then(
(->
# success!
localStorage.removeItem(docPath)
TabCAT.User.removeDocSpilled(docPath)
syncingSpilledDocs = true
callSyncSpilledDocsAgainIn(0)
),
(xhr) ->
# if it's not a network error, demote to a leftover doc
if xhr.status isnt 0
TabCAT.User.removeDocSpilled(docPath)
# if there's an auth issue, user will need to log in again
# befor we can make any progress
if xhr.status is 401
spilledDocSyncIsActive = false
syncingSpilledDocs = false
return
syncingSpilledDocs = false
callSyncSpilledDocsAgainIn(SYNC_SPILLED_DOCS_WAIT_TIME)
)
return
# get the next doc to sync. If you want to prioritize docs spilled by
# this user, use TabCAT.User.getNextDocSpilled() first.
getNextDocPathToSync = ->
docPaths = (path for path in _.keys(localStorage) \
when path[0] is '/').sort()
if _.isEmpty(docPaths)
return null
docPath = docPaths[0]
# this allows us to skip over documents and try them later
if localStorage.dbSpillSyncLastDoc
index = _.sortedIndex(docPaths, localStorage.dbSpillSyncLastDoc)
if docPaths[index] = localStorage.dbSpillSyncLastDoc
index += 1
if index < docPaths.length
docPath = docPaths[index]
return docPath
# hopefully this can keep us from exceeding max recursion depth
callSyncSpilledDocsAgainIn = (milliseconds) ->
TabCAT.UI.wait(milliseconds).then(syncSpilledDocs)
return
# Estimate % of local storage used. Probably right for the browsers
# we care about!
TabCAT.DB.percentOfLocalStorageUsed = ->
return 100 * charsInLocalStorage() / maxCharsInLocalStorage()
# number of chars currently stored in localStorage
charsInLocalStorage = ->
numChars = 0
for own key, value of localStorage
numChars += key.length + value.length
return numChars
# Loosely based on:
# http://dev-test.nemikor.com/web-storage/support-test/.
# Could be improved
maxCharsInLocalStorage = ->
ua = navigator.userAgent
if ua.indexOf('Firefox') isnt -1
return 4.98 * 1024 * 1024
else if ua.indexOf('IE') isnt -1
return 4.75 * 1024 * 1024
else
return 2.49 * 1024 * 1024
| 176025 | ###
Copyright (c) 2013, Regents of the University of California
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
# a thin layer over CouchDB that handles auto-merging conflicting documents
# and spilling to localStorage on network errors.
@TabCAT ?= {}
TabCAT.DB = {}
# so we don't have to type window.localStorage in functions
localStorage = @localStorage
# Promise (can't fail): upload a document to CouchDB, auto-resolving conflicts,
# and spilling to localStorage on any error.
#
# This will update the _rev field of doc, or, if we spill it to
# localStorage, _rev will be deleted.
#
# If options.expectConflict is true, we always try to GET the old version of
# the doc before we PUT the new one. This is just an optimization.
#
# options:
# - now: timeout is relative to this time (set this to $.now())
# - timeout: timeout in milliseconds
TabCAT.DB.putDoc = (db, doc, options) ->
# force timeout to be relative to now
if options?.timeout? and not options.now?
options = _.extend(options, now: $.now())
# don't even try if the user isn't authenticated; it'll cause 401s.
# also don't bother if we're offline (this is an optimization)
if not TabCAT.User.isAuthenticated() or navigator.onLine is false
TabCAT.DB.spillDocToLocalStorage(db, doc)
$.Deferred().resolve()
else
putDocIntoCouchDB(db, doc, options).then(
null,
->
TabCAT.DB.spillDocToLocalStorage(db, doc)
$.Deferred().resolve()
)
# Promise: putDoc() minus handling of offline/network errors. This can fail.
putDocIntoCouchDB = (db, doc, options) ->
if options?.expectConflict
resolvePutConflict(db, doc, options)
else
TabCAT.Couch.putDoc(db, doc, _.pick(options ? {}, 'now', 'timeout')).then(
null,
(xhr) -> switch xhr.status
when 409
resolvePutConflict(db, doc, options)
else
xhr
)
# helper for TabCAT.DB.forcePutDoc()
resolvePutConflict = (db, doc, options) ->
# make sure to putDoc() first when retrying
if options?
options = _.omit(options, 'expectConflict')
TabCAT.Couch.getDoc(
db, doc._id, _.pick(options ? {}, 'now', 'timeout')).then(
((oldDoc) ->
# resolve conflict
TabCAT.DB.merge(doc, oldDoc)
doc._rev = oldDoc._rev
# recursively call putDoc(), in the unlikely event
# that the old doc was changed since calling TabCAT.Couch.getDoc()
TabCAT.DB.putDoc(db, doc, options)
),
(xhr) -> switch xhr.status
# catch new docs with bad _rev field (and very rare race conditions)
when 404
if doc._rev?
delete doc._rev
TabCAT.DB.putDoc(db, doc, options)
else
xhr
)
# Merge oldDoc into doc, inferring the method to use from doc.
#
# Currently, we only handle docs with type 'patient'.
TabCAT.DB.merge = (doc, oldDoc) ->
merge = pickMergeFunc(doc)
if merge?
merge(doc, oldDoc)
# helper for TabCAT.Couch.merge() and TabCAT.DB.putDocOffline
pickMergeFunc = (doc) ->
switch doc.type
when 'patient'
TabCAT.Patient.merge
# Put a document into localStorage for safe-keeping, possibly
# merging with a previously stored version of the document.
#
# If doc._rev is set, delete it; we don't track revisions in localStorage.
TabCAT.DB.spillDocToLocalStorage = (db, doc) ->
key = <KEY>doc._<KEY>
# most docs don't have a merge function, so save decoding the JSON
# if there's no merging to do
if localStorage[key]?
merge = pickMergeFunc(doc)
if merge?
oldDoc = try JSON.parse(localStorage[key])
if oldDoc?
merge(doc, oldDoc)
if doc._rev?
delete doc._rev
localStorage[key] = JSON.stringify(doc)
# keep track of this as a doc the current user can vouch for
TabCAT.User.addDocSpilled(key)
# activate sync callback if it's not already running
TabCAT.DB.startSpilledDocSync()
return
# are we attempting to sync spilled docs?
spilledDocsSyncIsActive = false
# are we actually succeeding in syncing spilled docs?
syncingSpilledDocs = false
# are we currently syncing spilled docs? (for status bar)
TabCAT.DB.syncingSpilledDocs = ->
syncingSpilledDocs
# are there any spilled docs left to sync?
TabCAT.DB.spilledDocsRemain = ->
!!getNextDocPathToSync()
# Kick off syncing of spilled docs. You can pretty much call this anywhere
# (e.g. on page load)
TabCAT.DB.startSpilledDocSync = ->
if not spilledDocSyncIsActive
spilledDocSyncIsActive = true
syncSpilledDocs()
return
SYNC_SPILLED_DOCS_WAIT_TIME = 5000
syncSpilledDocs = ->
# if we're not really logged in, there's nothing to do
if not TabCAT.User.isAuthenticated()
spilledDocSyncIsActive = false
return
# if offline, wait until we're back online
if navigator.onLine is false
# not going to use 'online' event; it doesn't seem to be
# well synced with navigator.onLine
syncingSpilledDocs = false
callSyncSpilledDocsAgainIn(SYNC_SPILLED_DOCS_WAIT_TIME)
return
# pick a document to upload
# start with docs spilled by this user
docPath = TabCAT.User.getNextDocSpilled()
vouchForDoc = !!docPath
# if there aren't any, grab any doc
if not docPath?
docPath = getNextDocPathToSync()
if not docPath?
# no more docs; we are done!
localStorage.removeItem('dbSpillSyncLastDoc')
spilledDocSyncIsActive = false
syncingSpilledDocs = false
return
localStorage.dbSpillSyncLastDoc = docPath
doc = try JSON.parse(localStorage[docPath])
[__, db, docId] = docPath.split('/')
# whoops, something wrong with this doc, remove it
if not (doc? and db? and doc._id is docId)
localStorage.removeItem(docPath)
TabCAT.User.removeDocSpilled(docPath)
callSyncSpilledDocsAgainIn(0)
return
# respect security policy
user = TabCAT.User.get()
if doc.user? and not (vouchForDoc and doc.user is user)
if doc.user.slice(-1) isnt '?'
doc.user += '?'
doc.uploadedBy = user
# try syncing the doc
putDocIntoCouchDB(db, doc).then(
(->
# success!
localStorage.removeItem(docPath)
TabCAT.User.removeDocSpilled(docPath)
syncingSpilledDocs = true
callSyncSpilledDocsAgainIn(0)
),
(xhr) ->
# if it's not a network error, demote to a leftover doc
if xhr.status isnt 0
TabCAT.User.removeDocSpilled(docPath)
# if there's an auth issue, user will need to log in again
# befor we can make any progress
if xhr.status is 401
spilledDocSyncIsActive = false
syncingSpilledDocs = false
return
syncingSpilledDocs = false
callSyncSpilledDocsAgainIn(SYNC_SPILLED_DOCS_WAIT_TIME)
)
return
# get the next doc to sync. If you want to prioritize docs spilled by
# this user, use TabCAT.User.getNextDocSpilled() first.
getNextDocPathToSync = ->
docPaths = (path for path in _.keys(localStorage) \
when path[0] is '/').sort()
if _.isEmpty(docPaths)
return null
docPath = docPaths[0]
# this allows us to skip over documents and try them later
if localStorage.dbSpillSyncLastDoc
index = _.sortedIndex(docPaths, localStorage.dbSpillSyncLastDoc)
if docPaths[index] = localStorage.dbSpillSyncLastDoc
index += 1
if index < docPaths.length
docPath = docPaths[index]
return docPath
# hopefully this can keep us from exceeding max recursion depth
callSyncSpilledDocsAgainIn = (milliseconds) ->
TabCAT.UI.wait(milliseconds).then(syncSpilledDocs)
return
# Estimate % of local storage used. Probably right for the browsers
# we care about!
TabCAT.DB.percentOfLocalStorageUsed = ->
return 100 * charsInLocalStorage() / maxCharsInLocalStorage()
# number of chars currently stored in localStorage
charsInLocalStorage = ->
numChars = 0
for own key, value of localStorage
numChars += key.length + value.length
return numChars
# Loosely based on:
# http://dev-test.nemikor.com/web-storage/support-test/.
# Could be improved
maxCharsInLocalStorage = ->
ua = navigator.userAgent
if ua.indexOf('Firefox') isnt -1
return 4.98 * 1024 * 1024
else if ua.indexOf('IE') isnt -1
return 4.75 * 1024 * 1024
else
return 2.49 * 1024 * 1024
| true | ###
Copyright (c) 2013, Regents of the University of California
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
# a thin layer over CouchDB that handles auto-merging conflicting documents
# and spilling to localStorage on network errors.
@TabCAT ?= {}
TabCAT.DB = {}
# so we don't have to type window.localStorage in functions
localStorage = @localStorage
# Promise (can't fail): upload a document to CouchDB, auto-resolving conflicts,
# and spilling to localStorage on any error.
#
# This will update the _rev field of doc, or, if we spill it to
# localStorage, _rev will be deleted.
#
# If options.expectConflict is true, we always try to GET the old version of
# the doc before we PUT the new one. This is just an optimization.
#
# options:
# - now: timeout is relative to this time (set this to $.now())
# - timeout: timeout in milliseconds
TabCAT.DB.putDoc = (db, doc, options) ->
# force timeout to be relative to now
if options?.timeout? and not options.now?
options = _.extend(options, now: $.now())
# don't even try if the user isn't authenticated; it'll cause 401s.
# also don't bother if we're offline (this is an optimization)
if not TabCAT.User.isAuthenticated() or navigator.onLine is false
TabCAT.DB.spillDocToLocalStorage(db, doc)
$.Deferred().resolve()
else
putDocIntoCouchDB(db, doc, options).then(
null,
->
TabCAT.DB.spillDocToLocalStorage(db, doc)
$.Deferred().resolve()
)
# Promise: putDoc() minus handling of offline/network errors. This can fail.
putDocIntoCouchDB = (db, doc, options) ->
if options?.expectConflict
resolvePutConflict(db, doc, options)
else
TabCAT.Couch.putDoc(db, doc, _.pick(options ? {}, 'now', 'timeout')).then(
null,
(xhr) -> switch xhr.status
when 409
resolvePutConflict(db, doc, options)
else
xhr
)
# helper for TabCAT.DB.forcePutDoc()
resolvePutConflict = (db, doc, options) ->
# make sure to putDoc() first when retrying
if options?
options = _.omit(options, 'expectConflict')
TabCAT.Couch.getDoc(
db, doc._id, _.pick(options ? {}, 'now', 'timeout')).then(
((oldDoc) ->
# resolve conflict
TabCAT.DB.merge(doc, oldDoc)
doc._rev = oldDoc._rev
# recursively call putDoc(), in the unlikely event
# that the old doc was changed since calling TabCAT.Couch.getDoc()
TabCAT.DB.putDoc(db, doc, options)
),
(xhr) -> switch xhr.status
# catch new docs with bad _rev field (and very rare race conditions)
when 404
if doc._rev?
delete doc._rev
TabCAT.DB.putDoc(db, doc, options)
else
xhr
)
# Merge oldDoc into doc, inferring the method to use from doc.
#
# Currently, we only handle docs with type 'patient'.
TabCAT.DB.merge = (doc, oldDoc) ->
merge = pickMergeFunc(doc)
if merge?
merge(doc, oldDoc)
# helper for TabCAT.Couch.merge() and TabCAT.DB.putDocOffline
pickMergeFunc = (doc) ->
switch doc.type
when 'patient'
TabCAT.Patient.merge
# Put a document into localStorage for safe-keeping, possibly
# merging with a previously stored version of the document.
#
# If doc._rev is set, delete it; we don't track revisions in localStorage.
TabCAT.DB.spillDocToLocalStorage = (db, doc) ->
key = PI:KEY:<KEY>END_PIdoc._PI:KEY:<KEY>END_PI
# most docs don't have a merge function, so save decoding the JSON
# if there's no merging to do
if localStorage[key]?
merge = pickMergeFunc(doc)
if merge?
oldDoc = try JSON.parse(localStorage[key])
if oldDoc?
merge(doc, oldDoc)
if doc._rev?
delete doc._rev
localStorage[key] = JSON.stringify(doc)
# keep track of this as a doc the current user can vouch for
TabCAT.User.addDocSpilled(key)
# activate sync callback if it's not already running
TabCAT.DB.startSpilledDocSync()
return
# are we attempting to sync spilled docs?
spilledDocsSyncIsActive = false
# are we actually succeeding in syncing spilled docs?
syncingSpilledDocs = false
# are we currently syncing spilled docs? (for status bar)
TabCAT.DB.syncingSpilledDocs = ->
syncingSpilledDocs
# are there any spilled docs left to sync?
TabCAT.DB.spilledDocsRemain = ->
!!getNextDocPathToSync()
# Kick off syncing of spilled docs. You can pretty much call this anywhere
# (e.g. on page load)
TabCAT.DB.startSpilledDocSync = ->
if not spilledDocSyncIsActive
spilledDocSyncIsActive = true
syncSpilledDocs()
return
SYNC_SPILLED_DOCS_WAIT_TIME = 5000
syncSpilledDocs = ->
# if we're not really logged in, there's nothing to do
if not TabCAT.User.isAuthenticated()
spilledDocSyncIsActive = false
return
# if offline, wait until we're back online
if navigator.onLine is false
# not going to use 'online' event; it doesn't seem to be
# well synced with navigator.onLine
syncingSpilledDocs = false
callSyncSpilledDocsAgainIn(SYNC_SPILLED_DOCS_WAIT_TIME)
return
# pick a document to upload
# start with docs spilled by this user
docPath = TabCAT.User.getNextDocSpilled()
vouchForDoc = !!docPath
# if there aren't any, grab any doc
if not docPath?
docPath = getNextDocPathToSync()
if not docPath?
# no more docs; we are done!
localStorage.removeItem('dbSpillSyncLastDoc')
spilledDocSyncIsActive = false
syncingSpilledDocs = false
return
localStorage.dbSpillSyncLastDoc = docPath
doc = try JSON.parse(localStorage[docPath])
[__, db, docId] = docPath.split('/')
# whoops, something wrong with this doc, remove it
if not (doc? and db? and doc._id is docId)
localStorage.removeItem(docPath)
TabCAT.User.removeDocSpilled(docPath)
callSyncSpilledDocsAgainIn(0)
return
# respect security policy
user = TabCAT.User.get()
if doc.user? and not (vouchForDoc and doc.user is user)
if doc.user.slice(-1) isnt '?'
doc.user += '?'
doc.uploadedBy = user
# try syncing the doc
putDocIntoCouchDB(db, doc).then(
(->
# success!
localStorage.removeItem(docPath)
TabCAT.User.removeDocSpilled(docPath)
syncingSpilledDocs = true
callSyncSpilledDocsAgainIn(0)
),
(xhr) ->
# if it's not a network error, demote to a leftover doc
if xhr.status isnt 0
TabCAT.User.removeDocSpilled(docPath)
# if there's an auth issue, user will need to log in again
# befor we can make any progress
if xhr.status is 401
spilledDocSyncIsActive = false
syncingSpilledDocs = false
return
syncingSpilledDocs = false
callSyncSpilledDocsAgainIn(SYNC_SPILLED_DOCS_WAIT_TIME)
)
return
# get the next doc to sync. If you want to prioritize docs spilled by
# this user, use TabCAT.User.getNextDocSpilled() first.
getNextDocPathToSync = ->
docPaths = (path for path in _.keys(localStorage) \
when path[0] is '/').sort()
if _.isEmpty(docPaths)
return null
docPath = docPaths[0]
# this allows us to skip over documents and try them later
if localStorage.dbSpillSyncLastDoc
index = _.sortedIndex(docPaths, localStorage.dbSpillSyncLastDoc)
if docPaths[index] = localStorage.dbSpillSyncLastDoc
index += 1
if index < docPaths.length
docPath = docPaths[index]
return docPath
# hopefully this can keep us from exceeding max recursion depth
callSyncSpilledDocsAgainIn = (milliseconds) ->
TabCAT.UI.wait(milliseconds).then(syncSpilledDocs)
return
# Estimate % of local storage used. Probably right for the browsers
# we care about!
TabCAT.DB.percentOfLocalStorageUsed = ->
return 100 * charsInLocalStorage() / maxCharsInLocalStorage()
# number of chars currently stored in localStorage
charsInLocalStorage = ->
numChars = 0
for own key, value of localStorage
numChars += key.length + value.length
return numChars
# Loosely based on:
# http://dev-test.nemikor.com/web-storage/support-test/.
# Could be improved
maxCharsInLocalStorage = ->
ua = navigator.userAgent
if ua.indexOf('Firefox') isnt -1
return 4.98 * 1024 * 1024
else if ua.indexOf('IE') isnt -1
return 4.75 * 1024 * 1024
else
return 2.49 * 1024 * 1024
|
[
{
"context": "rom foo where age > #{22}\"\n conditions = { name:'John Doe', }\n show SQL\"select * from foo $where#{conditio",
"end": 2753,
"score": 0.9997769594192505,
"start": 2745,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "alues#{ {joe: 22, bar: 'ok'} }\"\n obj = { first: 'John', last: 'Doe', }\n show SQL\"insert into foo $keys",
"end": 3133,
"score": 0.9998564720153809,
"start": 3129,
"tag": "NAME",
"value": "John"
},
{
"context": "22, bar: 'ok'} }\"\n obj = { first: 'John', last: 'Doe', }\n show SQL\"insert into foo $keys#{Object.keys",
"end": 3146,
"score": 0.9997990131378174,
"start": 3143,
"tag": "NAME",
"value": "Doe"
}
] | dev/snippets/src/sql-templating.coffee | loveencounterflow/hengist | 0 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'SQL-TEMPLATING'
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
info = CND.get_logger 'info', badge
urge = CND.get_logger 'urge', badge
help = CND.get_logger 'help', badge
whisper = CND.get_logger 'whisper', badge
echo = CND.echo.bind CND
#-----------------------------------------------------------------------------------------------------------
@demo_sql_tokenizer = ->
cfg =
regExp: ( require 'mysql-tokenizer/lib/regexp-sql92' )
tokenize = ( require 'mysql-tokenizer' ) cfg
sql = """select *, 'helo world' as "text" from blah order by 1; insert sfksi 1286982342 &/$/&;"""
tokens = tokenize sql + '\n'
colors = [ ( ( P... ) -> CND.reverse CND.blue P... ), ( ( P... ) -> CND.reverse CND.yellow P... ), ]
color_count = colors.length
tokens = ( colors[ idx %% color_count ] token for token, idx in tokens )
info tokens.join ''
#-----------------------------------------------------------------------------------------------------------
@demo_sql_templating_pgsqwell = ->
SQL = require 'pgsqwell'
{ escapeSQLIdentifier
sqlPart
emptySQLPart
joinSQLValues } = SQL
SQL = SQL.default
#.........................................................................................................
limit = null
limit = 10
limit_sql = if limit? then sqlPart"LIMIT #{limit}" else emptySQLPart
query = SQL"""SELECT id FROM users WHERE name=#{'toto'} #{limit_sql}"""
query2 = SQL"""SELECT id FROM #{escapeSQLIdentifier('table')}"""
query3 = SQL"""SELECT id FROM users WHERE id IN #{joinSQLValues([1, 2])}"""
mergedQuery = SQL"""
#{query}
UNION
#{query2}
UNION
#{query3}
"""
{ text, values, } = query; info '^337^', { text, values, }
{ text, values, } = query2; info '^337^', { text, values, }
{ text, values, } = query3; info '^337^', { text, values, }
{ text, values, } = mergedQuery; info '^337^', { text, values, }
#-----------------------------------------------------------------------------------------------------------
@demo_sql_template = ->
SQL = require 'sql-template'
show = ( fragment ) -> help ( rpr fragment.text ), ( CND.gold rpr fragment.values )
show SQL"select * from foo"
show SQL"select * from foo where age > #{22}"
conditions = { name:'John Doe', }
show SQL"select * from foo $where#{conditions}"
conditions = { id: [ 1, 2, 3, ], type:'snow', }
show SQL"select * from foo $where#{conditions}"
show SQL"update foo $set#{ {joe: 22, bar: 'ok'} }"
show SQL"insert into foo $keys#{["joe", "bar"]} values (#{22}, #{'ok'})}"
show SQL"insert into foo ( joe, bar ) $values#{ {joe: 22, bar: 'ok'} }"
obj = { first: 'John', last: 'Doe', }
show SQL"insert into foo $keys#{Object.keys(obj)} $values#{obj}"
show SQL"select * from $id#{'foo'}"
show SQL"select * from $id#{'foo'} where id $in#{[1,2,3]}"
return null
#===========================================================================================================
class Sql
#---------------------------------------------------------------------------------------------------------
constructor: ( cfg ) ->
# super()
@types = new ( require 'intertype' ).Intertype()
@cfg = cfg ### TAINT freeze ###
return undefined
#---------------------------------------------------------------------------------------------------------
SQL: String.raw
# SQL: ( parts, values... ) =>
# debug '^557^', [ parts, values, @cfg, ]
# return "your SQL string: #{rpr parts}, values: #{rpr values}"
#---------------------------------------------------------------------------------------------------------
I: ( name ) => '"' + ( name.replace /"/g, '""' ) + '"'
#---------------------------------------------------------------------------------------------------------
L: ( x ) =>
return 'null' unless x?
switch type = @types.type_of x
when 'text' then return "'" + ( x.replace /'/g, "''" ) + "'"
# when 'list' then return "'#{@list_as_json x}'"
when 'float' then return x.toString()
when 'boolean' then return ( if x then '1' else '0' )
when 'list'
throw new Error "^dba@23^ use `X()` for lists"
throw new Error '^dba@323^', type, x
# throw new E.Dba_sql_value_error '^dba@323^', type, x
#---------------------------------------------------------------------------------------------------------
X: ( x ) =>
throw new Error "^dba@132^ expected a list, got a #{type}" unless ( type = @types.type_of x ) is 'list'
return '( ' + ( ( @L e for e in x ).join ', ' ) + ' )'
#-----------------------------------------------------------------------------------------------------------
@demo_Xxx = ->
sql = new Sql { this_setting: true, that_setting: 123, }
{ SQL
I
L
X } = sql
table = 'that other "table"'
a_max = 123
limit = 10
truth = true
strange = "strange 'value'%"
selection = [ 'the', 'one', 'or', 'other', ]
info '^3344^\n', SQL"""
select
a, b, c
from #{I table}
where #{truth}
and ( a > #{L a_max} )
and ( b like #{L strange} )
and ( c in #{X selection} )
limit #{L limit};
"""
return null
############################################################################################################
if module is require.main then do =>
# @demo_sql_tokenizer()
# @demo_sql_templating_pgsqwell()
# @demo_sql_template()
@demo_Xxx()
| 75478 |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'SQL-TEMPLATING'
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
info = CND.get_logger 'info', badge
urge = CND.get_logger 'urge', badge
help = CND.get_logger 'help', badge
whisper = CND.get_logger 'whisper', badge
echo = CND.echo.bind CND
#-----------------------------------------------------------------------------------------------------------
@demo_sql_tokenizer = ->
cfg =
regExp: ( require 'mysql-tokenizer/lib/regexp-sql92' )
tokenize = ( require 'mysql-tokenizer' ) cfg
sql = """select *, 'helo world' as "text" from blah order by 1; insert sfksi 1286982342 &/$/&;"""
tokens = tokenize sql + '\n'
colors = [ ( ( P... ) -> CND.reverse CND.blue P... ), ( ( P... ) -> CND.reverse CND.yellow P... ), ]
color_count = colors.length
tokens = ( colors[ idx %% color_count ] token for token, idx in tokens )
info tokens.join ''
#-----------------------------------------------------------------------------------------------------------
@demo_sql_templating_pgsqwell = ->
SQL = require 'pgsqwell'
{ escapeSQLIdentifier
sqlPart
emptySQLPart
joinSQLValues } = SQL
SQL = SQL.default
#.........................................................................................................
limit = null
limit = 10
limit_sql = if limit? then sqlPart"LIMIT #{limit}" else emptySQLPart
query = SQL"""SELECT id FROM users WHERE name=#{'toto'} #{limit_sql}"""
query2 = SQL"""SELECT id FROM #{escapeSQLIdentifier('table')}"""
query3 = SQL"""SELECT id FROM users WHERE id IN #{joinSQLValues([1, 2])}"""
mergedQuery = SQL"""
#{query}
UNION
#{query2}
UNION
#{query3}
"""
{ text, values, } = query; info '^337^', { text, values, }
{ text, values, } = query2; info '^337^', { text, values, }
{ text, values, } = query3; info '^337^', { text, values, }
{ text, values, } = mergedQuery; info '^337^', { text, values, }
#-----------------------------------------------------------------------------------------------------------
@demo_sql_template = ->
SQL = require 'sql-template'
show = ( fragment ) -> help ( rpr fragment.text ), ( CND.gold rpr fragment.values )
show SQL"select * from foo"
show SQL"select * from foo where age > #{22}"
conditions = { name:'<NAME>', }
show SQL"select * from foo $where#{conditions}"
conditions = { id: [ 1, 2, 3, ], type:'snow', }
show SQL"select * from foo $where#{conditions}"
show SQL"update foo $set#{ {joe: 22, bar: 'ok'} }"
show SQL"insert into foo $keys#{["joe", "bar"]} values (#{22}, #{'ok'})}"
show SQL"insert into foo ( joe, bar ) $values#{ {joe: 22, bar: 'ok'} }"
obj = { first: '<NAME>', last: '<NAME>', }
show SQL"insert into foo $keys#{Object.keys(obj)} $values#{obj}"
show SQL"select * from $id#{'foo'}"
show SQL"select * from $id#{'foo'} where id $in#{[1,2,3]}"
return null
#===========================================================================================================
class Sql
#---------------------------------------------------------------------------------------------------------
constructor: ( cfg ) ->
# super()
@types = new ( require 'intertype' ).Intertype()
@cfg = cfg ### TAINT freeze ###
return undefined
#---------------------------------------------------------------------------------------------------------
SQL: String.raw
# SQL: ( parts, values... ) =>
# debug '^557^', [ parts, values, @cfg, ]
# return "your SQL string: #{rpr parts}, values: #{rpr values}"
#---------------------------------------------------------------------------------------------------------
I: ( name ) => '"' + ( name.replace /"/g, '""' ) + '"'
#---------------------------------------------------------------------------------------------------------
L: ( x ) =>
return 'null' unless x?
switch type = @types.type_of x
when 'text' then return "'" + ( x.replace /'/g, "''" ) + "'"
# when 'list' then return "'#{@list_as_json x}'"
when 'float' then return x.toString()
when 'boolean' then return ( if x then '1' else '0' )
when 'list'
throw new Error "^dba@23^ use `X()` for lists"
throw new Error '^dba@323^', type, x
# throw new E.Dba_sql_value_error '^dba@323^', type, x
#---------------------------------------------------------------------------------------------------------
X: ( x ) =>
throw new Error "^dba@132^ expected a list, got a #{type}" unless ( type = @types.type_of x ) is 'list'
return '( ' + ( ( @L e for e in x ).join ', ' ) + ' )'
#-----------------------------------------------------------------------------------------------------------
@demo_Xxx = ->
sql = new Sql { this_setting: true, that_setting: 123, }
{ SQL
I
L
X } = sql
table = 'that other "table"'
a_max = 123
limit = 10
truth = true
strange = "strange 'value'%"
selection = [ 'the', 'one', 'or', 'other', ]
info '^3344^\n', SQL"""
select
a, b, c
from #{I table}
where #{truth}
and ( a > #{L a_max} )
and ( b like #{L strange} )
and ( c in #{X selection} )
limit #{L limit};
"""
return null
############################################################################################################
if module is require.main then do =>
# @demo_sql_tokenizer()
# @demo_sql_templating_pgsqwell()
# @demo_sql_template()
@demo_Xxx()
| true |
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'SQL-TEMPLATING'
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
info = CND.get_logger 'info', badge
urge = CND.get_logger 'urge', badge
help = CND.get_logger 'help', badge
whisper = CND.get_logger 'whisper', badge
echo = CND.echo.bind CND
#-----------------------------------------------------------------------------------------------------------
@demo_sql_tokenizer = ->
cfg =
regExp: ( require 'mysql-tokenizer/lib/regexp-sql92' )
tokenize = ( require 'mysql-tokenizer' ) cfg
sql = """select *, 'helo world' as "text" from blah order by 1; insert sfksi 1286982342 &/$/&;"""
tokens = tokenize sql + '\n'
colors = [ ( ( P... ) -> CND.reverse CND.blue P... ), ( ( P... ) -> CND.reverse CND.yellow P... ), ]
color_count = colors.length
tokens = ( colors[ idx %% color_count ] token for token, idx in tokens )
info tokens.join ''
#-----------------------------------------------------------------------------------------------------------
@demo_sql_templating_pgsqwell = ->
SQL = require 'pgsqwell'
{ escapeSQLIdentifier
sqlPart
emptySQLPart
joinSQLValues } = SQL
SQL = SQL.default
#.........................................................................................................
limit = null
limit = 10
limit_sql = if limit? then sqlPart"LIMIT #{limit}" else emptySQLPart
query = SQL"""SELECT id FROM users WHERE name=#{'toto'} #{limit_sql}"""
query2 = SQL"""SELECT id FROM #{escapeSQLIdentifier('table')}"""
query3 = SQL"""SELECT id FROM users WHERE id IN #{joinSQLValues([1, 2])}"""
mergedQuery = SQL"""
#{query}
UNION
#{query2}
UNION
#{query3}
"""
{ text, values, } = query; info '^337^', { text, values, }
{ text, values, } = query2; info '^337^', { text, values, }
{ text, values, } = query3; info '^337^', { text, values, }
{ text, values, } = mergedQuery; info '^337^', { text, values, }
#-----------------------------------------------------------------------------------------------------------
@demo_sql_template = ->
SQL = require 'sql-template'
show = ( fragment ) -> help ( rpr fragment.text ), ( CND.gold rpr fragment.values )
show SQL"select * from foo"
show SQL"select * from foo where age > #{22}"
conditions = { name:'PI:NAME:<NAME>END_PI', }
show SQL"select * from foo $where#{conditions}"
conditions = { id: [ 1, 2, 3, ], type:'snow', }
show SQL"select * from foo $where#{conditions}"
show SQL"update foo $set#{ {joe: 22, bar: 'ok'} }"
show SQL"insert into foo $keys#{["joe", "bar"]} values (#{22}, #{'ok'})}"
show SQL"insert into foo ( joe, bar ) $values#{ {joe: 22, bar: 'ok'} }"
obj = { first: 'PI:NAME:<NAME>END_PI', last: 'PI:NAME:<NAME>END_PI', }
show SQL"insert into foo $keys#{Object.keys(obj)} $values#{obj}"
show SQL"select * from $id#{'foo'}"
show SQL"select * from $id#{'foo'} where id $in#{[1,2,3]}"
return null
#===========================================================================================================
class Sql
#---------------------------------------------------------------------------------------------------------
constructor: ( cfg ) ->
# super()
@types = new ( require 'intertype' ).Intertype()
@cfg = cfg ### TAINT freeze ###
return undefined
#---------------------------------------------------------------------------------------------------------
SQL: String.raw
# SQL: ( parts, values... ) =>
# debug '^557^', [ parts, values, @cfg, ]
# return "your SQL string: #{rpr parts}, values: #{rpr values}"
#---------------------------------------------------------------------------------------------------------
I: ( name ) => '"' + ( name.replace /"/g, '""' ) + '"'
#---------------------------------------------------------------------------------------------------------
L: ( x ) =>
return 'null' unless x?
switch type = @types.type_of x
when 'text' then return "'" + ( x.replace /'/g, "''" ) + "'"
# when 'list' then return "'#{@list_as_json x}'"
when 'float' then return x.toString()
when 'boolean' then return ( if x then '1' else '0' )
when 'list'
throw new Error "^dba@23^ use `X()` for lists"
throw new Error '^dba@323^', type, x
# throw new E.Dba_sql_value_error '^dba@323^', type, x
#---------------------------------------------------------------------------------------------------------
X: ( x ) =>
throw new Error "^dba@132^ expected a list, got a #{type}" unless ( type = @types.type_of x ) is 'list'
return '( ' + ( ( @L e for e in x ).join ', ' ) + ' )'
#-----------------------------------------------------------------------------------------------------------
@demo_Xxx = ->
sql = new Sql { this_setting: true, that_setting: 123, }
{ SQL
I
L
X } = sql
table = 'that other "table"'
a_max = 123
limit = 10
truth = true
strange = "strange 'value'%"
selection = [ 'the', 'one', 'or', 'other', ]
info '^3344^\n', SQL"""
select
a, b, c
from #{I table}
where #{truth}
and ( a > #{L a_max} )
and ( b like #{L strange} )
and ( c in #{X selection} )
limit #{L limit};
"""
return null
############################################################################################################
if module is require.main then do =>
# @demo_sql_tokenizer()
# @demo_sql_templating_pgsqwell()
# @demo_sql_template()
@demo_Xxx()
|
[
{
"context": "rUrl', ->\n indicator = new Indicator(\n name: \"Phosphate P Diddy\"\n indicatorationConfig:\n esriConfig:\n ",
"end": 1672,
"score": 0.999803900718689,
"start": 1655,
"tag": "NAME",
"value": "Phosphate P Diddy"
}
] | server/components/indicatorator/test/units/getters/esri.coffee | unepwcmc/NRT | 0 | assert = require('chai').assert
sinon = require('sinon')
request = require('request')
Indicator = require('../../../../../models/indicator').model
EsriGetter = require("../../../getters/esri")
suite('Esri getter')
test('.buildUrl throws an error if the Indicator does not have any Esri configs', ->
indicator = new Indicator()
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator does not define a esriConfig attribute")
)
test('.buildUrl throws an error if the Indicator esriConfig does not specify a serviceName', ->
indicator = new Indicator(
indicatorationConfig:
esriConfig: {}
)
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator esriConfig does not define a serviceName attribute")
)
test('.buildUrl throws an error if the Indicator esriConfig does not specify a featureServer', ->
indicator = new Indicator(
indicatorationConfig:
esriConfig:
serviceName: ''
)
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator esriConfig does not define a featureServer attribute")
)
test('.buildUrl throws an error if the Indicator esriConfig does not specify a serverUrl', ->
indicator = new Indicator(
indicatorationConfig:
esriConfig:
serviceName: ''
featureServer: ''
)
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator esriConfig does not define a serverUrl attribute")
)
test('.buildUrl constructs the correct URL with serviceName, featureServer, serverUrl', ->
indicator = new Indicator(
name: "Phosphate P Diddy"
indicatorationConfig:
esriConfig:
serverUrl: 'http://esri-server.com/rest/services'
serviceName: 'WQ'
featureServer: '4'
)
getter = new EsriGetter(indicator)
builtUrl = getter.buildUrl()
expectedUrl = "http://esri-server.com/rest/services/WQ/FeatureServer/4/query"
assert.strictEqual builtUrl, expectedUrl
)
test(".fetch builds a request URL, queries it, and returns the data", (done) ->
getter = new EsriGetter({})
fakeEsriURL = "http://fake.esri-server/rest/services"
sinon.stub(getter, 'buildUrl', ->
return fakeEsriURL
)
theData = {some: 'data', goes: 'in', here: 'ok'}
getStub = sinon.stub(request, 'get', (options, cb) ->
cb(null, body: JSON.stringify(theData))
)
getter.fetch().then((fetchedData)->
try
assert.isTrue(
getStub.calledWith({url: fakeEsriURL, qs: getter.getQueryParams()}),
"Expected request.get to be called with the result of @buildUrl,
but called with #{getStub.getCall(0).args}"
)
assert.deepEqual(fetchedData, theData,
"Expected fetch to return the rows of the get request"
)
done()
catch err
done(err)
finally
getStub.restore()
).fail((err) ->
getStub.restore()
done(err)
)
)
test(".fetch throws an error if the Esri server returns an error", (done) ->
getter = new EsriGetter({})
fakeEsriURL = "http://fake.esri-server/rest/services"
sinon.stub(getter, 'buildUrl', ->
return fakeEsriURL
)
errorResponse = {
"error": {
"code": 400,
"details": [
"Invalid Layer or Table ID: 987."
],
"message": "Invalid or missing input parameters."
}
}
getStub = sinon.stub(request, 'get', (options, cb) ->
cb(null, body: JSON.stringify(errorResponse))
)
getter.fetch().then(->
getStub.restore()
done(new Error("👴👵 Expected fetch not to succeed"))
).fail( (errorThrown)->
try
assert.deepEqual(errorThrown, errorResponse.error,
"Expected fetch to return the rows of the get request"
)
done()
catch err
done(err)
finally
getStub.restore()
)
)
| 13363 | assert = require('chai').assert
sinon = require('sinon')
request = require('request')
Indicator = require('../../../../../models/indicator').model
EsriGetter = require("../../../getters/esri")
suite('Esri getter')
test('.buildUrl throws an error if the Indicator does not have any Esri configs', ->
indicator = new Indicator()
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator does not define a esriConfig attribute")
)
test('.buildUrl throws an error if the Indicator esriConfig does not specify a serviceName', ->
indicator = new Indicator(
indicatorationConfig:
esriConfig: {}
)
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator esriConfig does not define a serviceName attribute")
)
test('.buildUrl throws an error if the Indicator esriConfig does not specify a featureServer', ->
indicator = new Indicator(
indicatorationConfig:
esriConfig:
serviceName: ''
)
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator esriConfig does not define a featureServer attribute")
)
test('.buildUrl throws an error if the Indicator esriConfig does not specify a serverUrl', ->
indicator = new Indicator(
indicatorationConfig:
esriConfig:
serviceName: ''
featureServer: ''
)
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator esriConfig does not define a serverUrl attribute")
)
test('.buildUrl constructs the correct URL with serviceName, featureServer, serverUrl', ->
indicator = new Indicator(
name: "<NAME>"
indicatorationConfig:
esriConfig:
serverUrl: 'http://esri-server.com/rest/services'
serviceName: 'WQ'
featureServer: '4'
)
getter = new EsriGetter(indicator)
builtUrl = getter.buildUrl()
expectedUrl = "http://esri-server.com/rest/services/WQ/FeatureServer/4/query"
assert.strictEqual builtUrl, expectedUrl
)
test(".fetch builds a request URL, queries it, and returns the data", (done) ->
getter = new EsriGetter({})
fakeEsriURL = "http://fake.esri-server/rest/services"
sinon.stub(getter, 'buildUrl', ->
return fakeEsriURL
)
theData = {some: 'data', goes: 'in', here: 'ok'}
getStub = sinon.stub(request, 'get', (options, cb) ->
cb(null, body: JSON.stringify(theData))
)
getter.fetch().then((fetchedData)->
try
assert.isTrue(
getStub.calledWith({url: fakeEsriURL, qs: getter.getQueryParams()}),
"Expected request.get to be called with the result of @buildUrl,
but called with #{getStub.getCall(0).args}"
)
assert.deepEqual(fetchedData, theData,
"Expected fetch to return the rows of the get request"
)
done()
catch err
done(err)
finally
getStub.restore()
).fail((err) ->
getStub.restore()
done(err)
)
)
test(".fetch throws an error if the Esri server returns an error", (done) ->
getter = new EsriGetter({})
fakeEsriURL = "http://fake.esri-server/rest/services"
sinon.stub(getter, 'buildUrl', ->
return fakeEsriURL
)
errorResponse = {
"error": {
"code": 400,
"details": [
"Invalid Layer or Table ID: 987."
],
"message": "Invalid or missing input parameters."
}
}
getStub = sinon.stub(request, 'get', (options, cb) ->
cb(null, body: JSON.stringify(errorResponse))
)
getter.fetch().then(->
getStub.restore()
done(new Error("👴👵 Expected fetch not to succeed"))
).fail( (errorThrown)->
try
assert.deepEqual(errorThrown, errorResponse.error,
"Expected fetch to return the rows of the get request"
)
done()
catch err
done(err)
finally
getStub.restore()
)
)
| true | assert = require('chai').assert
sinon = require('sinon')
request = require('request')
Indicator = require('../../../../../models/indicator').model
EsriGetter = require("../../../getters/esri")
suite('Esri getter')
test('.buildUrl throws an error if the Indicator does not have any Esri configs', ->
indicator = new Indicator()
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator does not define a esriConfig attribute")
)
test('.buildUrl throws an error if the Indicator esriConfig does not specify a serviceName', ->
indicator = new Indicator(
indicatorationConfig:
esriConfig: {}
)
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator esriConfig does not define a serviceName attribute")
)
test('.buildUrl throws an error if the Indicator esriConfig does not specify a featureServer', ->
indicator = new Indicator(
indicatorationConfig:
esriConfig:
serviceName: ''
)
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator esriConfig does not define a featureServer attribute")
)
test('.buildUrl throws an error if the Indicator esriConfig does not specify a serverUrl', ->
indicator = new Indicator(
indicatorationConfig:
esriConfig:
serviceName: ''
featureServer: ''
)
getter = new EsriGetter(indicator)
assert.throw( (->
getter.buildUrl()
), "Indicator esriConfig does not define a serverUrl attribute")
)
test('.buildUrl constructs the correct URL with serviceName, featureServer, serverUrl', ->
indicator = new Indicator(
name: "PI:NAME:<NAME>END_PI"
indicatorationConfig:
esriConfig:
serverUrl: 'http://esri-server.com/rest/services'
serviceName: 'WQ'
featureServer: '4'
)
getter = new EsriGetter(indicator)
builtUrl = getter.buildUrl()
expectedUrl = "http://esri-server.com/rest/services/WQ/FeatureServer/4/query"
assert.strictEqual builtUrl, expectedUrl
)
test(".fetch builds a request URL, queries it, and returns the data", (done) ->
getter = new EsriGetter({})
fakeEsriURL = "http://fake.esri-server/rest/services"
sinon.stub(getter, 'buildUrl', ->
return fakeEsriURL
)
theData = {some: 'data', goes: 'in', here: 'ok'}
getStub = sinon.stub(request, 'get', (options, cb) ->
cb(null, body: JSON.stringify(theData))
)
getter.fetch().then((fetchedData)->
try
assert.isTrue(
getStub.calledWith({url: fakeEsriURL, qs: getter.getQueryParams()}),
"Expected request.get to be called with the result of @buildUrl,
but called with #{getStub.getCall(0).args}"
)
assert.deepEqual(fetchedData, theData,
"Expected fetch to return the rows of the get request"
)
done()
catch err
done(err)
finally
getStub.restore()
).fail((err) ->
getStub.restore()
done(err)
)
)
test(".fetch throws an error if the Esri server returns an error", (done) ->
getter = new EsriGetter({})
fakeEsriURL = "http://fake.esri-server/rest/services"
sinon.stub(getter, 'buildUrl', ->
return fakeEsriURL
)
errorResponse = {
"error": {
"code": 400,
"details": [
"Invalid Layer or Table ID: 987."
],
"message": "Invalid or missing input parameters."
}
}
getStub = sinon.stub(request, 'get', (options, cb) ->
cb(null, body: JSON.stringify(errorResponse))
)
getter.fetch().then(->
getStub.restore()
done(new Error("👴👵 Expected fetch not to succeed"))
).fail( (errorThrown)->
try
assert.deepEqual(errorThrown, errorResponse.error,
"Expected fetch to return the rows of the get request"
)
done()
catch err
done(err)
finally
getStub.restore()
)
)
|
[
{
"context": "false\n )\n anon = new User(\n id: 1\n name: \"Unauthenticated Anonymous User\"\n email: \"anon@email.com\"\n website: \"https:",
"end": 314,
"score": 0.9866255521774292,
"start": 284,
"tag": "NAME",
"value": "Unauthenticated Anonymous User"
},
{
"context": "ame: \"Unauthenticated Anonymous User\"\n email: \"anon@email.com\"\n website: \"https://domain.com\"\n websiteAli",
"end": 342,
"score": 0.9999179840087891,
"start": 328,
"tag": "EMAIL",
"value": "anon@email.com"
}
] | app/scripts/models/person.coffee | nerdfiles/utxo_us | 0 | angular.module("utxo").factory "person", ($http, $timeout, $location) ->
User = Gisele.Model.create(
id:
type: Number
readOnly: true
name: String
email: String
active:
type: Boolean
default: false
)
anon = new User(
id: 1
name: "Unauthenticated Anonymous User"
email: "anon@email.com"
website: "https://domain.com"
websiteAlias: "domain.com"
colleague: [
1
2
]
)
anon
| 43939 | angular.module("utxo").factory "person", ($http, $timeout, $location) ->
User = Gisele.Model.create(
id:
type: Number
readOnly: true
name: String
email: String
active:
type: Boolean
default: false
)
anon = new User(
id: 1
name: "<NAME>"
email: "<EMAIL>"
website: "https://domain.com"
websiteAlias: "domain.com"
colleague: [
1
2
]
)
anon
| true | angular.module("utxo").factory "person", ($http, $timeout, $location) ->
User = Gisele.Model.create(
id:
type: Number
readOnly: true
name: String
email: String
active:
type: Boolean
default: false
)
anon = new User(
id: 1
name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
website: "https://domain.com"
websiteAlias: "domain.com"
colleague: [
1
2
]
)
anon
|
[
{
"context": "\n\n key = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmDMEWNU+YBYJKwYBBAHaRw8BAQdANDGlomfqnHvB2suF9Nsk27qprv4jyqUnGUxT\nezS17DyIYQQgFggACQUCWNU+6AIdAwAKCRByQpSZUUdJMCiQAQCA90BeuZfzJuEr\nSzTT76qks97wmTYTCI2Tklnkgfw9UAD/WJMsBW93I8YERc6TaAM7Ikw/XxF/Llhb\nWXmitXrgbQ+0ElJldm9rZWQgS2V5IFRlc3Rlcoh5BBMWCAAhBQJY1T5gAhsDBQsJ\nCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEHJClJlRR0kw3sEBAIc6PaPdgHIsi5Pz\nxZkDfwVa76Mvb8yug8HIW9A9swmYAP0ZSASv7N+f6wZUSJAun9E7pnfaA0y+bVs4\nWk0U7dsXDrg4BFjVPmASCisGAQQBl1UBBQEBB0CLNBYcjHxNQGfO8fcyp+QtsC8P\nd2dLxZR10SQnIaQWPAMBCAeIYQQYFggACQUCWNU+YAIbDAAKCRByQpSZUUdJMCot\nAQDaW0YiRIN64fCmnSJFNZTqM1V1VE1tLktUxwT5uilB9QD+JcppXFBLPB0oSlMu\n2LPpIrS71",
"end": 1119,
"score": 0.9993683099746704,
"start": 575,
"tag": "KEY",
"value": "mDMEWNU+YBYJKwYBBAHaRw8BAQdANDGlomfqnHvB2suF9Nsk27qprv4jyqUnGUxT\nezS17DyIYQQgFggACQUCWNU+6AIdAwAKCRByQpSZUUdJMCiQAQCA90BeuZfzJuEr\nSzTT76qks97wmTYTCI2Tklnkgfw9UAD/WJMsBW93I8YERc6TaAM7Ikw/XxF/Llhb\nWXmitXrgbQ+0ElJldm9rZWQgS2V5IFRlc3Rlcoh5BBMWCAAhBQJY1T5gAhsDBQsJ\nCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEHJClJlRR0kw3sEBAIc6PaPdgHIsi5Pz\nxZkDfwVa76Mvb8yug8HIW9A9swmYAP0ZSASv7N+f6wZUSJAun9E7pnfaA0y+bVs4\nWk0U7dsXDrg4BFjVPmASCisGAQQBl1UBBQEBB0CLNBYcjHxNQGfO8fcyp+QtsC8P\nd2dLxZR10SQnIaQWPAMBCAeIYQQYFggACQUCWNU+YAIbDAAKCRByQpSZUUdJMCot\nAQDaW0YiRIN64fCmnSJFNZTq"
},
{
"context": "bDAAKCRByQpSZUUdJMCot\nAQDaW0YiRIN64fCmnSJFNZTqM1V1VE1tLktUxwT5uilB9QD+JcppXFBLPB0oSlMu\n2LPpIrS71kVwXb+",
"end": 1125,
"score": 0.5061562061309814,
"start": 1123,
"tag": "KEY",
"value": "VE"
},
{
"context": "SZUUdJMCot\nAQDaW0YiRIN64fCmnSJFNZTqM1V1VE1tLktUxwT5uilB9QD+JcppXFBLPB0oSlMu\n2LPpIrS71kVwXb+yF3Rr8c87u",
"end": 1135,
"score": 0.5216020941734314,
"start": 1134,
"tag": "KEY",
"value": "5"
},
{
"context": "pass verification.\n-----BEGIN PGP SIGNATURE-----\n\niF4EARYIAAYFAljVPqgACgkQckKUmVFHSTB7SQEAn2D5cUbMp7/HTY+8v54uz7gL\nV1lAVqcNiyy7Srus5/UBALbH5jUIR2kZamWO0znZ7+ltz42cmZ+OESnfHxa4KUUB\n=+5R5\n-----END PGP SIGNATURE-----\n\"\"\"\n\n now = Ma",
"end": 1543,
"score": 0.8748508095741272,
"start": 1414,
"tag": "KEY",
"value": "iF4EARYIAAYFAljVPqgACgkQckKUmVFHSTB7SQEAn2D5cUbMp7/HTY+8v54uz7gL\nV1lAVqcNiyy7Srus5/UBALbH5jUIR2kZamWO0znZ7+ltz42cmZ+OESnfHxa4KUUB"
},
{
"context": "/UBALbH5jUIR2kZamWO0znZ7+ltz42cmZ+OESnfHxa4KUUB\n=+5R5\n-----END PGP SIGNATURE-----\n\"\"\"\n\n now = Math.f",
"end": 1547,
"score": 0.5967801213264465,
"start": 1546,
"tag": "KEY",
"value": "5"
},
{
"context": "eys.push \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlFgEWNkB0RYJKwYBBAHaRw8BAQdA4hcG1GlHLKQu1e3wGlt1nYOnanUIDZ+khCKC\njCsK5NYAAP4nvoBNpeP4MY36+z9YDh+ErdxWaMzCmGCHdMjydARScRHotAVBbGlj\nZYh5BBMWCAAhBQJY2QHRAhsDBQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJELy7\nf0GiDfzHy1gA/jdhdJf909xthPBDQsrwqISP4dLTWuC3BVSS6EKA9NPwAP9rJr8r\nexCp67hEbgh3DW6PvRTE98uQ2xq9DwsE20/kBJxdBFjZAdESCisGAQQBl1UBBQEB\nB0CLllnTNJJe8P6LegVgpvQcf4HNP5saxm5KKWIYCaowWQMBCAcAAP9hVRqTSXVt\nJZMEQbb+cifABP4nV0u5rqDhl6s+iwiBeA9WiGEEGBYIAAkFAljZAdECGwwACgkQ\nvLt/QaIN/MdpZwEA/nnrXhSvAQ/5vgRxE1MEgCtjqlUf4wBjOu/k+LhFcWUBAO2i\n25EtZWVtDKcJfQILvethtIglGMk8Dc3dcH9FSywC\n=LH1D\n-----END PGP PRIVATE KEY BLOCK-----\n\"\"\"\n\n keys.p",
"end": 2779,
"score": 0.9975219368934631,
"start": 2213,
"tag": "KEY",
"value": "lFgEWNkB0RYJKwYBBAHaRw8BAQdA4hcG1GlHLKQu1e3wGlt1nYOnanUIDZ+khCKC\njCsK5NYAAP4nvoBNpeP4MY36+z9YDh+ErdxWaMzCmGCHdMjydARScRHotAVBbGlj\nZYh5BBMWCAAhBQJY2QHRAhsDBQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJELy7\nf0GiDfzHy1gA/jdhdJf909xthPBDQsrwqISP4dLTWuC3BVSS6EKA9NPwAP9rJr8r\nexCp67hEbgh3DW6PvRTE98uQ2xq9DwsE20/kBJxdBFjZAdESCisGAQQBl1UBBQEB\nB0CLllnTNJJe8P6LegVgpvQcf4HNP5saxm5KKWIYCaowWQMBCAcAAP9hVRqTSXVt\nJZMEQbb+cifABP4nV0u5rqDhl6s+iwiBeA9WiGEEGBYIAAkFAljZAdECGwwACgkQ\nvLt/QaIN/MdpZwEA/nnrXhSvAQ/5vgRxE1MEgCtjqlUf4wBjOu/k+LhFcWUBAO2i\n25EtZWVtDKcJfQILvethtIglGMk8Dc3dcH9FSywC\n=LH1D"
},
{
"context": "eys.push \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlNkEWNkCiRMFK4EEACMEIwQBsUDs05PSWR3j3/yfnG/MYq8tJwXUymCP6GPhuLn1\ng7FdKvxGvx9S9QEzMo3M6x2x515ywYrKhS6+GdaXhD/7vpcAUQdjLyzYWrHtE50q\nzoxUjQ3Z5rDeNF9+YAOwvntwWi5xsIVAsKbW/yWqq+YnazZmcYr3Oj5/61z69uvL\nsw7JX64AAgjz1cim3YvBwqnmNBnQeS5aLyO7QVBjjsOLrVWA1iGmXWokS7iVJYRP\n1zQJwHe2zft7N4L+bPiQPjjJsbqEsijFsiK9tAVCb2JieYi9BBMTCgAhBQJY2QKJ\nAhsDBQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEONJWG038qWKGYQCCQEbZzUx\n0qkMFdJXUvNIZ/nBU64SY+I1akBDKGdZ0uNSzi1pkwW8lUYngVLM806Ya1gxeYwz\nSxKAU1lV2N9T/OwMkgIJAWFarehjKORU145RHNlF6CDmtppxdYWu/7eN0VEjpZMm\nxa3+AabFEd7UxVWtsoJO6IZBbH+bxN7nH0VqdZPCW9xn\n=88gx\n-----END PGP PRIVATE KEY BLOCK-----\n\"\"\"\n\n message",
"end": 3445,
"score": 0.9975401759147644,
"start": 2875,
"tag": "KEY",
"value": "lNkEWNkCiRMFK4EEACMEIwQBsUDs05PSWR3j3/yfnG/MYq8tJwXUymCP6GPhuLn1\ng7FdKvxGvx9S9QEzMo3M6x2x515ywYrKhS6+GdaXhD/7vpcAUQdjLyzYWrHtE50q\nzoxUjQ3Z5rDeNF9+YAOwvntwWi5xsIVAsKbW/yWqq+YnazZmcYr3Oj5/61z69uvL\nsw7JX64AAgjz1cim3YvBwqnmNBnQeS5aLyO7QVBjjsOLrVWA1iGmXWokS7iVJYRP\n1zQJwHe2zft7N4L+bPiQPjjJsbqEsijFsiK9tAVCb2JieYi9BBMTCgAhBQJY2QKJ\nAhsDBQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEONJWG038qWKGYQCCQEbZzUx\n0qkMFdJXUvNIZ/nBU64SY+I1akBDKGdZ0uNSzi1pkwW8lUYngVLM806Ya1gxeYwz\nSxKAU1lV2N9T/OwMkgIJAWFarehjKORU145RHNlF6CDmtppxdYWu/7eN0VEjpZMm\nxa3+AabFEd7UxVWtsoJO6IZBbH+bxN7nH0VqdZPCW9xn\n=88gx"
},
{
"context": "----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\nHi Alice!\n-----BEGIN PGP SIGNATURE-----\n\niF4EARYIAAYFAljZA",
"end": 3559,
"score": 0.9943844079971313,
"start": 3554,
"tag": "NAME",
"value": "Alice"
},
{
"context": ": SHA256\n\nHi Alice!\n-----BEGIN PGP SIGNATURE-----\n\niF4EARYIAAYFAljZAscACgkQvLt/QaIN/MeyogEApVNXk3huA7BnMBka1FcMm3qy\nRDwSBZOCIiqrUdoX8FEBAMSoFWK+JFjurbSBFhJsU9IVoJRXok8Nx0ykF4tXeKEG\n=yUJK\n-----END PGP SIGNATURE-----\n\"\"\"\n\n class KeyRing ",
"end": 3727,
"score": 0.9655498266220093,
"start": 3592,
"tag": "KEY",
"value": "iF4EARYIAAYFAljZAscACgkQvLt/QaIN/MeyogEApVNXk3huA7BnMBka1FcMm3qy\nRDwSBZOCIiqrUdoX8FEBAMSoFWK+JFjurbSBFhJsU9IVoJRXok8Nx0ykF4tXeKEG\n=yUJK"
},
{
"context": "age verified\"\n T.assert outmsg?.toString() is \"Hi Alice!\"\n cb()\n\n\n",
"end": 4151,
"score": 0.9763269424438477,
"start": 4146,
"tag": "NAME",
"value": "Alice"
}
] | test/files/keyfetcher.iced | samkenxstream/kbpgp | 464 | {KeyManager} = require '../../'
{do_message} = require '../../lib/openpgp/processor'
{PgpKeyRing} = require '../../lib/keyring'
exports.verify_revoked_with_keyfetcher = (T, cb) ->
# There was a bug/API misuse where PgpKeyRing subclass would fetch a
# key from remote source and then call `super` to give control back
# to the base class. Revoked keys were not properly filtered out and
# were still returned from fetcher coded in this fashion, so they
# would have been used for verification and other operations.
key = """-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEWNU+YBYJKwYBBAHaRw8BAQdANDGlomfqnHvB2suF9Nsk27qprv4jyqUnGUxT
ezS17DyIYQQgFggACQUCWNU+6AIdAwAKCRByQpSZUUdJMCiQAQCA90BeuZfzJuEr
SzTT76qks97wmTYTCI2Tklnkgfw9UAD/WJMsBW93I8YERc6TaAM7Ikw/XxF/Llhb
WXmitXrgbQ+0ElJldm9rZWQgS2V5IFRlc3Rlcoh5BBMWCAAhBQJY1T5gAhsDBQsJ
CAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEHJClJlRR0kw3sEBAIc6PaPdgHIsi5Pz
xZkDfwVa76Mvb8yug8HIW9A9swmYAP0ZSASv7N+f6wZUSJAun9E7pnfaA0y+bVs4
Wk0U7dsXDrg4BFjVPmASCisGAQQBl1UBBQEBB0CLNBYcjHxNQGfO8fcyp+QtsC8P
d2dLxZR10SQnIaQWPAMBCAeIYQQYFggACQUCWNU+YAIbDAAKCRByQpSZUUdJMCot
AQDaW0YiRIN64fCmnSJFNZTqM1V1VE1tLktUxwT5uilB9QD+JcppXFBLPB0oSlMu
2LPpIrS71kVwXb+yF3Rr8c87uAE=
=aPLq
-----END PGP PUBLIC KEY BLOCK-----
"""
message = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
This message was signed by a key that is revoked. It should not pass verification.
-----BEGIN PGP SIGNATURE-----
iF4EARYIAAYFAljVPqgACgkQckKUmVFHSTB7SQEAn2D5cUbMp7/HTY+8v54uz7gL
V1lAVqcNiyy7Srus5/UBALbH5jUIR2kZamWO0znZ7+ltz42cmZ+OESnfHxa4KUUB
=+5R5
-----END PGP SIGNATURE-----
"""
now = Math.floor(new Date(2017, 4, 1)/1000)
class KeyRing extends PgpKeyRing
fetch: (key_ids, ops, cb) ->
opts = { now }
await KeyManager.import_from_armored_pgp { raw: key, opts }, defer err, km
@add_key_manager km
super key_ids, ops, cb
await do_message { keyfetch : new KeyRing(), armored : message, now }, defer err, outmsg
T.assert err, "Failed to verify"
T.equal err.name, "RevokedKeyError", "Proper error"
cb()
exports.verify_keyfetcher = (T, cb) ->
# Do similar test as above, but with key that is not expired.
keys = []
keys.push """-----BEGIN PGP PRIVATE KEY BLOCK-----
lFgEWNkB0RYJKwYBBAHaRw8BAQdA4hcG1GlHLKQu1e3wGlt1nYOnanUIDZ+khCKC
jCsK5NYAAP4nvoBNpeP4MY36+z9YDh+ErdxWaMzCmGCHdMjydARScRHotAVBbGlj
ZYh5BBMWCAAhBQJY2QHRAhsDBQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJELy7
f0GiDfzHy1gA/jdhdJf909xthPBDQsrwqISP4dLTWuC3BVSS6EKA9NPwAP9rJr8r
exCp67hEbgh3DW6PvRTE98uQ2xq9DwsE20/kBJxdBFjZAdESCisGAQQBl1UBBQEB
B0CLllnTNJJe8P6LegVgpvQcf4HNP5saxm5KKWIYCaowWQMBCAcAAP9hVRqTSXVt
JZMEQbb+cifABP4nV0u5rqDhl6s+iwiBeA9WiGEEGBYIAAkFAljZAdECGwwACgkQ
vLt/QaIN/MdpZwEA/nnrXhSvAQ/5vgRxE1MEgCtjqlUf4wBjOu/k+LhFcWUBAO2i
25EtZWVtDKcJfQILvethtIglGMk8Dc3dcH9FSywC
=LH1D
-----END PGP PRIVATE KEY BLOCK-----
"""
keys.push """-----BEGIN PGP PRIVATE KEY BLOCK-----
lNkEWNkCiRMFK4EEACMEIwQBsUDs05PSWR3j3/yfnG/MYq8tJwXUymCP6GPhuLn1
g7FdKvxGvx9S9QEzMo3M6x2x515ywYrKhS6+GdaXhD/7vpcAUQdjLyzYWrHtE50q
zoxUjQ3Z5rDeNF9+YAOwvntwWi5xsIVAsKbW/yWqq+YnazZmcYr3Oj5/61z69uvL
sw7JX64AAgjz1cim3YvBwqnmNBnQeS5aLyO7QVBjjsOLrVWA1iGmXWokS7iVJYRP
1zQJwHe2zft7N4L+bPiQPjjJsbqEsijFsiK9tAVCb2JieYi9BBMTCgAhBQJY2QKJ
AhsDBQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEONJWG038qWKGYQCCQEbZzUx
0qkMFdJXUvNIZ/nBU64SY+I1akBDKGdZ0uNSzi1pkwW8lUYngVLM806Ya1gxeYwz
SxKAU1lV2N9T/OwMkgIJAWFarehjKORU145RHNlF6CDmtppxdYWu/7eN0VEjpZMm
xa3+AabFEd7UxVWtsoJO6IZBbH+bxN7nH0VqdZPCW9xn
=88gx
-----END PGP PRIVATE KEY BLOCK-----
"""
message = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
Hi Alice!
-----BEGIN PGP SIGNATURE-----
iF4EARYIAAYFAljZAscACgkQvLt/QaIN/MeyogEApVNXk3huA7BnMBka1FcMm3qy
RDwSBZOCIiqrUdoX8FEBAMSoFWK+JFjurbSBFhJsU9IVoJRXok8Nx0ykF4tXeKEG
=yUJK
-----END PGP SIGNATURE-----
"""
class KeyRing extends PgpKeyRing
fetch: (key_ids, ops, cb) ->
for key in keys
await KeyManager.import_from_armored_pgp { raw: key }, defer err, km
@add_key_manager km
super key_ids, ops, cb
await do_message { keyfetch : new KeyRing(), armored : message }, defer err, outmsg
T.no_error err, "Message verified"
T.assert outmsg?.toString() is "Hi Alice!"
cb()
| 57029 | {KeyManager} = require '../../'
{do_message} = require '../../lib/openpgp/processor'
{PgpKeyRing} = require '../../lib/keyring'
exports.verify_revoked_with_keyfetcher = (T, cb) ->
# There was a bug/API misuse where PgpKeyRing subclass would fetch a
# key from remote source and then call `super` to give control back
# to the base class. Revoked keys were not properly filtered out and
# were still returned from fetcher coded in this fashion, so they
# would have been used for verification and other operations.
key = """-----BEGIN PGP PUBLIC KEY BLOCK-----
<KEY>M1V1<KEY>1tLktUxwT<KEY>uilB9QD+JcppXFBLPB0oSlMu
2LPpIrS71kVwXb+yF3Rr8c87uAE=
=aPLq
-----END PGP PUBLIC KEY BLOCK-----
"""
message = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
This message was signed by a key that is revoked. It should not pass verification.
-----BEGIN PGP SIGNATURE-----
<KEY>
=+<KEY>R5
-----END PGP SIGNATURE-----
"""
now = Math.floor(new Date(2017, 4, 1)/1000)
class KeyRing extends PgpKeyRing
fetch: (key_ids, ops, cb) ->
opts = { now }
await KeyManager.import_from_armored_pgp { raw: key, opts }, defer err, km
@add_key_manager km
super key_ids, ops, cb
await do_message { keyfetch : new KeyRing(), armored : message, now }, defer err, outmsg
T.assert err, "Failed to verify"
T.equal err.name, "RevokedKeyError", "Proper error"
cb()
exports.verify_keyfetcher = (T, cb) ->
# Do similar test as above, but with key that is not expired.
keys = []
keys.push """-----BEGIN PGP PRIVATE KEY BLOCK-----
<KEY>
-----END PGP PRIVATE KEY BLOCK-----
"""
keys.push """-----BEGIN PGP PRIVATE KEY BLOCK-----
<KEY>
-----END PGP PRIVATE KEY BLOCK-----
"""
message = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
Hi <NAME>!
-----BEGIN PGP SIGNATURE-----
<KEY>
-----END PGP SIGNATURE-----
"""
class KeyRing extends PgpKeyRing
fetch: (key_ids, ops, cb) ->
for key in keys
await KeyManager.import_from_armored_pgp { raw: key }, defer err, km
@add_key_manager km
super key_ids, ops, cb
await do_message { keyfetch : new KeyRing(), armored : message }, defer err, outmsg
T.no_error err, "Message verified"
T.assert outmsg?.toString() is "Hi <NAME>!"
cb()
| true | {KeyManager} = require '../../'
{do_message} = require '../../lib/openpgp/processor'
{PgpKeyRing} = require '../../lib/keyring'
exports.verify_revoked_with_keyfetcher = (T, cb) ->
# There was a bug/API misuse where PgpKeyRing subclass would fetch a
# key from remote source and then call `super` to give control back
# to the base class. Revoked keys were not properly filtered out and
# were still returned from fetcher coded in this fashion, so they
# would have been used for verification and other operations.
key = """-----BEGIN PGP PUBLIC KEY BLOCK-----
PI:KEY:<KEY>END_PIM1V1PI:KEY:<KEY>END_PI1tLktUxwTPI:KEY:<KEY>END_PIuilB9QD+JcppXFBLPB0oSlMu
2LPpIrS71kVwXb+yF3Rr8c87uAE=
=aPLq
-----END PGP PUBLIC KEY BLOCK-----
"""
message = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
This message was signed by a key that is revoked. It should not pass verification.
-----BEGIN PGP SIGNATURE-----
PI:KEY:<KEY>END_PI
=+PI:KEY:<KEY>END_PIR5
-----END PGP SIGNATURE-----
"""
now = Math.floor(new Date(2017, 4, 1)/1000)
class KeyRing extends PgpKeyRing
fetch: (key_ids, ops, cb) ->
opts = { now }
await KeyManager.import_from_armored_pgp { raw: key, opts }, defer err, km
@add_key_manager km
super key_ids, ops, cb
await do_message { keyfetch : new KeyRing(), armored : message, now }, defer err, outmsg
T.assert err, "Failed to verify"
T.equal err.name, "RevokedKeyError", "Proper error"
cb()
exports.verify_keyfetcher = (T, cb) ->
# Do similar test as above, but with key that is not expired.
keys = []
keys.push """-----BEGIN PGP PRIVATE KEY BLOCK-----
PI:KEY:<KEY>END_PI
-----END PGP PRIVATE KEY BLOCK-----
"""
keys.push """-----BEGIN PGP PRIVATE KEY BLOCK-----
PI:KEY:<KEY>END_PI
-----END PGP PRIVATE KEY BLOCK-----
"""
message = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
Hi PI:NAME:<NAME>END_PI!
-----BEGIN PGP SIGNATURE-----
PI:KEY:<KEY>END_PI
-----END PGP SIGNATURE-----
"""
class KeyRing extends PgpKeyRing
fetch: (key_ids, ops, cb) ->
for key in keys
await KeyManager.import_from_armored_pgp { raw: key }, defer err, km
@add_key_manager km
super key_ids, ops, cb
await do_message { keyfetch : new KeyRing(), armored : message }, defer err, outmsg
T.no_error err, "Message verified"
T.assert outmsg?.toString() is "Hi PI:NAME:<NAME>END_PI!"
cb()
|
[
{
"context": " \n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) \n# ",
"end": 824,
"score": 0.9997847080230713,
"start": 814,
"tag": "NAME",
"value": "Mark Masse"
}
] | wrmldoc/js/app/apps/model/ModelApp.coffee | wrml/wrml | 47 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# CoffeeScript
@Wrmldoc.module "ModelApp", (ModelApp, App, Backbone, Marionette, $, _) ->
@startWithParent = false
class ModelApp.Router extends Marionette.AppRouter
# appRoutes:
# ":uri/edit" : "edit"
# ":uri" : "show"
#API =
# show: (dataModel) ->
# new ModelApp.Show.Controller(dataModel)
#region: App.mainRegion
#App.addInitializer ->
# new ModelApp.Router
# controller: API
@showView = (dataModel) ->
@controller = new ModelApp.Show.Controller(dataModel)
@saveDocument = ->
@controller.saveDocument()
ModelApp.on "start", (dataModel) ->
@showView(dataModel)
#newModel: (region) ->
# new ModelApp.New.Controller
# region: region
#edit: (uri, model) ->
# new ModelApp.Edit.Controller
# uri: uri
# model: model
#App.commands.setHandler "new:model", (region) ->
# API.newModel region
#App.vent.on "model:clicked model:created", (model) ->
# App.navigate model.uri
# API.edit model.uri, model
#App.vent.on "model:cancelled model:updated", (model) ->
# App.navigate model.uri
# API.show()
| 27894 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 <NAME> (OSS project WRML.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# CoffeeScript
@Wrmldoc.module "ModelApp", (ModelApp, App, Backbone, Marionette, $, _) ->
@startWithParent = false
class ModelApp.Router extends Marionette.AppRouter
# appRoutes:
# ":uri/edit" : "edit"
# ":uri" : "show"
#API =
# show: (dataModel) ->
# new ModelApp.Show.Controller(dataModel)
#region: App.mainRegion
#App.addInitializer ->
# new ModelApp.Router
# controller: API
@showView = (dataModel) ->
@controller = new ModelApp.Show.Controller(dataModel)
@saveDocument = ->
@controller.saveDocument()
ModelApp.on "start", (dataModel) ->
@showView(dataModel)
#newModel: (region) ->
# new ModelApp.New.Controller
# region: region
#edit: (uri, model) ->
# new ModelApp.Edit.Controller
# uri: uri
# model: model
#App.commands.setHandler "new:model", (region) ->
# API.newModel region
#App.vent.on "model:clicked model:created", (model) ->
# App.navigate model.uri
# API.edit model.uri, model
#App.vent.on "model:cancelled model:updated", (model) ->
# App.navigate model.uri
# API.show()
| true | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 PI:NAME:<NAME>END_PI (OSS project WRML.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# CoffeeScript
@Wrmldoc.module "ModelApp", (ModelApp, App, Backbone, Marionette, $, _) ->
@startWithParent = false
class ModelApp.Router extends Marionette.AppRouter
# appRoutes:
# ":uri/edit" : "edit"
# ":uri" : "show"
#API =
# show: (dataModel) ->
# new ModelApp.Show.Controller(dataModel)
#region: App.mainRegion
#App.addInitializer ->
# new ModelApp.Router
# controller: API
@showView = (dataModel) ->
@controller = new ModelApp.Show.Controller(dataModel)
@saveDocument = ->
@controller.saveDocument()
ModelApp.on "start", (dataModel) ->
@showView(dataModel)
#newModel: (region) ->
# new ModelApp.New.Controller
# region: region
#edit: (uri, model) ->
# new ModelApp.Edit.Controller
# uri: uri
# model: model
#App.commands.setHandler "new:model", (region) ->
# API.newModel region
#App.vent.on "model:clicked model:created", (model) ->
# App.navigate model.uri
# API.edit model.uri, model
#App.vent.on "model:cancelled model:updated", (model) ->
# App.navigate model.uri
# API.show()
|
[
{
"context": "ocument.activeElement.\n # See https://github.com/unpoly/unpoly/issues/103\n up.on 'up:click', submitButto",
"end": 10138,
"score": 0.9993040561676025,
"start": 10132,
"tag": "USERNAME",
"value": "unpoly"
},
{
"context": "andle the form.\n # https://groups.google.com/g/unpoly/c/wsiATxepVZk\n form = e.closest(button, 'form'",
"end": 10338,
"score": 0.8933992981910706,
"start": 10332,
"tag": "USERNAME",
"value": "unpoly"
},
{
"context": "\n <label>\n Password: <input type=\"password\" name=\"password\" />\n </label>\n\n <bu",
"end": 25613,
"score": 0.9988610744476318,
"start": 25605,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\n Password: <input type=\"password\" name=\"password\" />\n </label>\n\n <button type=\"submi",
"end": 25629,
"score": 0.9987633228302002,
"start": 25621,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\n <label>\n Password: <input type=\"password\" name=\"password\" up-validate />\n </label>\n",
"end": 26177,
"score": 0.996536910533905,
"start": 26169,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " E-mail: <input type=\"text\" name=\"email\" value=\"foo@bar.com\" />\n Has already been taken!\n </l",
"end": 27576,
"score": 0.9999041557312012,
"start": 27565,
"tag": "EMAIL",
"value": "foo@bar.com"
}
] | lib/assets/javascripts/unpoly/form.coffee | pfw/unpoly | 0 | ###**
Forms
=====
The `up.form` module helps you work with non-trivial forms.
@see form[up-submit]
@see form[up-validate]
@see input[up-switch]
@see form[up-autosubmit]
@module up.form
###
up.form = do ->
u = up.util
e = up.element
ATTRIBUTES_SUGGESTING_SUBMIT = ['[up-submit]', '[up-target]', '[up-layer]', '[up-transition]']
###**
Sets default options for form submission and validation.
@property up.form.config
@param {number} [config.observeDelay=0]
The number of miliseconds to wait before [`up.observe()`](/up.observe) runs the callback
after the input value changes. Use this to limit how often the callback
will be invoked for a fast typist.
@param {Array<string>} [config.submitSelectors]
An array of CSS selectors matching forms that will be [submitted through Unpoly](/form-up-follow).
You can configure Unpoly to handle *all* forms on a page without requiring an `[up-submit]` attribute:
```js
up.form.config.submitSelectors.push('form']
```
Individual forms may opt out with an `[up-submit=follow]` attribute.
You may configure additional exceptions in `config.noSubmitSelectors`.
@param {Array<string>} [config.noSubmitSelectors]
Exceptions to `config.submitSelectors`.
Matching forms will *not* be [submitted through Unpoly](/form-up-submit), even if they match `config.submitSelectors`.
@param {Array<string>} [config.validateTargets=['[up-fieldset]:has(&)', 'fieldset:has(&)', 'label:has(&)', 'form:has(&)']]
An array of CSS selectors that are searched around a form field
that wants to [validate](/up.validate).
The first matching selector will be updated with the validation messages from the server.
By default this looks for a `<fieldset>`, `<label>` or `<form>`
around the validating input field.
@param {string} [config.fieldSelectors]
An array of CSS selectors that represent form fields, such as `input` or `select`.
@param {string} [config.submitButtonSelectors]
An array of CSS selectors that represent submit buttons, such as `input[type=submit]`.
@stable
###
config = new up.Config ->
validateTargets: ['[up-fieldset]:has(:origin)', 'fieldset:has(:origin)', 'label:has(:origin)', 'form:has(:origin)']
fieldSelectors: ['select', 'input:not([type=submit]):not([type=image])', 'button[type]:not([type=submit])', 'textarea'],
submitSelectors: up.link.combineFollowableSelectors(['form'], ATTRIBUTES_SUGGESTING_SUBMIT)
noSubmitSelectors: ['[up-submit=false]', '[target]']
submitButtonSelectors: ['input[type=submit]', 'input[type=image]', 'button[type=submit]', 'button:not([type])']
observeDelay: 0
fullSubmitSelector = ->
config.submitSelectors.join(',')
abortScheduledValidate = null
reset = ->
config.reset()
###**
@function up.form.fieldSelector
@internal
###
fieldSelector = (suffix = '') ->
config.fieldSelectors.map((field) -> field + suffix).join(',')
###**
Returns a list of form fields within the given element.
You can configure what Unpoly considers a form field by adding CSS selectors to the
`up.form.config.fieldSelectors` array.
If the given element is itself a form field, a list of that given element is returned.
@function up.form.fields
@param {Element|jQuery} root
The element to scan for contained form fields.
If the element is itself a form field, a list of that element is returned.
@return {NodeList<Element>|Array<Element>}
@experimental
###
findFields = (root) ->
root = e.get(root) # unwrap jQuery
fields = e.subtree(root, fieldSelector())
# If findFields() is called with an entire form, gather fields outside the form
# element that are associated with the form (through <input form="id-of-form">, which
# is an HTML feature.)
if e.matches(root, 'form[id]')
outsideFieldSelector = fieldSelector(e.attributeSelector('form', root.getAttribute('id')))
outsideFields = e.all(outsideFieldSelector)
fields.push(outsideFields...)
fields = u.uniq(fields)
fields
###**
@function up.form.submittingButton
@param {Element} form
@internal
###
submittingButton = (form) ->
selector = submitButtonSelector()
focusedElement = document.activeElement
if focusedElement && e.matches(focusedElement, selector) && form.contains(focusedElement)
return focusedElement
else
# If no button is focused, we assume the first button in the form.
return e.get(form, selector)
###**
@function up.form.submitButtonSelector
@internal
###
submitButtonSelector = ->
config.submitButtonSelectors.join(',')
###**
Submits a form via AJAX and updates a page fragment with the response.
up.submit('form.new-user', { target: '.main' })
Instead of loading a new page, the form is submitted via AJAX.
The response is parsed for a CSS selector and the matching elements will
replace corresponding elements on the current page.
The unobtrusive variant of this is the `form[up-submit]` selector.
See its documentation to learn how form submissions work in Unpoly.
Submitting a form is considered [navigation](/navigation).
Emits the event [`up:form:submit`](/up:form:submit).
@function up.submit
@param {Element|jQuery|string} form
The form to submit.
If the argument points to an element that is not a form,
Unpoly will search its ancestors for the [closest](/up.fragment.closest) form.
@param {Object} [options]
[Render options](/up.render) that should be used for submitting the form.
Unpoly will parse render options from the given form's attributes
like `[up-target]` or `[up-transition]`. See `form[up-submit]` for a list
of supported attributes.
You may pass this additional `options` object to supplement or override
options parsed from the form attributes.
@return {Promise<up.RenderResult>}
A promise that will be fulfilled when the server response was rendered.
@stable
###
submit = up.mockable (form, options) ->
return up.render(submitOptions(form, options))
###**
Parses the [render](/up.render) options that would be used to
[`submit`](/up.submit) the given form, but does not render.
\#\#\# Example
Given a form element:
```html
<form action="/foo" method="post" up-target=".content">
...
</form>
```
We can parse the link's render options like this:
```js
let form = document.querySelector('form')
let options = up.form.submitOptions(form)
// => { url: '/foo', method: 'POST', target: '.content', ... }
```
@param {Element|jQuery|string} form
The form to submit.
@param {Object} [options]
Additional options for the form submission.
Will override any attribute values set on the given form element.
See `up.render()` for detailed documentation of individual option properties.
@function up.form.submitOptions
@return {Object}
@stable
###
submitOptions = (form, options) ->
options = u.options(options)
form = up.fragment.get(form)
form = e.closest(form, 'form')
parser = new up.OptionsParser(options, form)
# Parse params from form fields.
params = up.Params.fromForm(form)
if submitButton = submittingButton(form)
# Submit buttons with a [name] attribute will add to the params.
# Note that addField() will only add an entry if the given button has a [name] attribute.
params.addField(submitButton)
# Submit buttons may have [formmethod] and [formaction] attribute
# that override [method] and [action] attribute from the <form> element.
options.method ||= submitButton.getAttribute('formmethod')
options.url ||= submitButton.getAttribute('formaction')
params.addAll(options.params)
options.params = params
parser.string('url', attr: 'action', default: up.fragment.source(form))
parser.string('method', attr: ['up-method', 'data-method', 'method'], default: 'GET', normalize: u.normalizeMethod)
if options.method == 'GET'
# Only for GET forms, browsers discard all query params from the form's [action] URL.
# The URLs search part will be replaced with the serialized form data.
# See design/query-params-in-form-actions/cases.html for
# a demo of vanilla browser behavior.
options.url = up.Params.stripURL(options.url)
parser.string('failTarget', default: up.fragment.toTarget(form))
# The guardEvent will also be assigned an { renderOptions } property in up.render()
options.guardEvent ||= up.event.build('up:form:submit', log: 'Submitting form')
# Now that we have extracted everything form-specific into options, we can call
# up.link.followOptions(). This will also parse the myriads of other options
# that are possible on both <form> and <a> elements.
u.assign(options, up.link.followOptions(form, options))
return options
###**
This event is [emitted](/up.emit) when a form is [submitted](/up.submit) through Unpoly.
The event is emitted on the `<form>` element.
When the form is being [validated](/input-up-validate), this event is not emitted.
Instead an `up:form:validate` event is emitted.
\#\#\# Changing render options
Listeners may inspect and manipulate [render options](/up.render) for the coming fragment update.
The code below will use a custom [transition](/up-transition)
when a form submission [fails](/server-errors):
```js
up.on('up:form:submit', function(event, form) {
event.renderOptions.failTransition = 'shake'
})
```
@event up:form:submit
@param {Element} event.target
The `<form>` element that will be submitted.
@param {Object} event.renderOptions
An object with [render options](/up.render) for the fragment update
Listeners may inspect and modify these options.
@param event.preventDefault()
Event listeners may call this method to prevent the form from being submitted.
@stable
###
# MacOS does not focus buttons on click.
# That means that submittingButton() cannot rely on document.activeElement.
# See https://github.com/unpoly/unpoly/issues/103
up.on 'up:click', submitButtonSelector, (event, button) ->
# Don't mess with focus unless we know that we're going to handle the form.
# https://groups.google.com/g/unpoly/c/wsiATxepVZk
form = e.closest(button, 'form')
if form && isSubmittable(form)
button.focus()
###**
Observes form fields and runs a callback when a value changes.
This is useful for observing text fields while the user is typing.
The unobtrusive variant of this is the [`[up-observe]`](/up-observe) attribute.
\#\#\# Example
The following would print to the console whenever an input field changes:
up.observe('input.query', function(value) {
console.log('Query is now %o', value)
})
Instead of a single form field, you can also pass multiple fields,
a `<form>` or any container that contains form fields.
The callback will be run if any of the given fields change:
up.observe('form', function(value, name) {
console.log('The value of %o is now %o', name, value)
})
You may also pass the `{ batch: true }` option to receive all
changes since the last callback in a single object:
up.observe('form', { batch: true }, function(diff) {
console.log('Observed one or more changes: %o', diff)
})
@function up.observe
@param {string|Element|Array<Element>|jQuery} elements
The form fields that will be observed.
You can pass one or more fields, a `<form>` or any container that contains form fields.
The callback will be run if any of the given fields change.
@param {boolean} [options.batch=false]
If set to `true`, the `onChange` callback will receive multiple
detected changes in a single diff object as its argument.
@param {number} [options.delay=up.form.config.observeDelay]
The number of miliseconds to wait before executing the callback
after the input value changes. Use this to limit how often the callback
will be invoked for a fast typist.
@param {Function(value, name): string} onChange
The callback to run when the field's value changes.
If given as a function, it receives two arguments (`value`, `name`).
`value` is a string with the new attribute value and `string` is the name
of the form field that changed. If given as a string, it will be evaled as
JavaScript code in a context where (`value`, `name`) are set.
A long-running callback function may return a promise that settles when
the callback completes. In this case the callback will not be called again while
it is already running.
@return {Function()}
A destructor function that removes the observe watch when called.
@stable
###
observe = (elements, args...) ->
elements = e.list(elements)
fields = u.flatMap(elements, findFields)
callback = u.extractCallback(args) ? observeCallbackFromElement(elements[0]) ? up.fail('up.observe: No change callback given')
options = u.extractOptions(args)
options.delay = options.delay ? e.numberAttr(elements[0], 'up-delay') ? config.observeDelay
observer = new up.FieldObserver(fields, options, callback)
observer.start()
return -> observer.stop()
observeCallbackFromElement = (element) ->
if rawCallback = element.getAttribute('up-observe')
new Function('value', 'name', rawCallback)
###**
[Observes](/up.observe) a field or form and submits the form when a value changes.
Both the form and the changed field will be assigned a CSS class [`.up-active`](/form-up-active)
while the autosubmitted form is processing.
The unobtrusive variant of this is the [`[up-autosubmit]`](/form-up-autosubmit) attribute.
@function up.autosubmit
@param {string|Element|jQuery} target
The field or form to observe.
@param {Object} [options]
See options for [`up.observe()`](/up.observe)
@return {Function()}
A destructor function that removes the observe watch when called.
@stable
###
autosubmit = (target, options) ->
observe(target, options, -> submit(target))
findValidateTarget = (element, options) ->
container = getContainer(element)
if u.isElementish(options.target)
return up.fragment.toTarget(options.target)
else if givenTarget = options.target || element.getAttribute('up-validate') || container.getAttribute('up-validate')
return givenTarget
else if e.matches(element, 'form')
# If element is the form, we cannot find a better validate target than this.
return up.fragment.toTarget(element)
else
return findValidateTargetFromConfig(element, options) || up.fail('Could not find validation target for %o (tried defaults %o)', element, config.validateTargets)
findValidateTargetFromConfig = (element, options) ->
# for the first selector that has a match in the field's layer.
layer = up.layer.get(element)
return u.findResult config.validateTargets, (defaultTarget) ->
if up.fragment.get(defaultTarget, u.merge(options, { layer }))
# We want to return the selector, *not* the element. If we returned the element
# and derive a selector from that, any :has() expression would be lost.
return defaultTarget
###**
Performs a server-side validation of a form field.
`up.validate()` submits the given field's form with an additional `X-Up-Validate`
HTTP header. Upon seeing this header, the server is expected to validate (but not save)
the form submission and render a new copy of the form with validation errors.
The unobtrusive variant of this is the [`input[up-validate]`](/input-up-validate) selector.
See the documentation for [`input[up-validate]`](/input-up-validate) for more information
on how server-side validation works in Unpoly.
\#\#\# Example
```js
up.validate('input[name=email]', { target: '.email-errors' })
```
@function up.validate
@param {string|Element|jQuery} field
The form field to validate.
@param {string|Element|jQuery} [options.target]
The element that will be [updated](/up.render) with the validation results.
@return {Promise}
A promise that fulfills when the server-side
validation is received and the form was updated.
@stable
###
validate = (field, options) ->
# If passed a selector, up.fragment.get() will prefer a match on the current layer.
field = up.fragment.get(field)
options = u.options(options)
options.navigate = false
options.origin = field
options.history = false
options.target = findValidateTarget(field, options)
options.focus = 'keep'
# The protocol doesn't define whether the validation results in a status code.
# Hence we use the same options for both success and failure.
options.fail = false
# Make sure the X-Up-Validate header is present, so the server-side
# knows that it should not persist the form submission
options.headers ||= {}
options.headers[up.protocol.headerize('validate')] = field.getAttribute('name') || ':unknown'
# The guardEvent will also be assigned a { renderOptions } attribute in up.render()
options.guardEvent = up.event.build('up:form:validate', { field, log: 'Validating form' })
return submit(field, options)
###**
This event is emitted before a field is being [validated](/input-up-validate).
@event up:form:validate
@param {Element} event.field
The form field that has been changed and caused the validated request.
@param {Object} event.renderOptions
An object with [render options](/up.render) for the fragment update
that will show the validation results.
Listeners may inspect and modify these options.
@param event.preventDefault()
Event listeners may call this method to prevent the validation request
being sent to the server.
@stable
###
switcherValues = (field) ->
value = undefined
meta = undefined
if e.matches(field, 'input[type=checkbox]')
if field.checked
value = field.value
meta = ':checked'
else
meta = ':unchecked'
else if e.matches(field, 'input[type=radio]')
form = getContainer(field)
groupName = field.getAttribute('name')
checkedButton = form.querySelector("input[type=radio]#{e.attributeSelector('name', groupName)}:checked")
if checkedButton
meta = ':checked'
value = checkedButton.value
else
meta = ':unchecked'
else
value = field.value
values = []
if u.isPresent(value)
values.push(value)
values.push(':present')
else
values.push(':blank')
if u.isPresent(meta)
values.push(meta)
values
###**
Shows or hides a target selector depending on the value.
See [`input[up-switch]`](/input-up-switch) for more documentation and examples.
This function does not currently have a very useful API outside
of our use for `up-switch`'s UJS behavior, that's why it's currently
still marked `@internal`.
@function up.form.switchTargets
@param {Element} switcher
@param {string} [options.target]
The target selectors to switch.
Defaults to an `[up-switch]` attribute on the given field.
@internal
###
switchTargets = (switcher, options = {}) ->
targetSelector = options.target ? switcher.getAttribute('up-switch')
form = getContainer(switcher)
targetSelector or up.fail("No switch target given for %o", switcher)
fieldValues = switcherValues(switcher)
u.each e.all(form, targetSelector), (target) ->
switchTarget(target, fieldValues)
###**
@internal
###
switchTarget = up.mockable (target, fieldValues) ->
fieldValues ||= switcherValues(findSwitcherForTarget(target))
if hideValues = target.getAttribute('up-hide-for')
hideValues = u.splitValues(hideValues)
show = u.intersect(fieldValues, hideValues).length == 0
else
if showValues = target.getAttribute('up-show-for')
showValues = u.splitValues(showValues)
else
# If the target has neither up-show-for or up-hide-for attributes,
# assume the user wants the target to be visible whenever anything
# is checked or entered.
showValues = [':present', ':checked']
show = u.intersect(fieldValues, showValues).length > 0
e.toggle(target, show)
target.classList.add('up-switched')
###**
@internal
###
findSwitcherForTarget = (target) ->
form = getContainer(target)
switchers = e.all(form, '[up-switch]')
switcher = u.find switchers, (switcher) ->
targetSelector = switcher.getAttribute('up-switch')
e.matches(target, targetSelector)
return switcher or up.fail('Could not find [up-switch] field for %o', target)
getContainer = (element) ->
element.form || # Element#form will also work if the element is outside the form with an [form=form-id] attribute
e.closest(element, "form, #{up.layer.anySelector()}")
focusedField = ->
if (element = document.activeElement) && e.matches(element, fieldSelector())
return element
###**
Returns whether the given form will be [submitted](/up.follow) through Unpoly
instead of making a full page load.
By default Unpoly will follow forms if the element has
one of the following attributes:
- `[up-submit]`
- `[up-target]`
- `[up-layer]`
- `[up-transition]`
To consider other selectors to be submittable, see `up.form.config.submitSelectors`.
@function up.form.isSubmittable
@param {Element|jQuery|string} form
The form to check.
@stable
###
isSubmittable = (form) ->
form = up.fragment.get(form)
return e.matches(form, fullSubmitSelector()) && !isSubmitDisabled(form)
isSubmitDisabled = (form) ->
# We also don't want to handle cross-origin forms.
# That will be handled in `up.Change.FromURL#newPageReason`.
return e.matches(form, config.noSubmitSelectors.join(','))
###**
Submits this form via JavaScript and updates a fragment with the server response.
The server response is searched for the selector given in `up-target`.
The selector content is then [replaced](/up.replace) in the current page.
The programmatic variant of this is the [`up.submit()`](/up.submit) function.
\#\#\# Example
```html
<form method="post" action="/users" up-submit>
...
</form>
```
\#\#\# Handling validation errors
When the server was unable to save the form due to invalid params,
it will usually re-render an updated copy of the form with
validation messages.
For Unpoly to be able to detect a failed form submission,
the form must be re-rendered with a non-200 HTTP status code.
We recommend to use either 400 (bad request) or
422 (unprocessable entity).
In Ruby on Rails, you can pass a
[`:status` option to `render`](http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option)
for this:
```ruby
class UsersController < ApplicationController
def create
user_params = params[:user].permit(:email, :password)
@user = User.new(user_params)
if @user.save?
sign_in @user
else
render 'form', status: :bad_request
end
end
end
```
You may define different option for the failure case by infixing an attribute with `fail`:
```html
<form method="post" action="/action"
up-target=".content"
up-fail-target="form"
up-scroll="auto"
up-fail-scroll=".errors">
...
</form>
```
See [handling server errors](/server-errors) for details.
Note that you can also use
[`input[up-validate]`](/input-up-validate) to perform server-side
validations while the user is completing fields.
\#\#\# Giving feedback while the form is processing
The `<form>` element will be assigned a CSS class [`.up-active`](/form.up-active) while
the submission is loading.
\#\#\# Short notation
You may omit the `[up-submit]` attribute if the form has one of the following attributes:
- `[up-target]`
- `[up-layer]`
- `[up-transition]`
Such a form will still be submitted through Unpoly.
\#\#\# Handling all forms automatically
You can configure Unpoly to handle *all* forms on a page without requiring an `[up-submit]` attribute.
See [Handling all links and forms](/handling-everything).
@selector form[up-submit]
@params-note
All attributes for `a[up-follow]` may also be used.
@stable
###
up.on 'submit', fullSubmitSelector, (event, form) ->
# Users may configure up.form.config.submitSelectors.push('form')
# and then opt out individual forms with [up-submit=false].
if event.defaultPrevented || isSubmitDisabled(form)
return
abortScheduledValidate?()
up.event.halt(event)
up.log.muteUncriticalRejection submit(form)
###**
When a form field with this attribute is changed, the form is validated on the server
and is updated with validation messages.
To validate the form, Unpoly will submit the form with an additional `X-Up-Validate` HTTP header.
When seeing this header, the server is expected to validate (but not save)
the form submission and render a new copy of the form with validation errors.
The programmatic variant of this is the [`up.validate()`](/up.validate) function.
\#\#\# Example
Let's look at a standard registration form that asks for an e-mail and password:
<form action="/users">
<label>
E-mail: <input type="text" name="email" />
</label>
<label>
Password: <input type="password" name="password" />
</label>
<button type="submit">Register</button>
</form>
When the user changes the `email` field, we want to validate that
the e-mail address is valid and still available. Also we want to
change the `password` field for the minimum required password length.
We can do this by giving both fields an `up-validate` attribute:
<form action="/users">
<label>
E-mail: <input type="text" name="email" up-validate />
</label>
<label>
Password: <input type="password" name="password" up-validate />
</label>
<button type="submit">Register</button>
</form>
Whenever a field with `up-validate` changes, the form is POSTed to
`/users` with an additional `X-Up-Validate` HTTP header.
When seeing this header, the server is expected to validate (but not save)
the form submission and render a new copy of the form with validation errors.
In Ruby on Rails the processing action should behave like this:
class UsersController < ApplicationController
# This action handles POST /users
def create
user_params = params[:user].permit(:email, :password)
@user = User.new(user_params)
if request.headers['X-Up-Validate']
@user.valid? # run validations, but don't save to the database
render 'form' # render form with error messages
elsif @user.save?
sign_in @user
else
render 'form', status: :bad_request
end
end
end
Note that if you're using the `unpoly-rails` gem you can simply say `up.validate?`
instead of manually checking for `request.headers['X-Up-Validate']`.
The server now renders an updated copy of the form with eventual validation errors:
<form action="/users">
<label class="has-error">
E-mail: <input type="text" name="email" value="foo@bar.com" />
Has already been taken!
</label>
<button type="submit">Register</button>
</form>
The `<label>` around the e-mail field is now updated to have the `has-error`
class and display the validation message.
\#\#\# How validation results are displayed
Although the server will usually respond to a validation with a complete,
fresh copy of the form, Unpoly will by default not update the entire form.
This is done in order to preserve volatile state such as the scroll position
of `<textarea>` elements.
By default Unpoly looks for a `<fieldset>`, `<label>` or `<form>`
around the validating input field, or any element with an
`up-fieldset` attribute.
With the Bootstrap bindings, Unpoly will also look
for a container with the `form-group` class.
You can change this default behavior by setting `up.form.config.validateTargets`:
// Always update the entire form containing the current field ("&")
up.form.config.validateTargets = ['form &']
You can also individually override what to update by setting the `up-validate`
attribute to a CSS selector:
<input type="text" name="email" up-validate=".email-errors">
<span class="email-errors"></span>
\#\#\# Updating dependent fields
The `[up-validate]` behavior is also a great way to partially update a form
when one fields depends on the value of another field.
Let's say you have a form with one `<select>` to pick a department (sales, engineering, ...)
and another `<select>` to pick an employeee from the selected department:
<form action="/contracts">
<select name="department">...</select> <!-- options for all departments -->
<select name="employeed">...</select> <!-- options for employees of selected department -->
</form>
The list of employees needs to be updated as the appartment changes:
<form action="/contracts">
<select name="department" up-validate="[name=employee]">...</select>
<select name="employee">...</select>
</form>
In order to update the `department` field in addition to the `employee` field, you could say
`up-validate="&, [name=employee]"`, or simply `up-validate="form"` to update the entire form.
@selector input[up-validate]
@param up-validate
The CSS selector to update with the server response.
This defaults to a fieldset or form group around the validating field.
@stable
###
###**
Validates this form on the server when any field changes and shows validation errors.
You can configure what Unpoly considers a fieldset by adding CSS selectors to the
`up.form.config.validateTargets` array.
See `input[up-validate]` for detailed documentation.
@selector form[up-validate]
@param up-validate
The CSS selector to update with the server response.
This defaults to a fieldset or form group around the changing field.
@stable
###
up.on 'change', '[up-validate]', (event) ->
# Even though [up-validate] may be used on either an entire form or an individual input,
# the change event will trigger on a given field.
field = findFields(event.target)[0]
# There is an edge case where the user is changing an input with [up-validate],
# but blurs the input by directly clicking the submit button. In this case the
# following events will be emitted:
#
# - change on the input
# - focus on the button
# - submit on the form
#
# In this case we do not want to send a validate request to the server, but
# simply submit the form. Because this event handler does not know if a submit
# event is about to fire, we delay the validation to the next microtask.
# In case we receive a submit event after this, we can cancel the validation.
abortScheduledValidate = u.abortableMicrotask ->
up.log.muteUncriticalRejection validate(field)
###**
Show or hide elements when a form field is set to a given value.
\#\#\# Example: Select options
The controlling form field gets an `up-switch` attribute with a selector for the elements to show or hide:
<select name="advancedness" up-switch=".target">
<option value="basic">Basic parts</option>
<option value="advanced">Advanced parts</option>
<option value="very-advanced">Very advanced parts</option>
</select>
The target elements can use [`[up-show-for]`](/up-show-for) and [`[up-hide-for]`](/up-hide-for)
attributes to indicate for which values they should be shown or hidden:
<div class="target" up-show-for="basic">
only shown for advancedness = basic
</div>
<div class="target" up-hide-for="basic">
hidden for advancedness = basic
</div>
<div class="target" up-show-for="advanced very-advanced">
shown for advancedness = advanced or very-advanced
</div>
\#\#\# Example: Text field
The controlling `<input>` gets an `up-switch` attribute with a selector for the elements to show or hide:
<input type="text" name="user" up-switch=".target">
<div class="target" up-show-for="alice">
only shown for user alice
</div>
You can also use the pseudo-values `:blank` to match an empty input value,
or `:present` to match a non-empty input value:
<input type="text" name="user" up-switch=".target">
<div class="target" up-show-for=":blank">
please enter a username
</div>
\#\#\# Example: Checkbox
For checkboxes you can match against the pseudo-values `:checked` or `:unchecked`:
<input type="checkbox" name="flag" up-switch=".target">
<div class="target" up-show-for=":checked">
only shown when checkbox is checked
</div>
<div class="target" up-show-for=":cunhecked">
only shown when checkbox is unchecked
</div>
Of course you can also match against the `value` property of the checkbox element:
<input type="checkbox" name="flag" value="active" up-switch=".target">
<div class="target" up-show-for="active">
only shown when checkbox is checked
</div>
@selector input[up-switch]
@param up-switch
A CSS selector for elements whose visibility depends on this field's value.
@stable
###
###**
Only shows this element if an input field with [`[up-switch]`](/input-up-switch) has one of the given values.
See [`input[up-switch]`](/input-up-switch) for more documentation and examples.
@selector [up-show-for]
@param [up-show-for]
A space-separated list of input values for which this element should be shown.
@stable
###
###**
Hides this element if an input field with [`[up-switch]`](/input-up-switch) has one of the given values.
See [`input[up-switch]`](/input-up-switch) for more documentation and examples.
@selector [up-hide-for]
@param [up-hide-for]
A space-separated list of input values for which this element should be hidden.
@stable
###
up.compiler '[up-switch]', (switcher) ->
switchTargets(switcher)
up.on 'change', '[up-switch]', (event, switcher) ->
switchTargets(switcher)
up.compiler '[up-show-for]:not(.up-switched), [up-hide-for]:not(.up-switched)', (element) ->
switchTarget(element)
###**
Observes this field and runs a callback when a value changes.
This is useful for observing text fields while the user is typing.
If you want to submit the form after a change see [`input[up-autosubmit]`](/input-up-autosubmit).
The programmatic variant of this is the [`up.observe()`](/up.observe) function.
\#\#\# Example
The following would run a global `showSuggestions(value)` function
whenever the `<input>` changes:
<input name="query" up-observe="showSuggestions(value)">
Note that the parameter name in the markup must be called `value` or it will not work.
The parameter name can be called whatever you want in the JavaScript, however.
Also note that the function must be declared on the `window` object to work, like so:
window.showSuggestions = function(selectedValue) {
console.log(`Called showSuggestions() with ${selectedValue}`);
}
\#\#\# Callback context
The script given to `[up-observe]` runs with the following context:
| Name | Type | Description |
| -------- | --------- | ------------------------------------- |
| `value` | `string` | The current value of the field |
| `this` | `Element` | The form field |
| `$field` | `jQuery` | The form field as a jQuery collection |
\#\#\# Observing radio buttons
Multiple radio buttons with the same `[name]` (a radio button group)
produce a single value for the form.
To observe radio buttons group, use the `[up-observe]` attribute on an
element that contains all radio button elements with a given name:
<div up-observe="formatSelected(value)">
<input type="radio" name="format" value="html"> HTML format
<input type="radio" name="format" value="pdf"> PDF format
<input type="radio" name="format" value="txt"> Text format
</div>
@selector input[up-observe]
@param up-observe
The code to run when the field's value changes.
@param up-delay
The number of miliseconds to wait after a change before the code is run.
@stable
###
###**
Observes this form and runs a callback when any field changes.
This is useful for observing text fields while the user is typing.
If you want to submit the form after a change see [`input[up-autosubmit]`](/input-up-autosubmit).
The programmatic variant of this is the [`up.observe()`](/up.observe) function.
\#\#\# Example
The would call a function `somethingChanged(value)`
when any `<input>` within the `<form>` changes:
<form up-observe="somethingChanged(value)">
<input name="foo">
<input name="bar">
</form>
\#\#\# Callback context
The script given to `[up-observe]` runs with the following context:
| Name | Type | Description |
| -------- | --------- | ------------------------------------- |
| `value` | `string` | The current value of the field |
| `this` | `Element` | The form field |
| `$field` | `jQuery` | The form field as a jQuery collection |
@selector form[up-observe]
@param up-observe
The code to run when any field's value changes.
@param up-delay
The number of miliseconds to wait after a change before the code is run.
@stable
###
up.compiler '[up-observe]', (formOrField) -> observe(formOrField)
###**
Submits this field's form when this field changes its values.
Both the form and the changed field will be assigned a CSS class [`.up-active`](/form-up-active)
while the autosubmitted form is loading.
The programmatic variant of this is the [`up.autosubmit()`](/up.autosubmit) function.
\#\#\# Example
The following would automatically submit the form when the query is changed:
<form method="GET" action="/search">
<input type="search" name="query" up-autosubmit>
<input type="checkbox" name="archive"> Include archive
</form>
\#\#\# Auto-submitting radio buttons
Multiple radio buttons with the same `[name]` (a radio button group)
produce a single value for the form.
To auto-submit radio buttons group, use the `[up-submit]` attribute on an
element that contains all radio button elements with a given name:
<div up-autosubmit>
<input type="radio" name="format" value="html"> HTML format
<input type="radio" name="format" value="pdf"> PDF format
<input type="radio" name="format" value="txt"> Text format
</div>
@selector input[up-autosubmit]
@param [up-delay]
The number of miliseconds to wait after a change before the form is submitted.
@stable
###
###**
Submits the form when any field changes.
Both the form and the field will be assigned a CSS class [`.up-active`](/form-up-active)
while the autosubmitted form is loading.
The programmatic variant of this is the [`up.autosubmit()`](/up.autosubmit) function.
\#\#\# Example
This will submit the form when either query or checkbox was changed:
<form method="GET" action="/search" up-autosubmit>
<input type="search" name="query">
<input type="checkbox" name="archive"> Include archive
</form>
@selector form[up-autosubmit]
@param [up-delay]
The number of miliseconds to wait after a change before the form is submitted.
@stable
###
up.compiler '[up-autosubmit]', (formOrField) -> autosubmit(formOrField)
up.on 'up:framework:reset', reset
config: config
submit: submit
submitOptions: submitOptions
isSubmittable: isSubmittable
observe: observe
validate: validate
autosubmit: autosubmit
fieldSelector: fieldSelector
fields: findFields
focusedField: focusedField
switchTarget: switchTarget
up.submit = up.form.submit
up.observe = up.form.observe
up.autosubmit = up.form.autosubmit
up.validate = up.form.validate
| 29433 | ###**
Forms
=====
The `up.form` module helps you work with non-trivial forms.
@see form[up-submit]
@see form[up-validate]
@see input[up-switch]
@see form[up-autosubmit]
@module up.form
###
up.form = do ->
u = up.util
e = up.element
ATTRIBUTES_SUGGESTING_SUBMIT = ['[up-submit]', '[up-target]', '[up-layer]', '[up-transition]']
###**
Sets default options for form submission and validation.
@property up.form.config
@param {number} [config.observeDelay=0]
The number of miliseconds to wait before [`up.observe()`](/up.observe) runs the callback
after the input value changes. Use this to limit how often the callback
will be invoked for a fast typist.
@param {Array<string>} [config.submitSelectors]
An array of CSS selectors matching forms that will be [submitted through Unpoly](/form-up-follow).
You can configure Unpoly to handle *all* forms on a page without requiring an `[up-submit]` attribute:
```js
up.form.config.submitSelectors.push('form']
```
Individual forms may opt out with an `[up-submit=follow]` attribute.
You may configure additional exceptions in `config.noSubmitSelectors`.
@param {Array<string>} [config.noSubmitSelectors]
Exceptions to `config.submitSelectors`.
Matching forms will *not* be [submitted through Unpoly](/form-up-submit), even if they match `config.submitSelectors`.
@param {Array<string>} [config.validateTargets=['[up-fieldset]:has(&)', 'fieldset:has(&)', 'label:has(&)', 'form:has(&)']]
An array of CSS selectors that are searched around a form field
that wants to [validate](/up.validate).
The first matching selector will be updated with the validation messages from the server.
By default this looks for a `<fieldset>`, `<label>` or `<form>`
around the validating input field.
@param {string} [config.fieldSelectors]
An array of CSS selectors that represent form fields, such as `input` or `select`.
@param {string} [config.submitButtonSelectors]
An array of CSS selectors that represent submit buttons, such as `input[type=submit]`.
@stable
###
config = new up.Config ->
validateTargets: ['[up-fieldset]:has(:origin)', 'fieldset:has(:origin)', 'label:has(:origin)', 'form:has(:origin)']
fieldSelectors: ['select', 'input:not([type=submit]):not([type=image])', 'button[type]:not([type=submit])', 'textarea'],
submitSelectors: up.link.combineFollowableSelectors(['form'], ATTRIBUTES_SUGGESTING_SUBMIT)
noSubmitSelectors: ['[up-submit=false]', '[target]']
submitButtonSelectors: ['input[type=submit]', 'input[type=image]', 'button[type=submit]', 'button:not([type])']
observeDelay: 0
fullSubmitSelector = ->
config.submitSelectors.join(',')
abortScheduledValidate = null
reset = ->
config.reset()
###**
@function up.form.fieldSelector
@internal
###
fieldSelector = (suffix = '') ->
config.fieldSelectors.map((field) -> field + suffix).join(',')
###**
Returns a list of form fields within the given element.
You can configure what Unpoly considers a form field by adding CSS selectors to the
`up.form.config.fieldSelectors` array.
If the given element is itself a form field, a list of that given element is returned.
@function up.form.fields
@param {Element|jQuery} root
The element to scan for contained form fields.
If the element is itself a form field, a list of that element is returned.
@return {NodeList<Element>|Array<Element>}
@experimental
###
findFields = (root) ->
root = e.get(root) # unwrap jQuery
fields = e.subtree(root, fieldSelector())
# If findFields() is called with an entire form, gather fields outside the form
# element that are associated with the form (through <input form="id-of-form">, which
# is an HTML feature.)
if e.matches(root, 'form[id]')
outsideFieldSelector = fieldSelector(e.attributeSelector('form', root.getAttribute('id')))
outsideFields = e.all(outsideFieldSelector)
fields.push(outsideFields...)
fields = u.uniq(fields)
fields
###**
@function up.form.submittingButton
@param {Element} form
@internal
###
submittingButton = (form) ->
selector = submitButtonSelector()
focusedElement = document.activeElement
if focusedElement && e.matches(focusedElement, selector) && form.contains(focusedElement)
return focusedElement
else
# If no button is focused, we assume the first button in the form.
return e.get(form, selector)
###**
@function up.form.submitButtonSelector
@internal
###
submitButtonSelector = ->
config.submitButtonSelectors.join(',')
###**
Submits a form via AJAX and updates a page fragment with the response.
up.submit('form.new-user', { target: '.main' })
Instead of loading a new page, the form is submitted via AJAX.
The response is parsed for a CSS selector and the matching elements will
replace corresponding elements on the current page.
The unobtrusive variant of this is the `form[up-submit]` selector.
See its documentation to learn how form submissions work in Unpoly.
Submitting a form is considered [navigation](/navigation).
Emits the event [`up:form:submit`](/up:form:submit).
@function up.submit
@param {Element|jQuery|string} form
The form to submit.
If the argument points to an element that is not a form,
Unpoly will search its ancestors for the [closest](/up.fragment.closest) form.
@param {Object} [options]
[Render options](/up.render) that should be used for submitting the form.
Unpoly will parse render options from the given form's attributes
like `[up-target]` or `[up-transition]`. See `form[up-submit]` for a list
of supported attributes.
You may pass this additional `options` object to supplement or override
options parsed from the form attributes.
@return {Promise<up.RenderResult>}
A promise that will be fulfilled when the server response was rendered.
@stable
###
submit = up.mockable (form, options) ->
return up.render(submitOptions(form, options))
###**
Parses the [render](/up.render) options that would be used to
[`submit`](/up.submit) the given form, but does not render.
\#\#\# Example
Given a form element:
```html
<form action="/foo" method="post" up-target=".content">
...
</form>
```
We can parse the link's render options like this:
```js
let form = document.querySelector('form')
let options = up.form.submitOptions(form)
// => { url: '/foo', method: 'POST', target: '.content', ... }
```
@param {Element|jQuery|string} form
The form to submit.
@param {Object} [options]
Additional options for the form submission.
Will override any attribute values set on the given form element.
See `up.render()` for detailed documentation of individual option properties.
@function up.form.submitOptions
@return {Object}
@stable
###
submitOptions = (form, options) ->
options = u.options(options)
form = up.fragment.get(form)
form = e.closest(form, 'form')
parser = new up.OptionsParser(options, form)
# Parse params from form fields.
params = up.Params.fromForm(form)
if submitButton = submittingButton(form)
# Submit buttons with a [name] attribute will add to the params.
# Note that addField() will only add an entry if the given button has a [name] attribute.
params.addField(submitButton)
# Submit buttons may have [formmethod] and [formaction] attribute
# that override [method] and [action] attribute from the <form> element.
options.method ||= submitButton.getAttribute('formmethod')
options.url ||= submitButton.getAttribute('formaction')
params.addAll(options.params)
options.params = params
parser.string('url', attr: 'action', default: up.fragment.source(form))
parser.string('method', attr: ['up-method', 'data-method', 'method'], default: 'GET', normalize: u.normalizeMethod)
if options.method == 'GET'
# Only for GET forms, browsers discard all query params from the form's [action] URL.
# The URLs search part will be replaced with the serialized form data.
# See design/query-params-in-form-actions/cases.html for
# a demo of vanilla browser behavior.
options.url = up.Params.stripURL(options.url)
parser.string('failTarget', default: up.fragment.toTarget(form))
# The guardEvent will also be assigned an { renderOptions } property in up.render()
options.guardEvent ||= up.event.build('up:form:submit', log: 'Submitting form')
# Now that we have extracted everything form-specific into options, we can call
# up.link.followOptions(). This will also parse the myriads of other options
# that are possible on both <form> and <a> elements.
u.assign(options, up.link.followOptions(form, options))
return options
###**
This event is [emitted](/up.emit) when a form is [submitted](/up.submit) through Unpoly.
The event is emitted on the `<form>` element.
When the form is being [validated](/input-up-validate), this event is not emitted.
Instead an `up:form:validate` event is emitted.
\#\#\# Changing render options
Listeners may inspect and manipulate [render options](/up.render) for the coming fragment update.
The code below will use a custom [transition](/up-transition)
when a form submission [fails](/server-errors):
```js
up.on('up:form:submit', function(event, form) {
event.renderOptions.failTransition = 'shake'
})
```
@event up:form:submit
@param {Element} event.target
The `<form>` element that will be submitted.
@param {Object} event.renderOptions
An object with [render options](/up.render) for the fragment update
Listeners may inspect and modify these options.
@param event.preventDefault()
Event listeners may call this method to prevent the form from being submitted.
@stable
###
# MacOS does not focus buttons on click.
# That means that submittingButton() cannot rely on document.activeElement.
# See https://github.com/unpoly/unpoly/issues/103
up.on 'up:click', submitButtonSelector, (event, button) ->
# Don't mess with focus unless we know that we're going to handle the form.
# https://groups.google.com/g/unpoly/c/wsiATxepVZk
form = e.closest(button, 'form')
if form && isSubmittable(form)
button.focus()
###**
Observes form fields and runs a callback when a value changes.
This is useful for observing text fields while the user is typing.
The unobtrusive variant of this is the [`[up-observe]`](/up-observe) attribute.
\#\#\# Example
The following would print to the console whenever an input field changes:
up.observe('input.query', function(value) {
console.log('Query is now %o', value)
})
Instead of a single form field, you can also pass multiple fields,
a `<form>` or any container that contains form fields.
The callback will be run if any of the given fields change:
up.observe('form', function(value, name) {
console.log('The value of %o is now %o', name, value)
})
You may also pass the `{ batch: true }` option to receive all
changes since the last callback in a single object:
up.observe('form', { batch: true }, function(diff) {
console.log('Observed one or more changes: %o', diff)
})
@function up.observe
@param {string|Element|Array<Element>|jQuery} elements
The form fields that will be observed.
You can pass one or more fields, a `<form>` or any container that contains form fields.
The callback will be run if any of the given fields change.
@param {boolean} [options.batch=false]
If set to `true`, the `onChange` callback will receive multiple
detected changes in a single diff object as its argument.
@param {number} [options.delay=up.form.config.observeDelay]
The number of miliseconds to wait before executing the callback
after the input value changes. Use this to limit how often the callback
will be invoked for a fast typist.
@param {Function(value, name): string} onChange
The callback to run when the field's value changes.
If given as a function, it receives two arguments (`value`, `name`).
`value` is a string with the new attribute value and `string` is the name
of the form field that changed. If given as a string, it will be evaled as
JavaScript code in a context where (`value`, `name`) are set.
A long-running callback function may return a promise that settles when
the callback completes. In this case the callback will not be called again while
it is already running.
@return {Function()}
A destructor function that removes the observe watch when called.
@stable
###
observe = (elements, args...) ->
elements = e.list(elements)
fields = u.flatMap(elements, findFields)
callback = u.extractCallback(args) ? observeCallbackFromElement(elements[0]) ? up.fail('up.observe: No change callback given')
options = u.extractOptions(args)
options.delay = options.delay ? e.numberAttr(elements[0], 'up-delay') ? config.observeDelay
observer = new up.FieldObserver(fields, options, callback)
observer.start()
return -> observer.stop()
observeCallbackFromElement = (element) ->
if rawCallback = element.getAttribute('up-observe')
new Function('value', 'name', rawCallback)
###**
[Observes](/up.observe) a field or form and submits the form when a value changes.
Both the form and the changed field will be assigned a CSS class [`.up-active`](/form-up-active)
while the autosubmitted form is processing.
The unobtrusive variant of this is the [`[up-autosubmit]`](/form-up-autosubmit) attribute.
@function up.autosubmit
@param {string|Element|jQuery} target
The field or form to observe.
@param {Object} [options]
See options for [`up.observe()`](/up.observe)
@return {Function()}
A destructor function that removes the observe watch when called.
@stable
###
autosubmit = (target, options) ->
observe(target, options, -> submit(target))
findValidateTarget = (element, options) ->
container = getContainer(element)
if u.isElementish(options.target)
return up.fragment.toTarget(options.target)
else if givenTarget = options.target || element.getAttribute('up-validate') || container.getAttribute('up-validate')
return givenTarget
else if e.matches(element, 'form')
# If element is the form, we cannot find a better validate target than this.
return up.fragment.toTarget(element)
else
return findValidateTargetFromConfig(element, options) || up.fail('Could not find validation target for %o (tried defaults %o)', element, config.validateTargets)
findValidateTargetFromConfig = (element, options) ->
# for the first selector that has a match in the field's layer.
layer = up.layer.get(element)
return u.findResult config.validateTargets, (defaultTarget) ->
if up.fragment.get(defaultTarget, u.merge(options, { layer }))
# We want to return the selector, *not* the element. If we returned the element
# and derive a selector from that, any :has() expression would be lost.
return defaultTarget
###**
Performs a server-side validation of a form field.
`up.validate()` submits the given field's form with an additional `X-Up-Validate`
HTTP header. Upon seeing this header, the server is expected to validate (but not save)
the form submission and render a new copy of the form with validation errors.
The unobtrusive variant of this is the [`input[up-validate]`](/input-up-validate) selector.
See the documentation for [`input[up-validate]`](/input-up-validate) for more information
on how server-side validation works in Unpoly.
\#\#\# Example
```js
up.validate('input[name=email]', { target: '.email-errors' })
```
@function up.validate
@param {string|Element|jQuery} field
The form field to validate.
@param {string|Element|jQuery} [options.target]
The element that will be [updated](/up.render) with the validation results.
@return {Promise}
A promise that fulfills when the server-side
validation is received and the form was updated.
@stable
###
validate = (field, options) ->
# If passed a selector, up.fragment.get() will prefer a match on the current layer.
field = up.fragment.get(field)
options = u.options(options)
options.navigate = false
options.origin = field
options.history = false
options.target = findValidateTarget(field, options)
options.focus = 'keep'
# The protocol doesn't define whether the validation results in a status code.
# Hence we use the same options for both success and failure.
options.fail = false
# Make sure the X-Up-Validate header is present, so the server-side
# knows that it should not persist the form submission
options.headers ||= {}
options.headers[up.protocol.headerize('validate')] = field.getAttribute('name') || ':unknown'
# The guardEvent will also be assigned a { renderOptions } attribute in up.render()
options.guardEvent = up.event.build('up:form:validate', { field, log: 'Validating form' })
return submit(field, options)
###**
This event is emitted before a field is being [validated](/input-up-validate).
@event up:form:validate
@param {Element} event.field
The form field that has been changed and caused the validated request.
@param {Object} event.renderOptions
An object with [render options](/up.render) for the fragment update
that will show the validation results.
Listeners may inspect and modify these options.
@param event.preventDefault()
Event listeners may call this method to prevent the validation request
being sent to the server.
@stable
###
switcherValues = (field) ->
value = undefined
meta = undefined
if e.matches(field, 'input[type=checkbox]')
if field.checked
value = field.value
meta = ':checked'
else
meta = ':unchecked'
else if e.matches(field, 'input[type=radio]')
form = getContainer(field)
groupName = field.getAttribute('name')
checkedButton = form.querySelector("input[type=radio]#{e.attributeSelector('name', groupName)}:checked")
if checkedButton
meta = ':checked'
value = checkedButton.value
else
meta = ':unchecked'
else
value = field.value
values = []
if u.isPresent(value)
values.push(value)
values.push(':present')
else
values.push(':blank')
if u.isPresent(meta)
values.push(meta)
values
###**
Shows or hides a target selector depending on the value.
See [`input[up-switch]`](/input-up-switch) for more documentation and examples.
This function does not currently have a very useful API outside
of our use for `up-switch`'s UJS behavior, that's why it's currently
still marked `@internal`.
@function up.form.switchTargets
@param {Element} switcher
@param {string} [options.target]
The target selectors to switch.
Defaults to an `[up-switch]` attribute on the given field.
@internal
###
switchTargets = (switcher, options = {}) ->
targetSelector = options.target ? switcher.getAttribute('up-switch')
form = getContainer(switcher)
targetSelector or up.fail("No switch target given for %o", switcher)
fieldValues = switcherValues(switcher)
u.each e.all(form, targetSelector), (target) ->
switchTarget(target, fieldValues)
###**
@internal
###
switchTarget = up.mockable (target, fieldValues) ->
fieldValues ||= switcherValues(findSwitcherForTarget(target))
if hideValues = target.getAttribute('up-hide-for')
hideValues = u.splitValues(hideValues)
show = u.intersect(fieldValues, hideValues).length == 0
else
if showValues = target.getAttribute('up-show-for')
showValues = u.splitValues(showValues)
else
# If the target has neither up-show-for or up-hide-for attributes,
# assume the user wants the target to be visible whenever anything
# is checked or entered.
showValues = [':present', ':checked']
show = u.intersect(fieldValues, showValues).length > 0
e.toggle(target, show)
target.classList.add('up-switched')
###**
@internal
###
findSwitcherForTarget = (target) ->
form = getContainer(target)
switchers = e.all(form, '[up-switch]')
switcher = u.find switchers, (switcher) ->
targetSelector = switcher.getAttribute('up-switch')
e.matches(target, targetSelector)
return switcher or up.fail('Could not find [up-switch] field for %o', target)
getContainer = (element) ->
element.form || # Element#form will also work if the element is outside the form with an [form=form-id] attribute
e.closest(element, "form, #{up.layer.anySelector()}")
focusedField = ->
if (element = document.activeElement) && e.matches(element, fieldSelector())
return element
###**
Returns whether the given form will be [submitted](/up.follow) through Unpoly
instead of making a full page load.
By default Unpoly will follow forms if the element has
one of the following attributes:
- `[up-submit]`
- `[up-target]`
- `[up-layer]`
- `[up-transition]`
To consider other selectors to be submittable, see `up.form.config.submitSelectors`.
@function up.form.isSubmittable
@param {Element|jQuery|string} form
The form to check.
@stable
###
isSubmittable = (form) ->
form = up.fragment.get(form)
return e.matches(form, fullSubmitSelector()) && !isSubmitDisabled(form)
isSubmitDisabled = (form) ->
# We also don't want to handle cross-origin forms.
# That will be handled in `up.Change.FromURL#newPageReason`.
return e.matches(form, config.noSubmitSelectors.join(','))
###**
Submits this form via JavaScript and updates a fragment with the server response.
The server response is searched for the selector given in `up-target`.
The selector content is then [replaced](/up.replace) in the current page.
The programmatic variant of this is the [`up.submit()`](/up.submit) function.
\#\#\# Example
```html
<form method="post" action="/users" up-submit>
...
</form>
```
\#\#\# Handling validation errors
When the server was unable to save the form due to invalid params,
it will usually re-render an updated copy of the form with
validation messages.
For Unpoly to be able to detect a failed form submission,
the form must be re-rendered with a non-200 HTTP status code.
We recommend to use either 400 (bad request) or
422 (unprocessable entity).
In Ruby on Rails, you can pass a
[`:status` option to `render`](http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option)
for this:
```ruby
class UsersController < ApplicationController
def create
user_params = params[:user].permit(:email, :password)
@user = User.new(user_params)
if @user.save?
sign_in @user
else
render 'form', status: :bad_request
end
end
end
```
You may define different option for the failure case by infixing an attribute with `fail`:
```html
<form method="post" action="/action"
up-target=".content"
up-fail-target="form"
up-scroll="auto"
up-fail-scroll=".errors">
...
</form>
```
See [handling server errors](/server-errors) for details.
Note that you can also use
[`input[up-validate]`](/input-up-validate) to perform server-side
validations while the user is completing fields.
\#\#\# Giving feedback while the form is processing
The `<form>` element will be assigned a CSS class [`.up-active`](/form.up-active) while
the submission is loading.
\#\#\# Short notation
You may omit the `[up-submit]` attribute if the form has one of the following attributes:
- `[up-target]`
- `[up-layer]`
- `[up-transition]`
Such a form will still be submitted through Unpoly.
\#\#\# Handling all forms automatically
You can configure Unpoly to handle *all* forms on a page without requiring an `[up-submit]` attribute.
See [Handling all links and forms](/handling-everything).
@selector form[up-submit]
@params-note
All attributes for `a[up-follow]` may also be used.
@stable
###
up.on 'submit', fullSubmitSelector, (event, form) ->
# Users may configure up.form.config.submitSelectors.push('form')
# and then opt out individual forms with [up-submit=false].
if event.defaultPrevented || isSubmitDisabled(form)
return
abortScheduledValidate?()
up.event.halt(event)
up.log.muteUncriticalRejection submit(form)
###**
When a form field with this attribute is changed, the form is validated on the server
and is updated with validation messages.
To validate the form, Unpoly will submit the form with an additional `X-Up-Validate` HTTP header.
When seeing this header, the server is expected to validate (but not save)
the form submission and render a new copy of the form with validation errors.
The programmatic variant of this is the [`up.validate()`](/up.validate) function.
\#\#\# Example
Let's look at a standard registration form that asks for an e-mail and password:
<form action="/users">
<label>
E-mail: <input type="text" name="email" />
</label>
<label>
Password: <input type="<PASSWORD>" name="<PASSWORD>" />
</label>
<button type="submit">Register</button>
</form>
When the user changes the `email` field, we want to validate that
the e-mail address is valid and still available. Also we want to
change the `password` field for the minimum required password length.
We can do this by giving both fields an `up-validate` attribute:
<form action="/users">
<label>
E-mail: <input type="text" name="email" up-validate />
</label>
<label>
Password: <input type="<PASSWORD>" name="password" up-validate />
</label>
<button type="submit">Register</button>
</form>
Whenever a field with `up-validate` changes, the form is POSTed to
`/users` with an additional `X-Up-Validate` HTTP header.
When seeing this header, the server is expected to validate (but not save)
the form submission and render a new copy of the form with validation errors.
In Ruby on Rails the processing action should behave like this:
class UsersController < ApplicationController
# This action handles POST /users
def create
user_params = params[:user].permit(:email, :password)
@user = User.new(user_params)
if request.headers['X-Up-Validate']
@user.valid? # run validations, but don't save to the database
render 'form' # render form with error messages
elsif @user.save?
sign_in @user
else
render 'form', status: :bad_request
end
end
end
Note that if you're using the `unpoly-rails` gem you can simply say `up.validate?`
instead of manually checking for `request.headers['X-Up-Validate']`.
The server now renders an updated copy of the form with eventual validation errors:
<form action="/users">
<label class="has-error">
E-mail: <input type="text" name="email" value="<EMAIL>" />
Has already been taken!
</label>
<button type="submit">Register</button>
</form>
The `<label>` around the e-mail field is now updated to have the `has-error`
class and display the validation message.
\#\#\# How validation results are displayed
Although the server will usually respond to a validation with a complete,
fresh copy of the form, Unpoly will by default not update the entire form.
This is done in order to preserve volatile state such as the scroll position
of `<textarea>` elements.
By default Unpoly looks for a `<fieldset>`, `<label>` or `<form>`
around the validating input field, or any element with an
`up-fieldset` attribute.
With the Bootstrap bindings, Unpoly will also look
for a container with the `form-group` class.
You can change this default behavior by setting `up.form.config.validateTargets`:
// Always update the entire form containing the current field ("&")
up.form.config.validateTargets = ['form &']
You can also individually override what to update by setting the `up-validate`
attribute to a CSS selector:
<input type="text" name="email" up-validate=".email-errors">
<span class="email-errors"></span>
\#\#\# Updating dependent fields
The `[up-validate]` behavior is also a great way to partially update a form
when one fields depends on the value of another field.
Let's say you have a form with one `<select>` to pick a department (sales, engineering, ...)
and another `<select>` to pick an employeee from the selected department:
<form action="/contracts">
<select name="department">...</select> <!-- options for all departments -->
<select name="employeed">...</select> <!-- options for employees of selected department -->
</form>
The list of employees needs to be updated as the appartment changes:
<form action="/contracts">
<select name="department" up-validate="[name=employee]">...</select>
<select name="employee">...</select>
</form>
In order to update the `department` field in addition to the `employee` field, you could say
`up-validate="&, [name=employee]"`, or simply `up-validate="form"` to update the entire form.
@selector input[up-validate]
@param up-validate
The CSS selector to update with the server response.
This defaults to a fieldset or form group around the validating field.
@stable
###
###**
Validates this form on the server when any field changes and shows validation errors.
You can configure what Unpoly considers a fieldset by adding CSS selectors to the
`up.form.config.validateTargets` array.
See `input[up-validate]` for detailed documentation.
@selector form[up-validate]
@param up-validate
The CSS selector to update with the server response.
This defaults to a fieldset or form group around the changing field.
@stable
###
up.on 'change', '[up-validate]', (event) ->
# Even though [up-validate] may be used on either an entire form or an individual input,
# the change event will trigger on a given field.
field = findFields(event.target)[0]
# There is an edge case where the user is changing an input with [up-validate],
# but blurs the input by directly clicking the submit button. In this case the
# following events will be emitted:
#
# - change on the input
# - focus on the button
# - submit on the form
#
# In this case we do not want to send a validate request to the server, but
# simply submit the form. Because this event handler does not know if a submit
# event is about to fire, we delay the validation to the next microtask.
# In case we receive a submit event after this, we can cancel the validation.
abortScheduledValidate = u.abortableMicrotask ->
up.log.muteUncriticalRejection validate(field)
###**
Show or hide elements when a form field is set to a given value.
\#\#\# Example: Select options
The controlling form field gets an `up-switch` attribute with a selector for the elements to show or hide:
<select name="advancedness" up-switch=".target">
<option value="basic">Basic parts</option>
<option value="advanced">Advanced parts</option>
<option value="very-advanced">Very advanced parts</option>
</select>
The target elements can use [`[up-show-for]`](/up-show-for) and [`[up-hide-for]`](/up-hide-for)
attributes to indicate for which values they should be shown or hidden:
<div class="target" up-show-for="basic">
only shown for advancedness = basic
</div>
<div class="target" up-hide-for="basic">
hidden for advancedness = basic
</div>
<div class="target" up-show-for="advanced very-advanced">
shown for advancedness = advanced or very-advanced
</div>
\#\#\# Example: Text field
The controlling `<input>` gets an `up-switch` attribute with a selector for the elements to show or hide:
<input type="text" name="user" up-switch=".target">
<div class="target" up-show-for="alice">
only shown for user alice
</div>
You can also use the pseudo-values `:blank` to match an empty input value,
or `:present` to match a non-empty input value:
<input type="text" name="user" up-switch=".target">
<div class="target" up-show-for=":blank">
please enter a username
</div>
\#\#\# Example: Checkbox
For checkboxes you can match against the pseudo-values `:checked` or `:unchecked`:
<input type="checkbox" name="flag" up-switch=".target">
<div class="target" up-show-for=":checked">
only shown when checkbox is checked
</div>
<div class="target" up-show-for=":cunhecked">
only shown when checkbox is unchecked
</div>
Of course you can also match against the `value` property of the checkbox element:
<input type="checkbox" name="flag" value="active" up-switch=".target">
<div class="target" up-show-for="active">
only shown when checkbox is checked
</div>
@selector input[up-switch]
@param up-switch
A CSS selector for elements whose visibility depends on this field's value.
@stable
###
###**
Only shows this element if an input field with [`[up-switch]`](/input-up-switch) has one of the given values.
See [`input[up-switch]`](/input-up-switch) for more documentation and examples.
@selector [up-show-for]
@param [up-show-for]
A space-separated list of input values for which this element should be shown.
@stable
###
###**
Hides this element if an input field with [`[up-switch]`](/input-up-switch) has one of the given values.
See [`input[up-switch]`](/input-up-switch) for more documentation and examples.
@selector [up-hide-for]
@param [up-hide-for]
A space-separated list of input values for which this element should be hidden.
@stable
###
up.compiler '[up-switch]', (switcher) ->
switchTargets(switcher)
up.on 'change', '[up-switch]', (event, switcher) ->
switchTargets(switcher)
up.compiler '[up-show-for]:not(.up-switched), [up-hide-for]:not(.up-switched)', (element) ->
switchTarget(element)
###**
Observes this field and runs a callback when a value changes.
This is useful for observing text fields while the user is typing.
If you want to submit the form after a change see [`input[up-autosubmit]`](/input-up-autosubmit).
The programmatic variant of this is the [`up.observe()`](/up.observe) function.
\#\#\# Example
The following would run a global `showSuggestions(value)` function
whenever the `<input>` changes:
<input name="query" up-observe="showSuggestions(value)">
Note that the parameter name in the markup must be called `value` or it will not work.
The parameter name can be called whatever you want in the JavaScript, however.
Also note that the function must be declared on the `window` object to work, like so:
window.showSuggestions = function(selectedValue) {
console.log(`Called showSuggestions() with ${selectedValue}`);
}
\#\#\# Callback context
The script given to `[up-observe]` runs with the following context:
| Name | Type | Description |
| -------- | --------- | ------------------------------------- |
| `value` | `string` | The current value of the field |
| `this` | `Element` | The form field |
| `$field` | `jQuery` | The form field as a jQuery collection |
\#\#\# Observing radio buttons
Multiple radio buttons with the same `[name]` (a radio button group)
produce a single value for the form.
To observe radio buttons group, use the `[up-observe]` attribute on an
element that contains all radio button elements with a given name:
<div up-observe="formatSelected(value)">
<input type="radio" name="format" value="html"> HTML format
<input type="radio" name="format" value="pdf"> PDF format
<input type="radio" name="format" value="txt"> Text format
</div>
@selector input[up-observe]
@param up-observe
The code to run when the field's value changes.
@param up-delay
The number of miliseconds to wait after a change before the code is run.
@stable
###
###**
Observes this form and runs a callback when any field changes.
This is useful for observing text fields while the user is typing.
If you want to submit the form after a change see [`input[up-autosubmit]`](/input-up-autosubmit).
The programmatic variant of this is the [`up.observe()`](/up.observe) function.
\#\#\# Example
The would call a function `somethingChanged(value)`
when any `<input>` within the `<form>` changes:
<form up-observe="somethingChanged(value)">
<input name="foo">
<input name="bar">
</form>
\#\#\# Callback context
The script given to `[up-observe]` runs with the following context:
| Name | Type | Description |
| -------- | --------- | ------------------------------------- |
| `value` | `string` | The current value of the field |
| `this` | `Element` | The form field |
| `$field` | `jQuery` | The form field as a jQuery collection |
@selector form[up-observe]
@param up-observe
The code to run when any field's value changes.
@param up-delay
The number of miliseconds to wait after a change before the code is run.
@stable
###
up.compiler '[up-observe]', (formOrField) -> observe(formOrField)
###**
Submits this field's form when this field changes its values.
Both the form and the changed field will be assigned a CSS class [`.up-active`](/form-up-active)
while the autosubmitted form is loading.
The programmatic variant of this is the [`up.autosubmit()`](/up.autosubmit) function.
\#\#\# Example
The following would automatically submit the form when the query is changed:
<form method="GET" action="/search">
<input type="search" name="query" up-autosubmit>
<input type="checkbox" name="archive"> Include archive
</form>
\#\#\# Auto-submitting radio buttons
Multiple radio buttons with the same `[name]` (a radio button group)
produce a single value for the form.
To auto-submit radio buttons group, use the `[up-submit]` attribute on an
element that contains all radio button elements with a given name:
<div up-autosubmit>
<input type="radio" name="format" value="html"> HTML format
<input type="radio" name="format" value="pdf"> PDF format
<input type="radio" name="format" value="txt"> Text format
</div>
@selector input[up-autosubmit]
@param [up-delay]
The number of miliseconds to wait after a change before the form is submitted.
@stable
###
###**
Submits the form when any field changes.
Both the form and the field will be assigned a CSS class [`.up-active`](/form-up-active)
while the autosubmitted form is loading.
The programmatic variant of this is the [`up.autosubmit()`](/up.autosubmit) function.
\#\#\# Example
This will submit the form when either query or checkbox was changed:
<form method="GET" action="/search" up-autosubmit>
<input type="search" name="query">
<input type="checkbox" name="archive"> Include archive
</form>
@selector form[up-autosubmit]
@param [up-delay]
The number of miliseconds to wait after a change before the form is submitted.
@stable
###
up.compiler '[up-autosubmit]', (formOrField) -> autosubmit(formOrField)
up.on 'up:framework:reset', reset
config: config
submit: submit
submitOptions: submitOptions
isSubmittable: isSubmittable
observe: observe
validate: validate
autosubmit: autosubmit
fieldSelector: fieldSelector
fields: findFields
focusedField: focusedField
switchTarget: switchTarget
up.submit = up.form.submit
up.observe = up.form.observe
up.autosubmit = up.form.autosubmit
up.validate = up.form.validate
| true | ###**
Forms
=====
The `up.form` module helps you work with non-trivial forms.
@see form[up-submit]
@see form[up-validate]
@see input[up-switch]
@see form[up-autosubmit]
@module up.form
###
up.form = do ->
u = up.util
e = up.element
ATTRIBUTES_SUGGESTING_SUBMIT = ['[up-submit]', '[up-target]', '[up-layer]', '[up-transition]']
###**
Sets default options for form submission and validation.
@property up.form.config
@param {number} [config.observeDelay=0]
The number of miliseconds to wait before [`up.observe()`](/up.observe) runs the callback
after the input value changes. Use this to limit how often the callback
will be invoked for a fast typist.
@param {Array<string>} [config.submitSelectors]
An array of CSS selectors matching forms that will be [submitted through Unpoly](/form-up-follow).
You can configure Unpoly to handle *all* forms on a page without requiring an `[up-submit]` attribute:
```js
up.form.config.submitSelectors.push('form']
```
Individual forms may opt out with an `[up-submit=follow]` attribute.
You may configure additional exceptions in `config.noSubmitSelectors`.
@param {Array<string>} [config.noSubmitSelectors]
Exceptions to `config.submitSelectors`.
Matching forms will *not* be [submitted through Unpoly](/form-up-submit), even if they match `config.submitSelectors`.
@param {Array<string>} [config.validateTargets=['[up-fieldset]:has(&)', 'fieldset:has(&)', 'label:has(&)', 'form:has(&)']]
An array of CSS selectors that are searched around a form field
that wants to [validate](/up.validate).
The first matching selector will be updated with the validation messages from the server.
By default this looks for a `<fieldset>`, `<label>` or `<form>`
around the validating input field.
@param {string} [config.fieldSelectors]
An array of CSS selectors that represent form fields, such as `input` or `select`.
@param {string} [config.submitButtonSelectors]
An array of CSS selectors that represent submit buttons, such as `input[type=submit]`.
@stable
###
config = new up.Config ->
validateTargets: ['[up-fieldset]:has(:origin)', 'fieldset:has(:origin)', 'label:has(:origin)', 'form:has(:origin)']
fieldSelectors: ['select', 'input:not([type=submit]):not([type=image])', 'button[type]:not([type=submit])', 'textarea'],
submitSelectors: up.link.combineFollowableSelectors(['form'], ATTRIBUTES_SUGGESTING_SUBMIT)
noSubmitSelectors: ['[up-submit=false]', '[target]']
submitButtonSelectors: ['input[type=submit]', 'input[type=image]', 'button[type=submit]', 'button:not([type])']
observeDelay: 0
fullSubmitSelector = ->
config.submitSelectors.join(',')
abortScheduledValidate = null
reset = ->
config.reset()
###**
@function up.form.fieldSelector
@internal
###
fieldSelector = (suffix = '') ->
config.fieldSelectors.map((field) -> field + suffix).join(',')
###**
Returns a list of form fields within the given element.
You can configure what Unpoly considers a form field by adding CSS selectors to the
`up.form.config.fieldSelectors` array.
If the given element is itself a form field, a list of that given element is returned.
@function up.form.fields
@param {Element|jQuery} root
The element to scan for contained form fields.
If the element is itself a form field, a list of that element is returned.
@return {NodeList<Element>|Array<Element>}
@experimental
###
findFields = (root) ->
root = e.get(root) # unwrap jQuery
fields = e.subtree(root, fieldSelector())
# If findFields() is called with an entire form, gather fields outside the form
# element that are associated with the form (through <input form="id-of-form">, which
# is an HTML feature.)
if e.matches(root, 'form[id]')
outsideFieldSelector = fieldSelector(e.attributeSelector('form', root.getAttribute('id')))
outsideFields = e.all(outsideFieldSelector)
fields.push(outsideFields...)
fields = u.uniq(fields)
fields
###**
@function up.form.submittingButton
@param {Element} form
@internal
###
submittingButton = (form) ->
selector = submitButtonSelector()
focusedElement = document.activeElement
if focusedElement && e.matches(focusedElement, selector) && form.contains(focusedElement)
return focusedElement
else
# If no button is focused, we assume the first button in the form.
return e.get(form, selector)
###**
@function up.form.submitButtonSelector
@internal
###
submitButtonSelector = ->
config.submitButtonSelectors.join(',')
###**
Submits a form via AJAX and updates a page fragment with the response.
up.submit('form.new-user', { target: '.main' })
Instead of loading a new page, the form is submitted via AJAX.
The response is parsed for a CSS selector and the matching elements will
replace corresponding elements on the current page.
The unobtrusive variant of this is the `form[up-submit]` selector.
See its documentation to learn how form submissions work in Unpoly.
Submitting a form is considered [navigation](/navigation).
Emits the event [`up:form:submit`](/up:form:submit).
@function up.submit
@param {Element|jQuery|string} form
The form to submit.
If the argument points to an element that is not a form,
Unpoly will search its ancestors for the [closest](/up.fragment.closest) form.
@param {Object} [options]
[Render options](/up.render) that should be used for submitting the form.
Unpoly will parse render options from the given form's attributes
like `[up-target]` or `[up-transition]`. See `form[up-submit]` for a list
of supported attributes.
You may pass this additional `options` object to supplement or override
options parsed from the form attributes.
@return {Promise<up.RenderResult>}
A promise that will be fulfilled when the server response was rendered.
@stable
###
submit = up.mockable (form, options) ->
return up.render(submitOptions(form, options))
###**
Parses the [render](/up.render) options that would be used to
[`submit`](/up.submit) the given form, but does not render.
\#\#\# Example
Given a form element:
```html
<form action="/foo" method="post" up-target=".content">
...
</form>
```
We can parse the link's render options like this:
```js
let form = document.querySelector('form')
let options = up.form.submitOptions(form)
// => { url: '/foo', method: 'POST', target: '.content', ... }
```
@param {Element|jQuery|string} form
The form to submit.
@param {Object} [options]
Additional options for the form submission.
Will override any attribute values set on the given form element.
See `up.render()` for detailed documentation of individual option properties.
@function up.form.submitOptions
@return {Object}
@stable
###
submitOptions = (form, options) ->
options = u.options(options)
form = up.fragment.get(form)
form = e.closest(form, 'form')
parser = new up.OptionsParser(options, form)
# Parse params from form fields.
params = up.Params.fromForm(form)
if submitButton = submittingButton(form)
# Submit buttons with a [name] attribute will add to the params.
# Note that addField() will only add an entry if the given button has a [name] attribute.
params.addField(submitButton)
# Submit buttons may have [formmethod] and [formaction] attribute
# that override [method] and [action] attribute from the <form> element.
options.method ||= submitButton.getAttribute('formmethod')
options.url ||= submitButton.getAttribute('formaction')
params.addAll(options.params)
options.params = params
parser.string('url', attr: 'action', default: up.fragment.source(form))
parser.string('method', attr: ['up-method', 'data-method', 'method'], default: 'GET', normalize: u.normalizeMethod)
if options.method == 'GET'
# Only for GET forms, browsers discard all query params from the form's [action] URL.
# The URLs search part will be replaced with the serialized form data.
# See design/query-params-in-form-actions/cases.html for
# a demo of vanilla browser behavior.
options.url = up.Params.stripURL(options.url)
parser.string('failTarget', default: up.fragment.toTarget(form))
# The guardEvent will also be assigned an { renderOptions } property in up.render()
options.guardEvent ||= up.event.build('up:form:submit', log: 'Submitting form')
# Now that we have extracted everything form-specific into options, we can call
# up.link.followOptions(). This will also parse the myriads of other options
# that are possible on both <form> and <a> elements.
u.assign(options, up.link.followOptions(form, options))
return options
###**
This event is [emitted](/up.emit) when a form is [submitted](/up.submit) through Unpoly.
The event is emitted on the `<form>` element.
When the form is being [validated](/input-up-validate), this event is not emitted.
Instead an `up:form:validate` event is emitted.
\#\#\# Changing render options
Listeners may inspect and manipulate [render options](/up.render) for the coming fragment update.
The code below will use a custom [transition](/up-transition)
when a form submission [fails](/server-errors):
```js
up.on('up:form:submit', function(event, form) {
event.renderOptions.failTransition = 'shake'
})
```
@event up:form:submit
@param {Element} event.target
The `<form>` element that will be submitted.
@param {Object} event.renderOptions
An object with [render options](/up.render) for the fragment update
Listeners may inspect and modify these options.
@param event.preventDefault()
Event listeners may call this method to prevent the form from being submitted.
@stable
###
# MacOS does not focus buttons on click.
# That means that submittingButton() cannot rely on document.activeElement.
# See https://github.com/unpoly/unpoly/issues/103
up.on 'up:click', submitButtonSelector, (event, button) ->
# Don't mess with focus unless we know that we're going to handle the form.
# https://groups.google.com/g/unpoly/c/wsiATxepVZk
form = e.closest(button, 'form')
if form && isSubmittable(form)
button.focus()
###**
Observes form fields and runs a callback when a value changes.
This is useful for observing text fields while the user is typing.
The unobtrusive variant of this is the [`[up-observe]`](/up-observe) attribute.
\#\#\# Example
The following would print to the console whenever an input field changes:
up.observe('input.query', function(value) {
console.log('Query is now %o', value)
})
Instead of a single form field, you can also pass multiple fields,
a `<form>` or any container that contains form fields.
The callback will be run if any of the given fields change:
up.observe('form', function(value, name) {
console.log('The value of %o is now %o', name, value)
})
You may also pass the `{ batch: true }` option to receive all
changes since the last callback in a single object:
up.observe('form', { batch: true }, function(diff) {
console.log('Observed one or more changes: %o', diff)
})
@function up.observe
@param {string|Element|Array<Element>|jQuery} elements
The form fields that will be observed.
You can pass one or more fields, a `<form>` or any container that contains form fields.
The callback will be run if any of the given fields change.
@param {boolean} [options.batch=false]
If set to `true`, the `onChange` callback will receive multiple
detected changes in a single diff object as its argument.
@param {number} [options.delay=up.form.config.observeDelay]
The number of miliseconds to wait before executing the callback
after the input value changes. Use this to limit how often the callback
will be invoked for a fast typist.
@param {Function(value, name): string} onChange
The callback to run when the field's value changes.
If given as a function, it receives two arguments (`value`, `name`).
`value` is a string with the new attribute value and `string` is the name
of the form field that changed. If given as a string, it will be evaled as
JavaScript code in a context where (`value`, `name`) are set.
A long-running callback function may return a promise that settles when
the callback completes. In this case the callback will not be called again while
it is already running.
@return {Function()}
A destructor function that removes the observe watch when called.
@stable
###
observe = (elements, args...) ->
elements = e.list(elements)
fields = u.flatMap(elements, findFields)
callback = u.extractCallback(args) ? observeCallbackFromElement(elements[0]) ? up.fail('up.observe: No change callback given')
options = u.extractOptions(args)
options.delay = options.delay ? e.numberAttr(elements[0], 'up-delay') ? config.observeDelay
observer = new up.FieldObserver(fields, options, callback)
observer.start()
return -> observer.stop()
observeCallbackFromElement = (element) ->
if rawCallback = element.getAttribute('up-observe')
new Function('value', 'name', rawCallback)
###**
[Observes](/up.observe) a field or form and submits the form when a value changes.
Both the form and the changed field will be assigned a CSS class [`.up-active`](/form-up-active)
while the autosubmitted form is processing.
The unobtrusive variant of this is the [`[up-autosubmit]`](/form-up-autosubmit) attribute.
@function up.autosubmit
@param {string|Element|jQuery} target
The field or form to observe.
@param {Object} [options]
See options for [`up.observe()`](/up.observe)
@return {Function()}
A destructor function that removes the observe watch when called.
@stable
###
autosubmit = (target, options) ->
observe(target, options, -> submit(target))
findValidateTarget = (element, options) ->
container = getContainer(element)
if u.isElementish(options.target)
return up.fragment.toTarget(options.target)
else if givenTarget = options.target || element.getAttribute('up-validate') || container.getAttribute('up-validate')
return givenTarget
else if e.matches(element, 'form')
# If element is the form, we cannot find a better validate target than this.
return up.fragment.toTarget(element)
else
return findValidateTargetFromConfig(element, options) || up.fail('Could not find validation target for %o (tried defaults %o)', element, config.validateTargets)
findValidateTargetFromConfig = (element, options) ->
# for the first selector that has a match in the field's layer.
layer = up.layer.get(element)
return u.findResult config.validateTargets, (defaultTarget) ->
if up.fragment.get(defaultTarget, u.merge(options, { layer }))
# We want to return the selector, *not* the element. If we returned the element
# and derive a selector from that, any :has() expression would be lost.
return defaultTarget
###**
Performs a server-side validation of a form field.
`up.validate()` submits the given field's form with an additional `X-Up-Validate`
HTTP header. Upon seeing this header, the server is expected to validate (but not save)
the form submission and render a new copy of the form with validation errors.
The unobtrusive variant of this is the [`input[up-validate]`](/input-up-validate) selector.
See the documentation for [`input[up-validate]`](/input-up-validate) for more information
on how server-side validation works in Unpoly.
\#\#\# Example
```js
up.validate('input[name=email]', { target: '.email-errors' })
```
@function up.validate
@param {string|Element|jQuery} field
The form field to validate.
@param {string|Element|jQuery} [options.target]
The element that will be [updated](/up.render) with the validation results.
@return {Promise}
A promise that fulfills when the server-side
validation is received and the form was updated.
@stable
###
validate = (field, options) ->
# If passed a selector, up.fragment.get() will prefer a match on the current layer.
field = up.fragment.get(field)
options = u.options(options)
options.navigate = false
options.origin = field
options.history = false
options.target = findValidateTarget(field, options)
options.focus = 'keep'
# The protocol doesn't define whether the validation results in a status code.
# Hence we use the same options for both success and failure.
options.fail = false
# Make sure the X-Up-Validate header is present, so the server-side
# knows that it should not persist the form submission
options.headers ||= {}
options.headers[up.protocol.headerize('validate')] = field.getAttribute('name') || ':unknown'
# The guardEvent will also be assigned a { renderOptions } attribute in up.render()
options.guardEvent = up.event.build('up:form:validate', { field, log: 'Validating form' })
return submit(field, options)
###**
This event is emitted before a field is being [validated](/input-up-validate).
@event up:form:validate
@param {Element} event.field
The form field that has been changed and caused the validated request.
@param {Object} event.renderOptions
An object with [render options](/up.render) for the fragment update
that will show the validation results.
Listeners may inspect and modify these options.
@param event.preventDefault()
Event listeners may call this method to prevent the validation request
being sent to the server.
@stable
###
switcherValues = (field) ->
value = undefined
meta = undefined
if e.matches(field, 'input[type=checkbox]')
if field.checked
value = field.value
meta = ':checked'
else
meta = ':unchecked'
else if e.matches(field, 'input[type=radio]')
form = getContainer(field)
groupName = field.getAttribute('name')
checkedButton = form.querySelector("input[type=radio]#{e.attributeSelector('name', groupName)}:checked")
if checkedButton
meta = ':checked'
value = checkedButton.value
else
meta = ':unchecked'
else
value = field.value
values = []
if u.isPresent(value)
values.push(value)
values.push(':present')
else
values.push(':blank')
if u.isPresent(meta)
values.push(meta)
values
###**
Shows or hides a target selector depending on the value.
See [`input[up-switch]`](/input-up-switch) for more documentation and examples.
This function does not currently have a very useful API outside
of our use for `up-switch`'s UJS behavior, that's why it's currently
still marked `@internal`.
@function up.form.switchTargets
@param {Element} switcher
@param {string} [options.target]
The target selectors to switch.
Defaults to an `[up-switch]` attribute on the given field.
@internal
###
switchTargets = (switcher, options = {}) ->
targetSelector = options.target ? switcher.getAttribute('up-switch')
form = getContainer(switcher)
targetSelector or up.fail("No switch target given for %o", switcher)
fieldValues = switcherValues(switcher)
u.each e.all(form, targetSelector), (target) ->
switchTarget(target, fieldValues)
###**
@internal
###
switchTarget = up.mockable (target, fieldValues) ->
fieldValues ||= switcherValues(findSwitcherForTarget(target))
if hideValues = target.getAttribute('up-hide-for')
hideValues = u.splitValues(hideValues)
show = u.intersect(fieldValues, hideValues).length == 0
else
if showValues = target.getAttribute('up-show-for')
showValues = u.splitValues(showValues)
else
# If the target has neither up-show-for or up-hide-for attributes,
# assume the user wants the target to be visible whenever anything
# is checked or entered.
showValues = [':present', ':checked']
show = u.intersect(fieldValues, showValues).length > 0
e.toggle(target, show)
target.classList.add('up-switched')
###**
@internal
###
findSwitcherForTarget = (target) ->
form = getContainer(target)
switchers = e.all(form, '[up-switch]')
switcher = u.find switchers, (switcher) ->
targetSelector = switcher.getAttribute('up-switch')
e.matches(target, targetSelector)
return switcher or up.fail('Could not find [up-switch] field for %o', target)
getContainer = (element) ->
element.form || # Element#form will also work if the element is outside the form with an [form=form-id] attribute
e.closest(element, "form, #{up.layer.anySelector()}")
focusedField = ->
if (element = document.activeElement) && e.matches(element, fieldSelector())
return element
###**
Returns whether the given form will be [submitted](/up.follow) through Unpoly
instead of making a full page load.
By default Unpoly will follow forms if the element has
one of the following attributes:
- `[up-submit]`
- `[up-target]`
- `[up-layer]`
- `[up-transition]`
To consider other selectors to be submittable, see `up.form.config.submitSelectors`.
@function up.form.isSubmittable
@param {Element|jQuery|string} form
The form to check.
@stable
###
isSubmittable = (form) ->
form = up.fragment.get(form)
return e.matches(form, fullSubmitSelector()) && !isSubmitDisabled(form)
isSubmitDisabled = (form) ->
# We also don't want to handle cross-origin forms.
# That will be handled in `up.Change.FromURL#newPageReason`.
return e.matches(form, config.noSubmitSelectors.join(','))
###**
Submits this form via JavaScript and updates a fragment with the server response.
The server response is searched for the selector given in `up-target`.
The selector content is then [replaced](/up.replace) in the current page.
The programmatic variant of this is the [`up.submit()`](/up.submit) function.
\#\#\# Example
```html
<form method="post" action="/users" up-submit>
...
</form>
```
\#\#\# Handling validation errors
When the server was unable to save the form due to invalid params,
it will usually re-render an updated copy of the form with
validation messages.
For Unpoly to be able to detect a failed form submission,
the form must be re-rendered with a non-200 HTTP status code.
We recommend to use either 400 (bad request) or
422 (unprocessable entity).
In Ruby on Rails, you can pass a
[`:status` option to `render`](http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option)
for this:
```ruby
class UsersController < ApplicationController
def create
user_params = params[:user].permit(:email, :password)
@user = User.new(user_params)
if @user.save?
sign_in @user
else
render 'form', status: :bad_request
end
end
end
```
You may define different option for the failure case by infixing an attribute with `fail`:
```html
<form method="post" action="/action"
up-target=".content"
up-fail-target="form"
up-scroll="auto"
up-fail-scroll=".errors">
...
</form>
```
See [handling server errors](/server-errors) for details.
Note that you can also use
[`input[up-validate]`](/input-up-validate) to perform server-side
validations while the user is completing fields.
\#\#\# Giving feedback while the form is processing
The `<form>` element will be assigned a CSS class [`.up-active`](/form.up-active) while
the submission is loading.
\#\#\# Short notation
You may omit the `[up-submit]` attribute if the form has one of the following attributes:
- `[up-target]`
- `[up-layer]`
- `[up-transition]`
Such a form will still be submitted through Unpoly.
\#\#\# Handling all forms automatically
You can configure Unpoly to handle *all* forms on a page without requiring an `[up-submit]` attribute.
See [Handling all links and forms](/handling-everything).
@selector form[up-submit]
@params-note
All attributes for `a[up-follow]` may also be used.
@stable
###
up.on 'submit', fullSubmitSelector, (event, form) ->
# Users may configure up.form.config.submitSelectors.push('form')
# and then opt out individual forms with [up-submit=false].
if event.defaultPrevented || isSubmitDisabled(form)
return
abortScheduledValidate?()
up.event.halt(event)
up.log.muteUncriticalRejection submit(form)
###**
When a form field with this attribute is changed, the form is validated on the server
and is updated with validation messages.
To validate the form, Unpoly will submit the form with an additional `X-Up-Validate` HTTP header.
When seeing this header, the server is expected to validate (but not save)
the form submission and render a new copy of the form with validation errors.
The programmatic variant of this is the [`up.validate()`](/up.validate) function.
\#\#\# Example
Let's look at a standard registration form that asks for an e-mail and password:
<form action="/users">
<label>
E-mail: <input type="text" name="email" />
</label>
<label>
Password: <input type="PI:PASSWORD:<PASSWORD>END_PI" name="PI:PASSWORD:<PASSWORD>END_PI" />
</label>
<button type="submit">Register</button>
</form>
When the user changes the `email` field, we want to validate that
the e-mail address is valid and still available. Also we want to
change the `password` field for the minimum required password length.
We can do this by giving both fields an `up-validate` attribute:
<form action="/users">
<label>
E-mail: <input type="text" name="email" up-validate />
</label>
<label>
Password: <input type="PI:PASSWORD:<PASSWORD>END_PI" name="password" up-validate />
</label>
<button type="submit">Register</button>
</form>
Whenever a field with `up-validate` changes, the form is POSTed to
`/users` with an additional `X-Up-Validate` HTTP header.
When seeing this header, the server is expected to validate (but not save)
the form submission and render a new copy of the form with validation errors.
In Ruby on Rails the processing action should behave like this:
class UsersController < ApplicationController
# This action handles POST /users
def create
user_params = params[:user].permit(:email, :password)
@user = User.new(user_params)
if request.headers['X-Up-Validate']
@user.valid? # run validations, but don't save to the database
render 'form' # render form with error messages
elsif @user.save?
sign_in @user
else
render 'form', status: :bad_request
end
end
end
Note that if you're using the `unpoly-rails` gem you can simply say `up.validate?`
instead of manually checking for `request.headers['X-Up-Validate']`.
The server now renders an updated copy of the form with eventual validation errors:
<form action="/users">
<label class="has-error">
E-mail: <input type="text" name="email" value="PI:EMAIL:<EMAIL>END_PI" />
Has already been taken!
</label>
<button type="submit">Register</button>
</form>
The `<label>` around the e-mail field is now updated to have the `has-error`
class and display the validation message.
\#\#\# How validation results are displayed
Although the server will usually respond to a validation with a complete,
fresh copy of the form, Unpoly will by default not update the entire form.
This is done in order to preserve volatile state such as the scroll position
of `<textarea>` elements.
By default Unpoly looks for a `<fieldset>`, `<label>` or `<form>`
around the validating input field, or any element with an
`up-fieldset` attribute.
With the Bootstrap bindings, Unpoly will also look
for a container with the `form-group` class.
You can change this default behavior by setting `up.form.config.validateTargets`:
// Always update the entire form containing the current field ("&")
up.form.config.validateTargets = ['form &']
You can also individually override what to update by setting the `up-validate`
attribute to a CSS selector:
<input type="text" name="email" up-validate=".email-errors">
<span class="email-errors"></span>
\#\#\# Updating dependent fields
The `[up-validate]` behavior is also a great way to partially update a form
when one fields depends on the value of another field.
Let's say you have a form with one `<select>` to pick a department (sales, engineering, ...)
and another `<select>` to pick an employeee from the selected department:
<form action="/contracts">
<select name="department">...</select> <!-- options for all departments -->
<select name="employeed">...</select> <!-- options for employees of selected department -->
</form>
The list of employees needs to be updated as the appartment changes:
<form action="/contracts">
<select name="department" up-validate="[name=employee]">...</select>
<select name="employee">...</select>
</form>
In order to update the `department` field in addition to the `employee` field, you could say
`up-validate="&, [name=employee]"`, or simply `up-validate="form"` to update the entire form.
@selector input[up-validate]
@param up-validate
The CSS selector to update with the server response.
This defaults to a fieldset or form group around the validating field.
@stable
###
###**
Validates this form on the server when any field changes and shows validation errors.
You can configure what Unpoly considers a fieldset by adding CSS selectors to the
`up.form.config.validateTargets` array.
See `input[up-validate]` for detailed documentation.
@selector form[up-validate]
@param up-validate
The CSS selector to update with the server response.
This defaults to a fieldset or form group around the changing field.
@stable
###
up.on 'change', '[up-validate]', (event) ->
# Even though [up-validate] may be used on either an entire form or an individual input,
# the change event will trigger on a given field.
field = findFields(event.target)[0]
# There is an edge case where the user is changing an input with [up-validate],
# but blurs the input by directly clicking the submit button. In this case the
# following events will be emitted:
#
# - change on the input
# - focus on the button
# - submit on the form
#
# In this case we do not want to send a validate request to the server, but
# simply submit the form. Because this event handler does not know if a submit
# event is about to fire, we delay the validation to the next microtask.
# In case we receive a submit event after this, we can cancel the validation.
abortScheduledValidate = u.abortableMicrotask ->
up.log.muteUncriticalRejection validate(field)
###**
Show or hide elements when a form field is set to a given value.
\#\#\# Example: Select options
The controlling form field gets an `up-switch` attribute with a selector for the elements to show or hide:
<select name="advancedness" up-switch=".target">
<option value="basic">Basic parts</option>
<option value="advanced">Advanced parts</option>
<option value="very-advanced">Very advanced parts</option>
</select>
The target elements can use [`[up-show-for]`](/up-show-for) and [`[up-hide-for]`](/up-hide-for)
attributes to indicate for which values they should be shown or hidden:
<div class="target" up-show-for="basic">
only shown for advancedness = basic
</div>
<div class="target" up-hide-for="basic">
hidden for advancedness = basic
</div>
<div class="target" up-show-for="advanced very-advanced">
shown for advancedness = advanced or very-advanced
</div>
\#\#\# Example: Text field
The controlling `<input>` gets an `up-switch` attribute with a selector for the elements to show or hide:
<input type="text" name="user" up-switch=".target">
<div class="target" up-show-for="alice">
only shown for user alice
</div>
You can also use the pseudo-values `:blank` to match an empty input value,
or `:present` to match a non-empty input value:
<input type="text" name="user" up-switch=".target">
<div class="target" up-show-for=":blank">
please enter a username
</div>
\#\#\# Example: Checkbox
For checkboxes you can match against the pseudo-values `:checked` or `:unchecked`:
<input type="checkbox" name="flag" up-switch=".target">
<div class="target" up-show-for=":checked">
only shown when checkbox is checked
</div>
<div class="target" up-show-for=":cunhecked">
only shown when checkbox is unchecked
</div>
Of course you can also match against the `value` property of the checkbox element:
<input type="checkbox" name="flag" value="active" up-switch=".target">
<div class="target" up-show-for="active">
only shown when checkbox is checked
</div>
@selector input[up-switch]
@param up-switch
A CSS selector for elements whose visibility depends on this field's value.
@stable
###
###**
Only shows this element if an input field with [`[up-switch]`](/input-up-switch) has one of the given values.
See [`input[up-switch]`](/input-up-switch) for more documentation and examples.
@selector [up-show-for]
@param [up-show-for]
A space-separated list of input values for which this element should be shown.
@stable
###
###**
Hides this element if an input field with [`[up-switch]`](/input-up-switch) has one of the given values.
See [`input[up-switch]`](/input-up-switch) for more documentation and examples.
@selector [up-hide-for]
@param [up-hide-for]
A space-separated list of input values for which this element should be hidden.
@stable
###
up.compiler '[up-switch]', (switcher) ->
switchTargets(switcher)
up.on 'change', '[up-switch]', (event, switcher) ->
switchTargets(switcher)
up.compiler '[up-show-for]:not(.up-switched), [up-hide-for]:not(.up-switched)', (element) ->
switchTarget(element)
###**
Observes this field and runs a callback when a value changes.
This is useful for observing text fields while the user is typing.
If you want to submit the form after a change see [`input[up-autosubmit]`](/input-up-autosubmit).
The programmatic variant of this is the [`up.observe()`](/up.observe) function.
\#\#\# Example
The following would run a global `showSuggestions(value)` function
whenever the `<input>` changes:
<input name="query" up-observe="showSuggestions(value)">
Note that the parameter name in the markup must be called `value` or it will not work.
The parameter name can be called whatever you want in the JavaScript, however.
Also note that the function must be declared on the `window` object to work, like so:
window.showSuggestions = function(selectedValue) {
console.log(`Called showSuggestions() with ${selectedValue}`);
}
\#\#\# Callback context
The script given to `[up-observe]` runs with the following context:
| Name | Type | Description |
| -------- | --------- | ------------------------------------- |
| `value` | `string` | The current value of the field |
| `this` | `Element` | The form field |
| `$field` | `jQuery` | The form field as a jQuery collection |
\#\#\# Observing radio buttons
Multiple radio buttons with the same `[name]` (a radio button group)
produce a single value for the form.
To observe radio buttons group, use the `[up-observe]` attribute on an
element that contains all radio button elements with a given name:
<div up-observe="formatSelected(value)">
<input type="radio" name="format" value="html"> HTML format
<input type="radio" name="format" value="pdf"> PDF format
<input type="radio" name="format" value="txt"> Text format
</div>
@selector input[up-observe]
@param up-observe
The code to run when the field's value changes.
@param up-delay
The number of miliseconds to wait after a change before the code is run.
@stable
###
###**
Observes this form and runs a callback when any field changes.
This is useful for observing text fields while the user is typing.
If you want to submit the form after a change see [`input[up-autosubmit]`](/input-up-autosubmit).
The programmatic variant of this is the [`up.observe()`](/up.observe) function.
\#\#\# Example
The would call a function `somethingChanged(value)`
when any `<input>` within the `<form>` changes:
<form up-observe="somethingChanged(value)">
<input name="foo">
<input name="bar">
</form>
\#\#\# Callback context
The script given to `[up-observe]` runs with the following context:
| Name | Type | Description |
| -------- | --------- | ------------------------------------- |
| `value` | `string` | The current value of the field |
| `this` | `Element` | The form field |
| `$field` | `jQuery` | The form field as a jQuery collection |
@selector form[up-observe]
@param up-observe
The code to run when any field's value changes.
@param up-delay
The number of miliseconds to wait after a change before the code is run.
@stable
###
up.compiler '[up-observe]', (formOrField) -> observe(formOrField)
###**
Submits this field's form when this field changes its values.
Both the form and the changed field will be assigned a CSS class [`.up-active`](/form-up-active)
while the autosubmitted form is loading.
The programmatic variant of this is the [`up.autosubmit()`](/up.autosubmit) function.
\#\#\# Example
The following would automatically submit the form when the query is changed:
<form method="GET" action="/search">
<input type="search" name="query" up-autosubmit>
<input type="checkbox" name="archive"> Include archive
</form>
\#\#\# Auto-submitting radio buttons
Multiple radio buttons with the same `[name]` (a radio button group)
produce a single value for the form.
To auto-submit radio buttons group, use the `[up-submit]` attribute on an
element that contains all radio button elements with a given name:
<div up-autosubmit>
<input type="radio" name="format" value="html"> HTML format
<input type="radio" name="format" value="pdf"> PDF format
<input type="radio" name="format" value="txt"> Text format
</div>
@selector input[up-autosubmit]
@param [up-delay]
The number of miliseconds to wait after a change before the form is submitted.
@stable
###
###**
Submits the form when any field changes.
Both the form and the field will be assigned a CSS class [`.up-active`](/form-up-active)
while the autosubmitted form is loading.
The programmatic variant of this is the [`up.autosubmit()`](/up.autosubmit) function.
\#\#\# Example
This will submit the form when either query or checkbox was changed:
<form method="GET" action="/search" up-autosubmit>
<input type="search" name="query">
<input type="checkbox" name="archive"> Include archive
</form>
@selector form[up-autosubmit]
@param [up-delay]
The number of miliseconds to wait after a change before the form is submitted.
@stable
###
up.compiler '[up-autosubmit]', (formOrField) -> autosubmit(formOrField)
up.on 'up:framework:reset', reset
config: config
submit: submit
submitOptions: submitOptions
isSubmittable: isSubmittable
observe: observe
validate: validate
autosubmit: autosubmit
fieldSelector: fieldSelector
fields: findFields
focusedField: focusedField
switchTarget: switchTarget
up.submit = up.form.submit
up.observe = up.form.observe
up.autosubmit = up.form.autosubmit
up.validate = up.form.validate
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9987452030181885,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": " count the one we are adding, as well.\n # TODO(isaacs) clean this up\n state.pendingcb++\n doWrite ",
"end": 8622,
"score": 0.997931957244873,
"start": 8616,
"tag": "USERNAME",
"value": "isaacs"
}
] | lib/_stream_writable.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 bit simpler than readable streams.
# Implement an async ._write(chunk, cb), and it'll handle all
# the drain event emission and buffering.
WriteReq = (chunk, encoding, cb) ->
@chunk = chunk
@encoding = encoding
@callback = cb
return
WritableState = (options, stream) ->
options = options or {}
# object stream flag to indicate whether or not this stream
# contains buffers or objects.
@objectMode = !!options.objectMode
@objectMode = @objectMode or !!options.writableObjectMode if stream instanceof Stream.Duplex
# the point at which write() starts returning false
# Note: 0 is a valid value, means that we always return false if
# the entire buffer is not flushed immediately on write()
hwm = options.highWaterMark
defaultHwm = (if @objectMode then 16 else 16 * 1024)
@highWaterMark = (if (hwm or hwm is 0) then hwm else defaultHwm)
# cast to ints.
@highWaterMark = ~~@highWaterMark
@needDrain = false
# at the start of calling end()
@ending = false
# when end() has been called, and returned
@ended = false
# when 'finish' is emitted
@finished = false
# should we decode strings into buffers before passing to _write?
# this is here so that some node-core streams can optimize string
# handling at a lower level.
noDecode = options.decodeStrings is false
@decodeStrings = not noDecode
# Crypto is kind of old and crusty. Historically, its default string
# encoding is 'binary' so we have to make this configurable.
# Everything else in the universe uses 'utf8', though.
@defaultEncoding = options.defaultEncoding or "utf8"
# not an actual buffer we keep track of, but a measurement
# of how much we're waiting to get pushed to some underlying
# socket or file.
@length = 0
# a flag to see when we're in the middle of a write.
@writing = false
# when true all writes will be buffered until .uncork() call
@corked = 0
# a flag to be able to tell if the onwrite cb is called immediately,
# or on a later tick. We set this to true at first, because any
# actions that shouldn't happen until "later" should generally also
# not happen before the first write call.
@sync = true
# a flag to know if we're processing previously buffered items, which
# may call the _write() callback in the same tick, so that we don't
# end up in an overlapped onwrite situation.
@bufferProcessing = false
# the callback that's passed to _write(chunk,cb)
@onwrite = (er) ->
onwrite stream, er
return
# the callback that the user supplies to write(chunk,encoding,cb)
@writecb = null
# the amount that is being written when _write is called.
@writelen = 0
@buffer = []
# number of pending user-supplied write callbacks
# this must be 0 before 'finish' can be emitted
@pendingcb = 0
# emit prefinish if the only thing we're waiting for is _write cbs
# This is relevant for synchronous Transform streams
@prefinished = false
# True if the error was already emitted and should not be thrown again
@errorEmitted = false
return
Writable = (options) ->
# Writable ctor is applied to Duplexes, though they're not
# instanceof Writable, they're instanceof Readable.
return new Writable(options) if (this not instanceof Writable) and (this not instanceof Stream.Duplex)
@_writableState = new WritableState(options, this)
# legacy.
@writable = true
Stream.call this
return
# Otherwise people can pipe Writable streams, which is just wrong.
writeAfterEnd = (stream, state, cb) ->
er = new Error("write after end")
# TODO: defer error events consistently everywhere, not just the cb
stream.emit "error", er
process.nextTick ->
cb er
return
return
# If we get something that is not a buffer, string, null, or undefined,
# and we're not in objectMode, then that's an error.
# Otherwise stream chunks are all considered to be of length=1, and the
# watermarks determine how many objects to keep in the buffer, rather than
# how many bytes or characters.
validChunk = (stream, state, chunk, cb) ->
valid = true
if not util.isBuffer(chunk) and not util.isString(chunk) and not util.isNullOrUndefined(chunk) and not state.objectMode
er = new TypeError("Invalid non-string/buffer chunk")
stream.emit "error", er
process.nextTick ->
cb er
return
valid = false
valid
# node::ParseEncoding() requires lower case.
decodeChunk = (state, chunk, encoding) ->
chunk = new Buffer(chunk, encoding) if not state.objectMode and state.decodeStrings isnt false and util.isString(chunk)
chunk
# if we're already writing something, then just put this
# in the queue, and wait our turn. Otherwise, call _write
# If we return false, then we need a drain event, so set that flag.
writeOrBuffer = (stream, state, chunk, encoding, cb) ->
chunk = decodeChunk(state, chunk, encoding)
encoding = "buffer" if util.isBuffer(chunk)
len = (if state.objectMode then 1 else chunk.length)
state.length += len
ret = state.length < state.highWaterMark
# we must ensure that previous needDrain will not be reset to false.
state.needDrain = true unless ret
if state.writing or state.corked
state.buffer.push new WriteReq(chunk, encoding, cb)
else
doWrite stream, state, false, len, chunk, encoding, cb
ret
doWrite = (stream, state, writev, len, chunk, encoding, cb) ->
state.writelen = len
state.writecb = cb
state.writing = true
state.sync = true
if writev
stream._writev chunk, state.onwrite
else
stream._write chunk, encoding, state.onwrite
state.sync = false
return
onwriteError = (stream, state, sync, er, cb) ->
if sync
process.nextTick ->
state.pendingcb--
cb er
return
else
state.pendingcb--
cb er
stream._writableState.errorEmitted = true
stream.emit "error", er
return
onwriteStateUpdate = (state) ->
state.writing = false
state.writecb = null
state.length -= state.writelen
state.writelen = 0
return
onwrite = (stream, er) ->
state = stream._writableState
sync = state.sync
cb = state.writecb
onwriteStateUpdate state
if er
onwriteError stream, state, sync, er, cb
else
# Check if we're actually ready to finish, but don't emit yet
finished = needFinish(stream, state)
clearBuffer stream, state if not finished and not state.corked and not state.bufferProcessing and state.buffer.length
if sync
process.nextTick ->
afterWrite stream, state, finished, cb
return
else
afterWrite stream, state, finished, cb
return
afterWrite = (stream, state, finished, cb) ->
onwriteDrain stream, state unless finished
state.pendingcb--
cb()
finishMaybe stream, state
return
# Must force callback to be called on nextTick, so that we don't
# emit 'drain' before the write() consumer gets the 'false' return
# value, and has a chance to attach a 'drain' listener.
onwriteDrain = (stream, state) ->
if state.length is 0 and state.needDrain
state.needDrain = false
stream.emit "drain"
return
# if there's something in the buffer waiting, then process it
clearBuffer = (stream, state) ->
state.bufferProcessing = true
if stream._writev and state.buffer.length > 1
# Fast case, write everything using _writev()
cbs = []
c = 0
while c < state.buffer.length
cbs.push state.buffer[c].callback
c++
# count the one we are adding, as well.
# TODO(isaacs) clean this up
state.pendingcb++
doWrite stream, state, true, state.length, state.buffer, "", (err) ->
i = 0
while i < cbs.length
state.pendingcb--
cbs[i] err
i++
return
# Clear buffer
state.buffer = []
else
# Slow case, write chunks one-by-one
c = 0
while c < state.buffer.length
entry = state.buffer[c]
chunk = entry.chunk
encoding = entry.encoding
cb = entry.callback
len = (if state.objectMode then 1 else chunk.length)
doWrite stream, state, false, len, chunk, encoding, cb
# if we didn't call the onwrite immediately, then
# it means that we need to wait until it does.
# also, that means that the chunk and cb are currently
# being processed, so move the buffer counter past them.
if state.writing
c++
break
c++
if c < state.buffer.length
state.buffer = state.buffer.slice(c)
else
state.buffer.length = 0
state.bufferProcessing = false
return
# .end() fully uncorks
# ignore unnecessary end() calls.
needFinish = (stream, state) ->
state.ending and state.length is 0 and state.buffer.length is 0 and not state.finished and not state.writing
prefinish = (stream, state) ->
unless state.prefinished
state.prefinished = true
stream.emit "prefinish"
return
finishMaybe = (stream, state) ->
need = needFinish(stream, state)
if need
if state.pendingcb is 0
prefinish stream, state
state.finished = true
stream.emit "finish"
else
prefinish stream, state
need
endWritable = (stream, state, cb) ->
state.ending = true
finishMaybe stream, state
if cb
if state.finished
process.nextTick cb
else
stream.once "finish", cb
state.ended = true
return
"use strict"
module.exports = Writable
Writable.WritableState = WritableState
util = require("util")
Stream = require("stream")
util.inherits Writable, Stream
Writable::pipe = ->
@emit "error", new Error("Cannot pipe. Not readable.")
return
Writable::write = (chunk, encoding, cb) ->
state = @_writableState
ret = false
if util.isFunction(encoding)
cb = encoding
encoding = null
if util.isBuffer(chunk)
encoding = "buffer"
else encoding = state.defaultEncoding unless encoding
cb = -> unless util.isFunction(cb)
if state.ended
writeAfterEnd this, state, cb
else if validChunk(this, state, chunk, cb)
state.pendingcb++
ret = writeOrBuffer(this, state, chunk, encoding, cb)
ret
Writable::cork = ->
state = @_writableState
state.corked++
return
Writable::uncork = ->
state = @_writableState
if state.corked
state.corked--
clearBuffer this, state if not state.writing and not state.corked and not state.finished and not state.bufferProcessing and state.buffer.length
return
Writable::setDefaultEncoding = setDefaultEncoding = (encoding) ->
encoding = encoding.toLowerCase() if typeof encoding is "string"
throw new TypeError("Unknown encoding: " + encoding) unless Buffer.isEncoding(encoding)
@_writableState.defaultEncoding = encoding
return
Writable::_write = (chunk, encoding, cb) ->
cb new Error("not implemented")
return
Writable::_writev = null
Writable::end = (chunk, encoding, cb) ->
state = @_writableState
if util.isFunction(chunk)
cb = chunk
chunk = null
encoding = null
else if util.isFunction(encoding)
cb = encoding
encoding = null
@write chunk, encoding unless util.isNullOrUndefined(chunk)
if state.corked
state.corked = 1
@uncork()
endWritable this, state, cb if not state.ending and not state.finished
return
| 9109 | # 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 bit simpler than readable streams.
# Implement an async ._write(chunk, cb), and it'll handle all
# the drain event emission and buffering.
WriteReq = (chunk, encoding, cb) ->
@chunk = chunk
@encoding = encoding
@callback = cb
return
WritableState = (options, stream) ->
options = options or {}
# object stream flag to indicate whether or not this stream
# contains buffers or objects.
@objectMode = !!options.objectMode
@objectMode = @objectMode or !!options.writableObjectMode if stream instanceof Stream.Duplex
# the point at which write() starts returning false
# Note: 0 is a valid value, means that we always return false if
# the entire buffer is not flushed immediately on write()
hwm = options.highWaterMark
defaultHwm = (if @objectMode then 16 else 16 * 1024)
@highWaterMark = (if (hwm or hwm is 0) then hwm else defaultHwm)
# cast to ints.
@highWaterMark = ~~@highWaterMark
@needDrain = false
# at the start of calling end()
@ending = false
# when end() has been called, and returned
@ended = false
# when 'finish' is emitted
@finished = false
# should we decode strings into buffers before passing to _write?
# this is here so that some node-core streams can optimize string
# handling at a lower level.
noDecode = options.decodeStrings is false
@decodeStrings = not noDecode
# Crypto is kind of old and crusty. Historically, its default string
# encoding is 'binary' so we have to make this configurable.
# Everything else in the universe uses 'utf8', though.
@defaultEncoding = options.defaultEncoding or "utf8"
# not an actual buffer we keep track of, but a measurement
# of how much we're waiting to get pushed to some underlying
# socket or file.
@length = 0
# a flag to see when we're in the middle of a write.
@writing = false
# when true all writes will be buffered until .uncork() call
@corked = 0
# a flag to be able to tell if the onwrite cb is called immediately,
# or on a later tick. We set this to true at first, because any
# actions that shouldn't happen until "later" should generally also
# not happen before the first write call.
@sync = true
# a flag to know if we're processing previously buffered items, which
# may call the _write() callback in the same tick, so that we don't
# end up in an overlapped onwrite situation.
@bufferProcessing = false
# the callback that's passed to _write(chunk,cb)
@onwrite = (er) ->
onwrite stream, er
return
# the callback that the user supplies to write(chunk,encoding,cb)
@writecb = null
# the amount that is being written when _write is called.
@writelen = 0
@buffer = []
# number of pending user-supplied write callbacks
# this must be 0 before 'finish' can be emitted
@pendingcb = 0
# emit prefinish if the only thing we're waiting for is _write cbs
# This is relevant for synchronous Transform streams
@prefinished = false
# True if the error was already emitted and should not be thrown again
@errorEmitted = false
return
Writable = (options) ->
# Writable ctor is applied to Duplexes, though they're not
# instanceof Writable, they're instanceof Readable.
return new Writable(options) if (this not instanceof Writable) and (this not instanceof Stream.Duplex)
@_writableState = new WritableState(options, this)
# legacy.
@writable = true
Stream.call this
return
# Otherwise people can pipe Writable streams, which is just wrong.
writeAfterEnd = (stream, state, cb) ->
er = new Error("write after end")
# TODO: defer error events consistently everywhere, not just the cb
stream.emit "error", er
process.nextTick ->
cb er
return
return
# If we get something that is not a buffer, string, null, or undefined,
# and we're not in objectMode, then that's an error.
# Otherwise stream chunks are all considered to be of length=1, and the
# watermarks determine how many objects to keep in the buffer, rather than
# how many bytes or characters.
validChunk = (stream, state, chunk, cb) ->
valid = true
if not util.isBuffer(chunk) and not util.isString(chunk) and not util.isNullOrUndefined(chunk) and not state.objectMode
er = new TypeError("Invalid non-string/buffer chunk")
stream.emit "error", er
process.nextTick ->
cb er
return
valid = false
valid
# node::ParseEncoding() requires lower case.
decodeChunk = (state, chunk, encoding) ->
chunk = new Buffer(chunk, encoding) if not state.objectMode and state.decodeStrings isnt false and util.isString(chunk)
chunk
# if we're already writing something, then just put this
# in the queue, and wait our turn. Otherwise, call _write
# If we return false, then we need a drain event, so set that flag.
writeOrBuffer = (stream, state, chunk, encoding, cb) ->
chunk = decodeChunk(state, chunk, encoding)
encoding = "buffer" if util.isBuffer(chunk)
len = (if state.objectMode then 1 else chunk.length)
state.length += len
ret = state.length < state.highWaterMark
# we must ensure that previous needDrain will not be reset to false.
state.needDrain = true unless ret
if state.writing or state.corked
state.buffer.push new WriteReq(chunk, encoding, cb)
else
doWrite stream, state, false, len, chunk, encoding, cb
ret
doWrite = (stream, state, writev, len, chunk, encoding, cb) ->
state.writelen = len
state.writecb = cb
state.writing = true
state.sync = true
if writev
stream._writev chunk, state.onwrite
else
stream._write chunk, encoding, state.onwrite
state.sync = false
return
onwriteError = (stream, state, sync, er, cb) ->
if sync
process.nextTick ->
state.pendingcb--
cb er
return
else
state.pendingcb--
cb er
stream._writableState.errorEmitted = true
stream.emit "error", er
return
onwriteStateUpdate = (state) ->
state.writing = false
state.writecb = null
state.length -= state.writelen
state.writelen = 0
return
onwrite = (stream, er) ->
state = stream._writableState
sync = state.sync
cb = state.writecb
onwriteStateUpdate state
if er
onwriteError stream, state, sync, er, cb
else
# Check if we're actually ready to finish, but don't emit yet
finished = needFinish(stream, state)
clearBuffer stream, state if not finished and not state.corked and not state.bufferProcessing and state.buffer.length
if sync
process.nextTick ->
afterWrite stream, state, finished, cb
return
else
afterWrite stream, state, finished, cb
return
afterWrite = (stream, state, finished, cb) ->
onwriteDrain stream, state unless finished
state.pendingcb--
cb()
finishMaybe stream, state
return
# Must force callback to be called on nextTick, so that we don't
# emit 'drain' before the write() consumer gets the 'false' return
# value, and has a chance to attach a 'drain' listener.
onwriteDrain = (stream, state) ->
if state.length is 0 and state.needDrain
state.needDrain = false
stream.emit "drain"
return
# if there's something in the buffer waiting, then process it
clearBuffer = (stream, state) ->
state.bufferProcessing = true
if stream._writev and state.buffer.length > 1
# Fast case, write everything using _writev()
cbs = []
c = 0
while c < state.buffer.length
cbs.push state.buffer[c].callback
c++
# count the one we are adding, as well.
# TODO(isaacs) clean this up
state.pendingcb++
doWrite stream, state, true, state.length, state.buffer, "", (err) ->
i = 0
while i < cbs.length
state.pendingcb--
cbs[i] err
i++
return
# Clear buffer
state.buffer = []
else
# Slow case, write chunks one-by-one
c = 0
while c < state.buffer.length
entry = state.buffer[c]
chunk = entry.chunk
encoding = entry.encoding
cb = entry.callback
len = (if state.objectMode then 1 else chunk.length)
doWrite stream, state, false, len, chunk, encoding, cb
# if we didn't call the onwrite immediately, then
# it means that we need to wait until it does.
# also, that means that the chunk and cb are currently
# being processed, so move the buffer counter past them.
if state.writing
c++
break
c++
if c < state.buffer.length
state.buffer = state.buffer.slice(c)
else
state.buffer.length = 0
state.bufferProcessing = false
return
# .end() fully uncorks
# ignore unnecessary end() calls.
needFinish = (stream, state) ->
state.ending and state.length is 0 and state.buffer.length is 0 and not state.finished and not state.writing
prefinish = (stream, state) ->
unless state.prefinished
state.prefinished = true
stream.emit "prefinish"
return
finishMaybe = (stream, state) ->
need = needFinish(stream, state)
if need
if state.pendingcb is 0
prefinish stream, state
state.finished = true
stream.emit "finish"
else
prefinish stream, state
need
endWritable = (stream, state, cb) ->
state.ending = true
finishMaybe stream, state
if cb
if state.finished
process.nextTick cb
else
stream.once "finish", cb
state.ended = true
return
"use strict"
module.exports = Writable
Writable.WritableState = WritableState
util = require("util")
Stream = require("stream")
util.inherits Writable, Stream
Writable::pipe = ->
@emit "error", new Error("Cannot pipe. Not readable.")
return
Writable::write = (chunk, encoding, cb) ->
state = @_writableState
ret = false
if util.isFunction(encoding)
cb = encoding
encoding = null
if util.isBuffer(chunk)
encoding = "buffer"
else encoding = state.defaultEncoding unless encoding
cb = -> unless util.isFunction(cb)
if state.ended
writeAfterEnd this, state, cb
else if validChunk(this, state, chunk, cb)
state.pendingcb++
ret = writeOrBuffer(this, state, chunk, encoding, cb)
ret
Writable::cork = ->
state = @_writableState
state.corked++
return
Writable::uncork = ->
state = @_writableState
if state.corked
state.corked--
clearBuffer this, state if not state.writing and not state.corked and not state.finished and not state.bufferProcessing and state.buffer.length
return
Writable::setDefaultEncoding = setDefaultEncoding = (encoding) ->
encoding = encoding.toLowerCase() if typeof encoding is "string"
throw new TypeError("Unknown encoding: " + encoding) unless Buffer.isEncoding(encoding)
@_writableState.defaultEncoding = encoding
return
Writable::_write = (chunk, encoding, cb) ->
cb new Error("not implemented")
return
Writable::_writev = null
Writable::end = (chunk, encoding, cb) ->
state = @_writableState
if util.isFunction(chunk)
cb = chunk
chunk = null
encoding = null
else if util.isFunction(encoding)
cb = encoding
encoding = null
@write chunk, encoding unless util.isNullOrUndefined(chunk)
if state.corked
state.corked = 1
@uncork()
endWritable this, state, cb if not state.ending and not state.finished
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# A bit simpler than readable streams.
# Implement an async ._write(chunk, cb), and it'll handle all
# the drain event emission and buffering.
WriteReq = (chunk, encoding, cb) ->
@chunk = chunk
@encoding = encoding
@callback = cb
return
WritableState = (options, stream) ->
options = options or {}
# object stream flag to indicate whether or not this stream
# contains buffers or objects.
@objectMode = !!options.objectMode
@objectMode = @objectMode or !!options.writableObjectMode if stream instanceof Stream.Duplex
# the point at which write() starts returning false
# Note: 0 is a valid value, means that we always return false if
# the entire buffer is not flushed immediately on write()
hwm = options.highWaterMark
defaultHwm = (if @objectMode then 16 else 16 * 1024)
@highWaterMark = (if (hwm or hwm is 0) then hwm else defaultHwm)
# cast to ints.
@highWaterMark = ~~@highWaterMark
@needDrain = false
# at the start of calling end()
@ending = false
# when end() has been called, and returned
@ended = false
# when 'finish' is emitted
@finished = false
# should we decode strings into buffers before passing to _write?
# this is here so that some node-core streams can optimize string
# handling at a lower level.
noDecode = options.decodeStrings is false
@decodeStrings = not noDecode
# Crypto is kind of old and crusty. Historically, its default string
# encoding is 'binary' so we have to make this configurable.
# Everything else in the universe uses 'utf8', though.
@defaultEncoding = options.defaultEncoding or "utf8"
# not an actual buffer we keep track of, but a measurement
# of how much we're waiting to get pushed to some underlying
# socket or file.
@length = 0
# a flag to see when we're in the middle of a write.
@writing = false
# when true all writes will be buffered until .uncork() call
@corked = 0
# a flag to be able to tell if the onwrite cb is called immediately,
# or on a later tick. We set this to true at first, because any
# actions that shouldn't happen until "later" should generally also
# not happen before the first write call.
@sync = true
# a flag to know if we're processing previously buffered items, which
# may call the _write() callback in the same tick, so that we don't
# end up in an overlapped onwrite situation.
@bufferProcessing = false
# the callback that's passed to _write(chunk,cb)
@onwrite = (er) ->
onwrite stream, er
return
# the callback that the user supplies to write(chunk,encoding,cb)
@writecb = null
# the amount that is being written when _write is called.
@writelen = 0
@buffer = []
# number of pending user-supplied write callbacks
# this must be 0 before 'finish' can be emitted
@pendingcb = 0
# emit prefinish if the only thing we're waiting for is _write cbs
# This is relevant for synchronous Transform streams
@prefinished = false
# True if the error was already emitted and should not be thrown again
@errorEmitted = false
return
Writable = (options) ->
# Writable ctor is applied to Duplexes, though they're not
# instanceof Writable, they're instanceof Readable.
return new Writable(options) if (this not instanceof Writable) and (this not instanceof Stream.Duplex)
@_writableState = new WritableState(options, this)
# legacy.
@writable = true
Stream.call this
return
# Otherwise people can pipe Writable streams, which is just wrong.
writeAfterEnd = (stream, state, cb) ->
er = new Error("write after end")
# TODO: defer error events consistently everywhere, not just the cb
stream.emit "error", er
process.nextTick ->
cb er
return
return
# If we get something that is not a buffer, string, null, or undefined,
# and we're not in objectMode, then that's an error.
# Otherwise stream chunks are all considered to be of length=1, and the
# watermarks determine how many objects to keep in the buffer, rather than
# how many bytes or characters.
validChunk = (stream, state, chunk, cb) ->
valid = true
if not util.isBuffer(chunk) and not util.isString(chunk) and not util.isNullOrUndefined(chunk) and not state.objectMode
er = new TypeError("Invalid non-string/buffer chunk")
stream.emit "error", er
process.nextTick ->
cb er
return
valid = false
valid
# node::ParseEncoding() requires lower case.
decodeChunk = (state, chunk, encoding) ->
chunk = new Buffer(chunk, encoding) if not state.objectMode and state.decodeStrings isnt false and util.isString(chunk)
chunk
# if we're already writing something, then just put this
# in the queue, and wait our turn. Otherwise, call _write
# If we return false, then we need a drain event, so set that flag.
writeOrBuffer = (stream, state, chunk, encoding, cb) ->
chunk = decodeChunk(state, chunk, encoding)
encoding = "buffer" if util.isBuffer(chunk)
len = (if state.objectMode then 1 else chunk.length)
state.length += len
ret = state.length < state.highWaterMark
# we must ensure that previous needDrain will not be reset to false.
state.needDrain = true unless ret
if state.writing or state.corked
state.buffer.push new WriteReq(chunk, encoding, cb)
else
doWrite stream, state, false, len, chunk, encoding, cb
ret
doWrite = (stream, state, writev, len, chunk, encoding, cb) ->
state.writelen = len
state.writecb = cb
state.writing = true
state.sync = true
if writev
stream._writev chunk, state.onwrite
else
stream._write chunk, encoding, state.onwrite
state.sync = false
return
onwriteError = (stream, state, sync, er, cb) ->
if sync
process.nextTick ->
state.pendingcb--
cb er
return
else
state.pendingcb--
cb er
stream._writableState.errorEmitted = true
stream.emit "error", er
return
onwriteStateUpdate = (state) ->
state.writing = false
state.writecb = null
state.length -= state.writelen
state.writelen = 0
return
onwrite = (stream, er) ->
state = stream._writableState
sync = state.sync
cb = state.writecb
onwriteStateUpdate state
if er
onwriteError stream, state, sync, er, cb
else
# Check if we're actually ready to finish, but don't emit yet
finished = needFinish(stream, state)
clearBuffer stream, state if not finished and not state.corked and not state.bufferProcessing and state.buffer.length
if sync
process.nextTick ->
afterWrite stream, state, finished, cb
return
else
afterWrite stream, state, finished, cb
return
afterWrite = (stream, state, finished, cb) ->
onwriteDrain stream, state unless finished
state.pendingcb--
cb()
finishMaybe stream, state
return
# Must force callback to be called on nextTick, so that we don't
# emit 'drain' before the write() consumer gets the 'false' return
# value, and has a chance to attach a 'drain' listener.
onwriteDrain = (stream, state) ->
if state.length is 0 and state.needDrain
state.needDrain = false
stream.emit "drain"
return
# if there's something in the buffer waiting, then process it
clearBuffer = (stream, state) ->
state.bufferProcessing = true
if stream._writev and state.buffer.length > 1
# Fast case, write everything using _writev()
cbs = []
c = 0
while c < state.buffer.length
cbs.push state.buffer[c].callback
c++
# count the one we are adding, as well.
# TODO(isaacs) clean this up
state.pendingcb++
doWrite stream, state, true, state.length, state.buffer, "", (err) ->
i = 0
while i < cbs.length
state.pendingcb--
cbs[i] err
i++
return
# Clear buffer
state.buffer = []
else
# Slow case, write chunks one-by-one
c = 0
while c < state.buffer.length
entry = state.buffer[c]
chunk = entry.chunk
encoding = entry.encoding
cb = entry.callback
len = (if state.objectMode then 1 else chunk.length)
doWrite stream, state, false, len, chunk, encoding, cb
# if we didn't call the onwrite immediately, then
# it means that we need to wait until it does.
# also, that means that the chunk and cb are currently
# being processed, so move the buffer counter past them.
if state.writing
c++
break
c++
if c < state.buffer.length
state.buffer = state.buffer.slice(c)
else
state.buffer.length = 0
state.bufferProcessing = false
return
# .end() fully uncorks
# ignore unnecessary end() calls.
needFinish = (stream, state) ->
state.ending and state.length is 0 and state.buffer.length is 0 and not state.finished and not state.writing
prefinish = (stream, state) ->
unless state.prefinished
state.prefinished = true
stream.emit "prefinish"
return
finishMaybe = (stream, state) ->
need = needFinish(stream, state)
if need
if state.pendingcb is 0
prefinish stream, state
state.finished = true
stream.emit "finish"
else
prefinish stream, state
need
endWritable = (stream, state, cb) ->
state.ending = true
finishMaybe stream, state
if cb
if state.finished
process.nextTick cb
else
stream.once "finish", cb
state.ended = true
return
"use strict"
module.exports = Writable
Writable.WritableState = WritableState
util = require("util")
Stream = require("stream")
util.inherits Writable, Stream
Writable::pipe = ->
@emit "error", new Error("Cannot pipe. Not readable.")
return
Writable::write = (chunk, encoding, cb) ->
state = @_writableState
ret = false
if util.isFunction(encoding)
cb = encoding
encoding = null
if util.isBuffer(chunk)
encoding = "buffer"
else encoding = state.defaultEncoding unless encoding
cb = -> unless util.isFunction(cb)
if state.ended
writeAfterEnd this, state, cb
else if validChunk(this, state, chunk, cb)
state.pendingcb++
ret = writeOrBuffer(this, state, chunk, encoding, cb)
ret
Writable::cork = ->
state = @_writableState
state.corked++
return
Writable::uncork = ->
state = @_writableState
if state.corked
state.corked--
clearBuffer this, state if not state.writing and not state.corked and not state.finished and not state.bufferProcessing and state.buffer.length
return
Writable::setDefaultEncoding = setDefaultEncoding = (encoding) ->
encoding = encoding.toLowerCase() if typeof encoding is "string"
throw new TypeError("Unknown encoding: " + encoding) unless Buffer.isEncoding(encoding)
@_writableState.defaultEncoding = encoding
return
Writable::_write = (chunk, encoding, cb) ->
cb new Error("not implemented")
return
Writable::_writev = null
Writable::end = (chunk, encoding, cb) ->
state = @_writableState
if util.isFunction(chunk)
cb = chunk
chunk = null
encoding = null
else if util.isFunction(encoding)
cb = encoding
encoding = null
@write chunk, encoding unless util.isNullOrUndefined(chunk)
if state.corked
state.corked = 1
@uncork()
endWritable this, state, cb if not state.ending and not state.finished
return
|
[
{
"context": "e\n Ti.App.Properties.setString 'hatena_password', passwordField.value\n win.close()\n\nwin.add view\n",
"end": 1281,
"score": 0.5371274352073669,
"start": 1273,
"tag": "PASSWORD",
"value": "password"
}
] | Resources/config.coffee | naoya/HBFav | 5 | _ = require 'lib/underscore'
Ti.include 'ui.js'
view = Ti.UI.createView
layout: 'vertical'
nameLabel = Ti.UI.createLabel _($$.form.label).extend
top: 12
left: 15
text: "はてなID"
nameField = Ti.UI.createTextField _($$.form.textInput).extend
hintText: 'はてなID'
value: Ti.App.Properties.getString 'hatena_id'
clearButtonMode: Ti.UI.INPUT_BUTTONMODE_ONFOCUS
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE
nameNoteLabel = Ti.UI.createLabel _($$.form.notice).extend
top: 12
text: "プライベート設定のIDは利用できません"
passwordLabel = Ti.UI.createLabel _($$.form.label).extend
top: 12
left: 15
text: "パスワード"
passwordField = Ti.UI.createTextField _($$.form.textInput).extend
hintText: 'パスワード'
value: Ti.App.Properties.getString 'hatena_password'
passwordMask: true
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE
passwordNoteLabel = Ti.UI.createLabel _($$.form.notice).extend
top: 12
text: "はてなブックマークへの投稿機能を利用しない場合、パスワードの入力は不要です"
view.add nameLabel
view.add nameField
view.add nameNoteLabel
view.add passwordLabel
view.add passwordField
view.add passwordNoteLabel
win = Ti.UI.currentWindow
HBFav.UI.setupConfigWindow win, (e) ->
Ti.App.Properties.setString 'hatena_id', nameField.value
Ti.App.Properties.setString 'hatena_password', passwordField.value
win.close()
win.add view
| 199819 | _ = require 'lib/underscore'
Ti.include 'ui.js'
view = Ti.UI.createView
layout: 'vertical'
nameLabel = Ti.UI.createLabel _($$.form.label).extend
top: 12
left: 15
text: "はてなID"
nameField = Ti.UI.createTextField _($$.form.textInput).extend
hintText: 'はてなID'
value: Ti.App.Properties.getString 'hatena_id'
clearButtonMode: Ti.UI.INPUT_BUTTONMODE_ONFOCUS
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE
nameNoteLabel = Ti.UI.createLabel _($$.form.notice).extend
top: 12
text: "プライベート設定のIDは利用できません"
passwordLabel = Ti.UI.createLabel _($$.form.label).extend
top: 12
left: 15
text: "パスワード"
passwordField = Ti.UI.createTextField _($$.form.textInput).extend
hintText: 'パスワード'
value: Ti.App.Properties.getString 'hatena_password'
passwordMask: true
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE
passwordNoteLabel = Ti.UI.createLabel _($$.form.notice).extend
top: 12
text: "はてなブックマークへの投稿機能を利用しない場合、パスワードの入力は不要です"
view.add nameLabel
view.add nameField
view.add nameNoteLabel
view.add passwordLabel
view.add passwordField
view.add passwordNoteLabel
win = Ti.UI.currentWindow
HBFav.UI.setupConfigWindow win, (e) ->
Ti.App.Properties.setString 'hatena_id', nameField.value
Ti.App.Properties.setString 'hatena_password', <PASSWORD>Field.value
win.close()
win.add view
| true | _ = require 'lib/underscore'
Ti.include 'ui.js'
view = Ti.UI.createView
layout: 'vertical'
nameLabel = Ti.UI.createLabel _($$.form.label).extend
top: 12
left: 15
text: "はてなID"
nameField = Ti.UI.createTextField _($$.form.textInput).extend
hintText: 'はてなID'
value: Ti.App.Properties.getString 'hatena_id'
clearButtonMode: Ti.UI.INPUT_BUTTONMODE_ONFOCUS
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE
nameNoteLabel = Ti.UI.createLabel _($$.form.notice).extend
top: 12
text: "プライベート設定のIDは利用できません"
passwordLabel = Ti.UI.createLabel _($$.form.label).extend
top: 12
left: 15
text: "パスワード"
passwordField = Ti.UI.createTextField _($$.form.textInput).extend
hintText: 'パスワード'
value: Ti.App.Properties.getString 'hatena_password'
passwordMask: true
autocapitalization: Ti.UI.TEXT_AUTOCAPITALIZATION_NONE
passwordNoteLabel = Ti.UI.createLabel _($$.form.notice).extend
top: 12
text: "はてなブックマークへの投稿機能を利用しない場合、パスワードの入力は不要です"
view.add nameLabel
view.add nameField
view.add nameNoteLabel
view.add passwordLabel
view.add passwordField
view.add passwordNoteLabel
win = Ti.UI.currentWindow
HBFav.UI.setupConfigWindow win, (e) ->
Ti.App.Properties.setString 'hatena_id', nameField.value
Ti.App.Properties.setString 'hatena_password', PI:PASSWORD:<PASSWORD>END_PIField.value
win.close()
win.add view
|
[
{
"context": "dhub.com/v1/messages/?username=5306138494&api_key=996b0d7a9ebefde35e7a6a9b30e43f26749aa412\"\n json: \n groups: [173481]\n ",
"end": 906,
"score": 0.9997529983520508,
"start": 866,
"tag": "KEY",
"value": "996b0d7a9ebefde35e7a6a9b30e43f26749aa412"
}
] | cmdblu/server.coffee | octoblu/att-hackathon | 0 | Meshblu = require './src/meshblu'
Device = require './src/device'
{spawn} = require 'child_process'
request = require 'request'
device_uuid = process.env.DEVICE_UUID
device_token = process.env.DEVICE_TOKEN
payload_only = process.env.PAYLOAD_ONLY
meshblu_uri = process.env.MESHBLU_URI || 'wss://meshblu.octoblu.com'
meshblu = new Meshblu device_uuid, device_token, meshblu_uri, =>
console.log 'ready'
meshblu.connection.message({
"devices": "feadee3e-7cb5-4fb5-93bd-1bcdba8de1c5",
"subdevice" : "bean",
"topic" : '',
ack: 5,
"payload": {
"getAccelerometer":{}
}
});
meshblu.onMessage (message) =>
if payload_only
console.log JSON.stringify(message.payload)
else
console.log JSON.stringify(message)
try
request.post(
uri: "https://api.sendhub.com/v1/messages/?username=5306138494&api_key=996b0d7a9ebefde35e7a6a9b30e43f26749aa412"
json:
groups: [173481]
text: message.payload
,
(err, resp) =>
console.log err
console.log resp
)
catch error
console.log 'Error', error
| 12647 | Meshblu = require './src/meshblu'
Device = require './src/device'
{spawn} = require 'child_process'
request = require 'request'
device_uuid = process.env.DEVICE_UUID
device_token = process.env.DEVICE_TOKEN
payload_only = process.env.PAYLOAD_ONLY
meshblu_uri = process.env.MESHBLU_URI || 'wss://meshblu.octoblu.com'
meshblu = new Meshblu device_uuid, device_token, meshblu_uri, =>
console.log 'ready'
meshblu.connection.message({
"devices": "feadee3e-7cb5-4fb5-93bd-1bcdba8de1c5",
"subdevice" : "bean",
"topic" : '',
ack: 5,
"payload": {
"getAccelerometer":{}
}
});
meshblu.onMessage (message) =>
if payload_only
console.log JSON.stringify(message.payload)
else
console.log JSON.stringify(message)
try
request.post(
uri: "https://api.sendhub.com/v1/messages/?username=5306138494&api_key=<KEY>"
json:
groups: [173481]
text: message.payload
,
(err, resp) =>
console.log err
console.log resp
)
catch error
console.log 'Error', error
| true | Meshblu = require './src/meshblu'
Device = require './src/device'
{spawn} = require 'child_process'
request = require 'request'
device_uuid = process.env.DEVICE_UUID
device_token = process.env.DEVICE_TOKEN
payload_only = process.env.PAYLOAD_ONLY
meshblu_uri = process.env.MESHBLU_URI || 'wss://meshblu.octoblu.com'
meshblu = new Meshblu device_uuid, device_token, meshblu_uri, =>
console.log 'ready'
meshblu.connection.message({
"devices": "feadee3e-7cb5-4fb5-93bd-1bcdba8de1c5",
"subdevice" : "bean",
"topic" : '',
ack: 5,
"payload": {
"getAccelerometer":{}
}
});
meshblu.onMessage (message) =>
if payload_only
console.log JSON.stringify(message.payload)
else
console.log JSON.stringify(message)
try
request.post(
uri: "https://api.sendhub.com/v1/messages/?username=5306138494&api_key=PI:KEY:<KEY>END_PI"
json:
groups: [173481]
text: message.payload
,
(err, resp) =>
console.log err
console.log resp
)
catch error
console.log 'Error', error
|
[
{
"context": "lenders = [\n {\n name: 'alber'\n amount: 10000\n paid: true\n returned: t",
"end": 32,
"score": 0.9990614652633667,
"start": 27,
"tag": "NAME",
"value": "alber"
},
{
"context": "'sorry'\n greatness: 'great'\n }\n {\n name: 'gold'\n amount: 5000\n paid: true\n returned: tr",
"end": 170,
"score": 0.9991824626922607,
"start": 166,
"tag": "NAME",
"value": "gold"
},
{
"context": "oosball'\n greatness: 'gold'\n }\n {\n name: 'fly'\n amount: 3000\n paid: true\n returned: tr",
"end": 308,
"score": 0.9988910555839539,
"start": 305,
"tag": "NAME",
"value": "fly"
},
{
"context": "foosball'\n greatness: 'fly'\n }\n {\n name: 'slim'\n amount: 1500\n paid: true\n returned: tr",
"end": 446,
"score": 0.9993959665298462,
"start": 442,
"tag": "NAME",
"value": "slim"
}
] | javascripts/app/gold/lenders.coffee | cxyokk/debt | 2 | lenders = [
{
name: 'alber'
amount: 10000
paid: true
returned: true
hometown: 'gd'
hobby: 'sorry'
greatness: 'great'
}
{
name: 'gold'
amount: 5000
paid: true
returned: true
hometown: 'hb'
hobby: 'foosball'
greatness: 'gold'
}
{
name: 'fly'
amount: 3000
paid: true
returned: true
hometown: 'sx'
hobby: 'foosball'
greatness: 'fly'
}
{
name: 'slim'
amount: 1500
paid: true
returned: true
hometown: 'cq'
hobby: 'pes'
greatness: 'soccer'
}
]
lenders = _.shuffle lenders
window.debtApp ?= { }
window.debtApp.lenders = lenders
| 203924 | lenders = [
{
name: '<NAME>'
amount: 10000
paid: true
returned: true
hometown: 'gd'
hobby: 'sorry'
greatness: 'great'
}
{
name: '<NAME>'
amount: 5000
paid: true
returned: true
hometown: 'hb'
hobby: 'foosball'
greatness: 'gold'
}
{
name: '<NAME>'
amount: 3000
paid: true
returned: true
hometown: 'sx'
hobby: 'foosball'
greatness: 'fly'
}
{
name: '<NAME>'
amount: 1500
paid: true
returned: true
hometown: 'cq'
hobby: 'pes'
greatness: 'soccer'
}
]
lenders = _.shuffle lenders
window.debtApp ?= { }
window.debtApp.lenders = lenders
| true | lenders = [
{
name: 'PI:NAME:<NAME>END_PI'
amount: 10000
paid: true
returned: true
hometown: 'gd'
hobby: 'sorry'
greatness: 'great'
}
{
name: 'PI:NAME:<NAME>END_PI'
amount: 5000
paid: true
returned: true
hometown: 'hb'
hobby: 'foosball'
greatness: 'gold'
}
{
name: 'PI:NAME:<NAME>END_PI'
amount: 3000
paid: true
returned: true
hometown: 'sx'
hobby: 'foosball'
greatness: 'fly'
}
{
name: 'PI:NAME:<NAME>END_PI'
amount: 1500
paid: true
returned: true
hometown: 'cq'
hobby: 'pes'
greatness: 'soccer'
}
]
lenders = _.shuffle lenders
window.debtApp ?= { }
window.debtApp.lenders = lenders
|
[
{
"context": "nd.callThrough()\n\n teamId = 1\n email = 'test@example.com'\n config =\n pathParams:\n id:",
"end": 913,
"score": 0.9999281167984009,
"start": 897,
"tag": "EMAIL",
"value": "test@example.com"
},
{
"context": "lThrough()\n\n teamId = 1\n emailArray = ['test1@example.com', 'test2@example.com']\n config =\n pat",
"end": 1299,
"score": 0.9999266266822815,
"start": 1282,
"tag": "EMAIL",
"value": "test1@example.com"
},
{
"context": "mId = 1\n emailArray = ['test1@example.com', 'test2@example.com']\n config =\n pathParams:\n id",
"end": 1320,
"score": 0.9999270439147949,
"start": 1303,
"tag": "EMAIL",
"value": "test2@example.com"
},
{
"context": ".create, 'post').and.callThrough()\n\n name = 'name'\n config = data: name: name\n\n @action.t",
"end": 2308,
"score": 0.9940323233604431,
"start": 2304,
"tag": "USERNAME",
"value": "name"
}
] | talk-web/test/spec/actions/team.spec.coffee | ikingye/talk-os | 3,084 | xdescribe 'Actions: team', ->
beforeEach ->
@action = require 'actions/team'
@api = require 'network/api'
describe 'Method: teamSubscribe', ->
it 'should call api', ->
spyOn(@api.teams.subscribe, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
@action.teamSubscribe(teamId)
expect(@api.teams.subscribe.post).toHaveBeenCalledWith config
describe 'Method: teamUnsubscribe', ->
it 'should call api', ->
spyOn(@api.teams.unsubscribe, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
@action.teamUnsubscribe(teamId)
expect(@api.teams.unsubscribe.post).toHaveBeenCalledWith config
describe 'Method: teamInvite', ->
it 'should call api', ->
spyOn(@api.teams.invite, 'post').and.callThrough()
teamId = 1
email = 'test@example.com'
config =
pathParams:
id: teamId
data:
email: email
@action.teamInvite(teamId, email)
expect(@api.teams.invite.post).toHaveBeenCalledWith config
describe 'Method: batchInvite', ->
it 'should call api', ->
spyOn(@api.teams.batchinvite, 'post').and.callThrough()
teamId = 1
emailArray = ['test1@example.com', 'test2@example.com']
config =
pathParams:
id: teamId
data:
emails: emailArray
@action.batchInvite(teamId, emailArray)
expect(@api.teams.batchinvite.post).toHaveBeenCalledWith config
describe 'Method: teamUpdate', ->
it 'should call api', ->
spyOn(@api.teams.update, 'put').and.callThrough()
teamId = 1
data = {}
config =
pathParams:
id: teamId
data: data
@action.teamUpdate(teamId, data)
expect(@api.teams.update.put).toHaveBeenCalledWith config
describe 'Method: teamLeave', ->
it 'should call api', ->
spyOn(@api.teams.leave, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
@action.teamLeave(teamId)
expect(@api.teams.leave.post).toHaveBeenCalledWith config
describe 'Method: teamCreate', ->
it 'should call api', ->
spyOn(@api.teams.create, 'post').and.callThrough()
name = 'name'
config = data: name: name
@action.teamCreate(name)
expect(@api.teams.create.post).toHaveBeenCalledWith config
describe 'Method: teamsFetch', ->
it 'should call api', ->
spyOn(@api.teams.read, 'get').and.callThrough()
@action.teamsFetch()
expect(@api.teams.read.get).toHaveBeenCalled()
describe 'Method: teamUnpin', ->
it 'should call api', ->
spyOn(@api.teams.unpin, 'post').and.callThrough()
teamId = 1
targetId = 2
config =
pathParams:
id: teamId
targetId: targetId
@action.teamUnpin(teamId, targetId)
expect(@api.teams.unpin.post).toHaveBeenCalledWith config
describe 'Method: teamPin', ->
it 'should call api', ->
spyOn(@api.teams.pin, 'post').and.callThrough()
teamId = 1
targetId = 2
config =
pathParams:
id: teamId
targetId: targetId
@action.teamPin(teamId, targetId)
expect(@api.teams.pin.post).toHaveBeenCalledWith config
describe 'Method: getArchivedTopics', ->
it 'should call api', ->
spyOn(@api.teams.rooms, 'get').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
queryParams:
isArchived: true
@action.getArchivedTopics(teamId)
expect(@api.teams.rooms.get).toHaveBeenCalledWith config
describe 'Method: resetInviteUrl', ->
it 'should call api', ->
spyOn(@api.teams.refresh, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
data:
properties:
inviteCode: 1
@action.resetInviteUrl(teamId)
expect(@api.teams.refresh.post).toHaveBeenCalledWith config
| 204980 | xdescribe 'Actions: team', ->
beforeEach ->
@action = require 'actions/team'
@api = require 'network/api'
describe 'Method: teamSubscribe', ->
it 'should call api', ->
spyOn(@api.teams.subscribe, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
@action.teamSubscribe(teamId)
expect(@api.teams.subscribe.post).toHaveBeenCalledWith config
describe 'Method: teamUnsubscribe', ->
it 'should call api', ->
spyOn(@api.teams.unsubscribe, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
@action.teamUnsubscribe(teamId)
expect(@api.teams.unsubscribe.post).toHaveBeenCalledWith config
describe 'Method: teamInvite', ->
it 'should call api', ->
spyOn(@api.teams.invite, 'post').and.callThrough()
teamId = 1
email = '<EMAIL>'
config =
pathParams:
id: teamId
data:
email: email
@action.teamInvite(teamId, email)
expect(@api.teams.invite.post).toHaveBeenCalledWith config
describe 'Method: batchInvite', ->
it 'should call api', ->
spyOn(@api.teams.batchinvite, 'post').and.callThrough()
teamId = 1
emailArray = ['<EMAIL>', '<EMAIL>']
config =
pathParams:
id: teamId
data:
emails: emailArray
@action.batchInvite(teamId, emailArray)
expect(@api.teams.batchinvite.post).toHaveBeenCalledWith config
describe 'Method: teamUpdate', ->
it 'should call api', ->
spyOn(@api.teams.update, 'put').and.callThrough()
teamId = 1
data = {}
config =
pathParams:
id: teamId
data: data
@action.teamUpdate(teamId, data)
expect(@api.teams.update.put).toHaveBeenCalledWith config
describe 'Method: teamLeave', ->
it 'should call api', ->
spyOn(@api.teams.leave, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
@action.teamLeave(teamId)
expect(@api.teams.leave.post).toHaveBeenCalledWith config
describe 'Method: teamCreate', ->
it 'should call api', ->
spyOn(@api.teams.create, 'post').and.callThrough()
name = 'name'
config = data: name: name
@action.teamCreate(name)
expect(@api.teams.create.post).toHaveBeenCalledWith config
describe 'Method: teamsFetch', ->
it 'should call api', ->
spyOn(@api.teams.read, 'get').and.callThrough()
@action.teamsFetch()
expect(@api.teams.read.get).toHaveBeenCalled()
describe 'Method: teamUnpin', ->
it 'should call api', ->
spyOn(@api.teams.unpin, 'post').and.callThrough()
teamId = 1
targetId = 2
config =
pathParams:
id: teamId
targetId: targetId
@action.teamUnpin(teamId, targetId)
expect(@api.teams.unpin.post).toHaveBeenCalledWith config
describe 'Method: teamPin', ->
it 'should call api', ->
spyOn(@api.teams.pin, 'post').and.callThrough()
teamId = 1
targetId = 2
config =
pathParams:
id: teamId
targetId: targetId
@action.teamPin(teamId, targetId)
expect(@api.teams.pin.post).toHaveBeenCalledWith config
describe 'Method: getArchivedTopics', ->
it 'should call api', ->
spyOn(@api.teams.rooms, 'get').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
queryParams:
isArchived: true
@action.getArchivedTopics(teamId)
expect(@api.teams.rooms.get).toHaveBeenCalledWith config
describe 'Method: resetInviteUrl', ->
it 'should call api', ->
spyOn(@api.teams.refresh, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
data:
properties:
inviteCode: 1
@action.resetInviteUrl(teamId)
expect(@api.teams.refresh.post).toHaveBeenCalledWith config
| true | xdescribe 'Actions: team', ->
beforeEach ->
@action = require 'actions/team'
@api = require 'network/api'
describe 'Method: teamSubscribe', ->
it 'should call api', ->
spyOn(@api.teams.subscribe, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
@action.teamSubscribe(teamId)
expect(@api.teams.subscribe.post).toHaveBeenCalledWith config
describe 'Method: teamUnsubscribe', ->
it 'should call api', ->
spyOn(@api.teams.unsubscribe, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
@action.teamUnsubscribe(teamId)
expect(@api.teams.unsubscribe.post).toHaveBeenCalledWith config
describe 'Method: teamInvite', ->
it 'should call api', ->
spyOn(@api.teams.invite, 'post').and.callThrough()
teamId = 1
email = 'PI:EMAIL:<EMAIL>END_PI'
config =
pathParams:
id: teamId
data:
email: email
@action.teamInvite(teamId, email)
expect(@api.teams.invite.post).toHaveBeenCalledWith config
describe 'Method: batchInvite', ->
it 'should call api', ->
spyOn(@api.teams.batchinvite, 'post').and.callThrough()
teamId = 1
emailArray = ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI']
config =
pathParams:
id: teamId
data:
emails: emailArray
@action.batchInvite(teamId, emailArray)
expect(@api.teams.batchinvite.post).toHaveBeenCalledWith config
describe 'Method: teamUpdate', ->
it 'should call api', ->
spyOn(@api.teams.update, 'put').and.callThrough()
teamId = 1
data = {}
config =
pathParams:
id: teamId
data: data
@action.teamUpdate(teamId, data)
expect(@api.teams.update.put).toHaveBeenCalledWith config
describe 'Method: teamLeave', ->
it 'should call api', ->
spyOn(@api.teams.leave, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
@action.teamLeave(teamId)
expect(@api.teams.leave.post).toHaveBeenCalledWith config
describe 'Method: teamCreate', ->
it 'should call api', ->
spyOn(@api.teams.create, 'post').and.callThrough()
name = 'name'
config = data: name: name
@action.teamCreate(name)
expect(@api.teams.create.post).toHaveBeenCalledWith config
describe 'Method: teamsFetch', ->
it 'should call api', ->
spyOn(@api.teams.read, 'get').and.callThrough()
@action.teamsFetch()
expect(@api.teams.read.get).toHaveBeenCalled()
describe 'Method: teamUnpin', ->
it 'should call api', ->
spyOn(@api.teams.unpin, 'post').and.callThrough()
teamId = 1
targetId = 2
config =
pathParams:
id: teamId
targetId: targetId
@action.teamUnpin(teamId, targetId)
expect(@api.teams.unpin.post).toHaveBeenCalledWith config
describe 'Method: teamPin', ->
it 'should call api', ->
spyOn(@api.teams.pin, 'post').and.callThrough()
teamId = 1
targetId = 2
config =
pathParams:
id: teamId
targetId: targetId
@action.teamPin(teamId, targetId)
expect(@api.teams.pin.post).toHaveBeenCalledWith config
describe 'Method: getArchivedTopics', ->
it 'should call api', ->
spyOn(@api.teams.rooms, 'get').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
queryParams:
isArchived: true
@action.getArchivedTopics(teamId)
expect(@api.teams.rooms.get).toHaveBeenCalledWith config
describe 'Method: resetInviteUrl', ->
it 'should call api', ->
spyOn(@api.teams.refresh, 'post').and.callThrough()
teamId = 1
config =
pathParams:
id: teamId
data:
properties:
inviteCode: 1
@action.resetInviteUrl(teamId)
expect(@api.teams.refresh.post).toHaveBeenCalledWith config
|
[
{
"context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig",
"end": 74,
"score": 0.9998745918273926,
"start": 61,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "f the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyright and license informa",
"end": 96,
"score": 0.9999345541000366,
"start": 76,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
},
{
"context": "nput is abstraction of a command input\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\nclass Input\n\n\n\tconstruct",
"end": 379,
"score": 0.9998746514320374,
"start": 366,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "ion of a command input\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\nclass Input\n\n\n\tconstructor: (definition,comman",
"end": 401,
"score": 0.9999343752861023,
"start": 381,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
}
] | node_modules/konsserto/lib/src/Konsserto/Component/Console/Input/Input.coffee | konsserto/konsserto | 2 | ###
* This file is part of the Konsserto package.
*
* (c) Jessym Reziga <jessym@konsserto.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
InputDefinition = use('@Konsserto/Component/Console/Input/InputDefinition')
#
# Input is abstraction of a command input
#
# @author Jessym Reziga <jessym@konsserto.com>
#
class Input
constructor: (definition,command) ->
@arguments = {}
@options = {}
@interactive = true
if (definition == undefined)
definition = new InputDefinition()
else if definition.constructor.name == 'Array'
definition = new InputDefinition(definition)
@bind(definition,command)
@validate()
else
@bind(definition,command)
@validate()
bind: (definition) ->
@arguments = {}
@options = {}
@definition = definition
@parse()
parse: () -> # @abtract
validate: () ->
if Object.keys(@arguments).length < @definition.getArgumentRequiredCount()
throw new Error('Not enough arguments.')
isInteractive: () ->
return @interactive
setInteractive: (interactive) ->
@interactive = interactive
getArguments: () ->
return @definition.getArgumentDefaults().concat(@arguments)
getArgument: (name) ->
if !@definition.hasArgument(name)
throw new Error('The '+name+' argument does not exist.')
if @arguments[name] != undefined
return @arguments[name]
else
@definition.getArgument(name).getDefault()
getSynopsisBuffer: ()->
return @definition
setArgument: (name, value) ->
if !@definition.hasArgument(name)
throw new Error('The '+name+' argument does not exist.')
@arguments[name] = value
hasArgument: (name) ->
return @definition.hasArgument(name)
getOptions: () ->
return @definition.getOptionDefaults().concat(@options)
getOption: (name) ->
if !@definition.hasOption(name)
throw new Error('The '+name+' option does not exist.')
if @options[name] != undefined
return @options[name]
else
return @definition.getOption(name).getDefault()
setOption: (name, value) ->
if !@definition.hasOption(name)
throw new Error('The '+name+' option does not exist.')
@options[name] = value
hasOption: (name) ->
return @definition.hasOption(name)
escapeToken: (token) ->
if token.match('^[w-]+')
return token
return @escapeshellarg(token)
escapeshellarg: (str) ->
out = ''
out = str.replace(/[^\\]'/g, (m, i, s)->
return m.slice(0, 1) + '\\\'';
);
return out;
module.exports = Input; | 155865 | ###
* This file is part of the Konsserto package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
InputDefinition = use('@Konsserto/Component/Console/Input/InputDefinition')
#
# Input is abstraction of a command input
#
# @author <NAME> <<EMAIL>>
#
class Input
constructor: (definition,command) ->
@arguments = {}
@options = {}
@interactive = true
if (definition == undefined)
definition = new InputDefinition()
else if definition.constructor.name == 'Array'
definition = new InputDefinition(definition)
@bind(definition,command)
@validate()
else
@bind(definition,command)
@validate()
bind: (definition) ->
@arguments = {}
@options = {}
@definition = definition
@parse()
parse: () -> # @abtract
validate: () ->
if Object.keys(@arguments).length < @definition.getArgumentRequiredCount()
throw new Error('Not enough arguments.')
isInteractive: () ->
return @interactive
setInteractive: (interactive) ->
@interactive = interactive
getArguments: () ->
return @definition.getArgumentDefaults().concat(@arguments)
getArgument: (name) ->
if !@definition.hasArgument(name)
throw new Error('The '+name+' argument does not exist.')
if @arguments[name] != undefined
return @arguments[name]
else
@definition.getArgument(name).getDefault()
getSynopsisBuffer: ()->
return @definition
setArgument: (name, value) ->
if !@definition.hasArgument(name)
throw new Error('The '+name+' argument does not exist.')
@arguments[name] = value
hasArgument: (name) ->
return @definition.hasArgument(name)
getOptions: () ->
return @definition.getOptionDefaults().concat(@options)
getOption: (name) ->
if !@definition.hasOption(name)
throw new Error('The '+name+' option does not exist.')
if @options[name] != undefined
return @options[name]
else
return @definition.getOption(name).getDefault()
setOption: (name, value) ->
if !@definition.hasOption(name)
throw new Error('The '+name+' option does not exist.')
@options[name] = value
hasOption: (name) ->
return @definition.hasOption(name)
escapeToken: (token) ->
if token.match('^[w-]+')
return token
return @escapeshellarg(token)
escapeshellarg: (str) ->
out = ''
out = str.replace(/[^\\]'/g, (m, i, s)->
return m.slice(0, 1) + '\\\'';
);
return out;
module.exports = Input; | true | ###
* This file is part of the Konsserto package.
*
* (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
InputDefinition = use('@Konsserto/Component/Console/Input/InputDefinition')
#
# Input is abstraction of a command input
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
class Input
constructor: (definition,command) ->
@arguments = {}
@options = {}
@interactive = true
if (definition == undefined)
definition = new InputDefinition()
else if definition.constructor.name == 'Array'
definition = new InputDefinition(definition)
@bind(definition,command)
@validate()
else
@bind(definition,command)
@validate()
bind: (definition) ->
@arguments = {}
@options = {}
@definition = definition
@parse()
parse: () -> # @abtract
validate: () ->
if Object.keys(@arguments).length < @definition.getArgumentRequiredCount()
throw new Error('Not enough arguments.')
isInteractive: () ->
return @interactive
setInteractive: (interactive) ->
@interactive = interactive
getArguments: () ->
return @definition.getArgumentDefaults().concat(@arguments)
getArgument: (name) ->
if !@definition.hasArgument(name)
throw new Error('The '+name+' argument does not exist.')
if @arguments[name] != undefined
return @arguments[name]
else
@definition.getArgument(name).getDefault()
getSynopsisBuffer: ()->
return @definition
setArgument: (name, value) ->
if !@definition.hasArgument(name)
throw new Error('The '+name+' argument does not exist.')
@arguments[name] = value
hasArgument: (name) ->
return @definition.hasArgument(name)
getOptions: () ->
return @definition.getOptionDefaults().concat(@options)
getOption: (name) ->
if !@definition.hasOption(name)
throw new Error('The '+name+' option does not exist.')
if @options[name] != undefined
return @options[name]
else
return @definition.getOption(name).getDefault()
setOption: (name, value) ->
if !@definition.hasOption(name)
throw new Error('The '+name+' option does not exist.')
@options[name] = value
hasOption: (name) ->
return @definition.hasOption(name)
escapeToken: (token) ->
if token.match('^[w-]+')
return token
return @escapeshellarg(token)
escapeshellarg: (str) ->
out = ''
out = str.replace(/[^\\]'/g, (m, i, s)->
return m.slice(0, 1) + '\\\'';
);
return out;
module.exports = Input; |
[
{
"context": " 50, true\n\n @addCreditsText 'Copyright (c) 2014 Bryan Bibat.', 50, 100, \"http://bryanbibat.net\"\n @addCredi",
"end": 11391,
"score": 0.9998857378959656,
"start": 11380,
"tag": "NAME",
"value": "Bryan Bibat"
},
{
"context": "//phaser.io\"\n @addCreditsText 'Sprites (c) 2002 Ari Feldman,', 50, 135, \"www.widgetworx.com/spritelib/\"\n @",
"end": 11552,
"score": 0.9998262524604797,
"start": 11541,
"tag": "NAME",
"value": "Ari Feldman"
},
{
"context": "m/spritelib/\"\n @addCreditsText 'Sounds (c) 2013 dklon (Devin Watson),', 350, 135, \"http://opengameart.o",
"end": 11639,
"score": 0.8323136568069458,
"start": 11634,
"tag": "USERNAME",
"value": "dklon"
},
{
"context": "lib/\"\n @addCreditsText 'Sounds (c) 2013 dklon (Devin Watson),', 350, 135, \"http://opengameart.org/users/dklon",
"end": 11653,
"score": 0.9996901154518127,
"start": 11641,
"tag": "NAME",
"value": "Devin Watson"
},
{
"context": "tsText '\"Special Elite\" font (c) 2011 Astigmatic (Brian J. Bonislawsky)', 50, 205, \"http://www.astigmatic.com/\"\n\n\n sh",
"end": 11913,
"score": 0.9959923624992371,
"start": 11893,
"tag": "NAME",
"value": "Brian J. Bonislawsky"
},
{
"context": "raph.png' %>\")\n text = encodeURIComponent(\"Play Gunner, a WWII themed HTML5 game where you destroy waves",
"end": 12466,
"score": 0.938462495803833,
"start": 12460,
"tag": "NAME",
"value": "Gunner"
},
{
"context": "\"http://www.tumblr.com/share/link?url=#{url}&name=Gunner&description=#{text}\"\n @addIcon 310, 370, 'tumb",
"end": 12913,
"score": 0.9572854042053223,
"start": 12907,
"tag": "NAME",
"value": "Gunner"
}
] | assets/javascripts/mainMenu.coffee | datenshiZERO/gunner | 3 | Store = new Persist.Store('Gunner Scores')
Gunner = window.Gunner
class MainMenu
create: ->
@stage.backgroundColor = '#2F3942'
@titleText = @add.bitmapText(400, 150, 'Airborne', 'Gunner', 128)
Gunner.center(@titleText)
gl = Store.get('gameLength')
@game.lengthMultplier = if gl? then parseInt(gl) else 2
gt = Store.get('gameType')
@game.gameType = if gt? then gt else 'Time Attack'
@menuTexts = {}
@bitmapData = {}
@menuImages = []
@setupTopLevel()
addText: (text, x, y, selected, small) ->
bmd = @add.bitmapData(1, 1)
bmds = @add.sprite(0, 0, bmd)
mt = @add.bitmapText(x, y, (if selected then 'Airborne' else 'AirborneGray'), text, (if small then 26 else 32))
@menuTexts[text] = mt
Gunner.center mt
mt.inputEnabled = true
mt.events.onInputDown.add(@menuSelect, @menuTexts[text])
bmds.x = mt.x - 5
bmds.y = mt.y - 5
bmd.resize(mt.textWidth + 10, mt.textHeight + 3)
bmd.context.fillStyle = "#2F3942"
bmd.context.fillRect 0, 0, mt.textWidth + 10, mt.textHeight + 3
bmds.inputEnabled = true
bmds.events.onInputDown.add(@menuSelect, @menuTexts[text])
@bitmapData[text] = bmds
addTypewriterText: (text, x, y, size, centerType, link) ->
if link?
bmd = @add.bitmapData(1, 1)
bmds = @add.sprite(0, 0, bmd)
mt = @add.bitmapText(x, y, 'SpecialElite32', text, size)
mt.align = 'center'
@menuTexts[text] = mt
switch centerType
when 'horizontal'
Gunner.horizontalCenter(mt)
when 'vertical'
Gunner.verticalCenter(mt)
when 'both'
Gunner.center(mt)
if link?
mt.inputEnabled = true
mt.events.onInputDown.add( ->
win = window.open(this, '_blank')
win.focus()
, link)
bmds.x = mt.x - 5
bmds.y = mt.y - 3
bmd.resize(mt.textWidth + 10, mt.textHeight + 5)
bmd.context.fillStyle = "#2F3942"
bmd.context.fillRect 0, 0, mt.textWidth + 10, mt.textHeight + 5
bmds.inputEnabled = true
bmds.events.onInputDown.add( ->
win = window.open(this, '_blank')
win.focus()
, link)
@bitmapData[text] = bmds
return mt
addInstructionText: (text, x, y, header) ->
@addTypewriterText(text, x, y, (if header then 32 else 20), (if header then 'both' else 'vertical'))
addTutorialText: (text, x, y, header) ->
@addTypewriterText(text, x, y, (if header then 32 else 20), 'both')
addCreditsText: (text, x, y, link) ->
@addTypewriterText(text, x, y, 20, 'none', link)
menuSelect: ->
state = @game.state.getCurrentState()
switch @text
when "Back to Main Menu"
state.titleText.visible = true
state.setupTopLevel()
when "Play Game"
state.setupOptions()
when "Time Attack"
@game.gameType = 'Time Attack'
state.highlightType()
when "Survival"
@game.gameType = 'Survival'
state.highlightType()
when "Quick"
@game.lengthMultplier = 5
state.highlightLength()
when "Normal"
@game.lengthMultplier = 2
state.highlightLength()
when "Extended"
@game.lengthMultplier = 1
state.highlightLength()
when "Start Game"
@game.lengthMultplier = 2 unless @game.lengthMultplier?
Store.set('gameLength', @game.lengthMultplier)
@game.gameType = 'time atttack' unless @game.gameType?
Store.set('gameType', @game.gameType)
if Store.get('skipTutorial')?
@game.state.start('Game')
else
state.displayTutorial()
when "Skip this screen from now on"
Store.set('skipTutorial', 'skip')
@game.state.start('Game')
when "Proceed to Game"
@game.state.start('Game')
when "How To Play"
state.displayInstructions()
when "Previous Page"
state.displayInstructions()
when "Next Page"
state.displayInstructions2()
when "High Scores"
state.displayHighScores()
when "Credits & Misc"
state.displayCredits()
setupTopLevel: ->
@clearText()
@addText 'Play Game', 400, 310, true
@addText 'How To Play', 400, 360, false
@addText 'High Scores', 400, 410, false
@addText 'Credits & Misc', 400, 460, false
@game.menuIndex = 0
setupOptions: ->
@clearText()
@addText 'Time Attack', 230, 345, true, true
@addText 'Survival', 230, 385, false, true
@addText 'Quick', 570, 330, false, true
@addText 'Normal', 570, 370, true, true
@addText 'Extended', 570, 410, false, true
@addText 'Game Type', 230, 270, true
@addText 'Game Length', 570, 270, true
@highlightLength()
@highlightType()
@addText 'Start Game', 400, 500, true
@addText 'Back to Main Menu', 400, 540, false, true
highlightType: ->
@menuTexts["Time Attack"].destroy()
@menuTexts["Survival"].destroy()
@bitmapData["Time Attack"].destroy()
@bitmapData["Survival"].destroy()
switch @game.gameType
when 'Time Attack'
@addText 'Time Attack', 230, 345, true, true
@addText 'Survival', 230, 385, false, true
when 'Survival'
@addText 'Time Attack', 230, 345, false, true
@addText 'Survival', 230, 385, true, true
highlightLength: ->
@menuTexts["Quick"].destroy()
@menuTexts["Normal"].destroy()
@menuTexts["Extended"].destroy()
@bitmapData["Quick"].destroy()
@bitmapData["Normal"].destroy()
@bitmapData["Extended"].destroy()
switch @game.lengthMultplier
when 5
@addText 'Quick', 570, 330, true, true
@addText 'Normal', 570, 370, false, true
@addText 'Extended', 570, 410, false, true
when 2
@addText 'Quick', 570, 330, false, true
@addText 'Normal', 570, 370, true, true
@addText 'Extended', 570, 410, false, true
when 1
@addText 'Quick', 570, 330, false, true
@addText 'Normal', 570, 370, false, true
@addText 'Extended', 570, 410, true, true
displayInstructions: ->
@clearText()
@titleText.visible = false
@addInstructionText 'How To Play', 400, 50, true
@addTutorialText 'This game has 2 modes: ', 400, 100
@addInstructionText 'Time Attack - finish the game as soon as possible ', 70, 135
@addInstructionText 'Survival - destroy as many as enemies as you can before losing', 70, 160
@addTutorialText 'Shoot by clicking or tapping on the spot you wish to fire at.', 400, 210
@addTutorialText 'Hold down click/tap for continuous fire. You can also use the arrow', 400, 235
@addTutorialText 'keys to move the crosshair and Space Bar to fire.', 400, 260
@addTutorialText 'Shooting consumes energy, destroying enemies provide energy.', 400, 295
@addTutorialText 'Tougher enemies give more energy, but still count as 1 kill.', 400, 320
@addTutorialText "Enemies cannot damage you, but it's game over if you", 400, 355
@addTutorialText "waste all of your energy (i.e. it reaches 0)", 400, 380
@addTutorialText 'Click/tap the audio icon to change the volume.', 400, 415
@addTutorialText 'Click/tap the gears icon to pause and show options.', 400, 440
@addText 'Next Page', 400, 500, true
@addText 'Back to Main Menu', 400, 550, false
displayInstructions2: ->
@clearText()
@titleText.visible = false
@addInstructionText 'How To Play', 400, 50, true
@addTutorialText 'Click/tap the other icons to change shot types and firing modes.', 400, 90
@addInstructionText 'There are 3 shot types:', 40, 130
@addInstructionText 'Small - fast firing, good for spraying weak enemies. 1 energy per shot', 40, 165
@addInstructionText ' Keyboard shortcut: "1"', 40, 190
@addInstructionText 'Large - slower rate, but better against tougher enemies. 3 energy per', 40, 215
@addInstructionText ' shot. Shortcut: "2"', 40, 240
@addInstructionText 'Burst - slow strong shot that bursts into 5 shots after hitting', 40, 265
@addInstructionText ' 8 energy per shot. Shortcut: "3"', 40, 290
@addInstructionText 'And there are 3 firing modes:', 40, 325
@addInstructionText 'Single - single turret, fastest rate of fire. Shortcut: "Q"', 40, 360
@addInstructionText 'Triple - use 3 turrets but fire rate is halved. Shortcut: "W"', 40, 385
@addInstructionText 'Bomb - slowest fire rate, drop a bomb that explodes into 10 shots after', 40, 410
@addInstructionText ' a short delay. Shortcut: "E"', 40, 435
@addText 'Previous Page', 400, 500, true
@addText 'Back to Main Menu', 400, 550, false
displayTutorial: ->
@clearText()
@titleText.visible = false
if @game.gameType is 'Time Attack'
text = ' Time Attack '
@addTutorialText "Reach #{15000 / @game.lengthMultplier} kills or destroy an", 400, 155, true
@addTutorialText "Elite Fighter as soon as possible.", 400, 195, true
else
text = ' Survival '
@addTutorialText "Destroy as many enemies as possible.", 400, 155, true
@addTutorialText "You will lose energy every minute.", 400, 195, true
@menuTexts[text] = @add.bitmapText(400, 90, 'Airborne', text, 80)
Gunner.center(@menuTexts[text])
@addTutorialText "Click or tap screen to shoot. Different firing modes", 400, 260
@addTutorialText "can be selected at the bottom by clicking/tapping.", 400, 285
@addTutorialText "Shooting consumes energy, destroying enemies provide energy.", 400, 330
@addTutorialText "Tougher enemies give more energy but still count as 1 kill.", 400, 355
@addTutorialText "Enemies cannot damage you, but it's game over if you", 400, 400
@addTutorialText "waste all of your energy (i.e. reaches 0)", 400, 425
@addText 'Proceed to Game', 400, 500, true
@addText 'Skip this screen from now on', 400, 550, false
displayHighScores: ->
@clearText()
@addText ' Time Attack ', 230, 300, true
@addText ' Survival ', 570, 300, true
@addTutorialText 'Quick: ' +
if Store.get("bestTime-5")?
Gunner.timeDisplay(parseInt(Store.get("bestTime-5")))
else
'n/a'
, 230, 340
@addTutorialText 'Normal: ' +
if Store.get("bestTime-2")?
Gunner.timeDisplay(parseInt(Store.get("bestTime-2")))
else
'n/a'
, 230, 370
@addTutorialText 'Extended: ' +
if Store.get("bestTime-1")?
Gunner.timeDisplay(parseInt(Store.get("bestTime-5")))
else
'n/a'
, 230, 400
@addTutorialText ' Quick: ' +
if Store.get("survival-5")?
Store.get("survival-5") + ' kills '
else
'n/a '
, 570, 340
@addTutorialText ' Normal: ' +
if Store.get("survival-2")?
Store.get("survival-2") + ' kills '
else
'n/a '
, 570, 370
@addTutorialText ' Extended: ' +
if Store.get("survival-1")?
Store.get("survival-1") + ' kills '
else
'n/a '
, 570, 400
@addText 'Back to Main Menu', 400, 510, true
clearText: ->
text.destroy() for key, text of @menuTexts
sprite.destroy() for key, sprite of @bitmapData
image.destroy() for image in @menuImages
displayCredits: ->
@clearText()
@titleText.visible = false
@addInstructionText 'Credits', 400, 50, true
@addCreditsText 'Copyright (c) 2014 Bryan Bibat.', 50, 100, "http://bryanbibat.net"
@addCreditsText 'Made with Phaser 2.2.0', 375, 100, "http://phaser.io"
@addCreditsText 'Sprites (c) 2002 Ari Feldman,', 50, 135, "www.widgetworx.com/spritelib/"
@addCreditsText 'Sounds (c) 2013 dklon (Devin Watson),', 350, 135, "http://opengameart.org/users/dklon"
@addCreditsText '"Airborne" font (c) 2005 Charles Casimiro Design,', 50, 170, "http://charlescasimiro.com/airborne.html"
@addCreditsText '"Special Elite" font (c) 2011 Astigmatic (Brian J. Bonislawsky)', 50, 205, "http://www.astigmatic.com/"
share = @addInstructionText 'Spread the word:', 210, 300, true
book = @addTypewriterText "Read a book on how to make", 570, 280, 22, 'both', "https://leanpub.com/html5shootemupinanafternoon"
book2 = @addTypewriterText "HTML5 games like this:", 570, 305, 22, 'both', "https://leanpub.com/html5shootemupinanafternoon"
url = encodeURIComponent("http://games.bryanbibat.net/habagat/")
ogUrl = encodeURIComponent("<%= image_path 'opengraph.png' %>")
text = encodeURIComponent("Play Gunner, a WWII themed HTML5 game where you destroy waves of enemy planes and ships")
fullUrl = "https://twitter.com/intent/tweet?url=#{url}&text=#{text}"
@addIcon 110, 370, 'twitter', fullUrl
fullUrl ="https://www.facebook.com/dialog/share?app_id=488047311326879&href=#{url}&display=page&redirect_uri=https://facebook.com"
@addIcon 210, 370, 'facebook', fullUrl
fullUrl = "http://www.tumblr.com/share/link?url=#{url}&name=Gunner&description=#{text}"
@addIcon 310, 370, 'tumblr', fullUrl
fullUrl = "http://www.pinterest.com/pin/create/button/?url=#{url}&media=#{ogUrl}&description=#{text}"
@addIcon 160, 470, 'pinterest', fullUrl
fullUrl = "https://plus.google.com/share?url=#{url}"
@addIcon 260, 470, 'gplus', fullUrl
@addIcon 570, 420, 'book', "https://leanpub.com/html5shootemupinanafternoon"
@addText 'Back to Main Menu', 400, 560, true
addIcon: (x, y, filename, url) ->
icon = @add.sprite(x, y, 'assets', filename)
icon.anchor.setTo(0.5, 0.5)
icon.inputEnabled = true
icon.events.onInputDown.add( ->
win = window.open(url, '_blank')
win.focus()
, this)
@menuImages.push icon
Gunner.MainMenu = MainMenu
| 112961 | Store = new Persist.Store('Gunner Scores')
Gunner = window.Gunner
class MainMenu
create: ->
@stage.backgroundColor = '#2F3942'
@titleText = @add.bitmapText(400, 150, 'Airborne', 'Gunner', 128)
Gunner.center(@titleText)
gl = Store.get('gameLength')
@game.lengthMultplier = if gl? then parseInt(gl) else 2
gt = Store.get('gameType')
@game.gameType = if gt? then gt else 'Time Attack'
@menuTexts = {}
@bitmapData = {}
@menuImages = []
@setupTopLevel()
addText: (text, x, y, selected, small) ->
bmd = @add.bitmapData(1, 1)
bmds = @add.sprite(0, 0, bmd)
mt = @add.bitmapText(x, y, (if selected then 'Airborne' else 'AirborneGray'), text, (if small then 26 else 32))
@menuTexts[text] = mt
Gunner.center mt
mt.inputEnabled = true
mt.events.onInputDown.add(@menuSelect, @menuTexts[text])
bmds.x = mt.x - 5
bmds.y = mt.y - 5
bmd.resize(mt.textWidth + 10, mt.textHeight + 3)
bmd.context.fillStyle = "#2F3942"
bmd.context.fillRect 0, 0, mt.textWidth + 10, mt.textHeight + 3
bmds.inputEnabled = true
bmds.events.onInputDown.add(@menuSelect, @menuTexts[text])
@bitmapData[text] = bmds
addTypewriterText: (text, x, y, size, centerType, link) ->
if link?
bmd = @add.bitmapData(1, 1)
bmds = @add.sprite(0, 0, bmd)
mt = @add.bitmapText(x, y, 'SpecialElite32', text, size)
mt.align = 'center'
@menuTexts[text] = mt
switch centerType
when 'horizontal'
Gunner.horizontalCenter(mt)
when 'vertical'
Gunner.verticalCenter(mt)
when 'both'
Gunner.center(mt)
if link?
mt.inputEnabled = true
mt.events.onInputDown.add( ->
win = window.open(this, '_blank')
win.focus()
, link)
bmds.x = mt.x - 5
bmds.y = mt.y - 3
bmd.resize(mt.textWidth + 10, mt.textHeight + 5)
bmd.context.fillStyle = "#2F3942"
bmd.context.fillRect 0, 0, mt.textWidth + 10, mt.textHeight + 5
bmds.inputEnabled = true
bmds.events.onInputDown.add( ->
win = window.open(this, '_blank')
win.focus()
, link)
@bitmapData[text] = bmds
return mt
addInstructionText: (text, x, y, header) ->
@addTypewriterText(text, x, y, (if header then 32 else 20), (if header then 'both' else 'vertical'))
addTutorialText: (text, x, y, header) ->
@addTypewriterText(text, x, y, (if header then 32 else 20), 'both')
addCreditsText: (text, x, y, link) ->
@addTypewriterText(text, x, y, 20, 'none', link)
menuSelect: ->
state = @game.state.getCurrentState()
switch @text
when "Back to Main Menu"
state.titleText.visible = true
state.setupTopLevel()
when "Play Game"
state.setupOptions()
when "Time Attack"
@game.gameType = 'Time Attack'
state.highlightType()
when "Survival"
@game.gameType = 'Survival'
state.highlightType()
when "Quick"
@game.lengthMultplier = 5
state.highlightLength()
when "Normal"
@game.lengthMultplier = 2
state.highlightLength()
when "Extended"
@game.lengthMultplier = 1
state.highlightLength()
when "Start Game"
@game.lengthMultplier = 2 unless @game.lengthMultplier?
Store.set('gameLength', @game.lengthMultplier)
@game.gameType = 'time atttack' unless @game.gameType?
Store.set('gameType', @game.gameType)
if Store.get('skipTutorial')?
@game.state.start('Game')
else
state.displayTutorial()
when "Skip this screen from now on"
Store.set('skipTutorial', 'skip')
@game.state.start('Game')
when "Proceed to Game"
@game.state.start('Game')
when "How To Play"
state.displayInstructions()
when "Previous Page"
state.displayInstructions()
when "Next Page"
state.displayInstructions2()
when "High Scores"
state.displayHighScores()
when "Credits & Misc"
state.displayCredits()
setupTopLevel: ->
@clearText()
@addText 'Play Game', 400, 310, true
@addText 'How To Play', 400, 360, false
@addText 'High Scores', 400, 410, false
@addText 'Credits & Misc', 400, 460, false
@game.menuIndex = 0
setupOptions: ->
@clearText()
@addText 'Time Attack', 230, 345, true, true
@addText 'Survival', 230, 385, false, true
@addText 'Quick', 570, 330, false, true
@addText 'Normal', 570, 370, true, true
@addText 'Extended', 570, 410, false, true
@addText 'Game Type', 230, 270, true
@addText 'Game Length', 570, 270, true
@highlightLength()
@highlightType()
@addText 'Start Game', 400, 500, true
@addText 'Back to Main Menu', 400, 540, false, true
highlightType: ->
@menuTexts["Time Attack"].destroy()
@menuTexts["Survival"].destroy()
@bitmapData["Time Attack"].destroy()
@bitmapData["Survival"].destroy()
switch @game.gameType
when 'Time Attack'
@addText 'Time Attack', 230, 345, true, true
@addText 'Survival', 230, 385, false, true
when 'Survival'
@addText 'Time Attack', 230, 345, false, true
@addText 'Survival', 230, 385, true, true
highlightLength: ->
@menuTexts["Quick"].destroy()
@menuTexts["Normal"].destroy()
@menuTexts["Extended"].destroy()
@bitmapData["Quick"].destroy()
@bitmapData["Normal"].destroy()
@bitmapData["Extended"].destroy()
switch @game.lengthMultplier
when 5
@addText 'Quick', 570, 330, true, true
@addText 'Normal', 570, 370, false, true
@addText 'Extended', 570, 410, false, true
when 2
@addText 'Quick', 570, 330, false, true
@addText 'Normal', 570, 370, true, true
@addText 'Extended', 570, 410, false, true
when 1
@addText 'Quick', 570, 330, false, true
@addText 'Normal', 570, 370, false, true
@addText 'Extended', 570, 410, true, true
displayInstructions: ->
@clearText()
@titleText.visible = false
@addInstructionText 'How To Play', 400, 50, true
@addTutorialText 'This game has 2 modes: ', 400, 100
@addInstructionText 'Time Attack - finish the game as soon as possible ', 70, 135
@addInstructionText 'Survival - destroy as many as enemies as you can before losing', 70, 160
@addTutorialText 'Shoot by clicking or tapping on the spot you wish to fire at.', 400, 210
@addTutorialText 'Hold down click/tap for continuous fire. You can also use the arrow', 400, 235
@addTutorialText 'keys to move the crosshair and Space Bar to fire.', 400, 260
@addTutorialText 'Shooting consumes energy, destroying enemies provide energy.', 400, 295
@addTutorialText 'Tougher enemies give more energy, but still count as 1 kill.', 400, 320
@addTutorialText "Enemies cannot damage you, but it's game over if you", 400, 355
@addTutorialText "waste all of your energy (i.e. it reaches 0)", 400, 380
@addTutorialText 'Click/tap the audio icon to change the volume.', 400, 415
@addTutorialText 'Click/tap the gears icon to pause and show options.', 400, 440
@addText 'Next Page', 400, 500, true
@addText 'Back to Main Menu', 400, 550, false
displayInstructions2: ->
@clearText()
@titleText.visible = false
@addInstructionText 'How To Play', 400, 50, true
@addTutorialText 'Click/tap the other icons to change shot types and firing modes.', 400, 90
@addInstructionText 'There are 3 shot types:', 40, 130
@addInstructionText 'Small - fast firing, good for spraying weak enemies. 1 energy per shot', 40, 165
@addInstructionText ' Keyboard shortcut: "1"', 40, 190
@addInstructionText 'Large - slower rate, but better against tougher enemies. 3 energy per', 40, 215
@addInstructionText ' shot. Shortcut: "2"', 40, 240
@addInstructionText 'Burst - slow strong shot that bursts into 5 shots after hitting', 40, 265
@addInstructionText ' 8 energy per shot. Shortcut: "3"', 40, 290
@addInstructionText 'And there are 3 firing modes:', 40, 325
@addInstructionText 'Single - single turret, fastest rate of fire. Shortcut: "Q"', 40, 360
@addInstructionText 'Triple - use 3 turrets but fire rate is halved. Shortcut: "W"', 40, 385
@addInstructionText 'Bomb - slowest fire rate, drop a bomb that explodes into 10 shots after', 40, 410
@addInstructionText ' a short delay. Shortcut: "E"', 40, 435
@addText 'Previous Page', 400, 500, true
@addText 'Back to Main Menu', 400, 550, false
displayTutorial: ->
@clearText()
@titleText.visible = false
if @game.gameType is 'Time Attack'
text = ' Time Attack '
@addTutorialText "Reach #{15000 / @game.lengthMultplier} kills or destroy an", 400, 155, true
@addTutorialText "Elite Fighter as soon as possible.", 400, 195, true
else
text = ' Survival '
@addTutorialText "Destroy as many enemies as possible.", 400, 155, true
@addTutorialText "You will lose energy every minute.", 400, 195, true
@menuTexts[text] = @add.bitmapText(400, 90, 'Airborne', text, 80)
Gunner.center(@menuTexts[text])
@addTutorialText "Click or tap screen to shoot. Different firing modes", 400, 260
@addTutorialText "can be selected at the bottom by clicking/tapping.", 400, 285
@addTutorialText "Shooting consumes energy, destroying enemies provide energy.", 400, 330
@addTutorialText "Tougher enemies give more energy but still count as 1 kill.", 400, 355
@addTutorialText "Enemies cannot damage you, but it's game over if you", 400, 400
@addTutorialText "waste all of your energy (i.e. reaches 0)", 400, 425
@addText 'Proceed to Game', 400, 500, true
@addText 'Skip this screen from now on', 400, 550, false
displayHighScores: ->
@clearText()
@addText ' Time Attack ', 230, 300, true
@addText ' Survival ', 570, 300, true
@addTutorialText 'Quick: ' +
if Store.get("bestTime-5")?
Gunner.timeDisplay(parseInt(Store.get("bestTime-5")))
else
'n/a'
, 230, 340
@addTutorialText 'Normal: ' +
if Store.get("bestTime-2")?
Gunner.timeDisplay(parseInt(Store.get("bestTime-2")))
else
'n/a'
, 230, 370
@addTutorialText 'Extended: ' +
if Store.get("bestTime-1")?
Gunner.timeDisplay(parseInt(Store.get("bestTime-5")))
else
'n/a'
, 230, 400
@addTutorialText ' Quick: ' +
if Store.get("survival-5")?
Store.get("survival-5") + ' kills '
else
'n/a '
, 570, 340
@addTutorialText ' Normal: ' +
if Store.get("survival-2")?
Store.get("survival-2") + ' kills '
else
'n/a '
, 570, 370
@addTutorialText ' Extended: ' +
if Store.get("survival-1")?
Store.get("survival-1") + ' kills '
else
'n/a '
, 570, 400
@addText 'Back to Main Menu', 400, 510, true
clearText: ->
text.destroy() for key, text of @menuTexts
sprite.destroy() for key, sprite of @bitmapData
image.destroy() for image in @menuImages
displayCredits: ->
@clearText()
@titleText.visible = false
@addInstructionText 'Credits', 400, 50, true
@addCreditsText 'Copyright (c) 2014 <NAME>.', 50, 100, "http://bryanbibat.net"
@addCreditsText 'Made with Phaser 2.2.0', 375, 100, "http://phaser.io"
@addCreditsText 'Sprites (c) 2002 <NAME>,', 50, 135, "www.widgetworx.com/spritelib/"
@addCreditsText 'Sounds (c) 2013 dklon (<NAME>),', 350, 135, "http://opengameart.org/users/dklon"
@addCreditsText '"Airborne" font (c) 2005 Charles Casimiro Design,', 50, 170, "http://charlescasimiro.com/airborne.html"
@addCreditsText '"Special Elite" font (c) 2011 Astigmatic (<NAME>)', 50, 205, "http://www.astigmatic.com/"
share = @addInstructionText 'Spread the word:', 210, 300, true
book = @addTypewriterText "Read a book on how to make", 570, 280, 22, 'both', "https://leanpub.com/html5shootemupinanafternoon"
book2 = @addTypewriterText "HTML5 games like this:", 570, 305, 22, 'both', "https://leanpub.com/html5shootemupinanafternoon"
url = encodeURIComponent("http://games.bryanbibat.net/habagat/")
ogUrl = encodeURIComponent("<%= image_path 'opengraph.png' %>")
text = encodeURIComponent("Play <NAME>, a WWII themed HTML5 game where you destroy waves of enemy planes and ships")
fullUrl = "https://twitter.com/intent/tweet?url=#{url}&text=#{text}"
@addIcon 110, 370, 'twitter', fullUrl
fullUrl ="https://www.facebook.com/dialog/share?app_id=488047311326879&href=#{url}&display=page&redirect_uri=https://facebook.com"
@addIcon 210, 370, 'facebook', fullUrl
fullUrl = "http://www.tumblr.com/share/link?url=#{url}&name=<NAME>&description=#{text}"
@addIcon 310, 370, 'tumblr', fullUrl
fullUrl = "http://www.pinterest.com/pin/create/button/?url=#{url}&media=#{ogUrl}&description=#{text}"
@addIcon 160, 470, 'pinterest', fullUrl
fullUrl = "https://plus.google.com/share?url=#{url}"
@addIcon 260, 470, 'gplus', fullUrl
@addIcon 570, 420, 'book', "https://leanpub.com/html5shootemupinanafternoon"
@addText 'Back to Main Menu', 400, 560, true
addIcon: (x, y, filename, url) ->
icon = @add.sprite(x, y, 'assets', filename)
icon.anchor.setTo(0.5, 0.5)
icon.inputEnabled = true
icon.events.onInputDown.add( ->
win = window.open(url, '_blank')
win.focus()
, this)
@menuImages.push icon
Gunner.MainMenu = MainMenu
| true | Store = new Persist.Store('Gunner Scores')
Gunner = window.Gunner
class MainMenu
create: ->
@stage.backgroundColor = '#2F3942'
@titleText = @add.bitmapText(400, 150, 'Airborne', 'Gunner', 128)
Gunner.center(@titleText)
gl = Store.get('gameLength')
@game.lengthMultplier = if gl? then parseInt(gl) else 2
gt = Store.get('gameType')
@game.gameType = if gt? then gt else 'Time Attack'
@menuTexts = {}
@bitmapData = {}
@menuImages = []
@setupTopLevel()
addText: (text, x, y, selected, small) ->
bmd = @add.bitmapData(1, 1)
bmds = @add.sprite(0, 0, bmd)
mt = @add.bitmapText(x, y, (if selected then 'Airborne' else 'AirborneGray'), text, (if small then 26 else 32))
@menuTexts[text] = mt
Gunner.center mt
mt.inputEnabled = true
mt.events.onInputDown.add(@menuSelect, @menuTexts[text])
bmds.x = mt.x - 5
bmds.y = mt.y - 5
bmd.resize(mt.textWidth + 10, mt.textHeight + 3)
bmd.context.fillStyle = "#2F3942"
bmd.context.fillRect 0, 0, mt.textWidth + 10, mt.textHeight + 3
bmds.inputEnabled = true
bmds.events.onInputDown.add(@menuSelect, @menuTexts[text])
@bitmapData[text] = bmds
addTypewriterText: (text, x, y, size, centerType, link) ->
if link?
bmd = @add.bitmapData(1, 1)
bmds = @add.sprite(0, 0, bmd)
mt = @add.bitmapText(x, y, 'SpecialElite32', text, size)
mt.align = 'center'
@menuTexts[text] = mt
switch centerType
when 'horizontal'
Gunner.horizontalCenter(mt)
when 'vertical'
Gunner.verticalCenter(mt)
when 'both'
Gunner.center(mt)
if link?
mt.inputEnabled = true
mt.events.onInputDown.add( ->
win = window.open(this, '_blank')
win.focus()
, link)
bmds.x = mt.x - 5
bmds.y = mt.y - 3
bmd.resize(mt.textWidth + 10, mt.textHeight + 5)
bmd.context.fillStyle = "#2F3942"
bmd.context.fillRect 0, 0, mt.textWidth + 10, mt.textHeight + 5
bmds.inputEnabled = true
bmds.events.onInputDown.add( ->
win = window.open(this, '_blank')
win.focus()
, link)
@bitmapData[text] = bmds
return mt
addInstructionText: (text, x, y, header) ->
@addTypewriterText(text, x, y, (if header then 32 else 20), (if header then 'both' else 'vertical'))
addTutorialText: (text, x, y, header) ->
@addTypewriterText(text, x, y, (if header then 32 else 20), 'both')
addCreditsText: (text, x, y, link) ->
@addTypewriterText(text, x, y, 20, 'none', link)
menuSelect: ->
state = @game.state.getCurrentState()
switch @text
when "Back to Main Menu"
state.titleText.visible = true
state.setupTopLevel()
when "Play Game"
state.setupOptions()
when "Time Attack"
@game.gameType = 'Time Attack'
state.highlightType()
when "Survival"
@game.gameType = 'Survival'
state.highlightType()
when "Quick"
@game.lengthMultplier = 5
state.highlightLength()
when "Normal"
@game.lengthMultplier = 2
state.highlightLength()
when "Extended"
@game.lengthMultplier = 1
state.highlightLength()
when "Start Game"
@game.lengthMultplier = 2 unless @game.lengthMultplier?
Store.set('gameLength', @game.lengthMultplier)
@game.gameType = 'time atttack' unless @game.gameType?
Store.set('gameType', @game.gameType)
if Store.get('skipTutorial')?
@game.state.start('Game')
else
state.displayTutorial()
when "Skip this screen from now on"
Store.set('skipTutorial', 'skip')
@game.state.start('Game')
when "Proceed to Game"
@game.state.start('Game')
when "How To Play"
state.displayInstructions()
when "Previous Page"
state.displayInstructions()
when "Next Page"
state.displayInstructions2()
when "High Scores"
state.displayHighScores()
when "Credits & Misc"
state.displayCredits()
setupTopLevel: ->
@clearText()
@addText 'Play Game', 400, 310, true
@addText 'How To Play', 400, 360, false
@addText 'High Scores', 400, 410, false
@addText 'Credits & Misc', 400, 460, false
@game.menuIndex = 0
setupOptions: ->
@clearText()
@addText 'Time Attack', 230, 345, true, true
@addText 'Survival', 230, 385, false, true
@addText 'Quick', 570, 330, false, true
@addText 'Normal', 570, 370, true, true
@addText 'Extended', 570, 410, false, true
@addText 'Game Type', 230, 270, true
@addText 'Game Length', 570, 270, true
@highlightLength()
@highlightType()
@addText 'Start Game', 400, 500, true
@addText 'Back to Main Menu', 400, 540, false, true
highlightType: ->
@menuTexts["Time Attack"].destroy()
@menuTexts["Survival"].destroy()
@bitmapData["Time Attack"].destroy()
@bitmapData["Survival"].destroy()
switch @game.gameType
when 'Time Attack'
@addText 'Time Attack', 230, 345, true, true
@addText 'Survival', 230, 385, false, true
when 'Survival'
@addText 'Time Attack', 230, 345, false, true
@addText 'Survival', 230, 385, true, true
highlightLength: ->
@menuTexts["Quick"].destroy()
@menuTexts["Normal"].destroy()
@menuTexts["Extended"].destroy()
@bitmapData["Quick"].destroy()
@bitmapData["Normal"].destroy()
@bitmapData["Extended"].destroy()
switch @game.lengthMultplier
when 5
@addText 'Quick', 570, 330, true, true
@addText 'Normal', 570, 370, false, true
@addText 'Extended', 570, 410, false, true
when 2
@addText 'Quick', 570, 330, false, true
@addText 'Normal', 570, 370, true, true
@addText 'Extended', 570, 410, false, true
when 1
@addText 'Quick', 570, 330, false, true
@addText 'Normal', 570, 370, false, true
@addText 'Extended', 570, 410, true, true
displayInstructions: ->
@clearText()
@titleText.visible = false
@addInstructionText 'How To Play', 400, 50, true
@addTutorialText 'This game has 2 modes: ', 400, 100
@addInstructionText 'Time Attack - finish the game as soon as possible ', 70, 135
@addInstructionText 'Survival - destroy as many as enemies as you can before losing', 70, 160
@addTutorialText 'Shoot by clicking or tapping on the spot you wish to fire at.', 400, 210
@addTutorialText 'Hold down click/tap for continuous fire. You can also use the arrow', 400, 235
@addTutorialText 'keys to move the crosshair and Space Bar to fire.', 400, 260
@addTutorialText 'Shooting consumes energy, destroying enemies provide energy.', 400, 295
@addTutorialText 'Tougher enemies give more energy, but still count as 1 kill.', 400, 320
@addTutorialText "Enemies cannot damage you, but it's game over if you", 400, 355
@addTutorialText "waste all of your energy (i.e. it reaches 0)", 400, 380
@addTutorialText 'Click/tap the audio icon to change the volume.', 400, 415
@addTutorialText 'Click/tap the gears icon to pause and show options.', 400, 440
@addText 'Next Page', 400, 500, true
@addText 'Back to Main Menu', 400, 550, false
displayInstructions2: ->
@clearText()
@titleText.visible = false
@addInstructionText 'How To Play', 400, 50, true
@addTutorialText 'Click/tap the other icons to change shot types and firing modes.', 400, 90
@addInstructionText 'There are 3 shot types:', 40, 130
@addInstructionText 'Small - fast firing, good for spraying weak enemies. 1 energy per shot', 40, 165
@addInstructionText ' Keyboard shortcut: "1"', 40, 190
@addInstructionText 'Large - slower rate, but better against tougher enemies. 3 energy per', 40, 215
@addInstructionText ' shot. Shortcut: "2"', 40, 240
@addInstructionText 'Burst - slow strong shot that bursts into 5 shots after hitting', 40, 265
@addInstructionText ' 8 energy per shot. Shortcut: "3"', 40, 290
@addInstructionText 'And there are 3 firing modes:', 40, 325
@addInstructionText 'Single - single turret, fastest rate of fire. Shortcut: "Q"', 40, 360
@addInstructionText 'Triple - use 3 turrets but fire rate is halved. Shortcut: "W"', 40, 385
@addInstructionText 'Bomb - slowest fire rate, drop a bomb that explodes into 10 shots after', 40, 410
@addInstructionText ' a short delay. Shortcut: "E"', 40, 435
@addText 'Previous Page', 400, 500, true
@addText 'Back to Main Menu', 400, 550, false
displayTutorial: ->
@clearText()
@titleText.visible = false
if @game.gameType is 'Time Attack'
text = ' Time Attack '
@addTutorialText "Reach #{15000 / @game.lengthMultplier} kills or destroy an", 400, 155, true
@addTutorialText "Elite Fighter as soon as possible.", 400, 195, true
else
text = ' Survival '
@addTutorialText "Destroy as many enemies as possible.", 400, 155, true
@addTutorialText "You will lose energy every minute.", 400, 195, true
@menuTexts[text] = @add.bitmapText(400, 90, 'Airborne', text, 80)
Gunner.center(@menuTexts[text])
@addTutorialText "Click or tap screen to shoot. Different firing modes", 400, 260
@addTutorialText "can be selected at the bottom by clicking/tapping.", 400, 285
@addTutorialText "Shooting consumes energy, destroying enemies provide energy.", 400, 330
@addTutorialText "Tougher enemies give more energy but still count as 1 kill.", 400, 355
@addTutorialText "Enemies cannot damage you, but it's game over if you", 400, 400
@addTutorialText "waste all of your energy (i.e. reaches 0)", 400, 425
@addText 'Proceed to Game', 400, 500, true
@addText 'Skip this screen from now on', 400, 550, false
displayHighScores: ->
@clearText()
@addText ' Time Attack ', 230, 300, true
@addText ' Survival ', 570, 300, true
@addTutorialText 'Quick: ' +
if Store.get("bestTime-5")?
Gunner.timeDisplay(parseInt(Store.get("bestTime-5")))
else
'n/a'
, 230, 340
@addTutorialText 'Normal: ' +
if Store.get("bestTime-2")?
Gunner.timeDisplay(parseInt(Store.get("bestTime-2")))
else
'n/a'
, 230, 370
@addTutorialText 'Extended: ' +
if Store.get("bestTime-1")?
Gunner.timeDisplay(parseInt(Store.get("bestTime-5")))
else
'n/a'
, 230, 400
@addTutorialText ' Quick: ' +
if Store.get("survival-5")?
Store.get("survival-5") + ' kills '
else
'n/a '
, 570, 340
@addTutorialText ' Normal: ' +
if Store.get("survival-2")?
Store.get("survival-2") + ' kills '
else
'n/a '
, 570, 370
@addTutorialText ' Extended: ' +
if Store.get("survival-1")?
Store.get("survival-1") + ' kills '
else
'n/a '
, 570, 400
@addText 'Back to Main Menu', 400, 510, true
clearText: ->
text.destroy() for key, text of @menuTexts
sprite.destroy() for key, sprite of @bitmapData
image.destroy() for image in @menuImages
displayCredits: ->
@clearText()
@titleText.visible = false
@addInstructionText 'Credits', 400, 50, true
@addCreditsText 'Copyright (c) 2014 PI:NAME:<NAME>END_PI.', 50, 100, "http://bryanbibat.net"
@addCreditsText 'Made with Phaser 2.2.0', 375, 100, "http://phaser.io"
@addCreditsText 'Sprites (c) 2002 PI:NAME:<NAME>END_PI,', 50, 135, "www.widgetworx.com/spritelib/"
@addCreditsText 'Sounds (c) 2013 dklon (PI:NAME:<NAME>END_PI),', 350, 135, "http://opengameart.org/users/dklon"
@addCreditsText '"Airborne" font (c) 2005 Charles Casimiro Design,', 50, 170, "http://charlescasimiro.com/airborne.html"
@addCreditsText '"Special Elite" font (c) 2011 Astigmatic (PI:NAME:<NAME>END_PI)', 50, 205, "http://www.astigmatic.com/"
share = @addInstructionText 'Spread the word:', 210, 300, true
book = @addTypewriterText "Read a book on how to make", 570, 280, 22, 'both', "https://leanpub.com/html5shootemupinanafternoon"
book2 = @addTypewriterText "HTML5 games like this:", 570, 305, 22, 'both', "https://leanpub.com/html5shootemupinanafternoon"
url = encodeURIComponent("http://games.bryanbibat.net/habagat/")
ogUrl = encodeURIComponent("<%= image_path 'opengraph.png' %>")
text = encodeURIComponent("Play PI:NAME:<NAME>END_PI, a WWII themed HTML5 game where you destroy waves of enemy planes and ships")
fullUrl = "https://twitter.com/intent/tweet?url=#{url}&text=#{text}"
@addIcon 110, 370, 'twitter', fullUrl
fullUrl ="https://www.facebook.com/dialog/share?app_id=488047311326879&href=#{url}&display=page&redirect_uri=https://facebook.com"
@addIcon 210, 370, 'facebook', fullUrl
fullUrl = "http://www.tumblr.com/share/link?url=#{url}&name=PI:NAME:<NAME>END_PI&description=#{text}"
@addIcon 310, 370, 'tumblr', fullUrl
fullUrl = "http://www.pinterest.com/pin/create/button/?url=#{url}&media=#{ogUrl}&description=#{text}"
@addIcon 160, 470, 'pinterest', fullUrl
fullUrl = "https://plus.google.com/share?url=#{url}"
@addIcon 260, 470, 'gplus', fullUrl
@addIcon 570, 420, 'book', "https://leanpub.com/html5shootemupinanafternoon"
@addText 'Back to Main Menu', 400, 560, true
addIcon: (x, y, filename, url) ->
icon = @add.sprite(x, y, 'assets', filename)
icon.anchor.setTo(0.5, 0.5)
icon.inputEnabled = true
icon.events.onInputDown.add( ->
win = window.open(url, '_blank')
win.focus()
, this)
@menuImages.push icon
Gunner.MainMenu = MainMenu
|
[
{
"context": "{Object} query Query the collection á la `{name: \"Jim\"}`\n # @return {Array} Objects matching the q",
"end": 16085,
"score": 0.9896036982536316,
"start": 16082,
"tag": "NAME",
"value": "Jim"
}
] | src/model.coffee | killercup/angular-epicmodel | 0 | ###
# # Epic Model
###
angular.module('EpicModel', [
])
.provider "Collection", ->
###
# Create your own collection by injecting the `Collection` service and calling
# its 'new' method.
#
# @example
# ```coffeescript
# angular.module('Module', ['EpicModel'])
# .factory "API", (Collection) ->
# API =
# People: Collection.new 'People', {url: '/people/:id'},
# calculateStuff: (input) -> 42
# .controller "Ctrl", ($scope, ShittyAPI) ->
# $scope.list = API.People.all()
# ```
#
# **Immediate Return Data**
#
# Most methods return a promise, but the methods `all` and `get` methods
# return a special object instead, that contains the currently available data,
# a promise and flags to represent the data retrieval state. I.e., you can
# immediately use the return value in your views and the data will
# automatically appear once it has been retrieved (or updated).
#
# @example
# ```coffeescript
# Me = Collection.new "Me", is_singleton: true
# Me.all()
# #=> {data: {}, $resolved: false, $loading: true, $promise: {then, ...}}
# ```
###
# ## Global Config
###
#
# Just inject the `CollectionProvider` and set some globals.
#
# @example
# ```coffeescript
# angular.module('app', ['EpicModel'])
# .config (CollectionProvider) ->
# CollectionProvider.setBaseUrl('http://example.com/api/v1')
# ```
###
globalConfig =
baseUrl: ''
###
# @method Set Base URL
#
# @param {String} url The new base URL
# @return {String} The new base URL
# @throws {Error} When no URL is given
###
@setBaseUrl = (url='') ->
throw new Error "No URL given." unless url?
globalConfig.baseUrl = url
# - - -
#
# The service factory function
@$get = ($q, $http) ->
###
# ## Constructor
#
# Create a new Collection.
#
# @param {String} name The unique name of the new collection.
# @param {Object} [config] Configuration and settings
# @param {String|Function} [config.url] Resource URL
# @param {String|Function} [config.detailUrl] URL for single resource,
# default: `config.url + '/' + entry.id`. Will interpolate segments in
# curly brackets, e.g. transforming `/item/{_id}` to `'/item/'+entry._id`.
# If you supply a function, it will be called with the current entry,
# the base URL and the resource list url (`config.url`) and should return
# a string that will be used as URL.
# @param {String} [config.baseUrl] Overwrite base URL
# @param {Bool} [config.is_singleton] Whether resource returns an object
# @param {Object} [config.storage] Storage implementation, e.g.
# `CollectionLocalStorage` (see below)
# @param {Function} [config.storage.setItem]
# @param {Function} [config.storage.getItem]
# @param {Function} [config.storage.removeItem]
# @param {Function} [config.transformRequest=`_.identity`] Takes the
# _request_ `data` and a hint like 'array', 'one', 'save', 'destroy'
# and returns the transformed `data`. *NYI*
# @param {Function} [config.transformResponse=`_.identity`] Takes the
# _response_ `data` and a hint like 'array', 'one', 'save', 'destroy'
# and returns the transformed `data`.
# @param {Function} [config.matchingCriteria] Takes data object and returns
# matching criteria. Default: `(data) -> id: +data.id`
# @param {Object} [extras] Add custom methods to instance, functions will
# be have `config` as `this`, objects will used to construct new `$http`
# calls
# @return {Object} The collection
# @throws {Error} When no name is given
#
# @example
# ```coffeescript
# Collection.new 'User', {
# url: '/user' # also set implicitly from name
# is_singleton: true # Expect single object instead of array
# storage: myStorage # see below
# }, {
# something: (id) -> 42
# pay:
# method: 'PATCH'
# params:
# payout: true
# }
# ```
###
constructor = (name, config={}, extras={}) ->
# This will be returned.
exports = {}
# ### Options
throw new Error "No name given!" unless name?
###
# @method Config Getter
#
# @description Retrieve config value from instance
# @param {String} key
# @return {Any} Config value
###
exports.config = (key) ->
config[key]
config.url ||= '/' + name.toLowerCase()
config.baseUrl ||= globalConfig.baseUrl
config.listUrl ||= config.url
###
# @method Make Detail URL from Pattern
#
# @param {Object} entry The entry to URL points to
# @param {String} [listUrl=config.url]
# @param {String} [baseUrl=config.baseUrl]
# @return {String} Entry URL
###
config.parseUrlPattern = (entry, url) ->
substitutes = /\{([\w_.]*?)\}/g
entryUrl = url
_.each url.match(substitutes), (match) ->
# Remove braces and split on dots (might address sub-object, e.g.
# using `item.id`)
keys = match.replace('{', '').replace('}', '').split('.')
value = entry
_.each keys, (key) ->
value = value[key]
if value?
entryUrl = entryUrl.replace match, value
else
throw new Error "#{name} Model: Can't substitute #{match} in URL"+
"(entry has no value for #{key})"
return entryUrl
if _.isString config.detailUrl
makeDetailUrl = (entry) ->
config.parseUrlPattern(entry, "#{config.baseUrl}#{config.detailUrl}")
else
makeDetailUrl = (entry, listUrl=config.listUrl, baseUrl=config.baseUrl) ->
if entry.id?
"#{baseUrl}#{listUrl}/#{entry.id}"
else
throw new Error "#{name} Model: Need entry ID to construct URL"
if _.isFunction config.detailUrl
config.getDetailUrl = (entry, listUrl=config.listUrl, baseUrl=config.baseUrl) ->
config.detailUrl(entry, listUrl, baseUrl)
else
config.getDetailUrl = makeDetailUrl
IS_SINGLETON = !!config.is_singleton
config.transformRequest ||= _.identity
config.transformResponse ||= _.identity
config.matchingCriteria ||= (data) -> id: +data.id
# #### Storage Implementation
###
# Use key/value store to persist data.
#
# Key schema: "{collection name}.{all|data}"
#
# Use any implementation that has these methods:
#
# - `setItem(String key, value)`
# - `getItem(String key)`
# - `removeItem(String key)`
#
# ```coffeescript
# myStorage =
# getItem: (key) ->
# value = window.localStorage.getItem(key)
# value && JSON.parse(value)
# setItem: (key, value) ->
# window.localStorage.setItem(key, angular.toJson(value))
# removeItem: (key) ->
# window.localStorage.removeItem(key)
#
# Collection.new 'People', {storage: myStorage} # uses localStorage now
# ```
###
store = do ->
_store = {}
impl = config.storage or {}
_.each ['setItem', 'getItem', 'removeItem'], (method) ->
_store[method] = if _.isFunction impl[method]
impl[method]
else angular.noop
_store
# ### In Memory Data
###
# The Single Source of Truth
#
# @private
###
Data = {}
if IS_SINGLETON # Is single Model
_data =
data: store.getItem("#{name}.data") || {}
###
# @method Get Data
# @return {Object} data
###
Data.get = -> _data.data
###
# @method Replace Singleton Data
#
# @param {Object} data New data
# @return {Object} The complete data representation
###
Data.replace = (data) ->
_data.data = _.extend(_data.data, data)
store.setItem("#{name}.data", _data.data)
return _data.data
else # is Model[]
_data =
all: store.getItem("#{name}.all") || []
###
# @method Get Data
# @return {Array} data
###
Data.get = -> _data.all
###
# @method Replace Complete Collection Data
#
# @param {Array} data New data
# @return {Object} The complete data representation
###
Data.replace = (data) ->
_data.all.splice(0, data.length)
[].push.apply(_data.all, data)
store.setItem("#{name}.all", _data.all)
return _data.all
###
# @method Update Single Entry from Collection
#
# @description This will also add an entry if no existing one matches
# the criteria
#
# @param {Object} data New data
# @param {Object} criteria Used to find entry
# @return {Object} The updated entry
###
Data.updateEntry = (data, criteria) ->
hit = _.findWhere(_data.all, criteria)
if hit?
# update existing entry
hit = _.extend(hit, data)
else
# add new entry (on top of list)
_data.all.unshift(data)
store.setItem("#{name}.all", _data.all)
return if hit? then hit else data
###
# @method Remove Single Entry from Collection
#
# @param {Object} criteria Used to find entry
# @return {Bool} Whether removal was
###
Data.removeEntry = (criteria) ->
hit = _.findWhere(_data.all, criteria)
if hit?
_data.all.splice _data.all.indexOf(hit), 1
store.removeItem("#{name}.all", _data.all)
return hit?
config.Data = exports.Data = Data
# ### HTTP Requests and Stuff
###
# @method Retrieve List
#
# @description Gotta catch 'em all!
#
# @param {Object} [options] HTTP options
# @return {Promise} HTTP data
###
exports.fetchAll = (options={}) ->
httpOptions = _.defaults options,
method: "GET"
url: "#{config.baseUrl}#{config.url}"
$http(httpOptions)
.then (response) ->
unless _.isArray(response.data)
console.warn "#{name} Model", "API Respsonse was", response.data
throw new Error "#{name} Model: Expected array, got #{typeof response.data}"
response.data = config.transformResponse(response.data, 'array')
# replace array items with new data
response.data = Data.replace(response.data)
return $q.when(response)
###
# @method Retrieve Singleton
#
# @param {Object} [options] HTTP options
# @return {Promise} HTTP data
###
exports.fetch = (options={}) ->
httpOptions = _.defaults options,
method: "GET"
url: "#{config.baseUrl}#{config.url}"
$http(httpOptions)
.then (response) ->
unless _.isObject(response.data)
console.warn "#{name} Model", "API Respsonse was", response.data
throw new Error "#{name} Model: Expected object, got #{typeof response.data}"
response.data = config.transformResponse(response.data, 'one')
response.data = Data.replace(response.data)
return $q.when(response)
###
# @method Retrieve One
#
# @description This also updates the internal data collection, of course.
#
# @param {String} id The ID of the element to fetch.
# @param {Object} [options] HTTP options
# @return {Promise} HTTP data
#
# @todo Customize ID query
###
exports.fetchOne = (query, options={}) ->
try
_url = config.getDetailUrl(query, config.listUrl, config.baseUrl)
catch e
return $q.reject e.message || e
httpOptions = _.defaults options,
method: "GET"
url: _url
$http(httpOptions)
.then (res) ->
unless _.isObject(res.data)
console.warn "#{name} Model", "API Respsonse was", res.data
throw new Error "Expected object, got #{typeof res.data}"
res.data = config.transformResponse(res.data, 'one')
res.data = Data.updateEntry res.data, config.matchingCriteria(res.data)
return $q.when(res)
###
# @method Destroy some Entry
#
# @param {String} id The ID of the element to fetch.
# @param {Object} [options] HTTP options
# @return {Promise} Whether destruction was successful
# @throws {Error} When Collection is singleton or no ID is given
#
# @todo Customize ID query
###
exports.destroy = (query, options={}) ->
if IS_SINGLETON
throw new Error "#{name} Model: Singleton doesn't have `destroy` method."
try
_url = config.getDetailUrl(query, config.listUrl, config.baseUrl)
catch e
return $q.reject e.message || e
httpOptions = _.defaults options,
method: "DELETE"
url: _url
$http(httpOptions)
.then ({status, data}) ->
data = config.transformResponse(data, 'destroy')
return $q.when Data.removeEntry config.matchingCriteria(data)
###
# @method Save an Entry
#
# @param {Object} entry The entry to be saved.
# @param {Object} [options] HTTP options
# @return {Promise} Resolved with new entry or rejected with HTTP error
#
# @todo Customize ID query
###
exports.save = (entry, options={}) ->
if IS_SINGLETON
_url = "#{config.baseUrl}#{config.listUrl}"
else
try
_url = config.getDetailUrl(entry, config.listUrl, config.baseUrl)
catch e
return $q.reject e.message || e
httpOptions = _.defaults options,
method: "PUT"
url: _url
data: angular.toJson(entry)
return $http(httpOptions)
.then ({status, data}) ->
data = config.transformResponse(data, 'save')
if IS_SINGLETON
return $q.when Data.replace(data)
else
return $q.when Data.updateEntry data, config.matchingCriteria(data)
###
# @method Create an Entry
#
# @description Similar to save, but has no ID initially.
#
# @param {Object} entry Entry data
# @param {Object} [options] HTTP options
# @return {Promise} Resolves with new entry data or rejects with HTTP error
# @throws {Error} When Collection is singleton
###
exports.create = (entry, options={}) ->
if IS_SINGLETON
throw new Error "#{name} Model: Singleton doesn't have `destroy` method."
httpOptions = _.defaults options,
method: "POST"
url: "#{config.baseUrl}#{config.listUrl}"
data: angular.toJson(entry)
return $http(httpOptions)
.then ({status, data}) ->
return $q.when Data.updateEntry data, config.matchingCriteria(data)
# - - -
# ### Generic Getters
###
# @method Get Collection
#
# @param {Object} [options] HTTP options
# @return {Object} Immediate Return Data (see above)
###
exports.all = (options) ->
local =
$loading: true
if IS_SINGLETON
local.$promise = exports.fetch(options)
local.data = _data.data
else
local.$promise = exports.fetchAll(options)
local.all = _data.all
local.$promise = local.$promise
.then (response) ->
local.$loading = false
local.$resolved = true
$q.when(response)
.then null, (err) ->
local.$error = err
local.$loading = false
$q.reject(err)
return local
###
# @method Query Collection
#
# @param {Object} query Query the collection á la `{name: "Jim"}`
# @return {Array} Objects matching the query.
###
exports.where = (query) ->
_.where(_data.all, query)
###
# @method Get Single Collection Entry
#
# @param {Object} query The query that will be used in `matchingCriteria`
# @param {Object} [options] HTTP options
# @return {Object} Immediate Return Data (see above)
# @throws {Error} When Collection is singleton
#
# @todo Customize ID query
###
exports.get = (query, options) ->
if IS_SINGLETON
throw new Error "#{name} Model: Singleton doesn't have `get` method."
local =
$loading: true
local.data = _.findWhere _data.all, config.matchingCriteria(query)
local.$promise = exports.fetchOne(query, options)
.then (response) ->
local.data = response.data
local.$loading = false
local.$resolved = true
$q.when(response)
.then null, (err) ->
local.$error = err
local.$loading = false
$q.reject(err)
return local
# ### Mixin Extras
addExtraCall = (key, val) ->
unless val.url
val.url = "#{config.baseUrl}#{config.listUrl}/#{key}"
if _.isFunction val.onSuccess
success = _.bind(val.onSuccess, config)
delete val.onSuccess
if _.isFunction val.onFail
fail = _.bind(val.onFail, config)
delete val.onFail
# @todo Add data storage options
exports[key] = (data, options={}) ->
if !options.url
if _.isFunction(val.url)
options.url = val.url(data, config.listUrl, config.detailUrl)
else
options.url = config.parseUrlPattern(data, "#{config.baseUrl}#{val.url}")
call = $http _.defaults(options, val), data
call.then(success) if success?
call.then(null, fail) if fail?
return call
_.each extras, (val, key) ->
# Custom methods
if _.isFunction(val)
exports[key] = _.bind(val, config)
# Custom HTTP Call
else if _.isObject(val)
addExtraCall key, val
# - - -
exports
return new: constructor
return
.factory "CollectionLocalStorage", ->
# ## Storage Wrapper for LocalStorage
return unless window.localStorage?
return {
# ### Get Item
###
# @param {String} key
# @return {Any}
###
getItem: (key) ->
value = window.localStorage.getItem(key)
value && JSON.parse(value)
# ### Set Item
###
# @param {String} key
# @param {Any} value
# @return {Any}
###
setItem: (key, value) ->
window.localStorage.setItem(key, angular.toJson(value))
# ### Remove Item
###
# @param {String} key
###
removeItem: (key) ->
window.localStorage.removeItem(key)
}
| 166157 | ###
# # Epic Model
###
angular.module('EpicModel', [
])
.provider "Collection", ->
###
# Create your own collection by injecting the `Collection` service and calling
# its 'new' method.
#
# @example
# ```coffeescript
# angular.module('Module', ['EpicModel'])
# .factory "API", (Collection) ->
# API =
# People: Collection.new 'People', {url: '/people/:id'},
# calculateStuff: (input) -> 42
# .controller "Ctrl", ($scope, ShittyAPI) ->
# $scope.list = API.People.all()
# ```
#
# **Immediate Return Data**
#
# Most methods return a promise, but the methods `all` and `get` methods
# return a special object instead, that contains the currently available data,
# a promise and flags to represent the data retrieval state. I.e., you can
# immediately use the return value in your views and the data will
# automatically appear once it has been retrieved (or updated).
#
# @example
# ```coffeescript
# Me = Collection.new "Me", is_singleton: true
# Me.all()
# #=> {data: {}, $resolved: false, $loading: true, $promise: {then, ...}}
# ```
###
# ## Global Config
###
#
# Just inject the `CollectionProvider` and set some globals.
#
# @example
# ```coffeescript
# angular.module('app', ['EpicModel'])
# .config (CollectionProvider) ->
# CollectionProvider.setBaseUrl('http://example.com/api/v1')
# ```
###
globalConfig =
baseUrl: ''
###
# @method Set Base URL
#
# @param {String} url The new base URL
# @return {String} The new base URL
# @throws {Error} When no URL is given
###
@setBaseUrl = (url='') ->
throw new Error "No URL given." unless url?
globalConfig.baseUrl = url
# - - -
#
# The service factory function
@$get = ($q, $http) ->
###
# ## Constructor
#
# Create a new Collection.
#
# @param {String} name The unique name of the new collection.
# @param {Object} [config] Configuration and settings
# @param {String|Function} [config.url] Resource URL
# @param {String|Function} [config.detailUrl] URL for single resource,
# default: `config.url + '/' + entry.id`. Will interpolate segments in
# curly brackets, e.g. transforming `/item/{_id}` to `'/item/'+entry._id`.
# If you supply a function, it will be called with the current entry,
# the base URL and the resource list url (`config.url`) and should return
# a string that will be used as URL.
# @param {String} [config.baseUrl] Overwrite base URL
# @param {Bool} [config.is_singleton] Whether resource returns an object
# @param {Object} [config.storage] Storage implementation, e.g.
# `CollectionLocalStorage` (see below)
# @param {Function} [config.storage.setItem]
# @param {Function} [config.storage.getItem]
# @param {Function} [config.storage.removeItem]
# @param {Function} [config.transformRequest=`_.identity`] Takes the
# _request_ `data` and a hint like 'array', 'one', 'save', 'destroy'
# and returns the transformed `data`. *NYI*
# @param {Function} [config.transformResponse=`_.identity`] Takes the
# _response_ `data` and a hint like 'array', 'one', 'save', 'destroy'
# and returns the transformed `data`.
# @param {Function} [config.matchingCriteria] Takes data object and returns
# matching criteria. Default: `(data) -> id: +data.id`
# @param {Object} [extras] Add custom methods to instance, functions will
# be have `config` as `this`, objects will used to construct new `$http`
# calls
# @return {Object} The collection
# @throws {Error} When no name is given
#
# @example
# ```coffeescript
# Collection.new 'User', {
# url: '/user' # also set implicitly from name
# is_singleton: true # Expect single object instead of array
# storage: myStorage # see below
# }, {
# something: (id) -> 42
# pay:
# method: 'PATCH'
# params:
# payout: true
# }
# ```
###
constructor = (name, config={}, extras={}) ->
# This will be returned.
exports = {}
# ### Options
throw new Error "No name given!" unless name?
###
# @method Config Getter
#
# @description Retrieve config value from instance
# @param {String} key
# @return {Any} Config value
###
exports.config = (key) ->
config[key]
config.url ||= '/' + name.toLowerCase()
config.baseUrl ||= globalConfig.baseUrl
config.listUrl ||= config.url
###
# @method Make Detail URL from Pattern
#
# @param {Object} entry The entry to URL points to
# @param {String} [listUrl=config.url]
# @param {String} [baseUrl=config.baseUrl]
# @return {String} Entry URL
###
config.parseUrlPattern = (entry, url) ->
substitutes = /\{([\w_.]*?)\}/g
entryUrl = url
_.each url.match(substitutes), (match) ->
# Remove braces and split on dots (might address sub-object, e.g.
# using `item.id`)
keys = match.replace('{', '').replace('}', '').split('.')
value = entry
_.each keys, (key) ->
value = value[key]
if value?
entryUrl = entryUrl.replace match, value
else
throw new Error "#{name} Model: Can't substitute #{match} in URL"+
"(entry has no value for #{key})"
return entryUrl
if _.isString config.detailUrl
makeDetailUrl = (entry) ->
config.parseUrlPattern(entry, "#{config.baseUrl}#{config.detailUrl}")
else
makeDetailUrl = (entry, listUrl=config.listUrl, baseUrl=config.baseUrl) ->
if entry.id?
"#{baseUrl}#{listUrl}/#{entry.id}"
else
throw new Error "#{name} Model: Need entry ID to construct URL"
if _.isFunction config.detailUrl
config.getDetailUrl = (entry, listUrl=config.listUrl, baseUrl=config.baseUrl) ->
config.detailUrl(entry, listUrl, baseUrl)
else
config.getDetailUrl = makeDetailUrl
IS_SINGLETON = !!config.is_singleton
config.transformRequest ||= _.identity
config.transformResponse ||= _.identity
config.matchingCriteria ||= (data) -> id: +data.id
# #### Storage Implementation
###
# Use key/value store to persist data.
#
# Key schema: "{collection name}.{all|data}"
#
# Use any implementation that has these methods:
#
# - `setItem(String key, value)`
# - `getItem(String key)`
# - `removeItem(String key)`
#
# ```coffeescript
# myStorage =
# getItem: (key) ->
# value = window.localStorage.getItem(key)
# value && JSON.parse(value)
# setItem: (key, value) ->
# window.localStorage.setItem(key, angular.toJson(value))
# removeItem: (key) ->
# window.localStorage.removeItem(key)
#
# Collection.new 'People', {storage: myStorage} # uses localStorage now
# ```
###
store = do ->
_store = {}
impl = config.storage or {}
_.each ['setItem', 'getItem', 'removeItem'], (method) ->
_store[method] = if _.isFunction impl[method]
impl[method]
else angular.noop
_store
# ### In Memory Data
###
# The Single Source of Truth
#
# @private
###
Data = {}
if IS_SINGLETON # Is single Model
_data =
data: store.getItem("#{name}.data") || {}
###
# @method Get Data
# @return {Object} data
###
Data.get = -> _data.data
###
# @method Replace Singleton Data
#
# @param {Object} data New data
# @return {Object} The complete data representation
###
Data.replace = (data) ->
_data.data = _.extend(_data.data, data)
store.setItem("#{name}.data", _data.data)
return _data.data
else # is Model[]
_data =
all: store.getItem("#{name}.all") || []
###
# @method Get Data
# @return {Array} data
###
Data.get = -> _data.all
###
# @method Replace Complete Collection Data
#
# @param {Array} data New data
# @return {Object} The complete data representation
###
Data.replace = (data) ->
_data.all.splice(0, data.length)
[].push.apply(_data.all, data)
store.setItem("#{name}.all", _data.all)
return _data.all
###
# @method Update Single Entry from Collection
#
# @description This will also add an entry if no existing one matches
# the criteria
#
# @param {Object} data New data
# @param {Object} criteria Used to find entry
# @return {Object} The updated entry
###
Data.updateEntry = (data, criteria) ->
hit = _.findWhere(_data.all, criteria)
if hit?
# update existing entry
hit = _.extend(hit, data)
else
# add new entry (on top of list)
_data.all.unshift(data)
store.setItem("#{name}.all", _data.all)
return if hit? then hit else data
###
# @method Remove Single Entry from Collection
#
# @param {Object} criteria Used to find entry
# @return {Bool} Whether removal was
###
Data.removeEntry = (criteria) ->
hit = _.findWhere(_data.all, criteria)
if hit?
_data.all.splice _data.all.indexOf(hit), 1
store.removeItem("#{name}.all", _data.all)
return hit?
config.Data = exports.Data = Data
# ### HTTP Requests and Stuff
###
# @method Retrieve List
#
# @description Gotta catch 'em all!
#
# @param {Object} [options] HTTP options
# @return {Promise} HTTP data
###
exports.fetchAll = (options={}) ->
httpOptions = _.defaults options,
method: "GET"
url: "#{config.baseUrl}#{config.url}"
$http(httpOptions)
.then (response) ->
unless _.isArray(response.data)
console.warn "#{name} Model", "API Respsonse was", response.data
throw new Error "#{name} Model: Expected array, got #{typeof response.data}"
response.data = config.transformResponse(response.data, 'array')
# replace array items with new data
response.data = Data.replace(response.data)
return $q.when(response)
###
# @method Retrieve Singleton
#
# @param {Object} [options] HTTP options
# @return {Promise} HTTP data
###
exports.fetch = (options={}) ->
httpOptions = _.defaults options,
method: "GET"
url: "#{config.baseUrl}#{config.url}"
$http(httpOptions)
.then (response) ->
unless _.isObject(response.data)
console.warn "#{name} Model", "API Respsonse was", response.data
throw new Error "#{name} Model: Expected object, got #{typeof response.data}"
response.data = config.transformResponse(response.data, 'one')
response.data = Data.replace(response.data)
return $q.when(response)
###
# @method Retrieve One
#
# @description This also updates the internal data collection, of course.
#
# @param {String} id The ID of the element to fetch.
# @param {Object} [options] HTTP options
# @return {Promise} HTTP data
#
# @todo Customize ID query
###
exports.fetchOne = (query, options={}) ->
try
_url = config.getDetailUrl(query, config.listUrl, config.baseUrl)
catch e
return $q.reject e.message || e
httpOptions = _.defaults options,
method: "GET"
url: _url
$http(httpOptions)
.then (res) ->
unless _.isObject(res.data)
console.warn "#{name} Model", "API Respsonse was", res.data
throw new Error "Expected object, got #{typeof res.data}"
res.data = config.transformResponse(res.data, 'one')
res.data = Data.updateEntry res.data, config.matchingCriteria(res.data)
return $q.when(res)
###
# @method Destroy some Entry
#
# @param {String} id The ID of the element to fetch.
# @param {Object} [options] HTTP options
# @return {Promise} Whether destruction was successful
# @throws {Error} When Collection is singleton or no ID is given
#
# @todo Customize ID query
###
exports.destroy = (query, options={}) ->
if IS_SINGLETON
throw new Error "#{name} Model: Singleton doesn't have `destroy` method."
try
_url = config.getDetailUrl(query, config.listUrl, config.baseUrl)
catch e
return $q.reject e.message || e
httpOptions = _.defaults options,
method: "DELETE"
url: _url
$http(httpOptions)
.then ({status, data}) ->
data = config.transformResponse(data, 'destroy')
return $q.when Data.removeEntry config.matchingCriteria(data)
###
# @method Save an Entry
#
# @param {Object} entry The entry to be saved.
# @param {Object} [options] HTTP options
# @return {Promise} Resolved with new entry or rejected with HTTP error
#
# @todo Customize ID query
###
exports.save = (entry, options={}) ->
if IS_SINGLETON
_url = "#{config.baseUrl}#{config.listUrl}"
else
try
_url = config.getDetailUrl(entry, config.listUrl, config.baseUrl)
catch e
return $q.reject e.message || e
httpOptions = _.defaults options,
method: "PUT"
url: _url
data: angular.toJson(entry)
return $http(httpOptions)
.then ({status, data}) ->
data = config.transformResponse(data, 'save')
if IS_SINGLETON
return $q.when Data.replace(data)
else
return $q.when Data.updateEntry data, config.matchingCriteria(data)
###
# @method Create an Entry
#
# @description Similar to save, but has no ID initially.
#
# @param {Object} entry Entry data
# @param {Object} [options] HTTP options
# @return {Promise} Resolves with new entry data or rejects with HTTP error
# @throws {Error} When Collection is singleton
###
exports.create = (entry, options={}) ->
if IS_SINGLETON
throw new Error "#{name} Model: Singleton doesn't have `destroy` method."
httpOptions = _.defaults options,
method: "POST"
url: "#{config.baseUrl}#{config.listUrl}"
data: angular.toJson(entry)
return $http(httpOptions)
.then ({status, data}) ->
return $q.when Data.updateEntry data, config.matchingCriteria(data)
# - - -
# ### Generic Getters
###
# @method Get Collection
#
# @param {Object} [options] HTTP options
# @return {Object} Immediate Return Data (see above)
###
exports.all = (options) ->
local =
$loading: true
if IS_SINGLETON
local.$promise = exports.fetch(options)
local.data = _data.data
else
local.$promise = exports.fetchAll(options)
local.all = _data.all
local.$promise = local.$promise
.then (response) ->
local.$loading = false
local.$resolved = true
$q.when(response)
.then null, (err) ->
local.$error = err
local.$loading = false
$q.reject(err)
return local
###
# @method Query Collection
#
# @param {Object} query Query the collection á la `{name: "<NAME>"}`
# @return {Array} Objects matching the query.
###
exports.where = (query) ->
_.where(_data.all, query)
###
# @method Get Single Collection Entry
#
# @param {Object} query The query that will be used in `matchingCriteria`
# @param {Object} [options] HTTP options
# @return {Object} Immediate Return Data (see above)
# @throws {Error} When Collection is singleton
#
# @todo Customize ID query
###
exports.get = (query, options) ->
if IS_SINGLETON
throw new Error "#{name} Model: Singleton doesn't have `get` method."
local =
$loading: true
local.data = _.findWhere _data.all, config.matchingCriteria(query)
local.$promise = exports.fetchOne(query, options)
.then (response) ->
local.data = response.data
local.$loading = false
local.$resolved = true
$q.when(response)
.then null, (err) ->
local.$error = err
local.$loading = false
$q.reject(err)
return local
# ### Mixin Extras
addExtraCall = (key, val) ->
unless val.url
val.url = "#{config.baseUrl}#{config.listUrl}/#{key}"
if _.isFunction val.onSuccess
success = _.bind(val.onSuccess, config)
delete val.onSuccess
if _.isFunction val.onFail
fail = _.bind(val.onFail, config)
delete val.onFail
# @todo Add data storage options
exports[key] = (data, options={}) ->
if !options.url
if _.isFunction(val.url)
options.url = val.url(data, config.listUrl, config.detailUrl)
else
options.url = config.parseUrlPattern(data, "#{config.baseUrl}#{val.url}")
call = $http _.defaults(options, val), data
call.then(success) if success?
call.then(null, fail) if fail?
return call
_.each extras, (val, key) ->
# Custom methods
if _.isFunction(val)
exports[key] = _.bind(val, config)
# Custom HTTP Call
else if _.isObject(val)
addExtraCall key, val
# - - -
exports
return new: constructor
return
.factory "CollectionLocalStorage", ->
# ## Storage Wrapper for LocalStorage
return unless window.localStorage?
return {
# ### Get Item
###
# @param {String} key
# @return {Any}
###
getItem: (key) ->
value = window.localStorage.getItem(key)
value && JSON.parse(value)
# ### Set Item
###
# @param {String} key
# @param {Any} value
# @return {Any}
###
setItem: (key, value) ->
window.localStorage.setItem(key, angular.toJson(value))
# ### Remove Item
###
# @param {String} key
###
removeItem: (key) ->
window.localStorage.removeItem(key)
}
| true | ###
# # Epic Model
###
angular.module('EpicModel', [
])
.provider "Collection", ->
###
# Create your own collection by injecting the `Collection` service and calling
# its 'new' method.
#
# @example
# ```coffeescript
# angular.module('Module', ['EpicModel'])
# .factory "API", (Collection) ->
# API =
# People: Collection.new 'People', {url: '/people/:id'},
# calculateStuff: (input) -> 42
# .controller "Ctrl", ($scope, ShittyAPI) ->
# $scope.list = API.People.all()
# ```
#
# **Immediate Return Data**
#
# Most methods return a promise, but the methods `all` and `get` methods
# return a special object instead, that contains the currently available data,
# a promise and flags to represent the data retrieval state. I.e., you can
# immediately use the return value in your views and the data will
# automatically appear once it has been retrieved (or updated).
#
# @example
# ```coffeescript
# Me = Collection.new "Me", is_singleton: true
# Me.all()
# #=> {data: {}, $resolved: false, $loading: true, $promise: {then, ...}}
# ```
###
# ## Global Config
###
#
# Just inject the `CollectionProvider` and set some globals.
#
# @example
# ```coffeescript
# angular.module('app', ['EpicModel'])
# .config (CollectionProvider) ->
# CollectionProvider.setBaseUrl('http://example.com/api/v1')
# ```
###
globalConfig =
baseUrl: ''
###
# @method Set Base URL
#
# @param {String} url The new base URL
# @return {String} The new base URL
# @throws {Error} When no URL is given
###
@setBaseUrl = (url='') ->
throw new Error "No URL given." unless url?
globalConfig.baseUrl = url
# - - -
#
# The service factory function
@$get = ($q, $http) ->
###
# ## Constructor
#
# Create a new Collection.
#
# @param {String} name The unique name of the new collection.
# @param {Object} [config] Configuration and settings
# @param {String|Function} [config.url] Resource URL
# @param {String|Function} [config.detailUrl] URL for single resource,
# default: `config.url + '/' + entry.id`. Will interpolate segments in
# curly brackets, e.g. transforming `/item/{_id}` to `'/item/'+entry._id`.
# If you supply a function, it will be called with the current entry,
# the base URL and the resource list url (`config.url`) and should return
# a string that will be used as URL.
# @param {String} [config.baseUrl] Overwrite base URL
# @param {Bool} [config.is_singleton] Whether resource returns an object
# @param {Object} [config.storage] Storage implementation, e.g.
# `CollectionLocalStorage` (see below)
# @param {Function} [config.storage.setItem]
# @param {Function} [config.storage.getItem]
# @param {Function} [config.storage.removeItem]
# @param {Function} [config.transformRequest=`_.identity`] Takes the
# _request_ `data` and a hint like 'array', 'one', 'save', 'destroy'
# and returns the transformed `data`. *NYI*
# @param {Function} [config.transformResponse=`_.identity`] Takes the
# _response_ `data` and a hint like 'array', 'one', 'save', 'destroy'
# and returns the transformed `data`.
# @param {Function} [config.matchingCriteria] Takes data object and returns
# matching criteria. Default: `(data) -> id: +data.id`
# @param {Object} [extras] Add custom methods to instance, functions will
# be have `config` as `this`, objects will used to construct new `$http`
# calls
# @return {Object} The collection
# @throws {Error} When no name is given
#
# @example
# ```coffeescript
# Collection.new 'User', {
# url: '/user' # also set implicitly from name
# is_singleton: true # Expect single object instead of array
# storage: myStorage # see below
# }, {
# something: (id) -> 42
# pay:
# method: 'PATCH'
# params:
# payout: true
# }
# ```
###
constructor = (name, config={}, extras={}) ->
# This will be returned.
exports = {}
# ### Options
throw new Error "No name given!" unless name?
###
# @method Config Getter
#
# @description Retrieve config value from instance
# @param {String} key
# @return {Any} Config value
###
exports.config = (key) ->
config[key]
config.url ||= '/' + name.toLowerCase()
config.baseUrl ||= globalConfig.baseUrl
config.listUrl ||= config.url
###
# @method Make Detail URL from Pattern
#
# @param {Object} entry The entry to URL points to
# @param {String} [listUrl=config.url]
# @param {String} [baseUrl=config.baseUrl]
# @return {String} Entry URL
###
config.parseUrlPattern = (entry, url) ->
substitutes = /\{([\w_.]*?)\}/g
entryUrl = url
_.each url.match(substitutes), (match) ->
# Remove braces and split on dots (might address sub-object, e.g.
# using `item.id`)
keys = match.replace('{', '').replace('}', '').split('.')
value = entry
_.each keys, (key) ->
value = value[key]
if value?
entryUrl = entryUrl.replace match, value
else
throw new Error "#{name} Model: Can't substitute #{match} in URL"+
"(entry has no value for #{key})"
return entryUrl
if _.isString config.detailUrl
makeDetailUrl = (entry) ->
config.parseUrlPattern(entry, "#{config.baseUrl}#{config.detailUrl}")
else
makeDetailUrl = (entry, listUrl=config.listUrl, baseUrl=config.baseUrl) ->
if entry.id?
"#{baseUrl}#{listUrl}/#{entry.id}"
else
throw new Error "#{name} Model: Need entry ID to construct URL"
if _.isFunction config.detailUrl
config.getDetailUrl = (entry, listUrl=config.listUrl, baseUrl=config.baseUrl) ->
config.detailUrl(entry, listUrl, baseUrl)
else
config.getDetailUrl = makeDetailUrl
IS_SINGLETON = !!config.is_singleton
config.transformRequest ||= _.identity
config.transformResponse ||= _.identity
config.matchingCriteria ||= (data) -> id: +data.id
# #### Storage Implementation
###
# Use key/value store to persist data.
#
# Key schema: "{collection name}.{all|data}"
#
# Use any implementation that has these methods:
#
# - `setItem(String key, value)`
# - `getItem(String key)`
# - `removeItem(String key)`
#
# ```coffeescript
# myStorage =
# getItem: (key) ->
# value = window.localStorage.getItem(key)
# value && JSON.parse(value)
# setItem: (key, value) ->
# window.localStorage.setItem(key, angular.toJson(value))
# removeItem: (key) ->
# window.localStorage.removeItem(key)
#
# Collection.new 'People', {storage: myStorage} # uses localStorage now
# ```
###
store = do ->
_store = {}
impl = config.storage or {}
_.each ['setItem', 'getItem', 'removeItem'], (method) ->
_store[method] = if _.isFunction impl[method]
impl[method]
else angular.noop
_store
# ### In Memory Data
###
# The Single Source of Truth
#
# @private
###
Data = {}
if IS_SINGLETON # Is single Model
_data =
data: store.getItem("#{name}.data") || {}
###
# @method Get Data
# @return {Object} data
###
Data.get = -> _data.data
###
# @method Replace Singleton Data
#
# @param {Object} data New data
# @return {Object} The complete data representation
###
Data.replace = (data) ->
_data.data = _.extend(_data.data, data)
store.setItem("#{name}.data", _data.data)
return _data.data
else # is Model[]
_data =
all: store.getItem("#{name}.all") || []
###
# @method Get Data
# @return {Array} data
###
Data.get = -> _data.all
###
# @method Replace Complete Collection Data
#
# @param {Array} data New data
# @return {Object} The complete data representation
###
Data.replace = (data) ->
_data.all.splice(0, data.length)
[].push.apply(_data.all, data)
store.setItem("#{name}.all", _data.all)
return _data.all
###
# @method Update Single Entry from Collection
#
# @description This will also add an entry if no existing one matches
# the criteria
#
# @param {Object} data New data
# @param {Object} criteria Used to find entry
# @return {Object} The updated entry
###
Data.updateEntry = (data, criteria) ->
hit = _.findWhere(_data.all, criteria)
if hit?
# update existing entry
hit = _.extend(hit, data)
else
# add new entry (on top of list)
_data.all.unshift(data)
store.setItem("#{name}.all", _data.all)
return if hit? then hit else data
###
# @method Remove Single Entry from Collection
#
# @param {Object} criteria Used to find entry
# @return {Bool} Whether removal was
###
Data.removeEntry = (criteria) ->
hit = _.findWhere(_data.all, criteria)
if hit?
_data.all.splice _data.all.indexOf(hit), 1
store.removeItem("#{name}.all", _data.all)
return hit?
config.Data = exports.Data = Data
# ### HTTP Requests and Stuff
###
# @method Retrieve List
#
# @description Gotta catch 'em all!
#
# @param {Object} [options] HTTP options
# @return {Promise} HTTP data
###
exports.fetchAll = (options={}) ->
httpOptions = _.defaults options,
method: "GET"
url: "#{config.baseUrl}#{config.url}"
$http(httpOptions)
.then (response) ->
unless _.isArray(response.data)
console.warn "#{name} Model", "API Respsonse was", response.data
throw new Error "#{name} Model: Expected array, got #{typeof response.data}"
response.data = config.transformResponse(response.data, 'array')
# replace array items with new data
response.data = Data.replace(response.data)
return $q.when(response)
###
# @method Retrieve Singleton
#
# @param {Object} [options] HTTP options
# @return {Promise} HTTP data
###
exports.fetch = (options={}) ->
httpOptions = _.defaults options,
method: "GET"
url: "#{config.baseUrl}#{config.url}"
$http(httpOptions)
.then (response) ->
unless _.isObject(response.data)
console.warn "#{name} Model", "API Respsonse was", response.data
throw new Error "#{name} Model: Expected object, got #{typeof response.data}"
response.data = config.transformResponse(response.data, 'one')
response.data = Data.replace(response.data)
return $q.when(response)
###
# @method Retrieve One
#
# @description This also updates the internal data collection, of course.
#
# @param {String} id The ID of the element to fetch.
# @param {Object} [options] HTTP options
# @return {Promise} HTTP data
#
# @todo Customize ID query
###
exports.fetchOne = (query, options={}) ->
try
_url = config.getDetailUrl(query, config.listUrl, config.baseUrl)
catch e
return $q.reject e.message || e
httpOptions = _.defaults options,
method: "GET"
url: _url
$http(httpOptions)
.then (res) ->
unless _.isObject(res.data)
console.warn "#{name} Model", "API Respsonse was", res.data
throw new Error "Expected object, got #{typeof res.data}"
res.data = config.transformResponse(res.data, 'one')
res.data = Data.updateEntry res.data, config.matchingCriteria(res.data)
return $q.when(res)
###
# @method Destroy some Entry
#
# @param {String} id The ID of the element to fetch.
# @param {Object} [options] HTTP options
# @return {Promise} Whether destruction was successful
# @throws {Error} When Collection is singleton or no ID is given
#
# @todo Customize ID query
###
exports.destroy = (query, options={}) ->
if IS_SINGLETON
throw new Error "#{name} Model: Singleton doesn't have `destroy` method."
try
_url = config.getDetailUrl(query, config.listUrl, config.baseUrl)
catch e
return $q.reject e.message || e
httpOptions = _.defaults options,
method: "DELETE"
url: _url
$http(httpOptions)
.then ({status, data}) ->
data = config.transformResponse(data, 'destroy')
return $q.when Data.removeEntry config.matchingCriteria(data)
###
# @method Save an Entry
#
# @param {Object} entry The entry to be saved.
# @param {Object} [options] HTTP options
# @return {Promise} Resolved with new entry or rejected with HTTP error
#
# @todo Customize ID query
###
exports.save = (entry, options={}) ->
if IS_SINGLETON
_url = "#{config.baseUrl}#{config.listUrl}"
else
try
_url = config.getDetailUrl(entry, config.listUrl, config.baseUrl)
catch e
return $q.reject e.message || e
httpOptions = _.defaults options,
method: "PUT"
url: _url
data: angular.toJson(entry)
return $http(httpOptions)
.then ({status, data}) ->
data = config.transformResponse(data, 'save')
if IS_SINGLETON
return $q.when Data.replace(data)
else
return $q.when Data.updateEntry data, config.matchingCriteria(data)
###
# @method Create an Entry
#
# @description Similar to save, but has no ID initially.
#
# @param {Object} entry Entry data
# @param {Object} [options] HTTP options
# @return {Promise} Resolves with new entry data or rejects with HTTP error
# @throws {Error} When Collection is singleton
###
exports.create = (entry, options={}) ->
if IS_SINGLETON
throw new Error "#{name} Model: Singleton doesn't have `destroy` method."
httpOptions = _.defaults options,
method: "POST"
url: "#{config.baseUrl}#{config.listUrl}"
data: angular.toJson(entry)
return $http(httpOptions)
.then ({status, data}) ->
return $q.when Data.updateEntry data, config.matchingCriteria(data)
# - - -
# ### Generic Getters
###
# @method Get Collection
#
# @param {Object} [options] HTTP options
# @return {Object} Immediate Return Data (see above)
###
exports.all = (options) ->
local =
$loading: true
if IS_SINGLETON
local.$promise = exports.fetch(options)
local.data = _data.data
else
local.$promise = exports.fetchAll(options)
local.all = _data.all
local.$promise = local.$promise
.then (response) ->
local.$loading = false
local.$resolved = true
$q.when(response)
.then null, (err) ->
local.$error = err
local.$loading = false
$q.reject(err)
return local
###
# @method Query Collection
#
# @param {Object} query Query the collection á la `{name: "PI:NAME:<NAME>END_PI"}`
# @return {Array} Objects matching the query.
###
exports.where = (query) ->
_.where(_data.all, query)
###
# @method Get Single Collection Entry
#
# @param {Object} query The query that will be used in `matchingCriteria`
# @param {Object} [options] HTTP options
# @return {Object} Immediate Return Data (see above)
# @throws {Error} When Collection is singleton
#
# @todo Customize ID query
###
exports.get = (query, options) ->
if IS_SINGLETON
throw new Error "#{name} Model: Singleton doesn't have `get` method."
local =
$loading: true
local.data = _.findWhere _data.all, config.matchingCriteria(query)
local.$promise = exports.fetchOne(query, options)
.then (response) ->
local.data = response.data
local.$loading = false
local.$resolved = true
$q.when(response)
.then null, (err) ->
local.$error = err
local.$loading = false
$q.reject(err)
return local
# ### Mixin Extras
addExtraCall = (key, val) ->
unless val.url
val.url = "#{config.baseUrl}#{config.listUrl}/#{key}"
if _.isFunction val.onSuccess
success = _.bind(val.onSuccess, config)
delete val.onSuccess
if _.isFunction val.onFail
fail = _.bind(val.onFail, config)
delete val.onFail
# @todo Add data storage options
exports[key] = (data, options={}) ->
if !options.url
if _.isFunction(val.url)
options.url = val.url(data, config.listUrl, config.detailUrl)
else
options.url = config.parseUrlPattern(data, "#{config.baseUrl}#{val.url}")
call = $http _.defaults(options, val), data
call.then(success) if success?
call.then(null, fail) if fail?
return call
_.each extras, (val, key) ->
# Custom methods
if _.isFunction(val)
exports[key] = _.bind(val, config)
# Custom HTTP Call
else if _.isObject(val)
addExtraCall key, val
# - - -
exports
return new: constructor
return
.factory "CollectionLocalStorage", ->
# ## Storage Wrapper for LocalStorage
return unless window.localStorage?
return {
# ### Get Item
###
# @param {String} key
# @return {Any}
###
getItem: (key) ->
value = window.localStorage.getItem(key)
value && JSON.parse(value)
# ### Set Item
###
# @param {String} key
# @param {Any} value
# @return {Any}
###
setItem: (key, value) ->
window.localStorage.setItem(key, angular.toJson(value))
# ### Remove Item
###
# @param {String} key
###
removeItem: (key) ->
window.localStorage.removeItem(key)
}
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991456866264343,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "tls\")\ncacert = \"-----BEGIN CERTIFICATE-----\\n\" + \"MIIBxTCCAX8CAnXnMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYT",
"end": 1352,
"score": 0.7208572030067444,
"start": 1350,
"tag": "KEY",
"value": "MI"
},
{
"context": "-----BEGIN CERTIFICATE-----\\n\" + \"MIIBxTCCAX8CAnXnMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\\n\" ",
"end": 1368,
"score": 0.5149949789047241,
"start": 1366,
"tag": "KEY",
"value": "MA"
},
{
"context": "qGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\\n\" + \"VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEC",
"end": 1424,
"score": 0.5382813215255737,
"start": 1422,
"tag": "KEY",
"value": "QQ"
},
{
"context": "b3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\\n\" + \"VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\\n\"",
"end": 1438,
"score": 0.5623303055763245,
"start": 1426,
"tag": "KEY",
"value": "wJDQTEWMBQGA"
},
{
"context": "JBgNVBAYTAlVTMQswCQYD\\n\" + \"VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\\n\" + \"TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRow",
"end": 1486,
"score": 0.5722665190696716,
"start": 1443,
"tag": "KEY",
"value": "MNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\\"
},
{
"context": "xMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\\n\" + \"TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQD",
"end": 1494,
"score": 0.4976707696914673,
"start": 1492,
"tag": "KEY",
"value": "TG"
},
{
"context": "5n\\n\" + \"TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\\n\" + \"bmdsb29wLmNvbTAeFw0xNDA",
"end": 1536,
"score": 0.5147749185562134,
"start": 1533,
"tag": "KEY",
"value": "Row"
},
{
"context": "0xCzAJ\\n\" + \"BgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZ\\n\" + \"MBcGA1UEChMQU3Ryb25nTG9vcCwgSW5jLjESMBAGA1UEC",
"end": 1700,
"score": 0.9341516494750977,
"start": 1671,
"tag": "KEY",
"value": "1UEBxMNU2FuIEZyYW5jaXNjbzEZ\\n"
},
{
"context": "QQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZ\\n\" + \"MBcGA1UEChMQU3Ryb25nTG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRow\\n\" + \"GAYDVQQDExFjYS5zdHJvbmdsb29wLmNvbTBMMA0GCSqGS",
"end": 1771,
"score": 0.9143831133842468,
"start": 1705,
"tag": "KEY",
"value": "MBcGA1UEChMQU3Ryb25nTG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRow\\n"
},
{
"context": "G9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRow\\n\" + \"GAYDVQQDExFjYS5zdHJvbmdsb29wLmNvbTBMMA0GCSqGSIb3DQEBAQUAAzsAMDgC\\n\" + \"MQDKbQ6rIR5t1q1v4Ha36jrq0IkyUohy9EYNvLnXUly1P",
"end": 1842,
"score": 0.9262608885765076,
"start": 1776,
"tag": "KEY",
"value": "GAYDVQQDExFjYS5zdHJvbmdsb29wLmNvbTBMMA0GCSqGSIb3DQEBAQUAAzsAMDgC\\n"
},
{
"context": "mdsb29wLmNvbTBMMA0GCSqGSIb3DQEBAQUAAzsAMDgC\\n\" + \"MQDKbQ6rIR5t1q1v4Ha36jrq0IkyUohy9EYNvLnXUly1PGqxby0ILlAVJ8JawpY9\\n\" + \"AVkCAwEAATANBgkqhkiG9w0BAQUFAAMxALA1uS4CqQXRS",
"end": 1913,
"score": 0.8792028427124023,
"start": 1847,
"tag": "KEY",
"value": "MQDKbQ6rIR5t1q1v4Ha36jrq0IkyUohy9EYNvLnXUly1PGqxby0ILlAVJ8JawpY9\\n"
},
{
"context": "q0IkyUohy9EYNvLnXUly1PGqxby0ILlAVJ8JawpY9\\n\" + \"AVkCAwEAATANBgkqhkiG9w0BAQUFAAMxALA1uS4CqQXRSAyYTfio5oyLGz71a+NM\\n\" + \"+0AFLBwh5AQjhGd0FcenU4OfHxyDEOJT/Q==\\n\" + \"--",
"end": 1984,
"score": 0.7470112442970276,
"start": 1920,
"tag": "KEY",
"value": "kCAwEAATANBgkqhkiG9w0BAQUFAAMxALA1uS4CqQXRSAyYTfio5oyLGz71a+NM\\n"
},
{
"context": "BAQUFAAMxALA1uS4CqQXRSAyYTfio5oyLGz71a+NM\\n\" + \"+0AFLBwh5AQjhGd0FcenU4OfHxyDEOJT/Q==\\n\" + \"-----END C",
"end": 1992,
"score": 0.507224977016449,
"start": 1991,
"tag": "KEY",
"value": "A"
},
{
"context": "MxALA1uS4CqQXRSAyYTfio5oyLGz71a+NM\\n\" + \"+0AFLBwh5AQjhGd0FcenU4OfHxyDEOJT/Q==\\n\" + \"-----END CERTIFICA",
"end": 2000,
"score": 0.5150339007377625,
"start": 1998,
"tag": "KEY",
"value": "AQ"
},
{
"context": "oyLGz71a+NM\\n\" + \"+0AFLBwh5AQjhGd0FcenU4OfHxyDEOJT/Q==\\n\" + \"-----END CERTIFICATE-----\\n\"\ncert = \"---",
"end": 2021,
"score": 0.5305050015449524,
"start": 2021,
"tag": "KEY",
"value": ""
},
{
"context": "LGz71a+NM\\n\" + \"+0AFLBwh5AQjhGd0FcenU4OfHxyDEOJT/Q==\\n\" + \"-----END CERTIFICATE-----\\n\"\ncert = \"-----B",
"end": 2023,
"score": 0.710996687412262,
"start": 2023,
"tag": "KEY",
"value": ""
},
{
"context": "SqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\\n\" + \"VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\\n\" + \"TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowG",
"end": 2240,
"score": 0.9150054454803467,
"start": 2174,
"tag": "KEY",
"value": "VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\\n"
},
{
"context": "xMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\\n\" + \"TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\\n\" + \"bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2M",
"end": 2311,
"score": 0.9628618955612183,
"start": 2245,
"tag": "KEY",
"value": "TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\\n"
},
{
"context": "1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\\n\" + \"bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMBkxFzAV\\n\" + \"BgNVBAMTDnN0cm9uZ2xvb3AuY29tM",
"end": 2366,
"score": 0.7821986675262451,
"start": 2316,
"tag": "KEY",
"value": "bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMj"
},
{
"context": "mdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMBkxFzAV\\n\" + \"BgNVBAMTDnN0cm9uZ2xvb3AuY29tMEwwDQYJKoZIhvcNA",
"end": 2382,
"score": 0.7550057172775269,
"start": 2367,
"tag": "KEY",
"value": "1MDdaMBkxFzAV\\n"
},
{
"context": "DAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMBkxFzAV\\n\" + \"BgNVBAMTDnN0cm9uZ2xvb3AuY29tMEwwDQYJKoZIhvcNAQEBBQADOwAwOAIxAMfk\\n\" + \"I0LWU15pPUwIQNMnRVhhOibi0TQmAau8FBtgwEfGK01Wp",
"end": 2453,
"score": 0.8686590194702148,
"start": 2387,
"tag": "KEY",
"value": "BgNVBAMTDnN0cm9uZ2xvb3AuY29tMEwwDQYJKoZIhvcNAQEBBQADOwAwOAIxAMfk\\n"
},
{
"context": "3AuY29tMEwwDQYJKoZIhvcNAQEBBQADOwAwOAIxAMfk\\n\" + \"I0LWU15pPUwIQNMnRVhhOibi0TQmAau8FBtgwEfGK01WpfGUaJr1",
"end": 2460,
"score": 0.7038782835006714,
"start": 2458,
"tag": "KEY",
"value": "I0"
},
{
"context": "wDQYJKoZIhvcNAQEBBQADOwAwOAIxAMfk\\n\" + \"I0LWU15pPUwIQNMnRVhhOibi0TQmAau8FBtgwEfGK01WpfGUaJr1a41K8Uq7x",
"end": 2469,
"score": 0.621764063835144,
"start": 2468,
"tag": "KEY",
"value": "w"
},
{
"context": "ADOwAwOAIxAMfk\\n\" + \"I0LWU15pPUwIQNMnRVhhOibi0TQmAau8FBtgwEfGK01WpfGUaJr1a41K8Uq7xwID\\n\" + \"AQABoxkwFzAVBgNVHREEDjAMhwQAAAAAhwR/AAABMA0GC",
"end": 2524,
"score": 0.8320174217224121,
"start": 2487,
"tag": "KEY",
"value": "au8FBtgwEfGK01WpfGUaJr1a41K8Uq7xwID\\n"
},
{
"context": "i0TQmAau8FBtgwEfGK01WpfGUaJr1a41K8Uq7xwID\\n\" + \"AQABoxkwFzAVBgNVHREEDjAMhwQAAAAAhwR/AAABMA0GCSqGSIb3DQEBBQUAAzEA\\n\" + \"cGpYrhkrb7mIh9DNhV0qp7pGjqBzlHqB7KQXw2luLDp//",
"end": 2595,
"score": 0.7588978409767151,
"start": 2531,
"tag": "KEY",
"value": "ABoxkwFzAVBgNVHREEDjAMhwQAAAAAhwR/AAABMA0GCSqGSIb3DQEBBQUAAzEA\\n"
},
{
"context": "AMhwQAAAAAhwR/AAABMA0GCSqGSIb3DQEBBQUAAzEA\\n\" + \"cGpYrhkrb7mIh9DNhV0qp7pGjqBzlHqB7KQXw2luLDp//6dyHBMexDCQznkhZKRU\\n\" + \"--",
"end": 2623,
"score": 0.7129427194595337,
"start": 2601,
"tag": "KEY",
"value": "GpYrhkrb7mIh9DNhV0qp7p"
},
{
"context": "SqGSIb3DQEBBQUAAzEA\\n\" + \"cGpYrhkrb7mIh9DNhV0qp7pGjqBzlHqB7KQXw2luLDp//6dyHBMexDCQznkhZKRU\\n\" + \"-----END CERTIFICATE-----\\n\"\nkey = \"-----BEGI",
"end": 2666,
"score": 0.7812738418579102,
"start": 2624,
"tag": "KEY",
"value": "jqBzlHqB7KQXw2luLDp//6dyHBMexDCQznkhZKRU\\n"
},
{
"context": "nkhZKRU\\n\" + \"-----END CERTIFICATE-----\\n\"\nkey = \"-----BEGIN RSA PRIVATE KEY-----\\n\" + \"MIH0AgEAAjEAx+QjQtZTXmk9TAhA0ydFWGE6JuLRNCYBq7wU",
"end": 2743,
"score": 0.9958192110061646,
"start": 2712,
"tag": "KEY",
"value": "BEGIN RSA PRIVATE KEY-----\\n\" +"
},
{
"context": "---\\n\"\nkey = \"-----BEGIN RSA PRIVATE KEY-----\\n\" + \"MIH0AgEAAjEAx+QjQtZTXmk9TAhA0ydFWGE6JuLRNCYBq7wUG2",
"end": 2745,
"score": 0.5090879201889038,
"start": 2744,
"tag": "KEY",
"value": "\""
},
{
"context": "-\\n\"\nkey = \"-----BEGIN RSA PRIVATE KEY-----\\n\" + \"MIH0AgEAAjEAx+QjQtZTXmk9TAhA0ydFWGE6JuLRNCYBq7wUG2DAR8YrTVal8ZRo\\n\" + \"mvVrjUrxSrvHAgMBAAECMBCGccvSwC2r8Z9Zh1JtirQVxaL1WW",
"end": 2816,
"score": 0.9959115386009216,
"start": 2745,
"tag": "KEY",
"value": "MIH0AgEAAjEAx+QjQtZTXmk9TAhA0ydFWGE6JuLRNCYBq7wUG2DAR8YrTVal8ZRo\\n\" + \""
},
{
"context": "mk9TAhA0ydFWGE6JuLRNCYBq7wUG2DAR8YrTVal8ZRo\\n\" + \"mvVrjUrxSrvHAgMBAAECMBCGccvSwC2r8Z9Zh1JtirQVxaL1WWpAQfmVwLe0bAgg\\n\" + \"/JWMU/6hS36TsYyZMxwswQIZAPTAfht/zDLb7Hwgu2twsS",
"end": 2883,
"score": 0.9868234992027283,
"start": 2816,
"tag": "KEY",
"value": "mvVrjUrxSrvHAgMBAAECMBCGccvSwC2r8Z9Zh1JtirQVxaL1WWpAQfmVwLe0bAgg\\n\""
},
{
"context": "CMBCGccvSwC2r8Z9Zh1JtirQVxaL1WWpAQfmVwLe0bAgg\\n\" + \"/JWMU/6hS36TsYyZMxwswQIZAPTAfht/zDLb7Hwgu2twsS1Ra9w/yyvtlwIZANET\\n\" + \"26votwJAHK1yUrZGA5nnp5qcmQ/JUQIZAII5YV/UUZvF9",
"end": 2953,
"score": 0.9911867380142212,
"start": 2886,
"tag": "KEY",
"value": "\"/JWMU/6hS36TsYyZMxwswQIZAPTAfht/zDLb7Hwgu2twsS1Ra9w/yyvtlwIZANET\\n"
},
{
"context": "QIZAPTAfht/zDLb7Hwgu2twsS1Ra9w/yyvtlwIZANET\\n\" + \"26votwJAHK1yUrZGA5nnp5qcmQ/JUQIZAII5YV/UUZvF9D/fUplJ7puENPWNY9bN\\n\" + \"pQIZAMMwxuS3XiO7two2sQF6W+JTYyX1DPCwAQIZAOYg1",
"end": 3024,
"score": 0.9985912442207336,
"start": 2958,
"tag": "KEY",
"value": "26votwJAHK1yUrZGA5nnp5qcmQ/JUQIZAII5YV/UUZvF9D/fUplJ7puENPWNY9bN\\n"
},
{
"context": "5qcmQ/JUQIZAII5YV/UUZvF9D/fUplJ7puENPWNY9bN\\n\" + \"pQIZAMMwxuS3XiO7two2sQF6W+JTYyX1DPCwAQIZAOYg1TvEGT38k8e8jygv8E8w\\n\" + \"YqrWTeQFNQ==\\n\" + \"-----END RSA PRIVATE KEY--",
"end": 3095,
"score": 0.9842130541801453,
"start": 3029,
"tag": "KEY",
"value": "pQIZAMMwxuS3XiO7two2sQF6W+JTYyX1DPCwAQIZAOYg1TvEGT38k8e8jygv8E8w\\n"
},
{
"context": "F6W+JTYyX1DPCwAQIZAOYg1TvEGT38k8e8jygv8E8w\\n\" + \"YqrWTeQFNQ==\\n\" + \"-----END RSA PRIVATE KEY-----\\n\"\nc",
"end": 3103,
"score": 0.5150437355041504,
"start": 3101,
"tag": "KEY",
"value": "qr"
},
{
"context": "1DPCwAQIZAOYg1TvEGT38k8e8jygv8E8w\\n\" + \"YqrWTeQFNQ==\\n\" + \"-----END RSA PRIVATE KEY-----\\n\"\nca = [\n c",
"end": 3110,
"score": 0.7759860754013062,
"start": 3110,
"tag": "KEY",
"value": ""
},
{
"context": "AOYg1TvEGT38k8e8jygv8E8w\\n\" + \"YqrWTeQFNQ==\\n\" + \"-----END RSA PRIVATE KEY-----\\n\"\nca = [\n cert\n cacert\n]\nclientError = null\nconn",
"end": 3150,
"score": 0.81620192527771,
"start": 3124,
"tag": "KEY",
"value": "END RSA PRIVATE KEY-----\\n"
}
] | test/simple/test-tls-econnreset.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.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
common = require("../common")
assert = require("assert")
tls = require("tls")
cacert = "-----BEGIN CERTIFICATE-----\n" + "MIIBxTCCAX8CAnXnMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n" + "VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\n" + "TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\n" + "bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMH0xCzAJ\n" + "BgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZ\n" + "MBcGA1UEChMQU3Ryb25nTG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRow\n" + "GAYDVQQDExFjYS5zdHJvbmdsb29wLmNvbTBMMA0GCSqGSIb3DQEBAQUAAzsAMDgC\n" + "MQDKbQ6rIR5t1q1v4Ha36jrq0IkyUohy9EYNvLnXUly1PGqxby0ILlAVJ8JawpY9\n" + "AVkCAwEAATANBgkqhkiG9w0BAQUFAAMxALA1uS4CqQXRSAyYTfio5oyLGz71a+NM\n" + "+0AFLBwh5AQjhGd0FcenU4OfHxyDEOJT/Q==\n" + "-----END CERTIFICATE-----\n"
cert = "-----BEGIN CERTIFICATE-----\n" + "MIIBfDCCATYCAgQaMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n" + "VQQIEwJDQTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEZMBcGA1UEChMQU3Ryb25n\n" + "TG9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMRowGAYDVQQDExFjYS5zdHJv\n" + "bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMBkxFzAV\n" + "BgNVBAMTDnN0cm9uZ2xvb3AuY29tMEwwDQYJKoZIhvcNAQEBBQADOwAwOAIxAMfk\n" + "I0LWU15pPUwIQNMnRVhhOibi0TQmAau8FBtgwEfGK01WpfGUaJr1a41K8Uq7xwID\n" + "AQABoxkwFzAVBgNVHREEDjAMhwQAAAAAhwR/AAABMA0GCSqGSIb3DQEBBQUAAzEA\n" + "cGpYrhkrb7mIh9DNhV0qp7pGjqBzlHqB7KQXw2luLDp//6dyHBMexDCQznkhZKRU\n" + "-----END CERTIFICATE-----\n"
key = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIH0AgEAAjEAx+QjQtZTXmk9TAhA0ydFWGE6JuLRNCYBq7wUG2DAR8YrTVal8ZRo\n" + "mvVrjUrxSrvHAgMBAAECMBCGccvSwC2r8Z9Zh1JtirQVxaL1WWpAQfmVwLe0bAgg\n" + "/JWMU/6hS36TsYyZMxwswQIZAPTAfht/zDLb7Hwgu2twsS1Ra9w/yyvtlwIZANET\n" + "26votwJAHK1yUrZGA5nnp5qcmQ/JUQIZAII5YV/UUZvF9D/fUplJ7puENPWNY9bN\n" + "pQIZAMMwxuS3XiO7two2sQF6W+JTYyX1DPCwAQIZAOYg1TvEGT38k8e8jygv8E8w\n" + "YqrWTeQFNQ==\n" + "-----END RSA PRIVATE KEY-----\n"
ca = [
cert
cacert
]
clientError = null
connectError = null
server = tls.createServer(
ca: ca
cert: cert
key: key
, (conn) ->
throw "unreachable"return
).on("clientError", (err, conn) ->
assert not clientError and conn
clientError = err
return
).listen(common.PORT, ->
options =
ciphers: "AES128-GCM-SHA256"
port: common.PORT
ca: ca
tls.connect(options).on("error", (err) ->
assert not connectError
connectError = err
@destroy()
server.close()
return
).write "123"
return
)
process.on "exit", ->
assert clientError
assert connectError
assert /socket hang up/.test(clientError.message)
assert /ECONNRESET/.test(clientError.code)
return
| 163683 | # 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.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
common = require("../common")
assert = require("assert")
tls = require("tls")
cacert = "-----BEGIN CERTIFICATE-----\n" + "<KEY>IBxTCCAX8CAnXn<KEY>0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n" + "V<KEY>IE<KEY>1UEBx<KEY>n" + "<KEY>9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzM<KEY>GAYDVQQDExFjYS5zdHJv\n" + "bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMH0xCzAJ\n" + "BgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA<KEY>" + "<KEY>" + "<KEY>" + "<KEY>" + "AV<KEY>" + "+0<KEY>FLBwh5<KEY>jhGd0FcenU4OfHxyDEOJT<KEY>/Q<KEY>==\n" + "-----END CERTIFICATE-----\n"
cert = "-----BEGIN CERTIFICATE-----\n" + "MIIBfDCCATYCAgQaMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n" + "<KEY>" + "<KEY>" + "<KEY>E<KEY>" + "<KEY>" + "<KEY>LWU15pPU<KEY>IQNMnRVhhOibi0TQmA<KEY>" + "AQ<KEY>" + "c<KEY>G<KEY>" + "-----END CERTIFICATE-----\n"
key = "-----<KEY> <KEY> <KEY> <KEY> + <KEY>" + "<KEY>" + "<KEY>" + "Y<KEY>WTeQFNQ<KEY>==\n" + "-----<KEY>"
ca = [
cert
cacert
]
clientError = null
connectError = null
server = tls.createServer(
ca: ca
cert: cert
key: key
, (conn) ->
throw "unreachable"return
).on("clientError", (err, conn) ->
assert not clientError and conn
clientError = err
return
).listen(common.PORT, ->
options =
ciphers: "AES128-GCM-SHA256"
port: common.PORT
ca: ca
tls.connect(options).on("error", (err) ->
assert not connectError
connectError = err
@destroy()
server.close()
return
).write "123"
return
)
process.on "exit", ->
assert clientError
assert connectError
assert /socket hang up/.test(clientError.message)
assert /ECONNRESET/.test(clientError.code)
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
common = require("../common")
assert = require("assert")
tls = require("tls")
cacert = "-----BEGIN CERTIFICATE-----\n" + "PI:KEY:<KEY>END_PIIBxTCCAX8CAnXnPI:KEY:<KEY>END_PI0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n" + "VPI:KEY:<KEY>END_PIIEPI:KEY:<KEY>END_PI1UEBxPI:KEY:<KEY>END_PIn" + "PI:KEY:<KEY>END_PI9vcCwgSW5jLjESMBAGA1UECxMJU3Ryb25nT3BzMPI:KEY:<KEY>END_PIGAYDVQQDExFjYS5zdHJv\n" + "bmdsb29wLmNvbTAeFw0xNDAxMTcyMjE1MDdaFw00MTA2MDMyMjE1MDdaMH0xCzAJ\n" + "BgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGAPI:KEY:<KEY>END_PI" + "PI:KEY:<KEY>END_PI" + "PI:KEY:<KEY>END_PI" + "PI:KEY:<KEY>END_PI" + "AVPI:KEY:<KEY>END_PI" + "+0PI:KEY:<KEY>END_PIFLBwh5PI:KEY:<KEY>END_PIjhGd0FcenU4OfHxyDEOJTPI:KEY:<KEY>END_PI/QPI:KEY:<KEY>END_PI==\n" + "-----END CERTIFICATE-----\n"
cert = "-----BEGIN CERTIFICATE-----\n" + "MIIBfDCCATYCAgQaMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNVBAYTAlVTMQswCQYD\n" + "PI:KEY:<KEY>END_PI" + "PI:KEY:<KEY>END_PI" + "PI:KEY:<KEY>END_PIEPI:KEY:<KEY>END_PI" + "PI:KEY:<KEY>END_PI" + "PI:KEY:<KEY>END_PILWU15pPUPI:KEY:<KEY>END_PIIQNMnRVhhOibi0TQmAPI:KEY:<KEY>END_PI" + "AQPI:KEY:<KEY>END_PI" + "cPI:KEY:<KEY>END_PIGPI:KEY:<KEY>END_PI" + "-----END CERTIFICATE-----\n"
key = "-----PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI + PI:KEY:<KEY>END_PI" + "PI:KEY:<KEY>END_PI" + "PI:KEY:<KEY>END_PI" + "YPI:KEY:<KEY>END_PIWTeQFNQPI:KEY:<KEY>END_PI==\n" + "-----PI:KEY:<KEY>END_PI"
ca = [
cert
cacert
]
clientError = null
connectError = null
server = tls.createServer(
ca: ca
cert: cert
key: key
, (conn) ->
throw "unreachable"return
).on("clientError", (err, conn) ->
assert not clientError and conn
clientError = err
return
).listen(common.PORT, ->
options =
ciphers: "AES128-GCM-SHA256"
port: common.PORT
ca: ca
tls.connect(options).on("error", (err) ->
assert not connectError
connectError = err
@destroy()
server.close()
return
).write "123"
return
)
process.on "exit", ->
assert clientError
assert connectError
assert /socket hang up/.test(clientError.message)
assert /ECONNRESET/.test(clientError.code)
return
|
[
{
"context": "[\n {\n key: \"uuid\"\n }\n {\n key: \"token\"\n type: \"password\"\n }\n]\n",
"end": 45,
"score": 0.926978349685669,
"start": 40,
"tag": "KEY",
"value": "token"
}
] | public/schemas/api-authentication-form.cson | octoblu/endo-meshblu | 0 | [
{
key: "uuid"
}
{
key: "token"
type: "password"
}
]
| 36213 | [
{
key: "uuid"
}
{
key: "<KEY>"
type: "password"
}
]
| true | [
{
key: "uuid"
}
{
key: "PI:KEY:<KEY>END_PI"
type: "password"
}
]
|
[
{
"context": "s++\n keys1 = keys\n keys.should.contain 'bottles'\n m().keys (keys) ->\n callbacks++\n ",
"end": 1101,
"score": 0.5012433528900146,
"start": 1098,
"tag": "KEY",
"value": "bot"
}
] | test/fence.test.coffee | futuremint/fence.js | 1 | m = require '../index'
assert = require 'assert'
should = require 'should'
obj = {'bottles': 99}
coll = [ {type: 'cat', pattern: 'tiger'}, {type: 'rails', pattern: 'broken-mvc'} ]
reset = ->
obj = {'bottles': 99}
coll = [ {type: 'cat', pattern: 'tiger'}, {type: 'rails', pattern: 'broken-mvc'} ]
# Helper test to verify the method still returns the monadic object
isMonad = (args...) ->
if args.length == 1
result = m(obj)
method = args[0]
else
result = args[0]
method = args[1]
result[method]().should.equal result
module.exports =
'test .version': ->
m.version.should.match /^\d+\.\d+\.\d+$/
'test object wrapping': ->
m(obj).should.not.equal obj
m(obj).should.not.equal m(obj)
m().should.not.equal m()
m(obj).isCollection.should.be.false
m(coll).isCollection.should.be.true
'test wrapping self': ->
mobj = m(obj)
m(mobj).should.equal mobj
'test private closure': (beforeExit) ->
callbacks = 0
mobj = m(obj)
keys1 = null
mobj.keys (keys) ->
callbacks++
keys1 = keys
keys.should.contain 'bottles'
m().keys (keys) ->
callbacks++
keys.should.not.equal keys1
mobj.keys (keys) ->
callbacks++
keys.should.equal keys1
beforeExit ->
callbacks.should.equal 3
'test keys for object': ->
isMonad 'keys'
m(obj).keys (keys) ->
keys.should.be.instanceof Array
keys.should.have.length 1
keys.should.contain 'bottles'
'test keys for collection': ->
m(coll).keys (keys) ->
keys.should.be.instanceof Array
keys.should.have.length 0
'test all for object': (beforeExit) ->
isMonad 'all'
callbacks = 0
m(obj).all (collection) ->
callbacks++
collection.should.have.length 0
beforeExit ->
callbacks.should.equal 1
'test all for collection': ->
m(coll).all (collection) ->
collection.should.have.length (coll.length)
'test update for object': (beforeExit) ->
isMonad 'update'
callbacks = 0
m(obj).update(bottles: 100).val (doc) ->
callbacks++
doc.bottles.should.equal 100
reset()
m(obj).update(beer: 'lots').val (doc) ->
callbacks++
doc.should.not.have.property 'beer'
doc.bottles.should.equal 99
beforeExit ->
callbacks.should.equal 2
'test update for collection': (beforeExit) ->
callbacks = 0
mcoll = m(coll)
mcoll.
update(pattern: 'dictator').
val( (doc) ->
callbacks++
doc.should.not.have.property 'beer'
).
all( (collection) ->
callbacks++
collection.should.equal coll
collection[0].pattern.should.equal 'dictator'
collection[1].pattern.should.equal 'dictator')
beforeExit ->
callbacks.should.equal 2
'test model self extension': ->
m.fn.cars = {wrx: 'is fast'}
m('cars').should.have.property 'wrx'
m(type: 'cars').should.have.property 'wrx'
m(coll).should.not.have.property 'wrx'
m(coll, 'cars').should.have.property 'wrx'
'test asynchronous callbacks': (beforeExit)->
# Type field to trigger the extension
testObj =
type: 'test'
points: 0
# Extension
m.fn.test =
addPoints: m.fn.async (pts, doc, done) ->
doc.points = doc.points + pts
done()
# Loading up some deferred function executions
tester = m(testObj).addPoints(40).addPoints(2)
# Note that their execution has been delayed for later
testObj.points.should.equal 0
# Triggers execution, executing this lambda last
tester.val (doc) -> doc.points.should.equal 42
# Make sure the val callback really gets fired after the deferreds are done
beforeExit -> testObj.points.should.equal 42
'test asynchronous callbacks on collection': (beforeExit) ->
calls = 0
testColl = [{points: 0}, {points: 99}]
# This extension will get called by name
m.fn.test =
addPoints: m.fn.async (pts, doc, done) ->
calls++
doc.points = doc.points + pts
done()
tester = m(testColl, 'test')
tester.addPoints(10)
# Nothing fired yet...
testColl[0].points.should.equal 0
tester.all (coll) ->
coll[0].points.should.equal 10
coll[1].points.should.equal 109
beforeExit -> calls.should.equal testColl.length
'test reference': (beforeExit) ->
isMonad 'reference'
callbacks = 0
m(sq_class: 'test', _id: '123').reference (ref) ->
callbacks++
ref.sq_class.should.equal 'test'
ref.id.should.equal '123'
beforeExit ->
callbacks.should.equal 1
'test setting properties': (beforeExit) ->
callbacks = 0
m(obj).db (db) ->
callbacks++
db.should.be.ok
m(obj).set('db', 'heyo!!').db (db) ->
callbacks++
db.should.equal 'heyo!!'
beforeExit -> callbacks.should.equal 2
| 127028 | m = require '../index'
assert = require 'assert'
should = require 'should'
obj = {'bottles': 99}
coll = [ {type: 'cat', pattern: 'tiger'}, {type: 'rails', pattern: 'broken-mvc'} ]
reset = ->
obj = {'bottles': 99}
coll = [ {type: 'cat', pattern: 'tiger'}, {type: 'rails', pattern: 'broken-mvc'} ]
# Helper test to verify the method still returns the monadic object
isMonad = (args...) ->
if args.length == 1
result = m(obj)
method = args[0]
else
result = args[0]
method = args[1]
result[method]().should.equal result
module.exports =
'test .version': ->
m.version.should.match /^\d+\.\d+\.\d+$/
'test object wrapping': ->
m(obj).should.not.equal obj
m(obj).should.not.equal m(obj)
m().should.not.equal m()
m(obj).isCollection.should.be.false
m(coll).isCollection.should.be.true
'test wrapping self': ->
mobj = m(obj)
m(mobj).should.equal mobj
'test private closure': (beforeExit) ->
callbacks = 0
mobj = m(obj)
keys1 = null
mobj.keys (keys) ->
callbacks++
keys1 = keys
keys.should.contain '<KEY>tles'
m().keys (keys) ->
callbacks++
keys.should.not.equal keys1
mobj.keys (keys) ->
callbacks++
keys.should.equal keys1
beforeExit ->
callbacks.should.equal 3
'test keys for object': ->
isMonad 'keys'
m(obj).keys (keys) ->
keys.should.be.instanceof Array
keys.should.have.length 1
keys.should.contain 'bottles'
'test keys for collection': ->
m(coll).keys (keys) ->
keys.should.be.instanceof Array
keys.should.have.length 0
'test all for object': (beforeExit) ->
isMonad 'all'
callbacks = 0
m(obj).all (collection) ->
callbacks++
collection.should.have.length 0
beforeExit ->
callbacks.should.equal 1
'test all for collection': ->
m(coll).all (collection) ->
collection.should.have.length (coll.length)
'test update for object': (beforeExit) ->
isMonad 'update'
callbacks = 0
m(obj).update(bottles: 100).val (doc) ->
callbacks++
doc.bottles.should.equal 100
reset()
m(obj).update(beer: 'lots').val (doc) ->
callbacks++
doc.should.not.have.property 'beer'
doc.bottles.should.equal 99
beforeExit ->
callbacks.should.equal 2
'test update for collection': (beforeExit) ->
callbacks = 0
mcoll = m(coll)
mcoll.
update(pattern: 'dictator').
val( (doc) ->
callbacks++
doc.should.not.have.property 'beer'
).
all( (collection) ->
callbacks++
collection.should.equal coll
collection[0].pattern.should.equal 'dictator'
collection[1].pattern.should.equal 'dictator')
beforeExit ->
callbacks.should.equal 2
'test model self extension': ->
m.fn.cars = {wrx: 'is fast'}
m('cars').should.have.property 'wrx'
m(type: 'cars').should.have.property 'wrx'
m(coll).should.not.have.property 'wrx'
m(coll, 'cars').should.have.property 'wrx'
'test asynchronous callbacks': (beforeExit)->
# Type field to trigger the extension
testObj =
type: 'test'
points: 0
# Extension
m.fn.test =
addPoints: m.fn.async (pts, doc, done) ->
doc.points = doc.points + pts
done()
# Loading up some deferred function executions
tester = m(testObj).addPoints(40).addPoints(2)
# Note that their execution has been delayed for later
testObj.points.should.equal 0
# Triggers execution, executing this lambda last
tester.val (doc) -> doc.points.should.equal 42
# Make sure the val callback really gets fired after the deferreds are done
beforeExit -> testObj.points.should.equal 42
'test asynchronous callbacks on collection': (beforeExit) ->
calls = 0
testColl = [{points: 0}, {points: 99}]
# This extension will get called by name
m.fn.test =
addPoints: m.fn.async (pts, doc, done) ->
calls++
doc.points = doc.points + pts
done()
tester = m(testColl, 'test')
tester.addPoints(10)
# Nothing fired yet...
testColl[0].points.should.equal 0
tester.all (coll) ->
coll[0].points.should.equal 10
coll[1].points.should.equal 109
beforeExit -> calls.should.equal testColl.length
'test reference': (beforeExit) ->
isMonad 'reference'
callbacks = 0
m(sq_class: 'test', _id: '123').reference (ref) ->
callbacks++
ref.sq_class.should.equal 'test'
ref.id.should.equal '123'
beforeExit ->
callbacks.should.equal 1
'test setting properties': (beforeExit) ->
callbacks = 0
m(obj).db (db) ->
callbacks++
db.should.be.ok
m(obj).set('db', 'heyo!!').db (db) ->
callbacks++
db.should.equal 'heyo!!'
beforeExit -> callbacks.should.equal 2
| true | m = require '../index'
assert = require 'assert'
should = require 'should'
obj = {'bottles': 99}
coll = [ {type: 'cat', pattern: 'tiger'}, {type: 'rails', pattern: 'broken-mvc'} ]
reset = ->
obj = {'bottles': 99}
coll = [ {type: 'cat', pattern: 'tiger'}, {type: 'rails', pattern: 'broken-mvc'} ]
# Helper test to verify the method still returns the monadic object
isMonad = (args...) ->
if args.length == 1
result = m(obj)
method = args[0]
else
result = args[0]
method = args[1]
result[method]().should.equal result
module.exports =
'test .version': ->
m.version.should.match /^\d+\.\d+\.\d+$/
'test object wrapping': ->
m(obj).should.not.equal obj
m(obj).should.not.equal m(obj)
m().should.not.equal m()
m(obj).isCollection.should.be.false
m(coll).isCollection.should.be.true
'test wrapping self': ->
mobj = m(obj)
m(mobj).should.equal mobj
'test private closure': (beforeExit) ->
callbacks = 0
mobj = m(obj)
keys1 = null
mobj.keys (keys) ->
callbacks++
keys1 = keys
keys.should.contain 'PI:KEY:<KEY>END_PItles'
m().keys (keys) ->
callbacks++
keys.should.not.equal keys1
mobj.keys (keys) ->
callbacks++
keys.should.equal keys1
beforeExit ->
callbacks.should.equal 3
'test keys for object': ->
isMonad 'keys'
m(obj).keys (keys) ->
keys.should.be.instanceof Array
keys.should.have.length 1
keys.should.contain 'bottles'
'test keys for collection': ->
m(coll).keys (keys) ->
keys.should.be.instanceof Array
keys.should.have.length 0
'test all for object': (beforeExit) ->
isMonad 'all'
callbacks = 0
m(obj).all (collection) ->
callbacks++
collection.should.have.length 0
beforeExit ->
callbacks.should.equal 1
'test all for collection': ->
m(coll).all (collection) ->
collection.should.have.length (coll.length)
'test update for object': (beforeExit) ->
isMonad 'update'
callbacks = 0
m(obj).update(bottles: 100).val (doc) ->
callbacks++
doc.bottles.should.equal 100
reset()
m(obj).update(beer: 'lots').val (doc) ->
callbacks++
doc.should.not.have.property 'beer'
doc.bottles.should.equal 99
beforeExit ->
callbacks.should.equal 2
'test update for collection': (beforeExit) ->
callbacks = 0
mcoll = m(coll)
mcoll.
update(pattern: 'dictator').
val( (doc) ->
callbacks++
doc.should.not.have.property 'beer'
).
all( (collection) ->
callbacks++
collection.should.equal coll
collection[0].pattern.should.equal 'dictator'
collection[1].pattern.should.equal 'dictator')
beforeExit ->
callbacks.should.equal 2
'test model self extension': ->
m.fn.cars = {wrx: 'is fast'}
m('cars').should.have.property 'wrx'
m(type: 'cars').should.have.property 'wrx'
m(coll).should.not.have.property 'wrx'
m(coll, 'cars').should.have.property 'wrx'
'test asynchronous callbacks': (beforeExit)->
# Type field to trigger the extension
testObj =
type: 'test'
points: 0
# Extension
m.fn.test =
addPoints: m.fn.async (pts, doc, done) ->
doc.points = doc.points + pts
done()
# Loading up some deferred function executions
tester = m(testObj).addPoints(40).addPoints(2)
# Note that their execution has been delayed for later
testObj.points.should.equal 0
# Triggers execution, executing this lambda last
tester.val (doc) -> doc.points.should.equal 42
# Make sure the val callback really gets fired after the deferreds are done
beforeExit -> testObj.points.should.equal 42
'test asynchronous callbacks on collection': (beforeExit) ->
calls = 0
testColl = [{points: 0}, {points: 99}]
# This extension will get called by name
m.fn.test =
addPoints: m.fn.async (pts, doc, done) ->
calls++
doc.points = doc.points + pts
done()
tester = m(testColl, 'test')
tester.addPoints(10)
# Nothing fired yet...
testColl[0].points.should.equal 0
tester.all (coll) ->
coll[0].points.should.equal 10
coll[1].points.should.equal 109
beforeExit -> calls.should.equal testColl.length
'test reference': (beforeExit) ->
isMonad 'reference'
callbacks = 0
m(sq_class: 'test', _id: '123').reference (ref) ->
callbacks++
ref.sq_class.should.equal 'test'
ref.id.should.equal '123'
beforeExit ->
callbacks.should.equal 1
'test setting properties': (beforeExit) ->
callbacks = 0
m(obj).db (db) ->
callbacks++
db.should.be.ok
m(obj).set('db', 'heyo!!').db (db) ->
callbacks++
db.should.equal 'heyo!!'
beforeExit -> callbacks.should.equal 2
|
[
{
"context": "= new Batman.Request data:\n user:\n name: 'Jim'\n equal req.hasFileUploads(), false\n \ntest 'hasF",
"end": 461,
"score": 0.999725341796875,
"start": 458,
"tag": "NAME",
"value": "Jim"
}
] | tests/batman/request_test.coffee | airhorns/batman | 1 | oldSend = Batman.Request::send
oldFile = Batman.container.File
QUnit.module 'Batman.Request'
setup: ->
@sendSpy = createSpy()
Batman.Request::send = @sendSpy
Batman.container.File = class File
teardown: ->
Batman.container.File = oldFile
Batman.Request::send = oldSend
@request?.cancel()
test 'hasFileUploads() returns false when the request data has no file uploads', ->
req = new Batman.Request data:
user:
name: 'Jim'
equal req.hasFileUploads(), false
test 'hasFileUploads() returns true when the request data has a file upload in a nested object', ->
req = new Batman.Request data:
user:
avatar: new File()
equal req.hasFileUploads(), true
test 'hasFileUploads() returns true when the request data has a file upload in a nested array', ->
req = new Batman.Request data:
user:
avatars: [undefined, new File()]
equal req.hasFileUploads(), true
test 'should not fire if not given a url', ->
new Batman.Request
ok !@sendSpy.called
asyncTest 'should request a url with default get', 2, ->
@request = new Batman.Request
url: 'some/test/url.html'
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
equal req.url, 'some/test/url.html'
equal req.method, 'GET'
asyncTest 'should request a url with a different method, converting the method to uppercase', 1, ->
@request = new Batman.Request
url: 'B/test/url.html'
method: 'post'
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
equal req.method, 'POST'
asyncTest 'should request a url with data', 1, ->
new Batman.Request
url: 'some/test/url.html'
data:
a: "b"
c: 1
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
deepEqual req.data, {a: "b", c: 1}
asyncTest 'should call the success callback if the request was successful', 2, ->
postInstantiationObserver = createSpy()
optionsHashObserver = createSpy()
req = new Batman.Request
url: 'some/test/url.html'
success: optionsHashObserver
send: @sendSpy
req.on 'success', postInstantiationObserver
delay =>
req = @sendSpy.lastCallContext
req.fire 'success', 'some test data'
delay =>
deepEqual optionsHashObserver.lastCallArguments, ['some test data']
deepEqual postInstantiationObserver.lastCallArguments, ['some test data']
asyncTest 'should set headers', 2, ->
new Batman.Request
url: 'some/test/url.html'
headers: {'test_header': 'test-value'}
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
notEqual req.headers.test_header, undefined
equal req.headers.test_header, 'test-value'
if typeof Batman.container.FormData isnt 'undefined'
oldFormData = Batman.container.FormData
else
oldFormData = {}
class MockFormData extends MockClass
constructor: ->
super
@appended = []
@appends = 0
append: (k, v) ->
@appends++
@appended.push [k, v]
QUnit.module 'Batman.Request: serializing to FormData'
setup: ->
Batman.container.FormData = MockFormData
MockFormData.reset()
teardown: ->
Batman.container.FormData = oldFormData
test 'should serialize array data to FormData objects', ->
object =
foo: ["bar", "baz"]
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo[]", "bar"], ["foo[]", "baz"]]
test 'should serialize simple data to FormData objects', ->
object =
foo: "bar"
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo", "bar"]]
test 'should serialize object data to FormData objects', ->
object =
foo:
bar: "baz"
qux: "corge"
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo[bar]", "baz"], ["foo[qux]", "corge"]]
test 'should serialize nested object and array data to FormData objects', ->
object =
foo:
bar: ["baz", "qux"]
corge: [{ding: "dong"}, {walla: "walla"}]
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo[bar][]", "baz"], ["foo[bar][]", "qux"], ["corge[][ding]", "dong"], ["corge[][walla]", "walla"]]
| 96039 | oldSend = Batman.Request::send
oldFile = Batman.container.File
QUnit.module 'Batman.Request'
setup: ->
@sendSpy = createSpy()
Batman.Request::send = @sendSpy
Batman.container.File = class File
teardown: ->
Batman.container.File = oldFile
Batman.Request::send = oldSend
@request?.cancel()
test 'hasFileUploads() returns false when the request data has no file uploads', ->
req = new Batman.Request data:
user:
name: '<NAME>'
equal req.hasFileUploads(), false
test 'hasFileUploads() returns true when the request data has a file upload in a nested object', ->
req = new Batman.Request data:
user:
avatar: new File()
equal req.hasFileUploads(), true
test 'hasFileUploads() returns true when the request data has a file upload in a nested array', ->
req = new Batman.Request data:
user:
avatars: [undefined, new File()]
equal req.hasFileUploads(), true
test 'should not fire if not given a url', ->
new Batman.Request
ok !@sendSpy.called
asyncTest 'should request a url with default get', 2, ->
@request = new Batman.Request
url: 'some/test/url.html'
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
equal req.url, 'some/test/url.html'
equal req.method, 'GET'
asyncTest 'should request a url with a different method, converting the method to uppercase', 1, ->
@request = new Batman.Request
url: 'B/test/url.html'
method: 'post'
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
equal req.method, 'POST'
asyncTest 'should request a url with data', 1, ->
new Batman.Request
url: 'some/test/url.html'
data:
a: "b"
c: 1
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
deepEqual req.data, {a: "b", c: 1}
asyncTest 'should call the success callback if the request was successful', 2, ->
postInstantiationObserver = createSpy()
optionsHashObserver = createSpy()
req = new Batman.Request
url: 'some/test/url.html'
success: optionsHashObserver
send: @sendSpy
req.on 'success', postInstantiationObserver
delay =>
req = @sendSpy.lastCallContext
req.fire 'success', 'some test data'
delay =>
deepEqual optionsHashObserver.lastCallArguments, ['some test data']
deepEqual postInstantiationObserver.lastCallArguments, ['some test data']
asyncTest 'should set headers', 2, ->
new Batman.Request
url: 'some/test/url.html'
headers: {'test_header': 'test-value'}
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
notEqual req.headers.test_header, undefined
equal req.headers.test_header, 'test-value'
if typeof Batman.container.FormData isnt 'undefined'
oldFormData = Batman.container.FormData
else
oldFormData = {}
class MockFormData extends MockClass
constructor: ->
super
@appended = []
@appends = 0
append: (k, v) ->
@appends++
@appended.push [k, v]
QUnit.module 'Batman.Request: serializing to FormData'
setup: ->
Batman.container.FormData = MockFormData
MockFormData.reset()
teardown: ->
Batman.container.FormData = oldFormData
test 'should serialize array data to FormData objects', ->
object =
foo: ["bar", "baz"]
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo[]", "bar"], ["foo[]", "baz"]]
test 'should serialize simple data to FormData objects', ->
object =
foo: "bar"
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo", "bar"]]
test 'should serialize object data to FormData objects', ->
object =
foo:
bar: "baz"
qux: "corge"
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo[bar]", "baz"], ["foo[qux]", "corge"]]
test 'should serialize nested object and array data to FormData objects', ->
object =
foo:
bar: ["baz", "qux"]
corge: [{ding: "dong"}, {walla: "walla"}]
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo[bar][]", "baz"], ["foo[bar][]", "qux"], ["corge[][ding]", "dong"], ["corge[][walla]", "walla"]]
| true | oldSend = Batman.Request::send
oldFile = Batman.container.File
QUnit.module 'Batman.Request'
setup: ->
@sendSpy = createSpy()
Batman.Request::send = @sendSpy
Batman.container.File = class File
teardown: ->
Batman.container.File = oldFile
Batman.Request::send = oldSend
@request?.cancel()
test 'hasFileUploads() returns false when the request data has no file uploads', ->
req = new Batman.Request data:
user:
name: 'PI:NAME:<NAME>END_PI'
equal req.hasFileUploads(), false
test 'hasFileUploads() returns true when the request data has a file upload in a nested object', ->
req = new Batman.Request data:
user:
avatar: new File()
equal req.hasFileUploads(), true
test 'hasFileUploads() returns true when the request data has a file upload in a nested array', ->
req = new Batman.Request data:
user:
avatars: [undefined, new File()]
equal req.hasFileUploads(), true
test 'should not fire if not given a url', ->
new Batman.Request
ok !@sendSpy.called
asyncTest 'should request a url with default get', 2, ->
@request = new Batman.Request
url: 'some/test/url.html'
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
equal req.url, 'some/test/url.html'
equal req.method, 'GET'
asyncTest 'should request a url with a different method, converting the method to uppercase', 1, ->
@request = new Batman.Request
url: 'B/test/url.html'
method: 'post'
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
equal req.method, 'POST'
asyncTest 'should request a url with data', 1, ->
new Batman.Request
url: 'some/test/url.html'
data:
a: "b"
c: 1
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
deepEqual req.data, {a: "b", c: 1}
asyncTest 'should call the success callback if the request was successful', 2, ->
postInstantiationObserver = createSpy()
optionsHashObserver = createSpy()
req = new Batman.Request
url: 'some/test/url.html'
success: optionsHashObserver
send: @sendSpy
req.on 'success', postInstantiationObserver
delay =>
req = @sendSpy.lastCallContext
req.fire 'success', 'some test data'
delay =>
deepEqual optionsHashObserver.lastCallArguments, ['some test data']
deepEqual postInstantiationObserver.lastCallArguments, ['some test data']
asyncTest 'should set headers', 2, ->
new Batman.Request
url: 'some/test/url.html'
headers: {'test_header': 'test-value'}
send: @sendSpy
delay =>
req = @sendSpy.lastCallContext
notEqual req.headers.test_header, undefined
equal req.headers.test_header, 'test-value'
if typeof Batman.container.FormData isnt 'undefined'
oldFormData = Batman.container.FormData
else
oldFormData = {}
class MockFormData extends MockClass
constructor: ->
super
@appended = []
@appends = 0
append: (k, v) ->
@appends++
@appended.push [k, v]
QUnit.module 'Batman.Request: serializing to FormData'
setup: ->
Batman.container.FormData = MockFormData
MockFormData.reset()
teardown: ->
Batman.container.FormData = oldFormData
test 'should serialize array data to FormData objects', ->
object =
foo: ["bar", "baz"]
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo[]", "bar"], ["foo[]", "baz"]]
test 'should serialize simple data to FormData objects', ->
object =
foo: "bar"
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo", "bar"]]
test 'should serialize object data to FormData objects', ->
object =
foo:
bar: "baz"
qux: "corge"
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo[bar]", "baz"], ["foo[qux]", "corge"]]
test 'should serialize nested object and array data to FormData objects', ->
object =
foo:
bar: ["baz", "qux"]
corge: [{ding: "dong"}, {walla: "walla"}]
formData = Batman.Request.objectToFormData(object)
deepEqual formData.appended, [["foo[bar][]", "baz"], ["foo[bar][]", "qux"], ["corge[][ding]", "dong"], ["corge[][walla]", "walla"]]
|
[
{
"context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ",
"end": 33,
"score": 0.9998735189437866,
"start": 21,
"tag": "NAME",
"value": "John Judnich"
}
] | shaders/PlanetNearMeshShader.coffee | anandprabhakar0507/Kosmos | 46 | # Copyright (C) 2013 John Judnich
# Released under The MIT License - see "LICENSE" file for details.
frag = """
precision highp float;
varying vec3 vNormal;
varying vec2 vUV;
varying float camDist;
uniform float alpha;
uniform vec3 lightVec;
uniform sampler2D sampler;
uniform sampler2D detailSampler;
uniform vec4 uvRect;
uniform vec3 planetColor1;
uniform vec3 planetColor2;
const float uvScalar = 4097.0 / 4096.0;
#define ONE_TEXEL (1.0/4096.0)
vec3 computeLighting(float globalDot, float diffuse, float ambient, vec3 color)
{
float nightBlend = clamp(0.5 - globalDot * 4.0, 0.0, 1.0);
float nightLight = clamp(0.2 / sqrt(camDist) - 0.001, 0.0, 1.0);
float ambientNight = nightBlend * (ambient * ambient * 0.14 + 0.02) * nightLight;
vec3 nightColor = normalize(color) * 0.4 + vec3(0.4, 0.1, 1.0) * 0.4;
return color * diffuse + nightColor * ambientNight;
}
vec3 computeColor(float height, float ambient)
{
float selfShadowing = 1.00 - dot(planetColor1, vec3(1,1,1)/3.0);
vec3 color = vec3(1,1,1);
float edge = mix(1.0, ambient, selfShadowing);
color *= mix(planetColor2, vec3(1,1,1) * edge, clamp(abs(height - 0.0) / 1.5, 0.0, 1.0));
color *= mix(planetColor1, vec3(1,1,1) * edge, clamp(abs(height - 0.5) / 2.5, 0.0, 1.0));
color *= height * 0.25 + 1.00;
return color;
}
void main(void) {
// extract terrain info
vec4 tex = texture2D(sampler, vUV * uvScalar, -0.5);
vec3 norm = normalize(tex.xyz * 2.0 - 1.0);
// compute terrain shape features values
float globalDot = dot(lightVec, vNormal);
float diffuse = clamp(dot(lightVec, norm), 0.0, 1.0);
float ambient = clamp(1.0 - 2.0 * acos(dot(norm, normalize(vNormal))), 0.0, 1.0);
float height = tex.a;
// compute color based on terrain features
vec3 color = computeColor(height, ambient);
vec4 detailColor = texture2D(detailSampler, vUV * 128.0, -0.5) * 2.0 - 1.0;
float detailPower = clamp(1.0 / (camDist * 25.0), 0.0, 1.0) * (0.80 - clamp(globalDot, 0.0, 1.0) * 0.5);
color *= 1.0 + detailColor.xyz * detailPower;
gl_FragColor.xyz = computeLighting(globalDot, diffuse, ambient, color);
//gl_FragColor.xyz = detailColor.xyz;
gl_FragColor.w = 1.0; //alpha;
}
"""
vert = """
precision highp float;
attribute vec3 aUV;
uniform mat4 projMat;
uniform mat4 modelViewMat;
uniform mat3 cubeMat;
varying vec3 vNormal;
varying vec2 vUV;
varying float camDist;
uniform vec4 uvRect;
uniform sampler2D vertSampler;
const float uvScalar = 4097.0 / 4096.0;
void main(void) {
vec2 uv = aUV.xy * uvRect.zw + uvRect.xy;
vec3 aPos = vec3(uv * 2.0 - 1.0, 1.0);
aPos = normalize(aPos * cubeMat);
float height = texture2D(vertSampler, uv * uvScalar).a;
aPos *= 0.985 + (height - (uvRect.z * 3.0) * aUV.z) * 0.015;
vNormal = aPos;
vUV = uv.xy;
vec4 pos = vec4(aPos, 1.0);
pos = modelViewMat * pos;
gl_Position = projMat * pos;
camDist = length(pos.xyz);
}
"""
xgl.addProgram("planetNearMesh", vert, frag)
| 134139 | # Copyright (C) 2013 <NAME>
# Released under The MIT License - see "LICENSE" file for details.
frag = """
precision highp float;
varying vec3 vNormal;
varying vec2 vUV;
varying float camDist;
uniform float alpha;
uniform vec3 lightVec;
uniform sampler2D sampler;
uniform sampler2D detailSampler;
uniform vec4 uvRect;
uniform vec3 planetColor1;
uniform vec3 planetColor2;
const float uvScalar = 4097.0 / 4096.0;
#define ONE_TEXEL (1.0/4096.0)
vec3 computeLighting(float globalDot, float diffuse, float ambient, vec3 color)
{
float nightBlend = clamp(0.5 - globalDot * 4.0, 0.0, 1.0);
float nightLight = clamp(0.2 / sqrt(camDist) - 0.001, 0.0, 1.0);
float ambientNight = nightBlend * (ambient * ambient * 0.14 + 0.02) * nightLight;
vec3 nightColor = normalize(color) * 0.4 + vec3(0.4, 0.1, 1.0) * 0.4;
return color * diffuse + nightColor * ambientNight;
}
vec3 computeColor(float height, float ambient)
{
float selfShadowing = 1.00 - dot(planetColor1, vec3(1,1,1)/3.0);
vec3 color = vec3(1,1,1);
float edge = mix(1.0, ambient, selfShadowing);
color *= mix(planetColor2, vec3(1,1,1) * edge, clamp(abs(height - 0.0) / 1.5, 0.0, 1.0));
color *= mix(planetColor1, vec3(1,1,1) * edge, clamp(abs(height - 0.5) / 2.5, 0.0, 1.0));
color *= height * 0.25 + 1.00;
return color;
}
void main(void) {
// extract terrain info
vec4 tex = texture2D(sampler, vUV * uvScalar, -0.5);
vec3 norm = normalize(tex.xyz * 2.0 - 1.0);
// compute terrain shape features values
float globalDot = dot(lightVec, vNormal);
float diffuse = clamp(dot(lightVec, norm), 0.0, 1.0);
float ambient = clamp(1.0 - 2.0 * acos(dot(norm, normalize(vNormal))), 0.0, 1.0);
float height = tex.a;
// compute color based on terrain features
vec3 color = computeColor(height, ambient);
vec4 detailColor = texture2D(detailSampler, vUV * 128.0, -0.5) * 2.0 - 1.0;
float detailPower = clamp(1.0 / (camDist * 25.0), 0.0, 1.0) * (0.80 - clamp(globalDot, 0.0, 1.0) * 0.5);
color *= 1.0 + detailColor.xyz * detailPower;
gl_FragColor.xyz = computeLighting(globalDot, diffuse, ambient, color);
//gl_FragColor.xyz = detailColor.xyz;
gl_FragColor.w = 1.0; //alpha;
}
"""
vert = """
precision highp float;
attribute vec3 aUV;
uniform mat4 projMat;
uniform mat4 modelViewMat;
uniform mat3 cubeMat;
varying vec3 vNormal;
varying vec2 vUV;
varying float camDist;
uniform vec4 uvRect;
uniform sampler2D vertSampler;
const float uvScalar = 4097.0 / 4096.0;
void main(void) {
vec2 uv = aUV.xy * uvRect.zw + uvRect.xy;
vec3 aPos = vec3(uv * 2.0 - 1.0, 1.0);
aPos = normalize(aPos * cubeMat);
float height = texture2D(vertSampler, uv * uvScalar).a;
aPos *= 0.985 + (height - (uvRect.z * 3.0) * aUV.z) * 0.015;
vNormal = aPos;
vUV = uv.xy;
vec4 pos = vec4(aPos, 1.0);
pos = modelViewMat * pos;
gl_Position = projMat * pos;
camDist = length(pos.xyz);
}
"""
xgl.addProgram("planetNearMesh", vert, frag)
| true | # Copyright (C) 2013 PI:NAME:<NAME>END_PI
# Released under The MIT License - see "LICENSE" file for details.
frag = """
precision highp float;
varying vec3 vNormal;
varying vec2 vUV;
varying float camDist;
uniform float alpha;
uniform vec3 lightVec;
uniform sampler2D sampler;
uniform sampler2D detailSampler;
uniform vec4 uvRect;
uniform vec3 planetColor1;
uniform vec3 planetColor2;
const float uvScalar = 4097.0 / 4096.0;
#define ONE_TEXEL (1.0/4096.0)
vec3 computeLighting(float globalDot, float diffuse, float ambient, vec3 color)
{
float nightBlend = clamp(0.5 - globalDot * 4.0, 0.0, 1.0);
float nightLight = clamp(0.2 / sqrt(camDist) - 0.001, 0.0, 1.0);
float ambientNight = nightBlend * (ambient * ambient * 0.14 + 0.02) * nightLight;
vec3 nightColor = normalize(color) * 0.4 + vec3(0.4, 0.1, 1.0) * 0.4;
return color * diffuse + nightColor * ambientNight;
}
vec3 computeColor(float height, float ambient)
{
float selfShadowing = 1.00 - dot(planetColor1, vec3(1,1,1)/3.0);
vec3 color = vec3(1,1,1);
float edge = mix(1.0, ambient, selfShadowing);
color *= mix(planetColor2, vec3(1,1,1) * edge, clamp(abs(height - 0.0) / 1.5, 0.0, 1.0));
color *= mix(planetColor1, vec3(1,1,1) * edge, clamp(abs(height - 0.5) / 2.5, 0.0, 1.0));
color *= height * 0.25 + 1.00;
return color;
}
void main(void) {
// extract terrain info
vec4 tex = texture2D(sampler, vUV * uvScalar, -0.5);
vec3 norm = normalize(tex.xyz * 2.0 - 1.0);
// compute terrain shape features values
float globalDot = dot(lightVec, vNormal);
float diffuse = clamp(dot(lightVec, norm), 0.0, 1.0);
float ambient = clamp(1.0 - 2.0 * acos(dot(norm, normalize(vNormal))), 0.0, 1.0);
float height = tex.a;
// compute color based on terrain features
vec3 color = computeColor(height, ambient);
vec4 detailColor = texture2D(detailSampler, vUV * 128.0, -0.5) * 2.0 - 1.0;
float detailPower = clamp(1.0 / (camDist * 25.0), 0.0, 1.0) * (0.80 - clamp(globalDot, 0.0, 1.0) * 0.5);
color *= 1.0 + detailColor.xyz * detailPower;
gl_FragColor.xyz = computeLighting(globalDot, diffuse, ambient, color);
//gl_FragColor.xyz = detailColor.xyz;
gl_FragColor.w = 1.0; //alpha;
}
"""
vert = """
precision highp float;
attribute vec3 aUV;
uniform mat4 projMat;
uniform mat4 modelViewMat;
uniform mat3 cubeMat;
varying vec3 vNormal;
varying vec2 vUV;
varying float camDist;
uniform vec4 uvRect;
uniform sampler2D vertSampler;
const float uvScalar = 4097.0 / 4096.0;
void main(void) {
vec2 uv = aUV.xy * uvRect.zw + uvRect.xy;
vec3 aPos = vec3(uv * 2.0 - 1.0, 1.0);
aPos = normalize(aPos * cubeMat);
float height = texture2D(vertSampler, uv * uvScalar).a;
aPos *= 0.985 + (height - (uvRect.z * 3.0) * aUV.z) * 0.015;
vNormal = aPos;
vUV = uv.xy;
vec4 pos = vec4(aPos, 1.0);
pos = modelViewMat * pos;
gl_Position = projMat * pos;
camDist = length(pos.xyz);
}
"""
xgl.addProgram("planetNearMesh", vert, frag)
|
[
{
"context": "bot returns to 'listen' mode.\n\nAuthor(s): Cyrus Manouchehrian (Inital Version)\n Will Zuill\n\n",
"end": 683,
"score": 0.9998733401298523,
"start": 664,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "Manouchehrian (Inital Version)\n Will Zuill\n\nCopyright information:\n\nCopyright 2016 Hewlett-P",
"end": 731,
"score": 0.9998824000358582,
"start": 721,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": " \"\" Username to StormRunner Load\n# SRL_PASSWORD \"\" Password to StormRunner Load\n# SRL_TENANT_ID \"\" Tenant ID to StormRunner Load\n",
"end": 1612,
"score": 0.9187899231910706,
"start": 1584,
"tag": "PASSWORD",
"value": "Password to StormRunner Load"
},
{
"context": "antId (stormrunnerApiAdapter.js)\n#\n# Author(s): Will Zuill (inital Version)\n# Cyrus Manouchehr",
"end": 2706,
"score": 0.9998590350151062,
"start": 2696,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "s): Will Zuill (inital Version)\n# Cyrus Manouchehrian\n#################################################",
"end": 2759,
"score": 0.9998838305473328,
"start": 2740,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "antId (stormrunnerApiAdapter.js)\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 6149,
"score": 0.9998881816864014,
"start": 6130,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 6193,
"score": 0.9998763203620911,
"start": 6183,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "antId (stormrunnerApiAdapter.js)\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 11261,
"score": 0.9998836517333984,
"start": 11242,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 11305,
"score": 0.9998452067375183,
"start": 11295,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "he returned string 'tick' date @SRL I’m working on Will Zuill’s Projectinto a number\n # and then a date ",
"end": 13263,
"score": 0.9719292521476746,
"start": 13253,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "antId (stormrunnerApiAdapter.js)\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 15858,
"score": 0.9998917579650879,
"start": 15839,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 15902,
"score": 0.9998366236686707,
"start": 15892,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "antId (stormrunnerApiAdapter.js)\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 21294,
"score": 0.9998921155929565,
"start": 21275,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 21338,
"score": 0.9998478293418884,
"start": 21328,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "antId (stormrunnerApiAdapter.js)\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 27511,
"score": 0.9998897314071655,
"start": 27492,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 27555,
"score": 0.9998121857643127,
"start": 27545,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "ction (srl-openapi-proxy.coffee)\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 34614,
"score": 0.999890923500061,
"start": 34595,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 34658,
"score": 0.9998456835746765,
"start": 34648,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "bled>')\n#\n# Calls to: <none>\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 37084,
"score": 0.9999016523361206,
"start": 37065,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 37128,
"score": 0.999544084072113,
"start": 37118,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "tatus')\n#\n# Calls to: <none>\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 39531,
"score": 0.9998913407325745,
"start": 39512,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 39575,
"score": 0.999863862991333,
"start": 39565,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "hash>')\n#\n# Calls to: <none>\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 40186,
"score": 0.9999047517776489,
"start": 40167,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 40230,
"score": 0.9965343475341797,
"start": 40220,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "tatus')\n#\n# Calls to: <none>\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 40816,
"score": 0.9999040961265564,
"start": 40797,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 40860,
"score": 0.9985328316688538,
"start": 40850,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "tance')\n#\n# Calls to: <none>\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 41371,
"score": 0.9999048709869385,
"start": 41352,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 41415,
"score": 0.999157190322876,
"start": 41405,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": " room')\n#\n# Calls to: <none>\n#\n# Author(s): Cyrus Manouchehrian (inital version)\n# Will Zuill\n#####",
"end": 41900,
"score": 0.9998980760574341,
"start": 41881,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": "rus Manouchehrian (inital version)\n# Will Zuill\n#################################################",
"end": 41944,
"score": 0.9992856979370117,
"start": 41934,
"tag": "NAME",
"value": "Will Zuill"
},
{
"context": "sendCustomMessage(helpers.cofee)\n#\n# Author(s): Cyrus Manouchehrian\n# Will Zuill\n######################",
"end": 42518,
"score": 0.9998989105224609,
"start": 42499,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": " Author(s): Cyrus Manouchehrian\n# Will Zuill\n#################################################",
"end": 42545,
"score": 0.9996045231819153,
"start": 42535,
"tag": "NAME",
"value": "Will Zuill"
}
] | src/stormrunner-bot-logic.coffee | cyrusm86/srl_chatbot | 0 | ###
File Name: stormrunner-bot-logic.coffee
Written in: Coffee Script
Description: This file contains the routines that 'listen' for the user to type
various commands. Each of the available commands are listed below
and once the robot 'hears' the command, it processes the code contained
within the rountine. For example, if a user asks the bot to 'list projects'
the code under the routine robot.respond /list projects/i, (msg) is processed.
Upon completion of the rountine, the robot returns to 'listen' mode.
Author(s): Cyrus Manouchehrian (Inital Version)
Will Zuill
Copyright information:
Copyright 2016 Hewlett-Packard Development Company, L.P.
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.
###
# Configuration:
# HUBOT_SLACK_TOKEN "" Slack token for hubot
# https_proxy "" Proxy used for hubot
# SRL_SAAS_PREFIX "https://stormrunner-load.saas.hpe.com/v1" SaaS Rest API URL
# SRL_USERNAME "" Username to StormRunner Load
# SRL_PASSWORD "" Password to StormRunner Load
# SRL_TENANT_ID "" Tenant ID to StormRunner Load
#
# Set the file dependancies
Helpers = require './helpers'
StormrunnerApi = require "./libs/stormrunnerApiAdapter.js"
mockData = require "./mockData"
util = require('util')
module.exports = (robot) ->
Helpers.setRobot(robot)
robot.e.registerIntegration({short_desc: 'StormRunner Load hubot chatops integration', name: 'srl'})
################################################################################
# Name: list projects
#
# Description: Gets the current list of SRL projects detailed in the local
# hubot local web server. The local web server is populated in the
# 'get projects' section of the file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'list projects')
#
# Calls to: 'get projects' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): Will Zuill (inital Version)
# Cyrus Manouchehrian
################################################################################
# Add command to hubot help
#robot.commands.push "hubot list projects - Lists all the projects in the supplied tenant."
# listen for the response....
#robot.respond /list projects/i, (msg) ->
robot.e.create {verb:'list',entity:'projects',help: 'Lists all projects in supplied tenant',type:'respond'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Get the list of projects from the local Hubot web server. This will cause
# the 'get projects' section to fire in the file srl-openapi-proxy.coffee
# should the list of projects need to be populated or updated.
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getProjects")
.get() (err, res, body) ->
if err or res.statusCode!=200
# If we cannot find any projects, display the error code and drop.
msg.reply 'Sorry, there was an error retrieving the projects'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
# Format the returned list of projects as a JSON string
prjs = JSON.parse body
# Initialize all variables
attachments = []
strPrjID = ""
strPrjName = ""
# Loop through returned list of projects
for index,value of prjs
#console.log "Getting project for : #{value.id}"
# Append each project ID and Name to a two single string seperated
# by a carriage return (\n)
strPrjID = strPrjID + value.id + "\n"
strPrjName = strPrjName + value.name + "\n"
# End of Loop
# Format the list of projects (id and name) as a SLACK attachment
fields =
color : "#0000FF" # Add a Blue line
fields : [
{
title: "Project ID"
value: strPrjID
short: true
},
{
title: "Project Name"
value: strPrjName
short: true
}
]
attachments.push(fields)
#console.log("room="+msg.message.room)
# Construct a SLACK message to send to the appropriate chat room.
msgData = {
channel: msg.message.room
text: "Projects for tenant #{StormrunnerApi.getTenantId()}"
attachments: attachments
}
# Send the built message to the chat client/room.
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: list tests for project X
#
# Description: Gets a list of all the tests for the passed in SRL project name or
# project ID from the hubot local web server. The local web server
# is populated in the 'get Tests' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'list tests for
# project X')
#
# Calls to: 'get Tests' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
# Add command to hubot help
#robot.commands.push "hubot list tests - Lists all the tests for previously set project name or ID."
#robot.respond /list tests/i, (msg) ->
robot.e.create {verb:'list',entity:'tests',help: 'Lists all tests for previously set project name or ID',type:'respond'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the first variable part of the message (i.e. the project Name or
# Project ID)
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing tests for project #{intProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getTests?project=#{intProject}")
.get() (err, res, body) ->
# If we cannot find any tests, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the tests'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
tests = JSON.parse body
# Initalize all variables
attachments = []
strTestID = ""
strTestNameDate = ""
strTestDate = ""
strTestName = ""
intDate = 0
objDate = []
# if we have more than 10 runs
if tests.length > 20
# Display a message and remove all results after the 10th array element
strMessage = "There are a total of #{tests.length} tests in #{strProject}. We are displaying 20."
tests.splice(20,tests.length-20)
else
strMessage = "Here are all the tests in project #{strProject}"
# Loop through returned list of tests
for index,value of tests
#console.log "Getting tests for : #{value.id}"
# Append each Test ID to a single string seperated
# by a carriage return (\n)
strTestID = strTestID + value.id + "\n"
strTestName = strTestName + value.name + "\n"
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(value.createDate)
objDate = new Date(intDate)
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strTestDate = StormrunnerApi.fmtDate(objDate)
# As the 'attachment' formatting only has two columns and we want to
# display three (ID, Name and Creation Date) we need to format name
# and creation date into a single string. Therefore format it as:
# Test Name <TAB> (Test Creation Date)
strTestNameDate = strTestNameDate + value.name + "\t(" + strTestDate + ")" + "\n"
# End of Loop
# Format the list of tests (id and name/creation date) as a SLACK attachment
fields =
color : "#0000FF" # Add a Blue line
#footer: "----------------------------------------------------------------------------------------"
fields : [
{
title: "Test ID"
value: strTestID
short: true
},
{
title: "Test Name"
value: strTestName
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: strMessage
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: show latest run for test X in project Y
#
# Description: shows test details for the latest run of a test (the test ID is
# passed in) in a passed in project from the hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show latest run
# for test X in Project Y')
#
# Calls to: 'get runs' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
# Add command to hubot help
#robot.commands.push "hubot show latest run for test <test id> - Displays the latest run information for supplied test ID."
#robot.respond /show latest run for test (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'latest',
regex_suffix:{re: "run for test (.*)", optional: false},
help: 'Displays the latest run information for supplied test ID',type:'respond',
example: 'run for test 1234'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the two variables part of the message (i.e. first the Test ID and then the project Name or
# Project ID)
strTestId = msg.match[1]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing latest run for test #{strTestId} in Project #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRuns?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any tests, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the run for this test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
run = JSON.parse(body)
# Initialize all variables
attachments = []
strTestName = ""
strStartDate = ""
strDuration = ""
intDate = 0
intDuration = 0
objDate = []
# Set the test name
strTestName = run[0].testName
strColor = Helpers.getColor(robot,run[0].status)
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date @SRL I’m working on Will Zuill’s Projectinto a number
# and then a date object.
intDate = Number(run[0].startOn)
objDate = new Date(intDate)
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strStartDate = StormrunnerApi.fmtDate(objDate)
# The duration is stored in Microseconds. Thus, convert the returned
# string to an integer and call the function to format the duration
# into HH:MM:SS
intDuration = Number(run[0].duration)
strDuration = StormrunnerApi.fmtDuration(intDuration)
# Format the returned parameters as a SLACK attachment
fields =
color: strColor
fields : [
{
title: "Run ID"
value: run[0].id
short: true
},
{
title: "Status"
value: run[0].status
short: true
},
{
title: "Start Date"
value: strStartDate
short: true
},
{
title: "Duration"
value: strDuration
short: true
},
{
title: "Virtual Users Used"
value: run[0].vusersNum
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: "Latest run result for test #{strTestName} in project #{strProject}"
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: show runs for test X in project Y
#
# Description: Shows run details for the a test (the test ID is passed in)
# in a passed in project from the hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show runs
# for test X in Project Y')
#
# Calls to: 'get runs' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
# Add command to hubot help
#robot.commands.push "hubot show runs for test <test id> - Displays run information up to 10 runs for supplied test ID in project Name/ID."
#robot.respond /show runs for test (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'runs',
regex_suffix:{re: "for test (.*)", optional: false},
help: 'Displays run information for up to 10 runs for supplied test ID in project name/ID',type:'respond',
example: 'for test 123'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the two variables part of the message (i.e. first the Test ID and then the project Name or
# Project ID)
strTestId = msg.match[1]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing runs for test #{strTestId} in Project #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRuns?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any tests, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the runs for the test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
runs = JSON.parse(body)
# Initialize all variables
attachments = []
strTestName = ""
strMessage = ""
strStartDate = ""
strDuration = ""
strTestName = ""
intDate = 0
intDuration = 0
objDate = []
strTestName = runs[0].testName
# if we have more than 10 runs
if runs.length > 10
# Display a message and remove all results after the 10th array element
strMessage = "There are a total of #{runs.length} for test #{strTestName} in project #{strProject}. Only displaying last 10."
runs.splice(10,runs.length-10)
else
strMessage = "The last #{runs.length} run results for test #{strTestName} in project #{strProject}"
# for each of the runs
for index,value of runs
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(value.startOn)
objDate = new Date(intDate)
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strStartDate = StormrunnerApi.fmtDate(objDate)
# The duration is stored in Microseconds. Thus, convert the returned
# string to an integer and call the function to format the duration
# into HH:MM:SS
intDuration = Number(value.duration)
strDuration = StormrunnerApi.fmtDuration(intDuration)
strColor = Helpers.getColor(robot,value.status)
# Format the returned parameters as a SLACK attachment
fields =
color : strColor
footer: "----------------------------------------------------------------------------------------"
fields : [
{
title: "Run ID"
value: value.id
short: true
},
{
title: "Status"
value: value.status
short: true
},
{
title: "Start Date"
value: strStartDate
short: true
},
{
title: "Duration"
value: strDuration
short: true
},
{
title: "Virtual Users Used"
value: value.vusersNum
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: strMessage
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: list status for last X runs for test Y in project Z
#
# Description: Shows X (num of runs is passed in) number run details for the a
# test (the test ID is passed in) in a passed in project from the
# hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show runs
# for test X in Project Y')
#
# Calls to: 'get runs' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
# Add command to hubot help
#robot.commands.push "hubot list status for last <num of runs> runs for test <test id> - Displays the run information for X number of runs for supplied test ID in project Name/ID."
#robot.respond /list status for last (.*) runs for test (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'status',
regex_suffix:{re: "for last (.*) runs for test (.*)", optional: false},
help: 'Displays the run information for X number of runs for supplied test ID in project Name/ID',type:'respond',
example: 'for last 5 runs for test 123'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the three variables part of the message (i.e. first the number of runs, followed by
# the Test ID and then the project Name or Project ID)
strRunCnt = msg.match[1]
strTestId = msg.match[2]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing runs for test #{strTestId} in Project #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRuns?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any runs for the test, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the runs for the test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
runs = JSON.parse(body)
# Initialize all variables
attachments = []
strTestName = ""
strMessage = ""
strStartDate = ""
strDuration = ""
strHrs = ""
strMins = ""
strSecs = ""
intDate = 0
intDuration = 0
objDate = []
strColor = ""
strTestName = runs[0].testName
# if the number of runs is less than the asked for runs
if runs.length < Number(strRunCnt)
# Display a message saying we can only display X runs
strMessage = "There are only #{runs.length} runs for test #{strTestName} in project #{strProject}."
else
# if the total number of runs is greater than then number of runs asked for, then trim the
# array to limit it to the passed in number
if runs.length > Number(strRunCnt)
runs.splice(Number(strRunCnt),runs.length-Number(strRunCnt))
strMessage = "The last #{runs.length} run results for test #{strTestName} in project #{strProject}"
# for each of the runs
for index,value of runs
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(value.startOn)
objDate = new Date(intDate)
# We need need to get the time, therefore extract the hours, mins and seconds
# and convert them to a string
strHrs = objDate.getHours().toString()
strMins = objDate.getMinutes().toString()
strSecs = objDate.getSeconds().toString()
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strStartDate = StormrunnerApi.fmtDate(objDate) + " " + strHrs.lpad("0",2) + ":" + strMins.lpad("0",2) + ":" + strSecs.lpad("0",2)
# The duration is stored in Microseconds. Thus, convert the returned
# string to an integer and call the function to format the duration
# into HH:MM:SS
intDuration = Number(value.duration)
strDuration = StormrunnerApi.fmtDuration(intDuration)
strColor = Helpers.getColor(robot,value.status)
# Format the returned parameters as a SLACK attachment
fields =
color : strColor
footer: "----------------------------------------------------------------------------------------"
fields : [
{
title: "Run ID"
value: value.id
short: true
},
{
title: "Status"
value: value.status
short: true
},
{
title: "Start Date"
value: strStartDate
short: true
},
{
title: "Duration"
value: strDuration
short: true
},
{
title: "Virtual Users Used"
value: value.vusersNum
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: strMessage
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: show full results for run id X
#
# Description: Shows all the results for a run run ID is passed in) from the
# hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show full
# results for run id X')
#
# Calls to: 'get Run Results' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
# Add command to hubot help
#robot.commands.push "hubot show results for run id <Run id> - Displays results information for supplied run ID."
#robot.respond /show results for run id (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'results',
regex_suffix:{re: "for run (.*)", optional: false},
help: 'Displays results information for supplied run ID',type:'respond',
example: 'for run 123'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the variable part of the message (i.e. the run id)
strRunid = msg.match[1]
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRunResults?runid=#{strRunid}")
.get() (err, res, body) ->
# If we cannot find this run, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the run results'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
rslt = JSON.parse body
# Initialize all variables
attachments = []
strStartTime = ""
strEndTime = ""
strHrs = ""
strMins = ""
strSecs = ""
intDate = 0
objDate = []
strColor = ""
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(rslt.startTime)
objDate = new Date(intDate)
# We need need to get the time, therefore extract the hours, mins and seconds
# and convert them to a string
strHrs = objDate.getHours().toString()
strMins = objDate.getMinutes().toString()
strSecs = objDate.getSeconds().toString()
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!) and add on the time
strStartTime = StormrunnerApi.fmtDate(objDate) + " " + strHrs.lpad("0",2) + ":" + strMins.lpad("0",2) + ":" + strSecs.lpad("0",2)
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(rslt.endTime)
objDate = new Date(intDate)
# We need need to get the time, therefore extract the hours, mins and seconds
# and convert them to a string
strHrs = objDate.getHours().toString()
strMins = objDate.getMinutes().toString()
strSecs = objDate.getSeconds().toString()
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!) and add on the time.
strEndTime = StormrunnerApi.fmtDate(objDate) + " " + strHrs.lpad("0",2) + ":" + strMins.lpad("0",2) + ":" + strSecs.lpad("0",2)
strColor = Helpers.getColor(robot,rslt.uiStatus)
strMessage = Helpers.getQuote(robot,rslt.uiStatus)
fields =
color : strColor
fields : [
{
title: "Test ID"
value: rslt.testId
short: true
},
{
title: "UI Status"
value: rslt.uiStatus
short: true
},
{
title: "Start Time"
value: strStartTime
short: true
},
{
title: "End Time"
value: strEndTime
short: true
}
]
#check to see if VU's or VUH's are used and output correct format
#if VuserNum is greater than 0 and cost is defined (meaning a number is there)
#output both labels and values
#if there is only VuserNum, just output that label and value
#we are separating each license type used into its own array
if (rslt.uiVusersNum > 0 && rslt.actualUiCost != undefined)
uiusers = [
{
title: "UI Virtual Users"
value: rslt.uiVusersNum
short: true
},
{
title: "Actual UI Cost"
value: rslt.actualUiCost
short: true
}
]
#this is concatenating all the arrays used into one array, which gets
#pushed to the Attachments array
fields.fields = fields.fields.concat(uiusers)
else if (rslt.uiVusersNum > 0)
uiusers = [
{
title: "UI Virtual Users"
value: rslt.uiVusersNum
short: true
}
]
fields.fields = fields.fields.concat(uiusers)
if (rslt.apiVusersNum > 0 && rslt.actualApiCost != undefined)
apiusers = [
{
title: "API Virtual Users"
value: rslt.apiVusersNum
short: true
},
{
title: "Actual API Cost"
value: rslt.actualApiCost
short: true
}
]
fields.fields = fields.fields.concat(apiusers)
else if (rslt.apiVusersNum > 0)
apiusers = [
{
title: "API Virtual Users"
value: rslt.apiVusersNum
short: true
}
]
fields.fields = fields.fields.concat(apiusers)
if (rslt.devVusersNum > 0 && rslt.actualDevCost != undefined)
devusers = [
{
title: "DEV Virtual Users"
value: rslt.devVusersNum
short: true
},
{
title: "Actual DEV Cost"
value: rslt.actualDevCost
short: true
}
]
fields.fields = fields.fields.concat(devusers)
else if (rslt.devVusersNum > 0)
devusers = [
{
title: "DEV Virtual Users"
value: rslt.devVusersNum
short: true
}
]
fields.fields = fields.fields.concat(devusers)
attachments.push(fields)
msgData = {
channel: msg.message.room
text: "Here are the run results for run id #{strRunid}. " + strMessage
attachments: attachments
}
#robot.emit 'slack.attachment', msgData
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: run test
#
# Description: Tells the bot to run specified test ID
#
# Called From: (Direct from Chat client by typing the command 'run test (id)')
#
# Calls to: 'post Run' section (srl-openapi-proxy.coffee)
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
# Add command to hubot help
#robot.commands.push "hubot run test <test id> - Executes the supplied test ID project Name/ID."
#robot.respond /run test (.*)/i, (msg) ->
robot.e.create {verb:'run',entity:'test',
regex_suffix:{re: "(.*)", optional: false},
help: 'Executes the supplied test ID project Name/ID',type:'respond',
example: '1234'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the three variables part of the message (i.e. first the number of runs, followed by
# the Test ID and then the project Name or Project ID)
strTestId = msg.match[1]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Running test #{strTestId} in #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/postRun?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any runs for the test, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the runs for the test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
runs = JSON.parse(body)
# Initialize all variables
attachments = []
# Send the built message to the chat client/room.
# Send URL to runs page of specified test
strURL = ""
strURL = util.format('https://stormrunner-load.saas.hpe.com/loadTests/%s/runs/?TENANTID=%s&projectId=%s', strTestId, process.env.SRL_TENANT_ID, intProject)
msgData = {
channel: msg.message.room
text: "Your test is initializing and the Run ID is #{runs.runId}. Would you like a side of fries with that? \n #{strURL}"
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: set mock data <enabled/disabled>
#
# Description: Tells the bot to use mock data instead of pulling from
# the API's
#
# Called From: (Direct from Chat client by typing the command 'set mock
# data <enabled/disabled>')
#
# Calls to: <none>
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
robot.respond /set mock data (.*)/i, (msg) ->
robot.e.create {verb:'set',entity:'mock',
regex_suffix:{re: "data (.*)", optional: false},
help: 'Set Mock Data to enabled or disabled',type:'respond',
example: 'data enabled'},(msg)->
mockDataStatus= msg.match[1]
if mockDataStatus is "enabled"
robot.brain.set 'isMockData',true
else if mockDataStatus is "disabled"
robot.brain.set 'isMockData',false
else
msg.reply "Sorry, command not recognized!"
return
msg.reply "Mock data status set to : " + mockDataStatus
################################################################################
#robot.commands.push "hubot set project to <Project Name or ID> - Sets the project."
#robot.respond /set project to (.*)/i, (msg) ->
robot.e.create {verb:'set',entity:'project',
regex_suffix:{re: "to (.*)", optional: false},
help: 'Sets the project to Project Name or ID',type:'respond',
example: 'to Default Project or 12'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the variable part of the message (i.e. the project id or name)
strProject = msg.match[1]
robot.http("http://localhost:8080/hubot/stormrunner/proxy/setProject?project=#{strProject}")
.get() (err, res, body) ->
# If we cannot find this run, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error setting your desired project'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
setProject = JSON.parse body
attachments = []
msgData = {
channel: msg.message.room
text: "I'll set the project to be #{strProject}. Do you also want me to shut down all the garbage smashers on the detention level?"
attachments: attachments
}
#robot.emit 'slack.attachment', msgData
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: mock data status
#
# Description: Shows the current status of the mock data flag
#
# Called From: (Direct from Chat client by typing the command 'mock data
# status')
#
# Calls to: <none>
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
robot.respond /mock data status/i, (msg) ->
mockDataStatus = robot.brain.get 'isMockData'
msg.reply "Mock data status is #{mockDataStatus}"
############################################################################
# Name: set share room <channel name>
#
# Description: sets the room (channel) in which to post information
#
# Called From: (Direct from Chat client by typing the command 'set share
# room <channel name with a hash>')
#
# Calls to: <none>
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
robot.respond /set share room (.*)/i, (msg) ->
shareRoom= msg.match[1]
robot.brain.set "shareRoom",shareRoom
msg.reply "Share room set to #{shareRoom}"
############################################################################
# Name: get share room
#
# Description: Shows the current state of the share room (channel)
#
# Called From: (Direct from Chat client by typing the command 'mock data
# status')
#
# Calls to: <none>
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
robot.respond /get share room/i, (msg) ->
shareRoom= robot.brain.get "shareRoom"
msg.reply "Share room is #{shareRoom}"
############################################################################
# Name: get errror instance
#
# Description: ?????
#
# Called From: (Direct from Chat client by typing the command 'get error
# instance')
#
# Calls to: <none>
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
robot.respond /get error instance/i, (msg) ->
Helpers.setSharingRoom(robot,msg)
Helpers.shareToRoom(robot)
############################################################################
# Name: share to room
#
# Description: ???? (Doesn't work)
#
# Called From: (Direct from Chat client by typing the command 'share to room')
#
# Calls to: <none>
#
# Author(s): Cyrus Manouchehrian (inital version)
# Will Zuill
############################################################################
robot.respond /share to room/i, (msg) ->
Helpers.shareToRoom(robot)
############################################################################
# Name: catchAll
#
# Description: If none of the above commands are typed, then check to see
# if we are talking to the bot
#
# Called from: not being called from anywhere - a trapping function
#
# Calls to: setSharingRoom(helpers.coffee)
# sendCustomMessage(helpers.cofee)
#
# Author(s): Cyrus Manouchehrian
# Will Zuill
############################################################################
robot.catchAll (msg) ->
# Check to see if either the robot alias or name is in the contents of the message
# (we have to check for both with and without an @ symbol)
rexBotCalled = new RegExp "^(?:#{robot.alias}|@#{robot.alias}#{robot.name}|@#{robot.name}) (.*)","i"
strMessMatch = msg.message.text.match(rexBotCalled)
# if it does match (and therefore we are talkig to the bot directly) then send a message
if strMessMatch != null && strMessMatch.length > 1
Helpers.setSharingRoom(robot,msg)
msgData = {
channel: msg.message.room
text: "You want to do WHAT with me? That's illegal in all 50 states. Let's check the help."
}
Helpers.sendCustomMessage(robot,msgData)
| 118924 | ###
File Name: stormrunner-bot-logic.coffee
Written in: Coffee Script
Description: This file contains the routines that 'listen' for the user to type
various commands. Each of the available commands are listed below
and once the robot 'hears' the command, it processes the code contained
within the rountine. For example, if a user asks the bot to 'list projects'
the code under the routine robot.respond /list projects/i, (msg) is processed.
Upon completion of the rountine, the robot returns to 'listen' mode.
Author(s): <NAME> (Inital Version)
<NAME>
Copyright information:
Copyright 2016 Hewlett-Packard Development Company, L.P.
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.
###
# Configuration:
# HUBOT_SLACK_TOKEN "" Slack token for hubot
# https_proxy "" Proxy used for hubot
# SRL_SAAS_PREFIX "https://stormrunner-load.saas.hpe.com/v1" SaaS Rest API URL
# SRL_USERNAME "" Username to StormRunner Load
# SRL_PASSWORD "" <PASSWORD>
# SRL_TENANT_ID "" Tenant ID to StormRunner Load
#
# Set the file dependancies
Helpers = require './helpers'
StormrunnerApi = require "./libs/stormrunnerApiAdapter.js"
mockData = require "./mockData"
util = require('util')
module.exports = (robot) ->
Helpers.setRobot(robot)
robot.e.registerIntegration({short_desc: 'StormRunner Load hubot chatops integration', name: 'srl'})
################################################################################
# Name: list projects
#
# Description: Gets the current list of SRL projects detailed in the local
# hubot local web server. The local web server is populated in the
# 'get projects' section of the file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'list projects')
#
# Calls to: 'get projects' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): <NAME> (inital Version)
# <NAME>
################################################################################
# Add command to hubot help
#robot.commands.push "hubot list projects - Lists all the projects in the supplied tenant."
# listen for the response....
#robot.respond /list projects/i, (msg) ->
robot.e.create {verb:'list',entity:'projects',help: 'Lists all projects in supplied tenant',type:'respond'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Get the list of projects from the local Hubot web server. This will cause
# the 'get projects' section to fire in the file srl-openapi-proxy.coffee
# should the list of projects need to be populated or updated.
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getProjects")
.get() (err, res, body) ->
if err or res.statusCode!=200
# If we cannot find any projects, display the error code and drop.
msg.reply 'Sorry, there was an error retrieving the projects'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
# Format the returned list of projects as a JSON string
prjs = JSON.parse body
# Initialize all variables
attachments = []
strPrjID = ""
strPrjName = ""
# Loop through returned list of projects
for index,value of prjs
#console.log "Getting project for : #{value.id}"
# Append each project ID and Name to a two single string seperated
# by a carriage return (\n)
strPrjID = strPrjID + value.id + "\n"
strPrjName = strPrjName + value.name + "\n"
# End of Loop
# Format the list of projects (id and name) as a SLACK attachment
fields =
color : "#0000FF" # Add a Blue line
fields : [
{
title: "Project ID"
value: strPrjID
short: true
},
{
title: "Project Name"
value: strPrjName
short: true
}
]
attachments.push(fields)
#console.log("room="+msg.message.room)
# Construct a SLACK message to send to the appropriate chat room.
msgData = {
channel: msg.message.room
text: "Projects for tenant #{StormrunnerApi.getTenantId()}"
attachments: attachments
}
# Send the built message to the chat client/room.
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: list tests for project X
#
# Description: Gets a list of all the tests for the passed in SRL project name or
# project ID from the hubot local web server. The local web server
# is populated in the 'get Tests' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'list tests for
# project X')
#
# Calls to: 'get Tests' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
# Add command to hubot help
#robot.commands.push "hubot list tests - Lists all the tests for previously set project name or ID."
#robot.respond /list tests/i, (msg) ->
robot.e.create {verb:'list',entity:'tests',help: 'Lists all tests for previously set project name or ID',type:'respond'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the first variable part of the message (i.e. the project Name or
# Project ID)
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing tests for project #{intProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getTests?project=#{intProject}")
.get() (err, res, body) ->
# If we cannot find any tests, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the tests'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
tests = JSON.parse body
# Initalize all variables
attachments = []
strTestID = ""
strTestNameDate = ""
strTestDate = ""
strTestName = ""
intDate = 0
objDate = []
# if we have more than 10 runs
if tests.length > 20
# Display a message and remove all results after the 10th array element
strMessage = "There are a total of #{tests.length} tests in #{strProject}. We are displaying 20."
tests.splice(20,tests.length-20)
else
strMessage = "Here are all the tests in project #{strProject}"
# Loop through returned list of tests
for index,value of tests
#console.log "Getting tests for : #{value.id}"
# Append each Test ID to a single string seperated
# by a carriage return (\n)
strTestID = strTestID + value.id + "\n"
strTestName = strTestName + value.name + "\n"
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(value.createDate)
objDate = new Date(intDate)
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strTestDate = StormrunnerApi.fmtDate(objDate)
# As the 'attachment' formatting only has two columns and we want to
# display three (ID, Name and Creation Date) we need to format name
# and creation date into a single string. Therefore format it as:
# Test Name <TAB> (Test Creation Date)
strTestNameDate = strTestNameDate + value.name + "\t(" + strTestDate + ")" + "\n"
# End of Loop
# Format the list of tests (id and name/creation date) as a SLACK attachment
fields =
color : "#0000FF" # Add a Blue line
#footer: "----------------------------------------------------------------------------------------"
fields : [
{
title: "Test ID"
value: strTestID
short: true
},
{
title: "Test Name"
value: strTestName
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: strMessage
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: show latest run for test X in project Y
#
# Description: shows test details for the latest run of a test (the test ID is
# passed in) in a passed in project from the hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show latest run
# for test X in Project Y')
#
# Calls to: 'get runs' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
# Add command to hubot help
#robot.commands.push "hubot show latest run for test <test id> - Displays the latest run information for supplied test ID."
#robot.respond /show latest run for test (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'latest',
regex_suffix:{re: "run for test (.*)", optional: false},
help: 'Displays the latest run information for supplied test ID',type:'respond',
example: 'run for test 1234'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the two variables part of the message (i.e. first the Test ID and then the project Name or
# Project ID)
strTestId = msg.match[1]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing latest run for test #{strTestId} in Project #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRuns?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any tests, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the run for this test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
run = JSON.parse(body)
# Initialize all variables
attachments = []
strTestName = ""
strStartDate = ""
strDuration = ""
intDate = 0
intDuration = 0
objDate = []
# Set the test name
strTestName = run[0].testName
strColor = Helpers.getColor(robot,run[0].status)
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date @SRL I’m working on <NAME>’s Projectinto a number
# and then a date object.
intDate = Number(run[0].startOn)
objDate = new Date(intDate)
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strStartDate = StormrunnerApi.fmtDate(objDate)
# The duration is stored in Microseconds. Thus, convert the returned
# string to an integer and call the function to format the duration
# into HH:MM:SS
intDuration = Number(run[0].duration)
strDuration = StormrunnerApi.fmtDuration(intDuration)
# Format the returned parameters as a SLACK attachment
fields =
color: strColor
fields : [
{
title: "Run ID"
value: run[0].id
short: true
},
{
title: "Status"
value: run[0].status
short: true
},
{
title: "Start Date"
value: strStartDate
short: true
},
{
title: "Duration"
value: strDuration
short: true
},
{
title: "Virtual Users Used"
value: run[0].vusersNum
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: "Latest run result for test #{strTestName} in project #{strProject}"
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: show runs for test X in project Y
#
# Description: Shows run details for the a test (the test ID is passed in)
# in a passed in project from the hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show runs
# for test X in Project Y')
#
# Calls to: 'get runs' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
# Add command to hubot help
#robot.commands.push "hubot show runs for test <test id> - Displays run information up to 10 runs for supplied test ID in project Name/ID."
#robot.respond /show runs for test (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'runs',
regex_suffix:{re: "for test (.*)", optional: false},
help: 'Displays run information for up to 10 runs for supplied test ID in project name/ID',type:'respond',
example: 'for test 123'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the two variables part of the message (i.e. first the Test ID and then the project Name or
# Project ID)
strTestId = msg.match[1]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing runs for test #{strTestId} in Project #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRuns?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any tests, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the runs for the test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
runs = JSON.parse(body)
# Initialize all variables
attachments = []
strTestName = ""
strMessage = ""
strStartDate = ""
strDuration = ""
strTestName = ""
intDate = 0
intDuration = 0
objDate = []
strTestName = runs[0].testName
# if we have more than 10 runs
if runs.length > 10
# Display a message and remove all results after the 10th array element
strMessage = "There are a total of #{runs.length} for test #{strTestName} in project #{strProject}. Only displaying last 10."
runs.splice(10,runs.length-10)
else
strMessage = "The last #{runs.length} run results for test #{strTestName} in project #{strProject}"
# for each of the runs
for index,value of runs
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(value.startOn)
objDate = new Date(intDate)
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strStartDate = StormrunnerApi.fmtDate(objDate)
# The duration is stored in Microseconds. Thus, convert the returned
# string to an integer and call the function to format the duration
# into HH:MM:SS
intDuration = Number(value.duration)
strDuration = StormrunnerApi.fmtDuration(intDuration)
strColor = Helpers.getColor(robot,value.status)
# Format the returned parameters as a SLACK attachment
fields =
color : strColor
footer: "----------------------------------------------------------------------------------------"
fields : [
{
title: "Run ID"
value: value.id
short: true
},
{
title: "Status"
value: value.status
short: true
},
{
title: "Start Date"
value: strStartDate
short: true
},
{
title: "Duration"
value: strDuration
short: true
},
{
title: "Virtual Users Used"
value: value.vusersNum
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: strMessage
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: list status for last X runs for test Y in project Z
#
# Description: Shows X (num of runs is passed in) number run details for the a
# test (the test ID is passed in) in a passed in project from the
# hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show runs
# for test X in Project Y')
#
# Calls to: 'get runs' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
# Add command to hubot help
#robot.commands.push "hubot list status for last <num of runs> runs for test <test id> - Displays the run information for X number of runs for supplied test ID in project Name/ID."
#robot.respond /list status for last (.*) runs for test (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'status',
regex_suffix:{re: "for last (.*) runs for test (.*)", optional: false},
help: 'Displays the run information for X number of runs for supplied test ID in project Name/ID',type:'respond',
example: 'for last 5 runs for test 123'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the three variables part of the message (i.e. first the number of runs, followed by
# the Test ID and then the project Name or Project ID)
strRunCnt = msg.match[1]
strTestId = msg.match[2]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing runs for test #{strTestId} in Project #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRuns?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any runs for the test, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the runs for the test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
runs = JSON.parse(body)
# Initialize all variables
attachments = []
strTestName = ""
strMessage = ""
strStartDate = ""
strDuration = ""
strHrs = ""
strMins = ""
strSecs = ""
intDate = 0
intDuration = 0
objDate = []
strColor = ""
strTestName = runs[0].testName
# if the number of runs is less than the asked for runs
if runs.length < Number(strRunCnt)
# Display a message saying we can only display X runs
strMessage = "There are only #{runs.length} runs for test #{strTestName} in project #{strProject}."
else
# if the total number of runs is greater than then number of runs asked for, then trim the
# array to limit it to the passed in number
if runs.length > Number(strRunCnt)
runs.splice(Number(strRunCnt),runs.length-Number(strRunCnt))
strMessage = "The last #{runs.length} run results for test #{strTestName} in project #{strProject}"
# for each of the runs
for index,value of runs
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(value.startOn)
objDate = new Date(intDate)
# We need need to get the time, therefore extract the hours, mins and seconds
# and convert them to a string
strHrs = objDate.getHours().toString()
strMins = objDate.getMinutes().toString()
strSecs = objDate.getSeconds().toString()
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strStartDate = StormrunnerApi.fmtDate(objDate) + " " + strHrs.lpad("0",2) + ":" + strMins.lpad("0",2) + ":" + strSecs.lpad("0",2)
# The duration is stored in Microseconds. Thus, convert the returned
# string to an integer and call the function to format the duration
# into HH:MM:SS
intDuration = Number(value.duration)
strDuration = StormrunnerApi.fmtDuration(intDuration)
strColor = Helpers.getColor(robot,value.status)
# Format the returned parameters as a SLACK attachment
fields =
color : strColor
footer: "----------------------------------------------------------------------------------------"
fields : [
{
title: "Run ID"
value: value.id
short: true
},
{
title: "Status"
value: value.status
short: true
},
{
title: "Start Date"
value: strStartDate
short: true
},
{
title: "Duration"
value: strDuration
short: true
},
{
title: "Virtual Users Used"
value: value.vusersNum
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: strMessage
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: show full results for run id X
#
# Description: Shows all the results for a run run ID is passed in) from the
# hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show full
# results for run id X')
#
# Calls to: 'get Run Results' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
# Add command to hubot help
#robot.commands.push "hubot show results for run id <Run id> - Displays results information for supplied run ID."
#robot.respond /show results for run id (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'results',
regex_suffix:{re: "for run (.*)", optional: false},
help: 'Displays results information for supplied run ID',type:'respond',
example: 'for run 123'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the variable part of the message (i.e. the run id)
strRunid = msg.match[1]
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRunResults?runid=#{strRunid}")
.get() (err, res, body) ->
# If we cannot find this run, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the run results'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
rslt = JSON.parse body
# Initialize all variables
attachments = []
strStartTime = ""
strEndTime = ""
strHrs = ""
strMins = ""
strSecs = ""
intDate = 0
objDate = []
strColor = ""
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(rslt.startTime)
objDate = new Date(intDate)
# We need need to get the time, therefore extract the hours, mins and seconds
# and convert them to a string
strHrs = objDate.getHours().toString()
strMins = objDate.getMinutes().toString()
strSecs = objDate.getSeconds().toString()
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!) and add on the time
strStartTime = StormrunnerApi.fmtDate(objDate) + " " + strHrs.lpad("0",2) + ":" + strMins.lpad("0",2) + ":" + strSecs.lpad("0",2)
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(rslt.endTime)
objDate = new Date(intDate)
# We need need to get the time, therefore extract the hours, mins and seconds
# and convert them to a string
strHrs = objDate.getHours().toString()
strMins = objDate.getMinutes().toString()
strSecs = objDate.getSeconds().toString()
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!) and add on the time.
strEndTime = StormrunnerApi.fmtDate(objDate) + " " + strHrs.lpad("0",2) + ":" + strMins.lpad("0",2) + ":" + strSecs.lpad("0",2)
strColor = Helpers.getColor(robot,rslt.uiStatus)
strMessage = Helpers.getQuote(robot,rslt.uiStatus)
fields =
color : strColor
fields : [
{
title: "Test ID"
value: rslt.testId
short: true
},
{
title: "UI Status"
value: rslt.uiStatus
short: true
},
{
title: "Start Time"
value: strStartTime
short: true
},
{
title: "End Time"
value: strEndTime
short: true
}
]
#check to see if VU's or VUH's are used and output correct format
#if VuserNum is greater than 0 and cost is defined (meaning a number is there)
#output both labels and values
#if there is only VuserNum, just output that label and value
#we are separating each license type used into its own array
if (rslt.uiVusersNum > 0 && rslt.actualUiCost != undefined)
uiusers = [
{
title: "UI Virtual Users"
value: rslt.uiVusersNum
short: true
},
{
title: "Actual UI Cost"
value: rslt.actualUiCost
short: true
}
]
#this is concatenating all the arrays used into one array, which gets
#pushed to the Attachments array
fields.fields = fields.fields.concat(uiusers)
else if (rslt.uiVusersNum > 0)
uiusers = [
{
title: "UI Virtual Users"
value: rslt.uiVusersNum
short: true
}
]
fields.fields = fields.fields.concat(uiusers)
if (rslt.apiVusersNum > 0 && rslt.actualApiCost != undefined)
apiusers = [
{
title: "API Virtual Users"
value: rslt.apiVusersNum
short: true
},
{
title: "Actual API Cost"
value: rslt.actualApiCost
short: true
}
]
fields.fields = fields.fields.concat(apiusers)
else if (rslt.apiVusersNum > 0)
apiusers = [
{
title: "API Virtual Users"
value: rslt.apiVusersNum
short: true
}
]
fields.fields = fields.fields.concat(apiusers)
if (rslt.devVusersNum > 0 && rslt.actualDevCost != undefined)
devusers = [
{
title: "DEV Virtual Users"
value: rslt.devVusersNum
short: true
},
{
title: "Actual DEV Cost"
value: rslt.actualDevCost
short: true
}
]
fields.fields = fields.fields.concat(devusers)
else if (rslt.devVusersNum > 0)
devusers = [
{
title: "DEV Virtual Users"
value: rslt.devVusersNum
short: true
}
]
fields.fields = fields.fields.concat(devusers)
attachments.push(fields)
msgData = {
channel: msg.message.room
text: "Here are the run results for run id #{strRunid}. " + strMessage
attachments: attachments
}
#robot.emit 'slack.attachment', msgData
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: run test
#
# Description: Tells the bot to run specified test ID
#
# Called From: (Direct from Chat client by typing the command 'run test (id)')
#
# Calls to: 'post Run' section (srl-openapi-proxy.coffee)
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
# Add command to hubot help
#robot.commands.push "hubot run test <test id> - Executes the supplied test ID project Name/ID."
#robot.respond /run test (.*)/i, (msg) ->
robot.e.create {verb:'run',entity:'test',
regex_suffix:{re: "(.*)", optional: false},
help: 'Executes the supplied test ID project Name/ID',type:'respond',
example: '1234'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the three variables part of the message (i.e. first the number of runs, followed by
# the Test ID and then the project Name or Project ID)
strTestId = msg.match[1]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Running test #{strTestId} in #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/postRun?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any runs for the test, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the runs for the test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
runs = JSON.parse(body)
# Initialize all variables
attachments = []
# Send the built message to the chat client/room.
# Send URL to runs page of specified test
strURL = ""
strURL = util.format('https://stormrunner-load.saas.hpe.com/loadTests/%s/runs/?TENANTID=%s&projectId=%s', strTestId, process.env.SRL_TENANT_ID, intProject)
msgData = {
channel: msg.message.room
text: "Your test is initializing and the Run ID is #{runs.runId}. Would you like a side of fries with that? \n #{strURL}"
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: set mock data <enabled/disabled>
#
# Description: Tells the bot to use mock data instead of pulling from
# the API's
#
# Called From: (Direct from Chat client by typing the command 'set mock
# data <enabled/disabled>')
#
# Calls to: <none>
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
robot.respond /set mock data (.*)/i, (msg) ->
robot.e.create {verb:'set',entity:'mock',
regex_suffix:{re: "data (.*)", optional: false},
help: 'Set Mock Data to enabled or disabled',type:'respond',
example: 'data enabled'},(msg)->
mockDataStatus= msg.match[1]
if mockDataStatus is "enabled"
robot.brain.set 'isMockData',true
else if mockDataStatus is "disabled"
robot.brain.set 'isMockData',false
else
msg.reply "Sorry, command not recognized!"
return
msg.reply "Mock data status set to : " + mockDataStatus
################################################################################
#robot.commands.push "hubot set project to <Project Name or ID> - Sets the project."
#robot.respond /set project to (.*)/i, (msg) ->
robot.e.create {verb:'set',entity:'project',
regex_suffix:{re: "to (.*)", optional: false},
help: 'Sets the project to Project Name or ID',type:'respond',
example: 'to Default Project or 12'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the variable part of the message (i.e. the project id or name)
strProject = msg.match[1]
robot.http("http://localhost:8080/hubot/stormrunner/proxy/setProject?project=#{strProject}")
.get() (err, res, body) ->
# If we cannot find this run, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error setting your desired project'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
setProject = JSON.parse body
attachments = []
msgData = {
channel: msg.message.room
text: "I'll set the project to be #{strProject}. Do you also want me to shut down all the garbage smashers on the detention level?"
attachments: attachments
}
#robot.emit 'slack.attachment', msgData
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: mock data status
#
# Description: Shows the current status of the mock data flag
#
# Called From: (Direct from Chat client by typing the command 'mock data
# status')
#
# Calls to: <none>
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
robot.respond /mock data status/i, (msg) ->
mockDataStatus = robot.brain.get 'isMockData'
msg.reply "Mock data status is #{mockDataStatus}"
############################################################################
# Name: set share room <channel name>
#
# Description: sets the room (channel) in which to post information
#
# Called From: (Direct from Chat client by typing the command 'set share
# room <channel name with a hash>')
#
# Calls to: <none>
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
robot.respond /set share room (.*)/i, (msg) ->
shareRoom= msg.match[1]
robot.brain.set "shareRoom",shareRoom
msg.reply "Share room set to #{shareRoom}"
############################################################################
# Name: get share room
#
# Description: Shows the current state of the share room (channel)
#
# Called From: (Direct from Chat client by typing the command 'mock data
# status')
#
# Calls to: <none>
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
robot.respond /get share room/i, (msg) ->
shareRoom= robot.brain.get "shareRoom"
msg.reply "Share room is #{shareRoom}"
############################################################################
# Name: get errror instance
#
# Description: ?????
#
# Called From: (Direct from Chat client by typing the command 'get error
# instance')
#
# Calls to: <none>
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
robot.respond /get error instance/i, (msg) ->
Helpers.setSharingRoom(robot,msg)
Helpers.shareToRoom(robot)
############################################################################
# Name: share to room
#
# Description: ???? (Doesn't work)
#
# Called From: (Direct from Chat client by typing the command 'share to room')
#
# Calls to: <none>
#
# Author(s): <NAME> (inital version)
# <NAME>
############################################################################
robot.respond /share to room/i, (msg) ->
Helpers.shareToRoom(robot)
############################################################################
# Name: catchAll
#
# Description: If none of the above commands are typed, then check to see
# if we are talking to the bot
#
# Called from: not being called from anywhere - a trapping function
#
# Calls to: setSharingRoom(helpers.coffee)
# sendCustomMessage(helpers.cofee)
#
# Author(s): <NAME>
# <NAME>
############################################################################
robot.catchAll (msg) ->
# Check to see if either the robot alias or name is in the contents of the message
# (we have to check for both with and without an @ symbol)
rexBotCalled = new RegExp "^(?:#{robot.alias}|@#{robot.alias}#{robot.name}|@#{robot.name}) (.*)","i"
strMessMatch = msg.message.text.match(rexBotCalled)
# if it does match (and therefore we are talkig to the bot directly) then send a message
if strMessMatch != null && strMessMatch.length > 1
Helpers.setSharingRoom(robot,msg)
msgData = {
channel: msg.message.room
text: "You want to do WHAT with me? That's illegal in all 50 states. Let's check the help."
}
Helpers.sendCustomMessage(robot,msgData)
| true | ###
File Name: stormrunner-bot-logic.coffee
Written in: Coffee Script
Description: This file contains the routines that 'listen' for the user to type
various commands. Each of the available commands are listed below
and once the robot 'hears' the command, it processes the code contained
within the rountine. For example, if a user asks the bot to 'list projects'
the code under the routine robot.respond /list projects/i, (msg) is processed.
Upon completion of the rountine, the robot returns to 'listen' mode.
Author(s): PI:NAME:<NAME>END_PI (Inital Version)
PI:NAME:<NAME>END_PI
Copyright information:
Copyright 2016 Hewlett-Packard Development Company, L.P.
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.
###
# Configuration:
# HUBOT_SLACK_TOKEN "" Slack token for hubot
# https_proxy "" Proxy used for hubot
# SRL_SAAS_PREFIX "https://stormrunner-load.saas.hpe.com/v1" SaaS Rest API URL
# SRL_USERNAME "" Username to StormRunner Load
# SRL_PASSWORD "" PI:PASSWORD:<PASSWORD>END_PI
# SRL_TENANT_ID "" Tenant ID to StormRunner Load
#
# Set the file dependancies
Helpers = require './helpers'
StormrunnerApi = require "./libs/stormrunnerApiAdapter.js"
mockData = require "./mockData"
util = require('util')
module.exports = (robot) ->
Helpers.setRobot(robot)
robot.e.registerIntegration({short_desc: 'StormRunner Load hubot chatops integration', name: 'srl'})
################################################################################
# Name: list projects
#
# Description: Gets the current list of SRL projects detailed in the local
# hubot local web server. The local web server is populated in the
# 'get projects' section of the file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'list projects')
#
# Calls to: 'get projects' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): PI:NAME:<NAME>END_PI (inital Version)
# PI:NAME:<NAME>END_PI
################################################################################
# Add command to hubot help
#robot.commands.push "hubot list projects - Lists all the projects in the supplied tenant."
# listen for the response....
#robot.respond /list projects/i, (msg) ->
robot.e.create {verb:'list',entity:'projects',help: 'Lists all projects in supplied tenant',type:'respond'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Get the list of projects from the local Hubot web server. This will cause
# the 'get projects' section to fire in the file srl-openapi-proxy.coffee
# should the list of projects need to be populated or updated.
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getProjects")
.get() (err, res, body) ->
if err or res.statusCode!=200
# If we cannot find any projects, display the error code and drop.
msg.reply 'Sorry, there was an error retrieving the projects'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
# Format the returned list of projects as a JSON string
prjs = JSON.parse body
# Initialize all variables
attachments = []
strPrjID = ""
strPrjName = ""
# Loop through returned list of projects
for index,value of prjs
#console.log "Getting project for : #{value.id}"
# Append each project ID and Name to a two single string seperated
# by a carriage return (\n)
strPrjID = strPrjID + value.id + "\n"
strPrjName = strPrjName + value.name + "\n"
# End of Loop
# Format the list of projects (id and name) as a SLACK attachment
fields =
color : "#0000FF" # Add a Blue line
fields : [
{
title: "Project ID"
value: strPrjID
short: true
},
{
title: "Project Name"
value: strPrjName
short: true
}
]
attachments.push(fields)
#console.log("room="+msg.message.room)
# Construct a SLACK message to send to the appropriate chat room.
msgData = {
channel: msg.message.room
text: "Projects for tenant #{StormrunnerApi.getTenantId()}"
attachments: attachments
}
# Send the built message to the chat client/room.
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: list tests for project X
#
# Description: Gets a list of all the tests for the passed in SRL project name or
# project ID from the hubot local web server. The local web server
# is populated in the 'get Tests' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'list tests for
# project X')
#
# Calls to: 'get Tests' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
# Add command to hubot help
#robot.commands.push "hubot list tests - Lists all the tests for previously set project name or ID."
#robot.respond /list tests/i, (msg) ->
robot.e.create {verb:'list',entity:'tests',help: 'Lists all tests for previously set project name or ID',type:'respond'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the first variable part of the message (i.e. the project Name or
# Project ID)
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing tests for project #{intProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getTests?project=#{intProject}")
.get() (err, res, body) ->
# If we cannot find any tests, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the tests'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
tests = JSON.parse body
# Initalize all variables
attachments = []
strTestID = ""
strTestNameDate = ""
strTestDate = ""
strTestName = ""
intDate = 0
objDate = []
# if we have more than 10 runs
if tests.length > 20
# Display a message and remove all results after the 10th array element
strMessage = "There are a total of #{tests.length} tests in #{strProject}. We are displaying 20."
tests.splice(20,tests.length-20)
else
strMessage = "Here are all the tests in project #{strProject}"
# Loop through returned list of tests
for index,value of tests
#console.log "Getting tests for : #{value.id}"
# Append each Test ID to a single string seperated
# by a carriage return (\n)
strTestID = strTestID + value.id + "\n"
strTestName = strTestName + value.name + "\n"
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(value.createDate)
objDate = new Date(intDate)
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strTestDate = StormrunnerApi.fmtDate(objDate)
# As the 'attachment' formatting only has two columns and we want to
# display three (ID, Name and Creation Date) we need to format name
# and creation date into a single string. Therefore format it as:
# Test Name <TAB> (Test Creation Date)
strTestNameDate = strTestNameDate + value.name + "\t(" + strTestDate + ")" + "\n"
# End of Loop
# Format the list of tests (id and name/creation date) as a SLACK attachment
fields =
color : "#0000FF" # Add a Blue line
#footer: "----------------------------------------------------------------------------------------"
fields : [
{
title: "Test ID"
value: strTestID
short: true
},
{
title: "Test Name"
value: strTestName
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: strMessage
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: show latest run for test X in project Y
#
# Description: shows test details for the latest run of a test (the test ID is
# passed in) in a passed in project from the hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show latest run
# for test X in Project Y')
#
# Calls to: 'get runs' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
# Add command to hubot help
#robot.commands.push "hubot show latest run for test <test id> - Displays the latest run information for supplied test ID."
#robot.respond /show latest run for test (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'latest',
regex_suffix:{re: "run for test (.*)", optional: false},
help: 'Displays the latest run information for supplied test ID',type:'respond',
example: 'run for test 1234'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the two variables part of the message (i.e. first the Test ID and then the project Name or
# Project ID)
strTestId = msg.match[1]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing latest run for test #{strTestId} in Project #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRuns?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any tests, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the run for this test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
run = JSON.parse(body)
# Initialize all variables
attachments = []
strTestName = ""
strStartDate = ""
strDuration = ""
intDate = 0
intDuration = 0
objDate = []
# Set the test name
strTestName = run[0].testName
strColor = Helpers.getColor(robot,run[0].status)
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date @SRL I’m working on PI:NAME:<NAME>END_PI’s Projectinto a number
# and then a date object.
intDate = Number(run[0].startOn)
objDate = new Date(intDate)
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strStartDate = StormrunnerApi.fmtDate(objDate)
# The duration is stored in Microseconds. Thus, convert the returned
# string to an integer and call the function to format the duration
# into HH:MM:SS
intDuration = Number(run[0].duration)
strDuration = StormrunnerApi.fmtDuration(intDuration)
# Format the returned parameters as a SLACK attachment
fields =
color: strColor
fields : [
{
title: "Run ID"
value: run[0].id
short: true
},
{
title: "Status"
value: run[0].status
short: true
},
{
title: "Start Date"
value: strStartDate
short: true
},
{
title: "Duration"
value: strDuration
short: true
},
{
title: "Virtual Users Used"
value: run[0].vusersNum
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: "Latest run result for test #{strTestName} in project #{strProject}"
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: show runs for test X in project Y
#
# Description: Shows run details for the a test (the test ID is passed in)
# in a passed in project from the hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show runs
# for test X in Project Y')
#
# Calls to: 'get runs' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
# Add command to hubot help
#robot.commands.push "hubot show runs for test <test id> - Displays run information up to 10 runs for supplied test ID in project Name/ID."
#robot.respond /show runs for test (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'runs',
regex_suffix:{re: "for test (.*)", optional: false},
help: 'Displays run information for up to 10 runs for supplied test ID in project name/ID',type:'respond',
example: 'for test 123'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the two variables part of the message (i.e. first the Test ID and then the project Name or
# Project ID)
strTestId = msg.match[1]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing runs for test #{strTestId} in Project #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRuns?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any tests, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the runs for the test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
runs = JSON.parse(body)
# Initialize all variables
attachments = []
strTestName = ""
strMessage = ""
strStartDate = ""
strDuration = ""
strTestName = ""
intDate = 0
intDuration = 0
objDate = []
strTestName = runs[0].testName
# if we have more than 10 runs
if runs.length > 10
# Display a message and remove all results after the 10th array element
strMessage = "There are a total of #{runs.length} for test #{strTestName} in project #{strProject}. Only displaying last 10."
runs.splice(10,runs.length-10)
else
strMessage = "The last #{runs.length} run results for test #{strTestName} in project #{strProject}"
# for each of the runs
for index,value of runs
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(value.startOn)
objDate = new Date(intDate)
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strStartDate = StormrunnerApi.fmtDate(objDate)
# The duration is stored in Microseconds. Thus, convert the returned
# string to an integer and call the function to format the duration
# into HH:MM:SS
intDuration = Number(value.duration)
strDuration = StormrunnerApi.fmtDuration(intDuration)
strColor = Helpers.getColor(robot,value.status)
# Format the returned parameters as a SLACK attachment
fields =
color : strColor
footer: "----------------------------------------------------------------------------------------"
fields : [
{
title: "Run ID"
value: value.id
short: true
},
{
title: "Status"
value: value.status
short: true
},
{
title: "Start Date"
value: strStartDate
short: true
},
{
title: "Duration"
value: strDuration
short: true
},
{
title: "Virtual Users Used"
value: value.vusersNum
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: strMessage
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: list status for last X runs for test Y in project Z
#
# Description: Shows X (num of runs is passed in) number run details for the a
# test (the test ID is passed in) in a passed in project from the
# hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show runs
# for test X in Project Y')
#
# Calls to: 'get runs' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
# Add command to hubot help
#robot.commands.push "hubot list status for last <num of runs> runs for test <test id> - Displays the run information for X number of runs for supplied test ID in project Name/ID."
#robot.respond /list status for last (.*) runs for test (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'status',
regex_suffix:{re: "for last (.*) runs for test (.*)", optional: false},
help: 'Displays the run information for X number of runs for supplied test ID in project Name/ID',type:'respond',
example: 'for last 5 runs for test 123'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the three variables part of the message (i.e. first the number of runs, followed by
# the Test ID and then the project Name or Project ID)
strRunCnt = msg.match[1]
strTestId = msg.match[2]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Showing runs for test #{strTestId} in Project #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRuns?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any runs for the test, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the runs for the test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
runs = JSON.parse(body)
# Initialize all variables
attachments = []
strTestName = ""
strMessage = ""
strStartDate = ""
strDuration = ""
strHrs = ""
strMins = ""
strSecs = ""
intDate = 0
intDuration = 0
objDate = []
strColor = ""
strTestName = runs[0].testName
# if the number of runs is less than the asked for runs
if runs.length < Number(strRunCnt)
# Display a message saying we can only display X runs
strMessage = "There are only #{runs.length} runs for test #{strTestName} in project #{strProject}."
else
# if the total number of runs is greater than then number of runs asked for, then trim the
# array to limit it to the passed in number
if runs.length > Number(strRunCnt)
runs.splice(Number(strRunCnt),runs.length-Number(strRunCnt))
strMessage = "The last #{runs.length} run results for test #{strTestName} in project #{strProject}"
# for each of the runs
for index,value of runs
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(value.startOn)
objDate = new Date(intDate)
# We need need to get the time, therefore extract the hours, mins and seconds
# and convert them to a string
strHrs = objDate.getHours().toString()
strMins = objDate.getMinutes().toString()
strSecs = objDate.getSeconds().toString()
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!)
strStartDate = StormrunnerApi.fmtDate(objDate) + " " + strHrs.lpad("0",2) + ":" + strMins.lpad("0",2) + ":" + strSecs.lpad("0",2)
# The duration is stored in Microseconds. Thus, convert the returned
# string to an integer and call the function to format the duration
# into HH:MM:SS
intDuration = Number(value.duration)
strDuration = StormrunnerApi.fmtDuration(intDuration)
strColor = Helpers.getColor(robot,value.status)
# Format the returned parameters as a SLACK attachment
fields =
color : strColor
footer: "----------------------------------------------------------------------------------------"
fields : [
{
title: "Run ID"
value: value.id
short: true
},
{
title: "Status"
value: value.status
short: true
},
{
title: "Start Date"
value: strStartDate
short: true
},
{
title: "Duration"
value: strDuration
short: true
},
{
title: "Virtual Users Used"
value: value.vusersNum
short: true
}
]
attachments.push(fields)
# Send the built message to the chat client/room.
msgData = {
channel: msg.message.room
text: strMessage
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: show full results for run id X
#
# Description: Shows all the results for a run run ID is passed in) from the
# hubot local web server.
# The local web server is populated in the 'get Runs' section of the
# file srl-openaspi-proxy.coffee
#
# Called From: (Direct from Chat client by typing the command 'show full
# results for run id X')
#
# Calls to: 'get Run Results' section (srl-openapi-proxy.coffee)
# setSharingRoom (helpers.coffee)
# fmtDate (stormrunnerApiAdapter.js)
# fmtDuration (stormrunnerApiAdapter.js)
# sendCustomMessage (helpers.coffee)
# getTentantId (stormrunnerApiAdapter.js)
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
# Add command to hubot help
#robot.commands.push "hubot show results for run id <Run id> - Displays results information for supplied run ID."
#robot.respond /show results for run id (.*)/i, (msg) ->
robot.e.create {verb:'get',entity:'results',
regex_suffix:{re: "for run (.*)", optional: false},
help: 'Displays results information for supplied run ID',type:'respond',
example: 'for run 123'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the variable part of the message (i.e. the run id)
strRunid = msg.match[1]
robot.http("http://localhost:8080/hubot/stormrunner/proxy/getRunResults?runid=#{strRunid}")
.get() (err, res, body) ->
# If we cannot find this run, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the run results'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
rslt = JSON.parse body
# Initialize all variables
attachments = []
strStartTime = ""
strEndTime = ""
strHrs = ""
strMins = ""
strSecs = ""
intDate = 0
objDate = []
strColor = ""
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(rslt.startTime)
objDate = new Date(intDate)
# We need need to get the time, therefore extract the hours, mins and seconds
# and convert them to a string
strHrs = objDate.getHours().toString()
strMins = objDate.getMinutes().toString()
strSecs = objDate.getSeconds().toString()
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!) and add on the time
strStartTime = StormrunnerApi.fmtDate(objDate) + " " + strHrs.lpad("0",2) + ":" + strMins.lpad("0",2) + ":" + strSecs.lpad("0",2)
# As the date returned is in 'ticks' we need to format it
# Therefore, Convert the returned string 'tick' date into a number
# and then a date object.
intDate = Number(rslt.endTime)
objDate = new Date(intDate)
# We need need to get the time, therefore extract the hours, mins and seconds
# and convert them to a string
strHrs = objDate.getHours().toString()
strMins = objDate.getMinutes().toString()
strSecs = objDate.getSeconds().toString()
# Now we have the returned date in the right format - call a function
# to format the date into yyyy-mm-dd (tough luck USA!) and add on the time.
strEndTime = StormrunnerApi.fmtDate(objDate) + " " + strHrs.lpad("0",2) + ":" + strMins.lpad("0",2) + ":" + strSecs.lpad("0",2)
strColor = Helpers.getColor(robot,rslt.uiStatus)
strMessage = Helpers.getQuote(robot,rslt.uiStatus)
fields =
color : strColor
fields : [
{
title: "Test ID"
value: rslt.testId
short: true
},
{
title: "UI Status"
value: rslt.uiStatus
short: true
},
{
title: "Start Time"
value: strStartTime
short: true
},
{
title: "End Time"
value: strEndTime
short: true
}
]
#check to see if VU's or VUH's are used and output correct format
#if VuserNum is greater than 0 and cost is defined (meaning a number is there)
#output both labels and values
#if there is only VuserNum, just output that label and value
#we are separating each license type used into its own array
if (rslt.uiVusersNum > 0 && rslt.actualUiCost != undefined)
uiusers = [
{
title: "UI Virtual Users"
value: rslt.uiVusersNum
short: true
},
{
title: "Actual UI Cost"
value: rslt.actualUiCost
short: true
}
]
#this is concatenating all the arrays used into one array, which gets
#pushed to the Attachments array
fields.fields = fields.fields.concat(uiusers)
else if (rslt.uiVusersNum > 0)
uiusers = [
{
title: "UI Virtual Users"
value: rslt.uiVusersNum
short: true
}
]
fields.fields = fields.fields.concat(uiusers)
if (rslt.apiVusersNum > 0 && rslt.actualApiCost != undefined)
apiusers = [
{
title: "API Virtual Users"
value: rslt.apiVusersNum
short: true
},
{
title: "Actual API Cost"
value: rslt.actualApiCost
short: true
}
]
fields.fields = fields.fields.concat(apiusers)
else if (rslt.apiVusersNum > 0)
apiusers = [
{
title: "API Virtual Users"
value: rslt.apiVusersNum
short: true
}
]
fields.fields = fields.fields.concat(apiusers)
if (rslt.devVusersNum > 0 && rslt.actualDevCost != undefined)
devusers = [
{
title: "DEV Virtual Users"
value: rslt.devVusersNum
short: true
},
{
title: "Actual DEV Cost"
value: rslt.actualDevCost
short: true
}
]
fields.fields = fields.fields.concat(devusers)
else if (rslt.devVusersNum > 0)
devusers = [
{
title: "DEV Virtual Users"
value: rslt.devVusersNum
short: true
}
]
fields.fields = fields.fields.concat(devusers)
attachments.push(fields)
msgData = {
channel: msg.message.room
text: "Here are the run results for run id #{strRunid}. " + strMessage
attachments: attachments
}
#robot.emit 'slack.attachment', msgData
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: run test
#
# Description: Tells the bot to run specified test ID
#
# Called From: (Direct from Chat client by typing the command 'run test (id)')
#
# Calls to: 'post Run' section (srl-openapi-proxy.coffee)
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
# Add command to hubot help
#robot.commands.push "hubot run test <test id> - Executes the supplied test ID project Name/ID."
#robot.respond /run test (.*)/i, (msg) ->
robot.e.create {verb:'run',entity:'test',
regex_suffix:{re: "(.*)", optional: false},
help: 'Executes the supplied test ID project Name/ID',type:'respond',
example: '1234'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the three variables part of the message (i.e. first the number of runs, followed by
# the Test ID and then the project Name or Project ID)
strTestId = msg.match[1]
intProject = Helpers.myProject(robot) # Could be a Project Name or ID
strProject = Helpers.findProjName(robot,intProject)
robot.logger.debug "Running test #{strTestId} in #{strProject}"
robot.http("http://localhost:8080/hubot/stormrunner/proxy/postRun?project=#{intProject}&TestID=#{strTestId}")
.get() (err, res, body) ->
# If we cannot find any runs for the test, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error retrieving the runs for the test'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
runs = JSON.parse(body)
# Initialize all variables
attachments = []
# Send the built message to the chat client/room.
# Send URL to runs page of specified test
strURL = ""
strURL = util.format('https://stormrunner-load.saas.hpe.com/loadTests/%s/runs/?TENANTID=%s&projectId=%s', strTestId, process.env.SRL_TENANT_ID, intProject)
msgData = {
channel: msg.message.room
text: "Your test is initializing and the Run ID is #{runs.runId}. Would you like a side of fries with that? \n #{strURL}"
attachments: attachments
}
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: set mock data <enabled/disabled>
#
# Description: Tells the bot to use mock data instead of pulling from
# the API's
#
# Called From: (Direct from Chat client by typing the command 'set mock
# data <enabled/disabled>')
#
# Calls to: <none>
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
robot.respond /set mock data (.*)/i, (msg) ->
robot.e.create {verb:'set',entity:'mock',
regex_suffix:{re: "data (.*)", optional: false},
help: 'Set Mock Data to enabled or disabled',type:'respond',
example: 'data enabled'},(msg)->
mockDataStatus= msg.match[1]
if mockDataStatus is "enabled"
robot.brain.set 'isMockData',true
else if mockDataStatus is "disabled"
robot.brain.set 'isMockData',false
else
msg.reply "Sorry, command not recognized!"
return
msg.reply "Mock data status set to : " + mockDataStatus
################################################################################
#robot.commands.push "hubot set project to <Project Name or ID> - Sets the project."
#robot.respond /set project to (.*)/i, (msg) ->
robot.e.create {verb:'set',entity:'project',
regex_suffix:{re: "to (.*)", optional: false},
help: 'Sets the project to Project Name or ID',type:'respond',
example: 'to Default Project or 12'},(msg)->
Helpers.setSharingRoom(robot,msg)
# Extract the variable part of the message (i.e. the project id or name)
strProject = msg.match[1]
robot.http("http://localhost:8080/hubot/stormrunner/proxy/setProject?project=#{strProject}")
.get() (err, res, body) ->
# If we cannot find this run, display the error code and drop.
if err or res.statusCode!=200
msg.reply 'Sorry, there was an error setting your desired project'
msg.reply 'Status Code: ' + res.statusCode
return
robot.logger.debug "Res returned : \n" + body
setProject = JSON.parse body
attachments = []
msgData = {
channel: msg.message.room
text: "I'll set the project to be #{strProject}. Do you also want me to shut down all the garbage smashers on the detention level?"
attachments: attachments
}
#robot.emit 'slack.attachment', msgData
Helpers.sendCustomMessage(robot,msgData)
############################################################################
# Name: mock data status
#
# Description: Shows the current status of the mock data flag
#
# Called From: (Direct from Chat client by typing the command 'mock data
# status')
#
# Calls to: <none>
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
robot.respond /mock data status/i, (msg) ->
mockDataStatus = robot.brain.get 'isMockData'
msg.reply "Mock data status is #{mockDataStatus}"
############################################################################
# Name: set share room <channel name>
#
# Description: sets the room (channel) in which to post information
#
# Called From: (Direct from Chat client by typing the command 'set share
# room <channel name with a hash>')
#
# Calls to: <none>
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
robot.respond /set share room (.*)/i, (msg) ->
shareRoom= msg.match[1]
robot.brain.set "shareRoom",shareRoom
msg.reply "Share room set to #{shareRoom}"
############################################################################
# Name: get share room
#
# Description: Shows the current state of the share room (channel)
#
# Called From: (Direct from Chat client by typing the command 'mock data
# status')
#
# Calls to: <none>
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
robot.respond /get share room/i, (msg) ->
shareRoom= robot.brain.get "shareRoom"
msg.reply "Share room is #{shareRoom}"
############################################################################
# Name: get errror instance
#
# Description: ?????
#
# Called From: (Direct from Chat client by typing the command 'get error
# instance')
#
# Calls to: <none>
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
robot.respond /get error instance/i, (msg) ->
Helpers.setSharingRoom(robot,msg)
Helpers.shareToRoom(robot)
############################################################################
# Name: share to room
#
# Description: ???? (Doesn't work)
#
# Called From: (Direct from Chat client by typing the command 'share to room')
#
# Calls to: <none>
#
# Author(s): PI:NAME:<NAME>END_PI (inital version)
# PI:NAME:<NAME>END_PI
############################################################################
robot.respond /share to room/i, (msg) ->
Helpers.shareToRoom(robot)
############################################################################
# Name: catchAll
#
# Description: If none of the above commands are typed, then check to see
# if we are talking to the bot
#
# Called from: not being called from anywhere - a trapping function
#
# Calls to: setSharingRoom(helpers.coffee)
# sendCustomMessage(helpers.cofee)
#
# Author(s): PI:NAME:<NAME>END_PI
# PI:NAME:<NAME>END_PI
############################################################################
robot.catchAll (msg) ->
# Check to see if either the robot alias or name is in the contents of the message
# (we have to check for both with and without an @ symbol)
rexBotCalled = new RegExp "^(?:#{robot.alias}|@#{robot.alias}#{robot.name}|@#{robot.name}) (.*)","i"
strMessMatch = msg.message.text.match(rexBotCalled)
# if it does match (and therefore we are talkig to the bot directly) then send a message
if strMessMatch != null && strMessMatch.length > 1
Helpers.setSharingRoom(robot,msg)
msgData = {
channel: msg.message.room
text: "You want to do WHAT with me? That's illegal in all 50 states. Let's check the help."
}
Helpers.sendCustomMessage(robot,msgData)
|
[
{
"context": "urn\n , true\n\n commit = (key, val) ->\n key = \"cms4-#{key}\"\n #save to disk\n if val is `undefined`\n",
"end": 291,
"score": 0.9952952265739441,
"start": 284,
"tag": "KEY",
"value": "cms4-#{"
},
{
"context": "ys(localStorage).forEach (fullkey) ->\n key = /^cms4-(.*)/.test(fullkey) and RegExp.$1\n return unless",
"end": 541,
"score": 0.6894533038139343,
"start": 535,
"tag": "KEY",
"value": "cms4-("
}
] | src/admin/src/scripts/services/store.coffee | jpillora/cms4 | 1 | App.factory 'store', ($rootScope) ->
#isolate scope
scope = $rootScope.store = window.store = {}
$rootScope.$watch 'store', (s, prev) ->
for k of s
if k not of prev or s[k] isnt prev[k]
commit k, s[k]
return
, true
commit = (key, val) ->
key = "cms4-#{key}"
#save to disk
if val is `undefined`
localStorage.removeItem key
else
json = JSON.stringify(val)
localStorage.setItem key, json
return
#init
Object.keys(localStorage).forEach (fullkey) ->
key = /^cms4-(.*)/.test(fullkey) and RegExp.$1
return unless key
json = localStorage.getItem fullkey
scope[key] = JSON.parse json
scope | 86828 | App.factory 'store', ($rootScope) ->
#isolate scope
scope = $rootScope.store = window.store = {}
$rootScope.$watch 'store', (s, prev) ->
for k of s
if k not of prev or s[k] isnt prev[k]
commit k, s[k]
return
, true
commit = (key, val) ->
key = "<KEY>key}"
#save to disk
if val is `undefined`
localStorage.removeItem key
else
json = JSON.stringify(val)
localStorage.setItem key, json
return
#init
Object.keys(localStorage).forEach (fullkey) ->
key = /^<KEY>.*)/.test(fullkey) and RegExp.$1
return unless key
json = localStorage.getItem fullkey
scope[key] = JSON.parse json
scope | true | App.factory 'store', ($rootScope) ->
#isolate scope
scope = $rootScope.store = window.store = {}
$rootScope.$watch 'store', (s, prev) ->
for k of s
if k not of prev or s[k] isnt prev[k]
commit k, s[k]
return
, true
commit = (key, val) ->
key = "PI:KEY:<KEY>END_PIkey}"
#save to disk
if val is `undefined`
localStorage.removeItem key
else
json = JSON.stringify(val)
localStorage.setItem key, json
return
#init
Object.keys(localStorage).forEach (fullkey) ->
key = /^PI:KEY:<KEY>END_PI.*)/.test(fullkey) and RegExp.$1
return unless key
json = localStorage.getItem fullkey
scope[key] = JSON.parse json
scope |
[
{
"context": "\n\t\tfixLogger.error('[0] User(%s) supposed chunk '+@mname+'(%s) doesn\\'t exist. Attempting\n\t\t\tto fix it.', ",
"end": 1786,
"score": 0.8406521677970886,
"start": 1780,
"tag": "USERNAME",
"value": "@mname"
},
{
"context": " array.\n\t\t\t\t\tfixLogger.error('[1] %s '+@chunkModel.modelName+' found for user.', docs.length)\n\t\t\t\t\t# Updat",
"end": 2217,
"score": 0.5532349348068237,
"start": 2212,
"tag": "EMAIL",
"value": "model"
},
{
"context": "r exist? WTF\n\t\t\t\t\tfixLogger.error('[1] No '+@chunkModel.modelName+' found for user. Creating.')\n\t\t\t\t\tnewAttr = loda",
"end": 3040,
"score": 0.6938762068748474,
"start": 3025,
"tag": "EMAIL",
"value": "Model.modelName"
},
{
"context": "lease {$model:User}, '$fn'\n\t\tself = @\n\n\t\tif user[@cfield] and user[@cfield].length\n\t\t\tlatest = user[@cfiel",
"end": 4242,
"score": 0.6212228536605835,
"start": 4236,
"tag": "USERNAME",
"value": "cfield"
},
{
"context": " 'redoUser'+@itemModel.modelName,\n\t\t\tuser: { name: user.name, id: user._id }\n\t\t})\n\n\t\tgetChunk = (cb) =>\n\t\t\tif ",
"end": 11392,
"score": 0.9197030663490295,
"start": 11383,
"tag": "USERNAME",
"value": "user.name"
},
{
"context": "ve TMERA (chunk) =>\n\t\t\t\t\tupdate = {}\n\t\t\t\t\tupdate[@cfield] = [chunk._id]\n\t\t\t\t\tUser.findOneAndUpdate { _id: ",
"end": 11693,
"score": 0.9990736246109009,
"start": 11687,
"tag": "USERNAME",
"value": "cfield"
}
] | app/services/chunker.coffee | f03lipe/qilabs | 0 |
###*
* Chunker is a data model? for structuring notifications and karma points.
* It was created to facilitate aggregating items in chunks (ie notifications
* by type, or karma points by source).
* The Chunker methods handle creation and deletion (undoing) of these items,
* as well as ... ?
###
# Documentation? HAH, you wish.
assert = require 'assert'
lodash = require 'lodash'
async = require 'async'
mongoose = require 'mongoose'
bunyan = require 'app/config/bunyan'
please = require 'app/lib/please'
TMERA = require 'app/lib/tmera'
User = mongoose.model 'User'
class Chunker
logger = bunyan({ service: 'Chunker' })
# @cfield is an array of ids of @itemModel objects (containing many @itemModel's),
# the last of which is currently 'active' and holds the latest @itemModels.
constructor: (@cfield, @chunkModel, @itemModel, @Types, @Handlers, @Generators, @aggregateTimeout=Infinity) ->
@mname = @chunkModel.modelName
for type in @Types
assert typeof @Handlers[type].instance isnt 'undefined',
'Handler for instance of '+@mname+' of type '+type+' is not registered.'
assert typeof @Handlers[type].instance is 'function',
'Handler for instance of '+@mname+' of type '+type+' is not a function.'
assert typeof @Handlers[type].item isnt 'undefined',
'Handler for item of '+@mname+' of type '+type+' is not registered.'
assert typeof @Handlers[type].item is 'function',
'Handler for item of '+@mname+' of type '+type+' is not a function.'
# Fix a situtation when the last object the user chunk's id array doesn't exist.
fixUserAndGetChunk: (user, cb) ->
please {$model:User}, '$fn'
# Identify next logs.
fixLogger = logger.child({ attemptFix: Math.ceil(Math.random()*100) })
fixLogger.error('[0] User(%s) supposed chunk '+@mname+'(%s) doesn\'t exist. Attempting
to fix it.', user._id, user[@cfield][user[@cfield].length-1])
# Find chunks related to the user.
@itemModel
.find({ user: user._id })
.sort('updated_at')
.select('updated_at _id')
.exec TMERA (docs) =>
if docs.length
# There are real chunks related to that user. These may or may not have
# been in the @cfield array.
fixLogger.error('[1] %s '+@chunkModel.modelName+' found for user.', docs.length)
# Update user's @cfield with correct data.
update = { $set: {} }
update.$set[@cfield] = lodash.pluck(docs, '_id')
User.findOneAndUpdate { _id: user._id }, update, (err, udoc) =>
if err
fixLogger.error(err, '[3] Attempted fix: Failed to update '+@cfield+
' for user(%s).', user._id)
return
fixLogger.error('[3] Attempted fix: Fixed '+@cfield+' attribute
for user(%s).', user._id, udoc[@cfield])
# Get the last chunk (all of it, now)
@chunkModel.findOne { _id: docs[docs.length-1] }, (err, chunk) =>
if err or not udoc
throw err or new Error('Kill yourself. Really.')
cb(null, chunk)
else
# No chunks related to the user exist? WTF
fixLogger.error('[1] No '+@chunkModel.modelName+' found for user. Creating.')
newAttr = lodash.pluck(docs, '_id')
self.createChunk user, false, (err, chunk) =>
if err
fixLogger.error(err, '2. Failed to create chunk for user(%s)', user._id)
return cb(err)
if not chunk
throw new Error('WTF! created '+@chunkModel.modelName+' object is null')
cb(null, chunk)
createChunk: (user, push=false, cb) ->
please {$model:User}, {$is:false}, '$fn' # Non tested consequences for push=true
logger.debug('Creating '+@chunkModel.modelName+' chunk for user %s', user._id)
chunk = new @chunkModel {
user: user._id
}
chunk.save (err, chunk) =>
if err
logger.error(err, 'Failed to create '+@chunkModel.modelName+' chunk for user(%s)',
user._id)
return cb(err)
if push
action = { $push: {} }
action.$push[@cfield] = chunk._id
else
action = {}
action[@cfield] = [chunk._id]
User.findOneAndUpdate { _id: user._id }, action, (err) =>
if err
logger.error(err,
'Failed to save '+@cfield+' (=%s) attribute to user (%s)',
chunk._id, user._id)
cb(null, chunk)
getFromUser: (user, cb) ->
please {$model:User}, '$fn'
self = @
if user[@cfield] and user[@cfield].length
latest = user[@cfield][user[@cfield].length-1]
@chunkModel.findOne { _id: latest }, (err, chunk) =>
if err
logger.error(err, 'Failed finding '+@chunkModel.modelName+'(%s) for user(%s)',
latest, user._id)
throw err
if chunk
return cb(null, chunk)
else
# OPS! This shouldn't be happening.
# Log as error and try to fix it.
# Don't even try other ids in the @cfield field.
self.fixUserAndGetChunk(user, cb)
else
# Chunks are to be created when they're needed for the first time.
logger.debug("User (%s) has no "+@chunkModel.modelName+".", user._id)
self.createChunk user, false, (err, chunk) =>
if err
logger.error(err, 'Failed to create chunk for user(%s)', user._id)
return cb(err)
if not chunk
throw new Error('WTF! created '+@chunkModel.modelName+' object is null')
cb(null, chunk)
addItemToChunk: (item, chunk, cb) ->
please {$model:@itemModel}, {$model:@chunkModel}, '$fn'
@chunkModel.findOneAndUpdate {
_id: chunk._id
}, {
$push: { items: item }
$set: { updated_at: Date.now() }
}, TMERA (doc) ->
cb(null, doc)
aggregateInChunk: (item, latestItemData, instance, chunk, cb) ->
please {$model:@itemModel}, '$skip', '$skip', {$model:@chunkModel}, '$fn'
logger.debug("UPDATE", chunk._id, item)
@chunkModel.findOneAndUpdate {
_id: chunk._id
# 'items.identifier': item.identifier
'items._id': item._id
}, {
$set: {
updated_at: Date.now()
'items.$.object': latestItemData # Update object, just in case
}
'items.$.updated_at': Date.now()
$inc: { 'items.$.multiplier': 1 }
$push: { 'items.$.instances': instance }
}, cb
# API
add: (agent, receiver, type, data, cb) ->
self = @
object = self.Handlers[type].item(data)
# Items of a certain type may not aggregate, by not passing an instance
# function in their objects.
if self.Handlers[type].instance
object_inst = self.Handlers[type].instance(data, agent)
self.getFromUser receiver, (err, chunk) =>
logger.debug("Chunk found (%s)", chunk._id)
###
* Now we have chunk, check to see if there are items in it of same type
* (same notification identifier). If so, we need to decide whether
* we'll add the current notification to this item, as another instance.
* If that item was updated more than <self.aggregateTimeout>ms ago,
* DON'T aggregate!
###
notifs = lodash.where(chunk.items, { identifier: object.identifier })
makeNewItem = () =>
logger.info("Make new item")
if @Handlers[type].aggregate
ninstance = new self.itemModel(lodash.extend(object, { instances: [object_inst]}))
else
ninstance = new self.itemModel(lodash.extend(object))
self.addItemToChunk ninstance, chunk, (err, chunk) ->
if err
logger.error("Failed to addItemToChunk", { instance: ninstance })
return cb(err)
cb(null, chunk, object, object_inst)
aggregateExistingItem = (latestItem) =>
logger.info("aggregate")
# Item with that key already exists. Aggregate!
# Check if instance is already in that item (race condition?)
if lodash.find(latestItem.instances, { key: object_inst.key })
logger.warn("Instance with key %s was already in chunk %s (user=%s).",
object_inst.key, chunk._id, chunk.user)
return cb(null, null) # No object was/should be added
# I admit! What de fuk is dis progreming?
###
# The data relative to the notification we're creating might have been
# updated. (For instance, if the post title has changed...)
###
latestItemData = (new self.itemModel(object)).object
self.aggregateInChunk latestItem, latestItemData, object_inst,
chunk, TMERA (chunk, info) ->
# What the fuck happened?
if not chunk
logger.error("Chunk returned from aggregateInChunk is null",
object, object_inst)
return cb(null, null)
# Check if chunk returned has more than one of the instance we added (likely a
# race problem).
item = lodash.find(chunk.items, { identifier: object.identifier })
try # Hack to use forEach. U mad?
count = 0
item.instances.forEach (inst) ->
if inst.key is object_inst.key
if count is 1 # This is the second we found
console.log "ORIGINAL:", object_inst.key
console.log "SECOND FOUND:", inst.key
throw new Error("THEHEHEHE")
count += 1
catch e
console.log(e, lodash.keys(e))
# More than one instances found
logger.error("Instance with key %s not unique in chunk %s (user=%s).",
object_inst.key, chunk._id, chunk.user)
# Trigger fixDuplicateChunkInstance
self.fixDuplicateChunkInstance chunk._id, object.identifier, () ->
return cb(null, chunk) # As if no object has been added, because
cb(null, chunk, object, object_inst)
if @Handlers[type].aggregate and notifs.length
latestItem = new @itemModel(lodash.max(notifs, (i) -> i.updated_at))
# console.log('latestitem')
# console.log('item', latestItem)
# console.log('updated_at:', new Date(latestItem.updated_at))
# console.log(self.aggregateTimeout)
# console.log(new Date(latestItem.updated_at)*1+self.aggregateTimeout)
timedout = new Date() > (new Date(latestItem.updated_at)*1+self.aggregateTimeout)
if timedout
console.log('TIMEDOUT!')
makeNewItem()
else
aggregateExistingItem(latestItem)
else
makeNewItem()
remove: (agent, receiver, type, data, cb) ->
object = @Handlers[type].item(data)
if @Handlers[type].aggregate
object_inst = @Handlers[type].instance(data, agent)
count = 0
if @Handlers[type].aggregate
# Items of this type aggregate instances, so remove a single instance,
# not the whole item.
# Mongo will only take one item at a time in the following update (because $
# matches only the first array). T'will be necessary to call this until
# nothing item is removed. (ie. num == 1)
# see http://stackoverflow.com/questions/21637772
do removeAllItems = () =>
data = {
user: receiver._id
'items.identifier': object.identifier
'items.instances.key': object_inst.key
}
logger.debug("Attempting to remove. pass number #{count}.", data)
@chunkModel.update data, {
$pull: { 'items.$.instances': { key: object_inst.key } }
$inc: { 'items.$.multiplier': -1 }
}, TMERA (num, info) =>
if num is 1
count += 1
if count > 1
logger.error("Removed more than one item: "+count)
return removeAllItems()
else
cb(null, object, object_inst, count)
else
# update ALL chunks to user
@chunkModel.update {
user: user._id
}, {
$pull: { 'items.identifier': object.identifier }
}, TMERA (num, info) ->
cb(null, object)
redoUser: (user, cb) ->
# This is problematic when dealing with multiple chunks. Do expect bad things to happen.
# Better to create a reorderChunk routine to deal with it later.
please {$model:User}, '$fn'
logger = logger.child({
domain: 'redoUser'+@itemModel.modelName,
user: { name: user.name, id: user._id }
})
getChunk = (cb) =>
if user[@cfield].length
cb(user[@cfield][user[@cfield].length-1])
else
chunk = new @chunkModel {
user: user
created_at: Date.now()
updated_at: Date.now()
}
chunk.save TMERA (chunk) =>
update = {}
update[@cfield] = [chunk._id]
User.findOneAndUpdate { _id: user._id }, update, TMERA (doc) =>
if not doc
throw new Error('Failed to .')
cb(chunk._id)
generateToChunk = (chunkId, cb) =>
replaceChunkItemsOfType = (chunkId, type, items, cb) =>
# Replaces old items of this type with new ones.
# With this we don't have to reset the whole chunk with new items from the
# generators, items with types that don't have generators (points for problem
# solving?) (yet?) don't vanish when we redo.
addNew = (chunk) =>
logger.debug('Pulling of type %s from chunk %s.', type)
latest_update = lodash.max(lodash.pluck(items, 'updated_at')) or Date.now()
if chunk.updated_at and chunk.updated_at > latest_update
latest_update = chunk.updated_at
console.log latest_update
@chunkModel.findOneAndUpdate { _id: chunkId },
{ $push: { items: { $each: items } }, updated_at: latest_update },
TMERA (chunk) =>
logger.debug('Pushing of type %s to chunk %s.', type)
cb(null, chunk)
@chunkModel.findOneAndUpdate { _id: chunkId },
{ $pull: { items: { type: type } } }, TMERA (chunk) =>
console.log(chunk, chunkId, chunk and chunk.items.length)
addNew(chunk)
async.map lodash.pairs(@Generators), ((pair, done) =>
generator = pair[1]
logger.info('Calling generator '+pair[0])
generator user, (err, _items) =>
items = lodash.sortBy(lodash.flatten(_items), 'updated_at')
replaceChunkItemsOfType chunkId, pair[0], items, (err, chunk) =>
done(err)
), (err) =>
cb(err)
getChunk (chunkId) =>
generateToChunk chunkId, (err, chunk) =>
if err
throw err
@chunkModel.findOne { _id: chunkId }, TMERA (doc) =>
cb(null, doc)
module.exports = Chunker | 102489 |
###*
* Chunker is a data model? for structuring notifications and karma points.
* It was created to facilitate aggregating items in chunks (ie notifications
* by type, or karma points by source).
* The Chunker methods handle creation and deletion (undoing) of these items,
* as well as ... ?
###
# Documentation? HAH, you wish.
assert = require 'assert'
lodash = require 'lodash'
async = require 'async'
mongoose = require 'mongoose'
bunyan = require 'app/config/bunyan'
please = require 'app/lib/please'
TMERA = require 'app/lib/tmera'
User = mongoose.model 'User'
class Chunker
logger = bunyan({ service: 'Chunker' })
# @cfield is an array of ids of @itemModel objects (containing many @itemModel's),
# the last of which is currently 'active' and holds the latest @itemModels.
constructor: (@cfield, @chunkModel, @itemModel, @Types, @Handlers, @Generators, @aggregateTimeout=Infinity) ->
@mname = @chunkModel.modelName
for type in @Types
assert typeof @Handlers[type].instance isnt 'undefined',
'Handler for instance of '+@mname+' of type '+type+' is not registered.'
assert typeof @Handlers[type].instance is 'function',
'Handler for instance of '+@mname+' of type '+type+' is not a function.'
assert typeof @Handlers[type].item isnt 'undefined',
'Handler for item of '+@mname+' of type '+type+' is not registered.'
assert typeof @Handlers[type].item is 'function',
'Handler for item of '+@mname+' of type '+type+' is not a function.'
# Fix a situtation when the last object the user chunk's id array doesn't exist.
fixUserAndGetChunk: (user, cb) ->
please {$model:User}, '$fn'
# Identify next logs.
fixLogger = logger.child({ attemptFix: Math.ceil(Math.random()*100) })
fixLogger.error('[0] User(%s) supposed chunk '+@mname+'(%s) doesn\'t exist. Attempting
to fix it.', user._id, user[@cfield][user[@cfield].length-1])
# Find chunks related to the user.
@itemModel
.find({ user: user._id })
.sort('updated_at')
.select('updated_at _id')
.exec TMERA (docs) =>
if docs.length
# There are real chunks related to that user. These may or may not have
# been in the @cfield array.
fixLogger.error('[1] %s '+@chunkModel.<EMAIL>Name+' found for user.', docs.length)
# Update user's @cfield with correct data.
update = { $set: {} }
update.$set[@cfield] = lodash.pluck(docs, '_id')
User.findOneAndUpdate { _id: user._id }, update, (err, udoc) =>
if err
fixLogger.error(err, '[3] Attempted fix: Failed to update '+@cfield+
' for user(%s).', user._id)
return
fixLogger.error('[3] Attempted fix: Fixed '+@cfield+' attribute
for user(%s).', user._id, udoc[@cfield])
# Get the last chunk (all of it, now)
@chunkModel.findOne { _id: docs[docs.length-1] }, (err, chunk) =>
if err or not udoc
throw err or new Error('Kill yourself. Really.')
cb(null, chunk)
else
# No chunks related to the user exist? WTF
fixLogger.error('[1] No '+@chunk<EMAIL>+' found for user. Creating.')
newAttr = lodash.pluck(docs, '_id')
self.createChunk user, false, (err, chunk) =>
if err
fixLogger.error(err, '2. Failed to create chunk for user(%s)', user._id)
return cb(err)
if not chunk
throw new Error('WTF! created '+@chunkModel.modelName+' object is null')
cb(null, chunk)
createChunk: (user, push=false, cb) ->
please {$model:User}, {$is:false}, '$fn' # Non tested consequences for push=true
logger.debug('Creating '+@chunkModel.modelName+' chunk for user %s', user._id)
chunk = new @chunkModel {
user: user._id
}
chunk.save (err, chunk) =>
if err
logger.error(err, 'Failed to create '+@chunkModel.modelName+' chunk for user(%s)',
user._id)
return cb(err)
if push
action = { $push: {} }
action.$push[@cfield] = chunk._id
else
action = {}
action[@cfield] = [chunk._id]
User.findOneAndUpdate { _id: user._id }, action, (err) =>
if err
logger.error(err,
'Failed to save '+@cfield+' (=%s) attribute to user (%s)',
chunk._id, user._id)
cb(null, chunk)
getFromUser: (user, cb) ->
please {$model:User}, '$fn'
self = @
if user[@cfield] and user[@cfield].length
latest = user[@cfield][user[@cfield].length-1]
@chunkModel.findOne { _id: latest }, (err, chunk) =>
if err
logger.error(err, 'Failed finding '+@chunkModel.modelName+'(%s) for user(%s)',
latest, user._id)
throw err
if chunk
return cb(null, chunk)
else
# OPS! This shouldn't be happening.
# Log as error and try to fix it.
# Don't even try other ids in the @cfield field.
self.fixUserAndGetChunk(user, cb)
else
# Chunks are to be created when they're needed for the first time.
logger.debug("User (%s) has no "+@chunkModel.modelName+".", user._id)
self.createChunk user, false, (err, chunk) =>
if err
logger.error(err, 'Failed to create chunk for user(%s)', user._id)
return cb(err)
if not chunk
throw new Error('WTF! created '+@chunkModel.modelName+' object is null')
cb(null, chunk)
addItemToChunk: (item, chunk, cb) ->
please {$model:@itemModel}, {$model:@chunkModel}, '$fn'
@chunkModel.findOneAndUpdate {
_id: chunk._id
}, {
$push: { items: item }
$set: { updated_at: Date.now() }
}, TMERA (doc) ->
cb(null, doc)
aggregateInChunk: (item, latestItemData, instance, chunk, cb) ->
please {$model:@itemModel}, '$skip', '$skip', {$model:@chunkModel}, '$fn'
logger.debug("UPDATE", chunk._id, item)
@chunkModel.findOneAndUpdate {
_id: chunk._id
# 'items.identifier': item.identifier
'items._id': item._id
}, {
$set: {
updated_at: Date.now()
'items.$.object': latestItemData # Update object, just in case
}
'items.$.updated_at': Date.now()
$inc: { 'items.$.multiplier': 1 }
$push: { 'items.$.instances': instance }
}, cb
# API
add: (agent, receiver, type, data, cb) ->
self = @
object = self.Handlers[type].item(data)
# Items of a certain type may not aggregate, by not passing an instance
# function in their objects.
if self.Handlers[type].instance
object_inst = self.Handlers[type].instance(data, agent)
self.getFromUser receiver, (err, chunk) =>
logger.debug("Chunk found (%s)", chunk._id)
###
* Now we have chunk, check to see if there are items in it of same type
* (same notification identifier). If so, we need to decide whether
* we'll add the current notification to this item, as another instance.
* If that item was updated more than <self.aggregateTimeout>ms ago,
* DON'T aggregate!
###
notifs = lodash.where(chunk.items, { identifier: object.identifier })
makeNewItem = () =>
logger.info("Make new item")
if @Handlers[type].aggregate
ninstance = new self.itemModel(lodash.extend(object, { instances: [object_inst]}))
else
ninstance = new self.itemModel(lodash.extend(object))
self.addItemToChunk ninstance, chunk, (err, chunk) ->
if err
logger.error("Failed to addItemToChunk", { instance: ninstance })
return cb(err)
cb(null, chunk, object, object_inst)
aggregateExistingItem = (latestItem) =>
logger.info("aggregate")
# Item with that key already exists. Aggregate!
# Check if instance is already in that item (race condition?)
if lodash.find(latestItem.instances, { key: object_inst.key })
logger.warn("Instance with key %s was already in chunk %s (user=%s).",
object_inst.key, chunk._id, chunk.user)
return cb(null, null) # No object was/should be added
# I admit! What de fuk is dis progreming?
###
# The data relative to the notification we're creating might have been
# updated. (For instance, if the post title has changed...)
###
latestItemData = (new self.itemModel(object)).object
self.aggregateInChunk latestItem, latestItemData, object_inst,
chunk, TMERA (chunk, info) ->
# What the fuck happened?
if not chunk
logger.error("Chunk returned from aggregateInChunk is null",
object, object_inst)
return cb(null, null)
# Check if chunk returned has more than one of the instance we added (likely a
# race problem).
item = lodash.find(chunk.items, { identifier: object.identifier })
try # Hack to use forEach. U mad?
count = 0
item.instances.forEach (inst) ->
if inst.key is object_inst.key
if count is 1 # This is the second we found
console.log "ORIGINAL:", object_inst.key
console.log "SECOND FOUND:", inst.key
throw new Error("THEHEHEHE")
count += 1
catch e
console.log(e, lodash.keys(e))
# More than one instances found
logger.error("Instance with key %s not unique in chunk %s (user=%s).",
object_inst.key, chunk._id, chunk.user)
# Trigger fixDuplicateChunkInstance
self.fixDuplicateChunkInstance chunk._id, object.identifier, () ->
return cb(null, chunk) # As if no object has been added, because
cb(null, chunk, object, object_inst)
if @Handlers[type].aggregate and notifs.length
latestItem = new @itemModel(lodash.max(notifs, (i) -> i.updated_at))
# console.log('latestitem')
# console.log('item', latestItem)
# console.log('updated_at:', new Date(latestItem.updated_at))
# console.log(self.aggregateTimeout)
# console.log(new Date(latestItem.updated_at)*1+self.aggregateTimeout)
timedout = new Date() > (new Date(latestItem.updated_at)*1+self.aggregateTimeout)
if timedout
console.log('TIMEDOUT!')
makeNewItem()
else
aggregateExistingItem(latestItem)
else
makeNewItem()
remove: (agent, receiver, type, data, cb) ->
object = @Handlers[type].item(data)
if @Handlers[type].aggregate
object_inst = @Handlers[type].instance(data, agent)
count = 0
if @Handlers[type].aggregate
# Items of this type aggregate instances, so remove a single instance,
# not the whole item.
# Mongo will only take one item at a time in the following update (because $
# matches only the first array). T'will be necessary to call this until
# nothing item is removed. (ie. num == 1)
# see http://stackoverflow.com/questions/21637772
do removeAllItems = () =>
data = {
user: receiver._id
'items.identifier': object.identifier
'items.instances.key': object_inst.key
}
logger.debug("Attempting to remove. pass number #{count}.", data)
@chunkModel.update data, {
$pull: { 'items.$.instances': { key: object_inst.key } }
$inc: { 'items.$.multiplier': -1 }
}, TMERA (num, info) =>
if num is 1
count += 1
if count > 1
logger.error("Removed more than one item: "+count)
return removeAllItems()
else
cb(null, object, object_inst, count)
else
# update ALL chunks to user
@chunkModel.update {
user: user._id
}, {
$pull: { 'items.identifier': object.identifier }
}, TMERA (num, info) ->
cb(null, object)
redoUser: (user, cb) ->
# This is problematic when dealing with multiple chunks. Do expect bad things to happen.
# Better to create a reorderChunk routine to deal with it later.
please {$model:User}, '$fn'
logger = logger.child({
domain: 'redoUser'+@itemModel.modelName,
user: { name: user.name, id: user._id }
})
getChunk = (cb) =>
if user[@cfield].length
cb(user[@cfield][user[@cfield].length-1])
else
chunk = new @chunkModel {
user: user
created_at: Date.now()
updated_at: Date.now()
}
chunk.save TMERA (chunk) =>
update = {}
update[@cfield] = [chunk._id]
User.findOneAndUpdate { _id: user._id }, update, TMERA (doc) =>
if not doc
throw new Error('Failed to .')
cb(chunk._id)
generateToChunk = (chunkId, cb) =>
replaceChunkItemsOfType = (chunkId, type, items, cb) =>
# Replaces old items of this type with new ones.
# With this we don't have to reset the whole chunk with new items from the
# generators, items with types that don't have generators (points for problem
# solving?) (yet?) don't vanish when we redo.
addNew = (chunk) =>
logger.debug('Pulling of type %s from chunk %s.', type)
latest_update = lodash.max(lodash.pluck(items, 'updated_at')) or Date.now()
if chunk.updated_at and chunk.updated_at > latest_update
latest_update = chunk.updated_at
console.log latest_update
@chunkModel.findOneAndUpdate { _id: chunkId },
{ $push: { items: { $each: items } }, updated_at: latest_update },
TMERA (chunk) =>
logger.debug('Pushing of type %s to chunk %s.', type)
cb(null, chunk)
@chunkModel.findOneAndUpdate { _id: chunkId },
{ $pull: { items: { type: type } } }, TMERA (chunk) =>
console.log(chunk, chunkId, chunk and chunk.items.length)
addNew(chunk)
async.map lodash.pairs(@Generators), ((pair, done) =>
generator = pair[1]
logger.info('Calling generator '+pair[0])
generator user, (err, _items) =>
items = lodash.sortBy(lodash.flatten(_items), 'updated_at')
replaceChunkItemsOfType chunkId, pair[0], items, (err, chunk) =>
done(err)
), (err) =>
cb(err)
getChunk (chunkId) =>
generateToChunk chunkId, (err, chunk) =>
if err
throw err
@chunkModel.findOne { _id: chunkId }, TMERA (doc) =>
cb(null, doc)
module.exports = Chunker | true |
###*
* Chunker is a data model? for structuring notifications and karma points.
* It was created to facilitate aggregating items in chunks (ie notifications
* by type, or karma points by source).
* The Chunker methods handle creation and deletion (undoing) of these items,
* as well as ... ?
###
# Documentation? HAH, you wish.
assert = require 'assert'
lodash = require 'lodash'
async = require 'async'
mongoose = require 'mongoose'
bunyan = require 'app/config/bunyan'
please = require 'app/lib/please'
TMERA = require 'app/lib/tmera'
User = mongoose.model 'User'
class Chunker
logger = bunyan({ service: 'Chunker' })
# @cfield is an array of ids of @itemModel objects (containing many @itemModel's),
# the last of which is currently 'active' and holds the latest @itemModels.
constructor: (@cfield, @chunkModel, @itemModel, @Types, @Handlers, @Generators, @aggregateTimeout=Infinity) ->
@mname = @chunkModel.modelName
for type in @Types
assert typeof @Handlers[type].instance isnt 'undefined',
'Handler for instance of '+@mname+' of type '+type+' is not registered.'
assert typeof @Handlers[type].instance is 'function',
'Handler for instance of '+@mname+' of type '+type+' is not a function.'
assert typeof @Handlers[type].item isnt 'undefined',
'Handler for item of '+@mname+' of type '+type+' is not registered.'
assert typeof @Handlers[type].item is 'function',
'Handler for item of '+@mname+' of type '+type+' is not a function.'
# Fix a situtation when the last object the user chunk's id array doesn't exist.
fixUserAndGetChunk: (user, cb) ->
please {$model:User}, '$fn'
# Identify next logs.
fixLogger = logger.child({ attemptFix: Math.ceil(Math.random()*100) })
fixLogger.error('[0] User(%s) supposed chunk '+@mname+'(%s) doesn\'t exist. Attempting
to fix it.', user._id, user[@cfield][user[@cfield].length-1])
# Find chunks related to the user.
@itemModel
.find({ user: user._id })
.sort('updated_at')
.select('updated_at _id')
.exec TMERA (docs) =>
if docs.length
# There are real chunks related to that user. These may or may not have
# been in the @cfield array.
fixLogger.error('[1] %s '+@chunkModel.PI:EMAIL:<EMAIL>END_PIName+' found for user.', docs.length)
# Update user's @cfield with correct data.
update = { $set: {} }
update.$set[@cfield] = lodash.pluck(docs, '_id')
User.findOneAndUpdate { _id: user._id }, update, (err, udoc) =>
if err
fixLogger.error(err, '[3] Attempted fix: Failed to update '+@cfield+
' for user(%s).', user._id)
return
fixLogger.error('[3] Attempted fix: Fixed '+@cfield+' attribute
for user(%s).', user._id, udoc[@cfield])
# Get the last chunk (all of it, now)
@chunkModel.findOne { _id: docs[docs.length-1] }, (err, chunk) =>
if err or not udoc
throw err or new Error('Kill yourself. Really.')
cb(null, chunk)
else
# No chunks related to the user exist? WTF
fixLogger.error('[1] No '+@chunkPI:EMAIL:<EMAIL>END_PI+' found for user. Creating.')
newAttr = lodash.pluck(docs, '_id')
self.createChunk user, false, (err, chunk) =>
if err
fixLogger.error(err, '2. Failed to create chunk for user(%s)', user._id)
return cb(err)
if not chunk
throw new Error('WTF! created '+@chunkModel.modelName+' object is null')
cb(null, chunk)
createChunk: (user, push=false, cb) ->
please {$model:User}, {$is:false}, '$fn' # Non tested consequences for push=true
logger.debug('Creating '+@chunkModel.modelName+' chunk for user %s', user._id)
chunk = new @chunkModel {
user: user._id
}
chunk.save (err, chunk) =>
if err
logger.error(err, 'Failed to create '+@chunkModel.modelName+' chunk for user(%s)',
user._id)
return cb(err)
if push
action = { $push: {} }
action.$push[@cfield] = chunk._id
else
action = {}
action[@cfield] = [chunk._id]
User.findOneAndUpdate { _id: user._id }, action, (err) =>
if err
logger.error(err,
'Failed to save '+@cfield+' (=%s) attribute to user (%s)',
chunk._id, user._id)
cb(null, chunk)
getFromUser: (user, cb) ->
please {$model:User}, '$fn'
self = @
if user[@cfield] and user[@cfield].length
latest = user[@cfield][user[@cfield].length-1]
@chunkModel.findOne { _id: latest }, (err, chunk) =>
if err
logger.error(err, 'Failed finding '+@chunkModel.modelName+'(%s) for user(%s)',
latest, user._id)
throw err
if chunk
return cb(null, chunk)
else
# OPS! This shouldn't be happening.
# Log as error and try to fix it.
# Don't even try other ids in the @cfield field.
self.fixUserAndGetChunk(user, cb)
else
# Chunks are to be created when they're needed for the first time.
logger.debug("User (%s) has no "+@chunkModel.modelName+".", user._id)
self.createChunk user, false, (err, chunk) =>
if err
logger.error(err, 'Failed to create chunk for user(%s)', user._id)
return cb(err)
if not chunk
throw new Error('WTF! created '+@chunkModel.modelName+' object is null')
cb(null, chunk)
addItemToChunk: (item, chunk, cb) ->
please {$model:@itemModel}, {$model:@chunkModel}, '$fn'
@chunkModel.findOneAndUpdate {
_id: chunk._id
}, {
$push: { items: item }
$set: { updated_at: Date.now() }
}, TMERA (doc) ->
cb(null, doc)
aggregateInChunk: (item, latestItemData, instance, chunk, cb) ->
please {$model:@itemModel}, '$skip', '$skip', {$model:@chunkModel}, '$fn'
logger.debug("UPDATE", chunk._id, item)
@chunkModel.findOneAndUpdate {
_id: chunk._id
# 'items.identifier': item.identifier
'items._id': item._id
}, {
$set: {
updated_at: Date.now()
'items.$.object': latestItemData # Update object, just in case
}
'items.$.updated_at': Date.now()
$inc: { 'items.$.multiplier': 1 }
$push: { 'items.$.instances': instance }
}, cb
# API
add: (agent, receiver, type, data, cb) ->
self = @
object = self.Handlers[type].item(data)
# Items of a certain type may not aggregate, by not passing an instance
# function in their objects.
if self.Handlers[type].instance
object_inst = self.Handlers[type].instance(data, agent)
self.getFromUser receiver, (err, chunk) =>
logger.debug("Chunk found (%s)", chunk._id)
###
* Now we have chunk, check to see if there are items in it of same type
* (same notification identifier). If so, we need to decide whether
* we'll add the current notification to this item, as another instance.
* If that item was updated more than <self.aggregateTimeout>ms ago,
* DON'T aggregate!
###
notifs = lodash.where(chunk.items, { identifier: object.identifier })
makeNewItem = () =>
logger.info("Make new item")
if @Handlers[type].aggregate
ninstance = new self.itemModel(lodash.extend(object, { instances: [object_inst]}))
else
ninstance = new self.itemModel(lodash.extend(object))
self.addItemToChunk ninstance, chunk, (err, chunk) ->
if err
logger.error("Failed to addItemToChunk", { instance: ninstance })
return cb(err)
cb(null, chunk, object, object_inst)
aggregateExistingItem = (latestItem) =>
logger.info("aggregate")
# Item with that key already exists. Aggregate!
# Check if instance is already in that item (race condition?)
if lodash.find(latestItem.instances, { key: object_inst.key })
logger.warn("Instance with key %s was already in chunk %s (user=%s).",
object_inst.key, chunk._id, chunk.user)
return cb(null, null) # No object was/should be added
# I admit! What de fuk is dis progreming?
###
# The data relative to the notification we're creating might have been
# updated. (For instance, if the post title has changed...)
###
latestItemData = (new self.itemModel(object)).object
self.aggregateInChunk latestItem, latestItemData, object_inst,
chunk, TMERA (chunk, info) ->
# What the fuck happened?
if not chunk
logger.error("Chunk returned from aggregateInChunk is null",
object, object_inst)
return cb(null, null)
# Check if chunk returned has more than one of the instance we added (likely a
# race problem).
item = lodash.find(chunk.items, { identifier: object.identifier })
try # Hack to use forEach. U mad?
count = 0
item.instances.forEach (inst) ->
if inst.key is object_inst.key
if count is 1 # This is the second we found
console.log "ORIGINAL:", object_inst.key
console.log "SECOND FOUND:", inst.key
throw new Error("THEHEHEHE")
count += 1
catch e
console.log(e, lodash.keys(e))
# More than one instances found
logger.error("Instance with key %s not unique in chunk %s (user=%s).",
object_inst.key, chunk._id, chunk.user)
# Trigger fixDuplicateChunkInstance
self.fixDuplicateChunkInstance chunk._id, object.identifier, () ->
return cb(null, chunk) # As if no object has been added, because
cb(null, chunk, object, object_inst)
if @Handlers[type].aggregate and notifs.length
latestItem = new @itemModel(lodash.max(notifs, (i) -> i.updated_at))
# console.log('latestitem')
# console.log('item', latestItem)
# console.log('updated_at:', new Date(latestItem.updated_at))
# console.log(self.aggregateTimeout)
# console.log(new Date(latestItem.updated_at)*1+self.aggregateTimeout)
timedout = new Date() > (new Date(latestItem.updated_at)*1+self.aggregateTimeout)
if timedout
console.log('TIMEDOUT!')
makeNewItem()
else
aggregateExistingItem(latestItem)
else
makeNewItem()
remove: (agent, receiver, type, data, cb) ->
object = @Handlers[type].item(data)
if @Handlers[type].aggregate
object_inst = @Handlers[type].instance(data, agent)
count = 0
if @Handlers[type].aggregate
# Items of this type aggregate instances, so remove a single instance,
# not the whole item.
# Mongo will only take one item at a time in the following update (because $
# matches only the first array). T'will be necessary to call this until
# nothing item is removed. (ie. num == 1)
# see http://stackoverflow.com/questions/21637772
do removeAllItems = () =>
data = {
user: receiver._id
'items.identifier': object.identifier
'items.instances.key': object_inst.key
}
logger.debug("Attempting to remove. pass number #{count}.", data)
@chunkModel.update data, {
$pull: { 'items.$.instances': { key: object_inst.key } }
$inc: { 'items.$.multiplier': -1 }
}, TMERA (num, info) =>
if num is 1
count += 1
if count > 1
logger.error("Removed more than one item: "+count)
return removeAllItems()
else
cb(null, object, object_inst, count)
else
# update ALL chunks to user
@chunkModel.update {
user: user._id
}, {
$pull: { 'items.identifier': object.identifier }
}, TMERA (num, info) ->
cb(null, object)
redoUser: (user, cb) ->
# This is problematic when dealing with multiple chunks. Do expect bad things to happen.
# Better to create a reorderChunk routine to deal with it later.
please {$model:User}, '$fn'
logger = logger.child({
domain: 'redoUser'+@itemModel.modelName,
user: { name: user.name, id: user._id }
})
getChunk = (cb) =>
if user[@cfield].length
cb(user[@cfield][user[@cfield].length-1])
else
chunk = new @chunkModel {
user: user
created_at: Date.now()
updated_at: Date.now()
}
chunk.save TMERA (chunk) =>
update = {}
update[@cfield] = [chunk._id]
User.findOneAndUpdate { _id: user._id }, update, TMERA (doc) =>
if not doc
throw new Error('Failed to .')
cb(chunk._id)
generateToChunk = (chunkId, cb) =>
replaceChunkItemsOfType = (chunkId, type, items, cb) =>
# Replaces old items of this type with new ones.
# With this we don't have to reset the whole chunk with new items from the
# generators, items with types that don't have generators (points for problem
# solving?) (yet?) don't vanish when we redo.
addNew = (chunk) =>
logger.debug('Pulling of type %s from chunk %s.', type)
latest_update = lodash.max(lodash.pluck(items, 'updated_at')) or Date.now()
if chunk.updated_at and chunk.updated_at > latest_update
latest_update = chunk.updated_at
console.log latest_update
@chunkModel.findOneAndUpdate { _id: chunkId },
{ $push: { items: { $each: items } }, updated_at: latest_update },
TMERA (chunk) =>
logger.debug('Pushing of type %s to chunk %s.', type)
cb(null, chunk)
@chunkModel.findOneAndUpdate { _id: chunkId },
{ $pull: { items: { type: type } } }, TMERA (chunk) =>
console.log(chunk, chunkId, chunk and chunk.items.length)
addNew(chunk)
async.map lodash.pairs(@Generators), ((pair, done) =>
generator = pair[1]
logger.info('Calling generator '+pair[0])
generator user, (err, _items) =>
items = lodash.sortBy(lodash.flatten(_items), 'updated_at')
replaceChunkItemsOfType chunkId, pair[0], items, (err, chunk) =>
done(err)
), (err) =>
cb(err)
getChunk (chunkId) =>
generateToChunk chunkId, (err, chunk) =>
if err
throw err
@chunkModel.findOne { _id: chunkId }, TMERA (doc) =>
cb(null, doc)
module.exports = Chunker |
[
{
"context": "syntax by tweaking the code a bit.\n#\n# Author:\n# MattSJohnston\n\nmodule.exports = (robot) ->\n\n _ = require 'unde",
"end": 969,
"score": 0.9652135968208313,
"start": 956,
"tag": "NAME",
"value": "MattSJohnston"
}
] | src/scripts/status.coffee | Reelhouse/hubot-scripts | 1,450 | # Description
# Status is a simple user status message updater
#
# Dependencies:
# "underscore": "1.3.3"
#
# Configuration:
# None
#
# Commands:
# hubot away <away_message> - Sets you as "away" and optionally sets an away
# message. While away, anybody who mentions you
# will be shown your away message. Remember AIM?
#
# hubot return - Removes your away flag & away message
#
# hubot status <status_message> - Sets your status to status_message.
#
# hubot status <username> - Tells you the status of username
#
# Shortcuts Commands:
# hubot a <away_message>
# hubot r
# hubot s <status_message>
# hubot s <username>
#
# Notes:
# We opted to used the '/<trigger>' syntax in favor of the 'hubot <trigger>'
# syntax, because the commands are meant to be convenient. You can always
# change it to use the 'hubot <trigger>' syntax by tweaking the code a bit.
#
# Author:
# MattSJohnston
module.exports = (robot) ->
_ = require 'underscore'
robot.respond /(away|a$|a ) ?(.*)?/i, (msg) ->
hb_status = new Status robot
hb_status.update_away msg.message.user.name, msg.match[2]
msg.send msg.message.user.name + " is away."
robot.respond /(status|s)( |$)(.*)?/i, (msg) ->
hb_status = new Status robot
if !msg.match[3]?
hb_status.remove_status msg.message.user.name
msg.send msg.message.user.name + " has no more status."
else if (_.any (_.values _.pluck robot.brain.users, 'name'), (val) -> return val.toLowerCase() == msg.match[3].toLowerCase())
if hb_status.statuses_[msg.match[2].toLowerCase()]?
msg.send msg.match[3] + "'s status: " + hb_status.statuses_[msg.match[3].toLowerCase()]
else
msg.send msg.match[3] + " has no status set"
else
hb_status.update_status msg.message.user.name, msg.match[3]
msg.send msg.message.user.name + " has a new status."
robot.respond /statuses?/i, (msg) ->
hb_status = new Status robot
message = for user, s of hb_status.statuses_
"#{user}: #{s}"
msg.send message.join "\n"
robot.respond /(return|r$|r ) ?(.*)?/i, (msg) ->
hb_status = new Status robot
hb_status.update_away msg.message.user.name, null
msg.send msg.message.user.name + " has returned."
robot.hear /(^\w+\s?\w+\s?\w+):/i, (msg) ->
hb_status = new Status robot
mention = msg.match[1]
if hb_status.aways_[mention.toLowerCase()]?
msg.reply mention + " is away: " + hb_status.aways_[mention.toLowerCase()]
class Status
constructor: (robot) ->
robot.brain.data.statuses ?= {}
robot.brain.data.aways ?= {}
@statuses_ = robot.brain.data.statuses
@aways_ = robot.brain.data.aways
update_status: (name, message) ->
@statuses_[name.toLowerCase()] = message
remove_status: (name) ->
delete @statuses_[name.toLowerCase()]
update_away: (name, message) ->
@aways_[name.toLowerCase()] = message
| 156599 | # Description
# Status is a simple user status message updater
#
# Dependencies:
# "underscore": "1.3.3"
#
# Configuration:
# None
#
# Commands:
# hubot away <away_message> - Sets you as "away" and optionally sets an away
# message. While away, anybody who mentions you
# will be shown your away message. Remember AIM?
#
# hubot return - Removes your away flag & away message
#
# hubot status <status_message> - Sets your status to status_message.
#
# hubot status <username> - Tells you the status of username
#
# Shortcuts Commands:
# hubot a <away_message>
# hubot r
# hubot s <status_message>
# hubot s <username>
#
# Notes:
# We opted to used the '/<trigger>' syntax in favor of the 'hubot <trigger>'
# syntax, because the commands are meant to be convenient. You can always
# change it to use the 'hubot <trigger>' syntax by tweaking the code a bit.
#
# Author:
# <NAME>
module.exports = (robot) ->
_ = require 'underscore'
robot.respond /(away|a$|a ) ?(.*)?/i, (msg) ->
hb_status = new Status robot
hb_status.update_away msg.message.user.name, msg.match[2]
msg.send msg.message.user.name + " is away."
robot.respond /(status|s)( |$)(.*)?/i, (msg) ->
hb_status = new Status robot
if !msg.match[3]?
hb_status.remove_status msg.message.user.name
msg.send msg.message.user.name + " has no more status."
else if (_.any (_.values _.pluck robot.brain.users, 'name'), (val) -> return val.toLowerCase() == msg.match[3].toLowerCase())
if hb_status.statuses_[msg.match[2].toLowerCase()]?
msg.send msg.match[3] + "'s status: " + hb_status.statuses_[msg.match[3].toLowerCase()]
else
msg.send msg.match[3] + " has no status set"
else
hb_status.update_status msg.message.user.name, msg.match[3]
msg.send msg.message.user.name + " has a new status."
robot.respond /statuses?/i, (msg) ->
hb_status = new Status robot
message = for user, s of hb_status.statuses_
"#{user}: #{s}"
msg.send message.join "\n"
robot.respond /(return|r$|r ) ?(.*)?/i, (msg) ->
hb_status = new Status robot
hb_status.update_away msg.message.user.name, null
msg.send msg.message.user.name + " has returned."
robot.hear /(^\w+\s?\w+\s?\w+):/i, (msg) ->
hb_status = new Status robot
mention = msg.match[1]
if hb_status.aways_[mention.toLowerCase()]?
msg.reply mention + " is away: " + hb_status.aways_[mention.toLowerCase()]
class Status
constructor: (robot) ->
robot.brain.data.statuses ?= {}
robot.brain.data.aways ?= {}
@statuses_ = robot.brain.data.statuses
@aways_ = robot.brain.data.aways
update_status: (name, message) ->
@statuses_[name.toLowerCase()] = message
remove_status: (name) ->
delete @statuses_[name.toLowerCase()]
update_away: (name, message) ->
@aways_[name.toLowerCase()] = message
| true | # Description
# Status is a simple user status message updater
#
# Dependencies:
# "underscore": "1.3.3"
#
# Configuration:
# None
#
# Commands:
# hubot away <away_message> - Sets you as "away" and optionally sets an away
# message. While away, anybody who mentions you
# will be shown your away message. Remember AIM?
#
# hubot return - Removes your away flag & away message
#
# hubot status <status_message> - Sets your status to status_message.
#
# hubot status <username> - Tells you the status of username
#
# Shortcuts Commands:
# hubot a <away_message>
# hubot r
# hubot s <status_message>
# hubot s <username>
#
# Notes:
# We opted to used the '/<trigger>' syntax in favor of the 'hubot <trigger>'
# syntax, because the commands are meant to be convenient. You can always
# change it to use the 'hubot <trigger>' syntax by tweaking the code a bit.
#
# Author:
# PI:NAME:<NAME>END_PI
module.exports = (robot) ->
_ = require 'underscore'
robot.respond /(away|a$|a ) ?(.*)?/i, (msg) ->
hb_status = new Status robot
hb_status.update_away msg.message.user.name, msg.match[2]
msg.send msg.message.user.name + " is away."
robot.respond /(status|s)( |$)(.*)?/i, (msg) ->
hb_status = new Status robot
if !msg.match[3]?
hb_status.remove_status msg.message.user.name
msg.send msg.message.user.name + " has no more status."
else if (_.any (_.values _.pluck robot.brain.users, 'name'), (val) -> return val.toLowerCase() == msg.match[3].toLowerCase())
if hb_status.statuses_[msg.match[2].toLowerCase()]?
msg.send msg.match[3] + "'s status: " + hb_status.statuses_[msg.match[3].toLowerCase()]
else
msg.send msg.match[3] + " has no status set"
else
hb_status.update_status msg.message.user.name, msg.match[3]
msg.send msg.message.user.name + " has a new status."
robot.respond /statuses?/i, (msg) ->
hb_status = new Status robot
message = for user, s of hb_status.statuses_
"#{user}: #{s}"
msg.send message.join "\n"
robot.respond /(return|r$|r ) ?(.*)?/i, (msg) ->
hb_status = new Status robot
hb_status.update_away msg.message.user.name, null
msg.send msg.message.user.name + " has returned."
robot.hear /(^\w+\s?\w+\s?\w+):/i, (msg) ->
hb_status = new Status robot
mention = msg.match[1]
if hb_status.aways_[mention.toLowerCase()]?
msg.reply mention + " is away: " + hb_status.aways_[mention.toLowerCase()]
class Status
constructor: (robot) ->
robot.brain.data.statuses ?= {}
robot.brain.data.aways ?= {}
@statuses_ = robot.brain.data.statuses
@aways_ = robot.brain.data.aways
update_status: (name, message) ->
@statuses_[name.toLowerCase()] = message
remove_status: (name) ->
delete @statuses_[name.toLowerCase()]
update_away: (name, message) ->
@aways_[name.toLowerCase()] = message
|
[
{
"context": "App.data.sector_compare_return = [\n group: \"Merrill Lynch\"\n label: \"Mechanical engineering & industrial ",
"end": 60,
"score": 0.7469901442527771,
"start": 47,
"tag": "NAME",
"value": "Merrill Lynch"
},
{
"context": "47.603703145614\n type: \"money\"\n ,\n group: \"Merrill Lynch\"\n label: \"Miscellaneous consumer goods\"\n va",
"end": 194,
"score": 0.9631314873695374,
"start": 181,
"tag": "NAME",
"value": "Merrill Lynch"
},
{
"context": "89.180308185896\n type: \"money\"\n ,\n group: \"Merrill Lynch\"\n label: \"Petroleum\"\n value: 3937.970281974",
"end": 314,
"score": 0.9697559475898743,
"start": 301,
"tag": "NAME",
"value": "Merrill Lynch"
},
{
"context": "37.970281974645\n type: \"money\"\n ,\n group: \"Merrill Lynch\"\n label: \"Pharmaceuticals cosmetics & med. pro",
"end": 415,
"score": 0.9211824536323547,
"start": 402,
"tag": "NAME",
"value": "Merrill Lynch"
},
{
"context": "74.807224610915\n type: \"money\"\n ,\n group: \"Merrill Lynch\"\n label: \"Retail\"\n value: 27447.83173387832",
"end": 549,
"score": 0.9342339038848877,
"start": 536,
"tag": "NAME",
"value": "Merrill Lynch"
},
{
"context": "47.831733878324\n type: \"money\"\n ,\n group: \"Merrill Lynch\"\n label: \"Retail trade & department stores\"\n ",
"end": 648,
"score": 0.9301557540893555,
"start": 635,
"tag": "NAME",
"value": "Merrill Lynch"
},
{
"context": "35.627782905445\n type: \"money\"\n ,\n group: \"Merrill Lynch\"\n label: \"Short Term\"\n value: 8707.74977491",
"end": 773,
"score": 0.93202143907547,
"start": 760,
"tag": "NAME",
"value": "Merrill Lynch"
},
{
"context": "07.749774914644\n type: \"money\"\n ,\n group: \"Merrill Lynch\"\n label: \"Software & Programming\"\n value: 1",
"end": 875,
"score": 0.969172477722168,
"start": 862,
"tag": "NAME",
"value": "Merrill Lynch"
},
{
"context": "7326.4348387686\n type: \"money\"\n ,\n group: \"Merrill Lynch\"\n label: \"Telecommunication\"\n value: 9515.7",
"end": 989,
"score": 0.9591959118843079,
"start": 976,
"tag": "NAME",
"value": "Merrill Lynch"
},
{
"context": "515.74704319803\n type: \"money\"\n ,\n group: \"Merrill Lynch\"\n label: \"Financial analytics software\"\n va",
"end": 1097,
"score": 0.9172966480255127,
"start": 1084,
"tag": "NAME",
"value": "Merrill Lynch"
}
] | app/data/multi_group/sector_compare_return.coffee | Tuhaj/ember-charts | 1 | App.data.sector_compare_return = [
group: "Merrill Lynch"
label: "Mechanical engineering & industrial equip."
value: 4647.603703145614
type: "money"
,
group: "Merrill Lynch"
label: "Miscellaneous consumer goods"
value: 3189.180308185896
type: "money"
,
group: "Merrill Lynch"
label: "Petroleum"
value: 3937.970281974645
type: "money"
,
group: "Merrill Lynch"
label: "Pharmaceuticals cosmetics & med. products"
value: 10874.807224610915
type: "money"
,
group: "Merrill Lynch"
label: "Retail"
value: 27447.831733878324
type: "money"
,
group: "Merrill Lynch"
label: "Retail trade & department stores"
value: 31035.627782905445
type: "money"
,
group: "Merrill Lynch"
label: "Short Term"
value: 8707.749774914644
type: "money"
,
group: "Merrill Lynch"
label: "Software & Programming"
value: 117326.4348387686
type: "money"
,
group: "Merrill Lynch"
label: "Telecommunication"
value: 9515.74704319803
type: "money"
,
group: "Merrill Lynch"
label: "Financial analytics software"
value: 99310.60662117682
type: "money"
,
group: "Barclays"
label: "Mechanical engineering & industrial equip."
value: 6476.03703145614
type: "money"
,
group: "Barclays"
label: "Miscellaneous consumer goods"
value: 1891.80308185896
type: "money"
,
group: "Barclays"
label: "Petroleum"
value: 39379.70281974645
type: "money"
,
group: "Barclays"
label: "Pharmaceuticals cosmetics & med. products"
value: 8748.07224610915
type: "money"
,
group: "Barclays"
label: "Retail"
value: 74478.31733878324
type: "money"
,
group: "Barclays"
label: "Retail trade & department stores"
value: 10356.27782905445
type: "money"
,
group: "Barclays"
label: "Short Term"
value: 7077.49774914644
type: "money"
,
group: "Barclays"
label: "Software & Programming"
value: 173264.348387686
type: "money"
,
group: "Barclays"
label: "Telecommunication"
value: 5157.4704319803
type: "money"
,
group: "Barclays"
label: "Financial analytics software"
value: 93106.0662117682
type: "money"
,
group: "BlackRock"
label: "Mechanical engineering & industrial equip."
value: 4760.3703145614
type: "money"
,
group: "BlackRock"
label: "Miscellaneous consumer goods"
value: 8918.0308185896
type: "money"
,
group: "BlackRock"
label: "Petroleum"
value: 93797.0281974645
type: "money"
,
group: "BlackRock"
label: "Pharmaceuticals cosmetics & med. products"
value: 87480.7224610915
type: "money"
,
group: "BlackRock"
label: "Retail"
value: 44783.1733878324
type: "money"
,
group: "BlackRock"
label: "Retail trade & department stores"
value: 3562.7782905445
type: "money"
,
group: "BlackRock"
label: "Short Term"
value: 774.9774914644
type: "money"
,
group: "BlackRock"
label: "Software & Programming"
value: 73264.48387686
type: "money"
,
group: "BlackRock"
label: "Telecommunication"
value: 1574.704319803
type: "money"
,
group: "BlackRock"
label: "Financial analytics software"
value: 31060.662117682
type: "money"
,
group: "Vanguard"
label: "Mechanical engineering & industrial equip."
value: 7603.703145614
type: "money"
,
group: "Vanguard"
label: "Miscellaneous consumer goods"
value: 9180.308185896
type: "money"
,
group: "Vanguard"
label: "Petroleum"
value: 37970.281974645
type: "money"
,
group: "Vanguard"
label: "Pharmaceuticals cosmetics & med. products"
value: 74807.224610915
type: "money"
,
group: "Vanguard"
label: "Retail"
value: 47831.733878324
type: "money"
,
group: "Vanguard"
label: "Retail trade & department stores"
value: 35627.782905445
type: "money"
,
group: "Vanguard"
label: "Short Term"
value: 7749.774914644
type: "money"
,
group: "Vanguard"
label: "Software & Programming"
value: 326434.8387686
type: "money"
,
group: "Vanguard"
label: "Telecommunication"
value: 5747.04319803
type: "money"
,
group: "Vanguard"
label: "Financial analytics software"
value: 10606.62117682
type: "money"
,
group: "Benchmark"
label: "Mechanical engineering & industrial equip."
value: 6037.03145614
type: "money"
,
group: "Benchmark"
label: "Miscellaneous consumer goods"
value: 1803.08185896
type: "money"
,
group: "Benchmark"
label: "Petroleum"
value: 79702.81974645
type: "money"
,
group: "Benchmark"
label: "Pharmaceuticals cosmetics & med. products"
value: 48072.24610915
type: "money"
,
group: "Benchmark"
label: "Retail"
value: 78317.33878324
type: "money"
,
group: "Benchmark"
label: "Retail trade & department stores"
value: 56277.82905445
type: "money"
,
group: "Benchmark"
label: "Short Term"
value: 7497.74914644
type: "money"
,
group: "Benchmark"
label: "Software & Programming"
value: 264348.387686
type: "money"
,
group: "Benchmark"
label: "Telecommunication"
value: 7470.4319803
type: "money"
,
group: "Benchmark"
label: "Financial analytics software"
value: 6066.2117682
type: "money"
] | 103155 | App.data.sector_compare_return = [
group: "<NAME>"
label: "Mechanical engineering & industrial equip."
value: 4647.603703145614
type: "money"
,
group: "<NAME>"
label: "Miscellaneous consumer goods"
value: 3189.180308185896
type: "money"
,
group: "<NAME>"
label: "Petroleum"
value: 3937.970281974645
type: "money"
,
group: "<NAME>"
label: "Pharmaceuticals cosmetics & med. products"
value: 10874.807224610915
type: "money"
,
group: "<NAME>"
label: "Retail"
value: 27447.831733878324
type: "money"
,
group: "<NAME>"
label: "Retail trade & department stores"
value: 31035.627782905445
type: "money"
,
group: "<NAME>"
label: "Short Term"
value: 8707.749774914644
type: "money"
,
group: "<NAME>"
label: "Software & Programming"
value: 117326.4348387686
type: "money"
,
group: "<NAME>"
label: "Telecommunication"
value: 9515.74704319803
type: "money"
,
group: "<NAME>"
label: "Financial analytics software"
value: 99310.60662117682
type: "money"
,
group: "Barclays"
label: "Mechanical engineering & industrial equip."
value: 6476.03703145614
type: "money"
,
group: "Barclays"
label: "Miscellaneous consumer goods"
value: 1891.80308185896
type: "money"
,
group: "Barclays"
label: "Petroleum"
value: 39379.70281974645
type: "money"
,
group: "Barclays"
label: "Pharmaceuticals cosmetics & med. products"
value: 8748.07224610915
type: "money"
,
group: "Barclays"
label: "Retail"
value: 74478.31733878324
type: "money"
,
group: "Barclays"
label: "Retail trade & department stores"
value: 10356.27782905445
type: "money"
,
group: "Barclays"
label: "Short Term"
value: 7077.49774914644
type: "money"
,
group: "Barclays"
label: "Software & Programming"
value: 173264.348387686
type: "money"
,
group: "Barclays"
label: "Telecommunication"
value: 5157.4704319803
type: "money"
,
group: "Barclays"
label: "Financial analytics software"
value: 93106.0662117682
type: "money"
,
group: "BlackRock"
label: "Mechanical engineering & industrial equip."
value: 4760.3703145614
type: "money"
,
group: "BlackRock"
label: "Miscellaneous consumer goods"
value: 8918.0308185896
type: "money"
,
group: "BlackRock"
label: "Petroleum"
value: 93797.0281974645
type: "money"
,
group: "BlackRock"
label: "Pharmaceuticals cosmetics & med. products"
value: 87480.7224610915
type: "money"
,
group: "BlackRock"
label: "Retail"
value: 44783.1733878324
type: "money"
,
group: "BlackRock"
label: "Retail trade & department stores"
value: 3562.7782905445
type: "money"
,
group: "BlackRock"
label: "Short Term"
value: 774.9774914644
type: "money"
,
group: "BlackRock"
label: "Software & Programming"
value: 73264.48387686
type: "money"
,
group: "BlackRock"
label: "Telecommunication"
value: 1574.704319803
type: "money"
,
group: "BlackRock"
label: "Financial analytics software"
value: 31060.662117682
type: "money"
,
group: "Vanguard"
label: "Mechanical engineering & industrial equip."
value: 7603.703145614
type: "money"
,
group: "Vanguard"
label: "Miscellaneous consumer goods"
value: 9180.308185896
type: "money"
,
group: "Vanguard"
label: "Petroleum"
value: 37970.281974645
type: "money"
,
group: "Vanguard"
label: "Pharmaceuticals cosmetics & med. products"
value: 74807.224610915
type: "money"
,
group: "Vanguard"
label: "Retail"
value: 47831.733878324
type: "money"
,
group: "Vanguard"
label: "Retail trade & department stores"
value: 35627.782905445
type: "money"
,
group: "Vanguard"
label: "Short Term"
value: 7749.774914644
type: "money"
,
group: "Vanguard"
label: "Software & Programming"
value: 326434.8387686
type: "money"
,
group: "Vanguard"
label: "Telecommunication"
value: 5747.04319803
type: "money"
,
group: "Vanguard"
label: "Financial analytics software"
value: 10606.62117682
type: "money"
,
group: "Benchmark"
label: "Mechanical engineering & industrial equip."
value: 6037.03145614
type: "money"
,
group: "Benchmark"
label: "Miscellaneous consumer goods"
value: 1803.08185896
type: "money"
,
group: "Benchmark"
label: "Petroleum"
value: 79702.81974645
type: "money"
,
group: "Benchmark"
label: "Pharmaceuticals cosmetics & med. products"
value: 48072.24610915
type: "money"
,
group: "Benchmark"
label: "Retail"
value: 78317.33878324
type: "money"
,
group: "Benchmark"
label: "Retail trade & department stores"
value: 56277.82905445
type: "money"
,
group: "Benchmark"
label: "Short Term"
value: 7497.74914644
type: "money"
,
group: "Benchmark"
label: "Software & Programming"
value: 264348.387686
type: "money"
,
group: "Benchmark"
label: "Telecommunication"
value: 7470.4319803
type: "money"
,
group: "Benchmark"
label: "Financial analytics software"
value: 6066.2117682
type: "money"
] | true | App.data.sector_compare_return = [
group: "PI:NAME:<NAME>END_PI"
label: "Mechanical engineering & industrial equip."
value: 4647.603703145614
type: "money"
,
group: "PI:NAME:<NAME>END_PI"
label: "Miscellaneous consumer goods"
value: 3189.180308185896
type: "money"
,
group: "PI:NAME:<NAME>END_PI"
label: "Petroleum"
value: 3937.970281974645
type: "money"
,
group: "PI:NAME:<NAME>END_PI"
label: "Pharmaceuticals cosmetics & med. products"
value: 10874.807224610915
type: "money"
,
group: "PI:NAME:<NAME>END_PI"
label: "Retail"
value: 27447.831733878324
type: "money"
,
group: "PI:NAME:<NAME>END_PI"
label: "Retail trade & department stores"
value: 31035.627782905445
type: "money"
,
group: "PI:NAME:<NAME>END_PI"
label: "Short Term"
value: 8707.749774914644
type: "money"
,
group: "PI:NAME:<NAME>END_PI"
label: "Software & Programming"
value: 117326.4348387686
type: "money"
,
group: "PI:NAME:<NAME>END_PI"
label: "Telecommunication"
value: 9515.74704319803
type: "money"
,
group: "PI:NAME:<NAME>END_PI"
label: "Financial analytics software"
value: 99310.60662117682
type: "money"
,
group: "Barclays"
label: "Mechanical engineering & industrial equip."
value: 6476.03703145614
type: "money"
,
group: "Barclays"
label: "Miscellaneous consumer goods"
value: 1891.80308185896
type: "money"
,
group: "Barclays"
label: "Petroleum"
value: 39379.70281974645
type: "money"
,
group: "Barclays"
label: "Pharmaceuticals cosmetics & med. products"
value: 8748.07224610915
type: "money"
,
group: "Barclays"
label: "Retail"
value: 74478.31733878324
type: "money"
,
group: "Barclays"
label: "Retail trade & department stores"
value: 10356.27782905445
type: "money"
,
group: "Barclays"
label: "Short Term"
value: 7077.49774914644
type: "money"
,
group: "Barclays"
label: "Software & Programming"
value: 173264.348387686
type: "money"
,
group: "Barclays"
label: "Telecommunication"
value: 5157.4704319803
type: "money"
,
group: "Barclays"
label: "Financial analytics software"
value: 93106.0662117682
type: "money"
,
group: "BlackRock"
label: "Mechanical engineering & industrial equip."
value: 4760.3703145614
type: "money"
,
group: "BlackRock"
label: "Miscellaneous consumer goods"
value: 8918.0308185896
type: "money"
,
group: "BlackRock"
label: "Petroleum"
value: 93797.0281974645
type: "money"
,
group: "BlackRock"
label: "Pharmaceuticals cosmetics & med. products"
value: 87480.7224610915
type: "money"
,
group: "BlackRock"
label: "Retail"
value: 44783.1733878324
type: "money"
,
group: "BlackRock"
label: "Retail trade & department stores"
value: 3562.7782905445
type: "money"
,
group: "BlackRock"
label: "Short Term"
value: 774.9774914644
type: "money"
,
group: "BlackRock"
label: "Software & Programming"
value: 73264.48387686
type: "money"
,
group: "BlackRock"
label: "Telecommunication"
value: 1574.704319803
type: "money"
,
group: "BlackRock"
label: "Financial analytics software"
value: 31060.662117682
type: "money"
,
group: "Vanguard"
label: "Mechanical engineering & industrial equip."
value: 7603.703145614
type: "money"
,
group: "Vanguard"
label: "Miscellaneous consumer goods"
value: 9180.308185896
type: "money"
,
group: "Vanguard"
label: "Petroleum"
value: 37970.281974645
type: "money"
,
group: "Vanguard"
label: "Pharmaceuticals cosmetics & med. products"
value: 74807.224610915
type: "money"
,
group: "Vanguard"
label: "Retail"
value: 47831.733878324
type: "money"
,
group: "Vanguard"
label: "Retail trade & department stores"
value: 35627.782905445
type: "money"
,
group: "Vanguard"
label: "Short Term"
value: 7749.774914644
type: "money"
,
group: "Vanguard"
label: "Software & Programming"
value: 326434.8387686
type: "money"
,
group: "Vanguard"
label: "Telecommunication"
value: 5747.04319803
type: "money"
,
group: "Vanguard"
label: "Financial analytics software"
value: 10606.62117682
type: "money"
,
group: "Benchmark"
label: "Mechanical engineering & industrial equip."
value: 6037.03145614
type: "money"
,
group: "Benchmark"
label: "Miscellaneous consumer goods"
value: 1803.08185896
type: "money"
,
group: "Benchmark"
label: "Petroleum"
value: 79702.81974645
type: "money"
,
group: "Benchmark"
label: "Pharmaceuticals cosmetics & med. products"
value: 48072.24610915
type: "money"
,
group: "Benchmark"
label: "Retail"
value: 78317.33878324
type: "money"
,
group: "Benchmark"
label: "Retail trade & department stores"
value: 56277.82905445
type: "money"
,
group: "Benchmark"
label: "Short Term"
value: 7497.74914644
type: "money"
,
group: "Benchmark"
label: "Software & Programming"
value: 264348.387686
type: "money"
,
group: "Benchmark"
label: "Telecommunication"
value: 7470.4319803
type: "money"
,
group: "Benchmark"
label: "Financial analytics software"
value: 6066.2117682
type: "money"
] |
[
{
"context": " key += 'Right'\n when 3\n key = 'Numpad' + {\n Delete: 'Decimal'\n ",
"end": 19029,
"score": 0.9673675894737244,
"start": 19023,
"tag": "KEY",
"value": "Numpad"
}
] | engine/input.coffee | myou-engine/myou | 29 |
###
Input module, providing an API for remappeable buttons and axes,
with keyboard and gamepads as input sources for now.
It gives helpful error messages for the vast majority of mistakes.
Example:
axes = new @context.Axes2 'Joy:+X', 'Joy:+Y'
.add_inputs 'Key:ArrowLeft', 'Key:ArrowRight',
'Key:ArrowDown', 'Key:ArrowUp'
jump_btn = new @context.Button 'Key:Space', 'Joy:A', 'Joy:+Y2', 'Joy:RT'
jump_btn.on_press = some_function
console.log axes.value # {x: 0, y: 0, z: 0}
NOTE: I'm very satisfied with this API but not with the code structure.
Expect a rewrite as soon as we need a bit more functionality.
###
{vec3} = require 'vmath'
proxy_warn = {}
if Proxy?
# TODO: Only do this when not in production
warn_f = ->
stack = (new Error).stack.split('\n')
if /^Error/.test stack[0] then stack.shift()
throw Error "This method is not bound.
Declare it with a fat arrow (=>)\n" + stack[1]
proxy_warn = new Proxy {}, get: warn_f, set: warn_f
class Button
constructor: (@context, ids...) ->
for id in ids
{source, source_name, pad_index, label} =
@context.input_manager.parse_id id
if source?
source.add_button this, source_name, pad_index, label
@pressed = @just_pressed = @just_released = false
@_value = 0 # Semi axis simulation
press: ->
if not @pressed
@pressed = @just_pressed = true
@_value = 1
@context.input_manager.pending_reset.push this
@on_press?.call proxy_warn
return this
release: ->
if @pressed
@pressed = false
@just_released = true
@_value = 0
@context.input_manager.pending_reset.push this
@on_release?.call proxy_warn
return this
on_press: null
on_release: null
class Axis
constructor: (@context, minus, plus) ->
@value = 0
# Both of these can be semi axes or buttons,
# Only the property _value will be read from each
@_semi_axis_minus = []
@_semi_axis_plus = []
@_priority = 1 # last pressed key
@context.input_manager.all_axis.push this
@add_inputs minus, plus
add_inputs: (minus, plus) ->
if minus?
flip_minus = false
if not plus?
plus = minus
flip_minus = true
{source, source_name, pad_index, label} = \
@context.input_manager.parse_id minus, flip_minus
if not source?
# This way only suggests one semi axis when you try
# to use an implicit (opposite) axis, i.e. new Axis('X','Y')
return
source?.add_semi_axis this, source_name, pad_index, label, -1
{source, source_name, pad_index, label} = \
@context.input_manager.parse_id plus, false
source?.add_semi_axis this, source_name, pad_index, label, 1
return this
_update: ->
max_plus = max_minus = 0
for {_value, just_pressed} in @_semi_axis_plus
max_plus = Math.max max_plus, _value
if just_pressed then @_priority = 1
for {_value, just_pressed} in @_semi_axis_minus
max_minus = Math.max max_minus, _value
if just_pressed then @_priority = -1
# When both semi axes are digital,
# the last pressed button has the priority
if @_priority > 0
comparison = max_plus >= max_minus
else
comparison = max_plus > max_minus
if comparison
@value = max_plus
else
@value = -max_minus
return
class Axes2
constructor: (@context, minus_x, plus_x, minus_y, plus_y) ->
# vec3 instead of vec2 for convenience
@value = vec3.create()
@x_axis = new Axis @context
@y_axis = new Axis @context
@context.input_manager.all_axes2.push this
@add_inputs minus_x, plus_x, minus_y, plus_y
add_inputs: (minus_x, plus_x, minus_y, plus_y) ->
x = y = x2 = y2 = undefined
if minus_x?
if not plus_x? or minus_y? != plus_y?
throw Error "Invalid parameters. Expected two axes,
four semi axes or none."
if minus_y?
[x, x2] = [minus_x, plus_x]
[y, y2] = [minus_y, plus_y]
else
x = minus_x # actually +X
y = plus_x # actually +Y
@x_axis.add_inputs x, x2
@y_axis.add_inputs y, y2
return this
class InputManager
constructor: (@context) ->
@context.input_manager = this
@input_sources = {}
@input_source_list = []
@pending_reset = []
@all_axis = []
@all_axes2 = []
new KeyboardInputSource @context
new GamepadInputSource @context
update_axes: ->
for source in @input_source_list
source.update_controller()
for axis in @all_axis
axis._update()
for {value, x_axis, y_axis} in @all_axes2
value.x = x_axis.value
value.y = y_axis.value
return
reset_buttons: ->
for button in @pending_reset
button.just_pressed = button.just_released = false
return
parse_id: (id, flip_axis) ->
id = id.toString()
[source_name, label] = id.split ':'
pad_index = 0
if (m = source_name.match /([^\d]*)(\d+)$/)?
source_name = m[1]
pad_index = m[2]|0
source = @input_sources[source_name]
if not source?
console.error "Unknown input source: #{source_name}"
if not label?
if flip_axis
suggest = id
if not @input_sources.Joy.has_semi_axis(id)
suggest = @input_sources.Joy.suggest_semi_axis(id) ? id
console.error "Did you mean 'Joy:#{suggest}'?"
else
suggest = @input_sources.Key.suggest_button(id) ? id
console.error "Did you mean 'Key:#{suggest}'?"
return {}
if flip_axis
label = source.opposite_axis label
if not label?
# opposite_axis() did output an error
return {}
return {source, source_name, pad_index, label}
class InputSource
constructor: (@context) ->
@source_names = []
# Button objects will be referenced here
# For each pad_index, object with label as key, list of buttons as value
# [{label: [Button, Button, ...]}, ...]
# E.g. Joy3:B12 is (button for button in @buttons[3]['B12'])
@buttons = [{}]
# but semi axes will have just values
# and "axis" objects will reference the values
# but only after @ensure_semi_axis(label) has been called
@semi_axes = [{}] # [{label: {_value}}, ...]
register_source: (aliases) ->
for alias in aliases
@source_names.push alias
@context.input_manager.input_sources[alias] = this
@context.input_manager.input_source_list.push this
return
add_button: (button, source_name, pad_index, label) ->
if not @has_button label
sname = source_name + (if pad_index!=0 then pad_index else '')
console.error "Input #{sname} has no button #{label}"
if (suggestion = @suggest_button label)
console.error "Did you mean '#{sname}:#{suggestion}'?"
else
while @buttons.length <= pad_index
@buttons.push {}
buttons = @buttons[pad_index][label]
if not buttons?
buttons = @buttons[pad_index][label] = []
buttons.push button
add_semi_axis: (axis, source_name, pad_index, label, multiplier) ->
if @has_button label
b = new @context.Button
@add_button b, source_name, pad_index, label
if multiplier < 0
axis._semi_axis_minus.push b
else
axis._semi_axis_plus.push b
else if @has_semi_axis label
semi_axis = @ensure_semi_axis pad_index, label
if semi_axis?
if multiplier < 0
axis._semi_axis_minus.push semi_axis
else
axis._semi_axis_plus.push semi_axis
else
sname = source_name + (if pad_index!=0 then pad_index else '')
console.error "Input #{sname} has no semi axis or button '#{label}'"
if (suggestion = @suggest_semi_axis label)?
console.error "Did you mean '#{sname}:#{suggestion}'?"
has_button: (label) ->
throw Error "Abstract method"
has_semi_axis: (label) ->
throw Error "Abstract method"
suggest_button: ->
suggest_semi_axis: ->
update_controller: ->
throw Error "Abstract method"
opposite_axis: (label) ->
suggestion = @context.input_manager.input_sources.Joy.
suggest_semi_axis(label)
console.error "Input source '#{@source_names[0]}' doesn't have
opposite semi axis. Specify all semi axes."
if suggestion
console.error "Did you mean 'Joy:#{suggestion}'?"
ensure_semi_axis: (pad_index, label) ->
while @semi_axes.length <= pad_index
@semi_axes.push {}
semi_axes = @semi_axes[pad_index][label]
if not semi_axes?
semi_axes = @semi_axes[pad_index][label] = {_value: 0}
return semi_axes
ensure_all_existing_semi_axis: ->
for pad,pad_index in @semi_axes
for label of pad
@ensure_semi_axis pad_index, label
return
class KeyboardInputSource extends InputSource
constructor: (context) ->
super context
@register_source ['Key', 'Keyboard']
if 'code' of KeyboardEvent.prototype
window.addEventListener 'keydown', @_keydown
window.addEventListener 'keyup', @_keyup
else if 'key' of KeyboardEvent.prototype
window.addEventListener 'keydown', @_keydown_old
window.addEventListener 'keyup', @_keyup_old
else
console.error "Your browser is too old!"
has_button: (label) ->
# Can we know if a key exists without adding the whole list here?
return label.length > 1 \
and not /(^(Left|Right|Up|Down))|_/i.test(label) \
and not /(^(Control|Alt|Shift|Meta|OS|Command)$)|_/i.test(label) \
and not /^[^A-Z]/.test(label)
has_semi_axis: (label) -> false
suggest_button: (label) ->
# We guess 95% of the mistakes here
if label.length == 1
suggestion = polyfill_keyevent_code label, 0
if label != suggestion
return suggestion
incorrect_side = label.match /^(Left|Right|Up|Down)(.*)/i
if incorrect_side?
[_, side, rest] = incorrect_side
return capital(rest.replace('_','') or 'Arrow') + capital(side)
if label == 'Command'
return 'OSLeft'
keys_that_need_side = label.match /^(Control|Alt|Shift|Meta|OS)$/i
if keys_that_need_side?
return capital label+'Left'
under_scored = label.split '_'
suggestion = (capital x for x in under_scored).join('')
if suggestion != label
return suggestion
return null
suggest_semi_axis: (label) -> @suggest_button label
update_controller: ->
_keydown: (event) =>
buttons = @buttons[0][event.code]
if buttons?
for button in buttons
button.press()
event.preventDefault()
return
_keyup: (event) =>
buttons = @buttons[0][event.code]
if buttons?
for button in buttons
button.release()
return
_keydown_old: (event) =>
{key, location} = event
event.code = polyfill_keyevent_code key, location
@_keydown event
_keyup_old: (event) =>
{key, location} = event
event.code = polyfill_keyevent_code key, location
@_keyup event
class GamepadInputSource extends InputSource
button_mappings =
'A': 0, 'Cross': 0,
'B': 1, 'Circle': 1,
'X': 2, 'Square': 2,
'Y': 3, 'Triangle': 3,
'LB': 4, 'L1': 4,
'RB': 5, 'R1': 5,
# 'LT': 6, 'L2': 6, # These are semi-axes
# 'RT': 7, 'R2': 7,
'Select': 8, 'Back': 8, 'Share': 8,
'Start': 9, 'Forward': 9, 'Options': 9,
'LS': 10, 'L3': 10,
'RS': 11, 'R3': 11,
'Up': 12, 'DPadUp': 12,
'Down': 13, 'DPadDown': 13,
'Left': 14, 'DPadLeft': 14,
'Right': 15, 'DPadRight': 15,
'System': 16, 'Guide': 16, 'PS': 16
'TouchPad': 17,
button_names = [ 'A', 'B', 'X', 'Y', 'L1', 'R1', 'L2', 'R2', 'Select',
'Start', 'L3', 'R3', 'Up', 'Down', 'Left', 'Right', 'System', 'TouchPad'
]
constructor: (context, id) ->
super context
if not navigator.getGamepads?
return
@register_source ['Joy', 'Joystick', 'Gamepad']
@gamepads = []
@buttons_as_semi_axes = []
# @gamepads = navigator.getGamepads()
window.addEventListener 'gamepadconnected', =>
console.log "A gamepad has been connected or detected"
@gamepads = navigator.getGamepads()
@ensure_all_existing_semi_axis()
window.addEventListener 'gamepaddisconnected', =>
console.log "A gamepad has been disconnected"
@gamepads = navigator.getGamepads()
@ensure_all_existing_semi_axis()
add_button: (button, source_name, pad_index, label) ->
# TODO: This is super ugly!!! We need a generic button/semi_axis class
# All buttons are treated as semi axes for now
if (hb = @has_button label)
index = button_mappings[label]
if index?
label = 'B'+index
super(button, source_name, pad_index, label)
if hb
semi_axis = @ensure_semi_axis pad_index, label
@buttons_as_semi_axes.push button, semi_axis
return
has_button: (label) ->
return label of button_mappings or /^B\d+$/.test(label) \
or @has_semi_axis label
has_semi_axis: (label) ->
return /^([+-](X[12]?|Y[12]?|Axis\d+)|LT|RT|L2|R2)$/.test label
suggest_button: (label) ->
if /^\d+$/.test label
return 'B'+label
label_low = label.replace(/button|[^A-Za-z]+/gi, '').toLowerCase()
for name of button_mappings
if label_low == name.toLowerCase()
return name
return
suggest_semi_axis: (label) ->
if /^\d+$/.test label
return '+Axis' + label
if @has_semi_axis '+' + label
return '+' + label
return @suggest_button label
opposite_axis: (label) ->
if /^[+-]/.test label
return {'+': '-', '-': '+'}[label[0]] + label[1...]
console.error "Input '#{label}' has no opposite semi axis."
if /^(X|Y|Axis)\d*$/.test label
console.error "Did you mean '+#{label}'?"
console.error "Otherwise, specify both semi axes."
else
console.error "Specify both semi axes."
ensure_semi_axis: (pad_index, label) ->
semi_axis = super(pad_index, label)
gamepad = semi_axis.gamepad = @gamepads[pad_index]
# TODO: Remap known non-standard gamepads to standard ones
# E.g. PS4 controller is remapped in Chrome but not in Firefox
semi_axis.type = ''
semi_axis.index = 0
semi_axis.multiplier = 1
if gamepad?
type = 'axes'
xy = label.match /^[+-]([XY])([12]?)$/
if xy?
index = 0
if xy[1] == 'Y'
index = 1
if xy[2] == '2'
index += 2
else if /^(LT|L2)$/.test label
type = 'buttons'
index = 6
else if /^(RT|R2)$/.test label
type = 'buttons'
index = 7
else # +AxisN and Bn
match = label.match /^([+-]Axis|B)(\d+)$/
index = match[2]|0
if match[1] == 'B'
type = 'buttons'
semi_axis.type = type
semi_axis.index = index
if label[0] == '-'
semi_axis.multiplier = -1
if gamepad.mapping == 'standard' and (index == 1 or index == 3)
# We invert Y axes on purpose to match handness
semi_axis.multiplier *= -1
return semi_axis
update_controller: ->
# NOTE: Looks like Chrome only updates gamepad values if we call this
if @gamepads.length
# TODO: Investigate why we had to disable this line in Daydream
navigator.getGamepads()
for pad in @semi_axes
for label, semi_axis of pad
{gamepad, type, index, multiplier} = semi_axis
if gamepad?
n = gamepad[type][index]
semi_axis._value = Math.max 0, ((n.value ? n) * multiplier)
# semi_axis.pressed = n.pressed
# TODO: Redo parts relevant to this, preserving the API
# but making more configurable
{buttons_as_semi_axes} = this
for button,i in buttons_as_semi_axes by 2
semi_axis = buttons_as_semi_axes[i+1]
# TODO: This value is rather arbitrary
# TODO: Do we need hysteresis?
{index} = semi_axis
pressed = semi_axis._value > 0.333
# pressed = semi_axis.pressed or semi_axis._value > 0.333
if pressed != button.pressed
if pressed
button.press()
else
button.release()
return
## Helper functions
capital = (str) ->
return str[0].toUpperCase() + str[1...].toLowerCase()
polyfill_keyevent_code = (key, location) ->
switch location
when 0
key = {
' ': 'Space'
',': 'Comma'
'.': 'Period'
'-': 'Minus'
'/': 'Slash'
'\\': 'Backslash'
'+': 'Plus'
'=': 'Equal'
'`': 'Backquote'
}[key] ? key
if /^\d$/.test key
key = 'Digit'+key
else if key.length == 1
key = 'Key'+key.toUpperCase()
when 1
key += 'Left'
when 2
key += 'Right'
when 3
key = 'Numpad' + {
Delete: 'Decimal'
'.': 'Decimal'
Insert: '0'
End: '1'
ArrowDown: '2'
PageDown: '3'
ArrowLeft: '4'
Unidentified: '5'
ArrowRight: '6'
Home: '7'
ArrowUp: '8'
PageUp: '9'
'+': 'Add'
'-': 'Substract'
'*': 'Multiply'
'/': 'Divide'
}[key] ? key
return key
module.exports = {Button, Axis, Axes2, InputSource, InputManager}
| 87222 |
###
Input module, providing an API for remappeable buttons and axes,
with keyboard and gamepads as input sources for now.
It gives helpful error messages for the vast majority of mistakes.
Example:
axes = new @context.Axes2 'Joy:+X', 'Joy:+Y'
.add_inputs 'Key:ArrowLeft', 'Key:ArrowRight',
'Key:ArrowDown', 'Key:ArrowUp'
jump_btn = new @context.Button 'Key:Space', 'Joy:A', 'Joy:+Y2', 'Joy:RT'
jump_btn.on_press = some_function
console.log axes.value # {x: 0, y: 0, z: 0}
NOTE: I'm very satisfied with this API but not with the code structure.
Expect a rewrite as soon as we need a bit more functionality.
###
{vec3} = require 'vmath'
proxy_warn = {}
if Proxy?
# TODO: Only do this when not in production
warn_f = ->
stack = (new Error).stack.split('\n')
if /^Error/.test stack[0] then stack.shift()
throw Error "This method is not bound.
Declare it with a fat arrow (=>)\n" + stack[1]
proxy_warn = new Proxy {}, get: warn_f, set: warn_f
class Button
constructor: (@context, ids...) ->
for id in ids
{source, source_name, pad_index, label} =
@context.input_manager.parse_id id
if source?
source.add_button this, source_name, pad_index, label
@pressed = @just_pressed = @just_released = false
@_value = 0 # Semi axis simulation
press: ->
if not @pressed
@pressed = @just_pressed = true
@_value = 1
@context.input_manager.pending_reset.push this
@on_press?.call proxy_warn
return this
release: ->
if @pressed
@pressed = false
@just_released = true
@_value = 0
@context.input_manager.pending_reset.push this
@on_release?.call proxy_warn
return this
on_press: null
on_release: null
class Axis
constructor: (@context, minus, plus) ->
@value = 0
# Both of these can be semi axes or buttons,
# Only the property _value will be read from each
@_semi_axis_minus = []
@_semi_axis_plus = []
@_priority = 1 # last pressed key
@context.input_manager.all_axis.push this
@add_inputs minus, plus
add_inputs: (minus, plus) ->
if minus?
flip_minus = false
if not plus?
plus = minus
flip_minus = true
{source, source_name, pad_index, label} = \
@context.input_manager.parse_id minus, flip_minus
if not source?
# This way only suggests one semi axis when you try
# to use an implicit (opposite) axis, i.e. new Axis('X','Y')
return
source?.add_semi_axis this, source_name, pad_index, label, -1
{source, source_name, pad_index, label} = \
@context.input_manager.parse_id plus, false
source?.add_semi_axis this, source_name, pad_index, label, 1
return this
_update: ->
max_plus = max_minus = 0
for {_value, just_pressed} in @_semi_axis_plus
max_plus = Math.max max_plus, _value
if just_pressed then @_priority = 1
for {_value, just_pressed} in @_semi_axis_minus
max_minus = Math.max max_minus, _value
if just_pressed then @_priority = -1
# When both semi axes are digital,
# the last pressed button has the priority
if @_priority > 0
comparison = max_plus >= max_minus
else
comparison = max_plus > max_minus
if comparison
@value = max_plus
else
@value = -max_minus
return
class Axes2
constructor: (@context, minus_x, plus_x, minus_y, plus_y) ->
# vec3 instead of vec2 for convenience
@value = vec3.create()
@x_axis = new Axis @context
@y_axis = new Axis @context
@context.input_manager.all_axes2.push this
@add_inputs minus_x, plus_x, minus_y, plus_y
add_inputs: (minus_x, plus_x, minus_y, plus_y) ->
x = y = x2 = y2 = undefined
if minus_x?
if not plus_x? or minus_y? != plus_y?
throw Error "Invalid parameters. Expected two axes,
four semi axes or none."
if minus_y?
[x, x2] = [minus_x, plus_x]
[y, y2] = [minus_y, plus_y]
else
x = minus_x # actually +X
y = plus_x # actually +Y
@x_axis.add_inputs x, x2
@y_axis.add_inputs y, y2
return this
class InputManager
constructor: (@context) ->
@context.input_manager = this
@input_sources = {}
@input_source_list = []
@pending_reset = []
@all_axis = []
@all_axes2 = []
new KeyboardInputSource @context
new GamepadInputSource @context
update_axes: ->
for source in @input_source_list
source.update_controller()
for axis in @all_axis
axis._update()
for {value, x_axis, y_axis} in @all_axes2
value.x = x_axis.value
value.y = y_axis.value
return
reset_buttons: ->
for button in @pending_reset
button.just_pressed = button.just_released = false
return
parse_id: (id, flip_axis) ->
id = id.toString()
[source_name, label] = id.split ':'
pad_index = 0
if (m = source_name.match /([^\d]*)(\d+)$/)?
source_name = m[1]
pad_index = m[2]|0
source = @input_sources[source_name]
if not source?
console.error "Unknown input source: #{source_name}"
if not label?
if flip_axis
suggest = id
if not @input_sources.Joy.has_semi_axis(id)
suggest = @input_sources.Joy.suggest_semi_axis(id) ? id
console.error "Did you mean 'Joy:#{suggest}'?"
else
suggest = @input_sources.Key.suggest_button(id) ? id
console.error "Did you mean 'Key:#{suggest}'?"
return {}
if flip_axis
label = source.opposite_axis label
if not label?
# opposite_axis() did output an error
return {}
return {source, source_name, pad_index, label}
class InputSource
constructor: (@context) ->
@source_names = []
# Button objects will be referenced here
# For each pad_index, object with label as key, list of buttons as value
# [{label: [Button, Button, ...]}, ...]
# E.g. Joy3:B12 is (button for button in @buttons[3]['B12'])
@buttons = [{}]
# but semi axes will have just values
# and "axis" objects will reference the values
# but only after @ensure_semi_axis(label) has been called
@semi_axes = [{}] # [{label: {_value}}, ...]
register_source: (aliases) ->
for alias in aliases
@source_names.push alias
@context.input_manager.input_sources[alias] = this
@context.input_manager.input_source_list.push this
return
add_button: (button, source_name, pad_index, label) ->
if not @has_button label
sname = source_name + (if pad_index!=0 then pad_index else '')
console.error "Input #{sname} has no button #{label}"
if (suggestion = @suggest_button label)
console.error "Did you mean '#{sname}:#{suggestion}'?"
else
while @buttons.length <= pad_index
@buttons.push {}
buttons = @buttons[pad_index][label]
if not buttons?
buttons = @buttons[pad_index][label] = []
buttons.push button
add_semi_axis: (axis, source_name, pad_index, label, multiplier) ->
if @has_button label
b = new @context.Button
@add_button b, source_name, pad_index, label
if multiplier < 0
axis._semi_axis_minus.push b
else
axis._semi_axis_plus.push b
else if @has_semi_axis label
semi_axis = @ensure_semi_axis pad_index, label
if semi_axis?
if multiplier < 0
axis._semi_axis_minus.push semi_axis
else
axis._semi_axis_plus.push semi_axis
else
sname = source_name + (if pad_index!=0 then pad_index else '')
console.error "Input #{sname} has no semi axis or button '#{label}'"
if (suggestion = @suggest_semi_axis label)?
console.error "Did you mean '#{sname}:#{suggestion}'?"
has_button: (label) ->
throw Error "Abstract method"
has_semi_axis: (label) ->
throw Error "Abstract method"
suggest_button: ->
suggest_semi_axis: ->
update_controller: ->
throw Error "Abstract method"
opposite_axis: (label) ->
suggestion = @context.input_manager.input_sources.Joy.
suggest_semi_axis(label)
console.error "Input source '#{@source_names[0]}' doesn't have
opposite semi axis. Specify all semi axes."
if suggestion
console.error "Did you mean 'Joy:#{suggestion}'?"
ensure_semi_axis: (pad_index, label) ->
while @semi_axes.length <= pad_index
@semi_axes.push {}
semi_axes = @semi_axes[pad_index][label]
if not semi_axes?
semi_axes = @semi_axes[pad_index][label] = {_value: 0}
return semi_axes
ensure_all_existing_semi_axis: ->
for pad,pad_index in @semi_axes
for label of pad
@ensure_semi_axis pad_index, label
return
class KeyboardInputSource extends InputSource
constructor: (context) ->
super context
@register_source ['Key', 'Keyboard']
if 'code' of KeyboardEvent.prototype
window.addEventListener 'keydown', @_keydown
window.addEventListener 'keyup', @_keyup
else if 'key' of KeyboardEvent.prototype
window.addEventListener 'keydown', @_keydown_old
window.addEventListener 'keyup', @_keyup_old
else
console.error "Your browser is too old!"
has_button: (label) ->
# Can we know if a key exists without adding the whole list here?
return label.length > 1 \
and not /(^(Left|Right|Up|Down))|_/i.test(label) \
and not /(^(Control|Alt|Shift|Meta|OS|Command)$)|_/i.test(label) \
and not /^[^A-Z]/.test(label)
has_semi_axis: (label) -> false
suggest_button: (label) ->
# We guess 95% of the mistakes here
if label.length == 1
suggestion = polyfill_keyevent_code label, 0
if label != suggestion
return suggestion
incorrect_side = label.match /^(Left|Right|Up|Down)(.*)/i
if incorrect_side?
[_, side, rest] = incorrect_side
return capital(rest.replace('_','') or 'Arrow') + capital(side)
if label == 'Command'
return 'OSLeft'
keys_that_need_side = label.match /^(Control|Alt|Shift|Meta|OS)$/i
if keys_that_need_side?
return capital label+'Left'
under_scored = label.split '_'
suggestion = (capital x for x in under_scored).join('')
if suggestion != label
return suggestion
return null
suggest_semi_axis: (label) -> @suggest_button label
update_controller: ->
_keydown: (event) =>
buttons = @buttons[0][event.code]
if buttons?
for button in buttons
button.press()
event.preventDefault()
return
_keyup: (event) =>
buttons = @buttons[0][event.code]
if buttons?
for button in buttons
button.release()
return
_keydown_old: (event) =>
{key, location} = event
event.code = polyfill_keyevent_code key, location
@_keydown event
_keyup_old: (event) =>
{key, location} = event
event.code = polyfill_keyevent_code key, location
@_keyup event
class GamepadInputSource extends InputSource
button_mappings =
'A': 0, 'Cross': 0,
'B': 1, 'Circle': 1,
'X': 2, 'Square': 2,
'Y': 3, 'Triangle': 3,
'LB': 4, 'L1': 4,
'RB': 5, 'R1': 5,
# 'LT': 6, 'L2': 6, # These are semi-axes
# 'RT': 7, 'R2': 7,
'Select': 8, 'Back': 8, 'Share': 8,
'Start': 9, 'Forward': 9, 'Options': 9,
'LS': 10, 'L3': 10,
'RS': 11, 'R3': 11,
'Up': 12, 'DPadUp': 12,
'Down': 13, 'DPadDown': 13,
'Left': 14, 'DPadLeft': 14,
'Right': 15, 'DPadRight': 15,
'System': 16, 'Guide': 16, 'PS': 16
'TouchPad': 17,
button_names = [ 'A', 'B', 'X', 'Y', 'L1', 'R1', 'L2', 'R2', 'Select',
'Start', 'L3', 'R3', 'Up', 'Down', 'Left', 'Right', 'System', 'TouchPad'
]
constructor: (context, id) ->
super context
if not navigator.getGamepads?
return
@register_source ['Joy', 'Joystick', 'Gamepad']
@gamepads = []
@buttons_as_semi_axes = []
# @gamepads = navigator.getGamepads()
window.addEventListener 'gamepadconnected', =>
console.log "A gamepad has been connected or detected"
@gamepads = navigator.getGamepads()
@ensure_all_existing_semi_axis()
window.addEventListener 'gamepaddisconnected', =>
console.log "A gamepad has been disconnected"
@gamepads = navigator.getGamepads()
@ensure_all_existing_semi_axis()
add_button: (button, source_name, pad_index, label) ->
# TODO: This is super ugly!!! We need a generic button/semi_axis class
# All buttons are treated as semi axes for now
if (hb = @has_button label)
index = button_mappings[label]
if index?
label = 'B'+index
super(button, source_name, pad_index, label)
if hb
semi_axis = @ensure_semi_axis pad_index, label
@buttons_as_semi_axes.push button, semi_axis
return
has_button: (label) ->
return label of button_mappings or /^B\d+$/.test(label) \
or @has_semi_axis label
has_semi_axis: (label) ->
return /^([+-](X[12]?|Y[12]?|Axis\d+)|LT|RT|L2|R2)$/.test label
suggest_button: (label) ->
if /^\d+$/.test label
return 'B'+label
label_low = label.replace(/button|[^A-Za-z]+/gi, '').toLowerCase()
for name of button_mappings
if label_low == name.toLowerCase()
return name
return
suggest_semi_axis: (label) ->
if /^\d+$/.test label
return '+Axis' + label
if @has_semi_axis '+' + label
return '+' + label
return @suggest_button label
opposite_axis: (label) ->
if /^[+-]/.test label
return {'+': '-', '-': '+'}[label[0]] + label[1...]
console.error "Input '#{label}' has no opposite semi axis."
if /^(X|Y|Axis)\d*$/.test label
console.error "Did you mean '+#{label}'?"
console.error "Otherwise, specify both semi axes."
else
console.error "Specify both semi axes."
ensure_semi_axis: (pad_index, label) ->
semi_axis = super(pad_index, label)
gamepad = semi_axis.gamepad = @gamepads[pad_index]
# TODO: Remap known non-standard gamepads to standard ones
# E.g. PS4 controller is remapped in Chrome but not in Firefox
semi_axis.type = ''
semi_axis.index = 0
semi_axis.multiplier = 1
if gamepad?
type = 'axes'
xy = label.match /^[+-]([XY])([12]?)$/
if xy?
index = 0
if xy[1] == 'Y'
index = 1
if xy[2] == '2'
index += 2
else if /^(LT|L2)$/.test label
type = 'buttons'
index = 6
else if /^(RT|R2)$/.test label
type = 'buttons'
index = 7
else # +AxisN and Bn
match = label.match /^([+-]Axis|B)(\d+)$/
index = match[2]|0
if match[1] == 'B'
type = 'buttons'
semi_axis.type = type
semi_axis.index = index
if label[0] == '-'
semi_axis.multiplier = -1
if gamepad.mapping == 'standard' and (index == 1 or index == 3)
# We invert Y axes on purpose to match handness
semi_axis.multiplier *= -1
return semi_axis
update_controller: ->
# NOTE: Looks like Chrome only updates gamepad values if we call this
if @gamepads.length
# TODO: Investigate why we had to disable this line in Daydream
navigator.getGamepads()
for pad in @semi_axes
for label, semi_axis of pad
{gamepad, type, index, multiplier} = semi_axis
if gamepad?
n = gamepad[type][index]
semi_axis._value = Math.max 0, ((n.value ? n) * multiplier)
# semi_axis.pressed = n.pressed
# TODO: Redo parts relevant to this, preserving the API
# but making more configurable
{buttons_as_semi_axes} = this
for button,i in buttons_as_semi_axes by 2
semi_axis = buttons_as_semi_axes[i+1]
# TODO: This value is rather arbitrary
# TODO: Do we need hysteresis?
{index} = semi_axis
pressed = semi_axis._value > 0.333
# pressed = semi_axis.pressed or semi_axis._value > 0.333
if pressed != button.pressed
if pressed
button.press()
else
button.release()
return
## Helper functions
capital = (str) ->
return str[0].toUpperCase() + str[1...].toLowerCase()
polyfill_keyevent_code = (key, location) ->
switch location
when 0
key = {
' ': 'Space'
',': 'Comma'
'.': 'Period'
'-': 'Minus'
'/': 'Slash'
'\\': 'Backslash'
'+': 'Plus'
'=': 'Equal'
'`': 'Backquote'
}[key] ? key
if /^\d$/.test key
key = 'Digit'+key
else if key.length == 1
key = 'Key'+key.toUpperCase()
when 1
key += 'Left'
when 2
key += 'Right'
when 3
key = '<KEY>' + {
Delete: 'Decimal'
'.': 'Decimal'
Insert: '0'
End: '1'
ArrowDown: '2'
PageDown: '3'
ArrowLeft: '4'
Unidentified: '5'
ArrowRight: '6'
Home: '7'
ArrowUp: '8'
PageUp: '9'
'+': 'Add'
'-': 'Substract'
'*': 'Multiply'
'/': 'Divide'
}[key] ? key
return key
module.exports = {Button, Axis, Axes2, InputSource, InputManager}
| true |
###
Input module, providing an API for remappeable buttons and axes,
with keyboard and gamepads as input sources for now.
It gives helpful error messages for the vast majority of mistakes.
Example:
axes = new @context.Axes2 'Joy:+X', 'Joy:+Y'
.add_inputs 'Key:ArrowLeft', 'Key:ArrowRight',
'Key:ArrowDown', 'Key:ArrowUp'
jump_btn = new @context.Button 'Key:Space', 'Joy:A', 'Joy:+Y2', 'Joy:RT'
jump_btn.on_press = some_function
console.log axes.value # {x: 0, y: 0, z: 0}
NOTE: I'm very satisfied with this API but not with the code structure.
Expect a rewrite as soon as we need a bit more functionality.
###
{vec3} = require 'vmath'
proxy_warn = {}
if Proxy?
# TODO: Only do this when not in production
warn_f = ->
stack = (new Error).stack.split('\n')
if /^Error/.test stack[0] then stack.shift()
throw Error "This method is not bound.
Declare it with a fat arrow (=>)\n" + stack[1]
proxy_warn = new Proxy {}, get: warn_f, set: warn_f
class Button
constructor: (@context, ids...) ->
for id in ids
{source, source_name, pad_index, label} =
@context.input_manager.parse_id id
if source?
source.add_button this, source_name, pad_index, label
@pressed = @just_pressed = @just_released = false
@_value = 0 # Semi axis simulation
press: ->
if not @pressed
@pressed = @just_pressed = true
@_value = 1
@context.input_manager.pending_reset.push this
@on_press?.call proxy_warn
return this
release: ->
if @pressed
@pressed = false
@just_released = true
@_value = 0
@context.input_manager.pending_reset.push this
@on_release?.call proxy_warn
return this
on_press: null
on_release: null
class Axis
constructor: (@context, minus, plus) ->
@value = 0
# Both of these can be semi axes or buttons,
# Only the property _value will be read from each
@_semi_axis_minus = []
@_semi_axis_plus = []
@_priority = 1 # last pressed key
@context.input_manager.all_axis.push this
@add_inputs minus, plus
add_inputs: (minus, plus) ->
if minus?
flip_minus = false
if not plus?
plus = minus
flip_minus = true
{source, source_name, pad_index, label} = \
@context.input_manager.parse_id minus, flip_minus
if not source?
# This way only suggests one semi axis when you try
# to use an implicit (opposite) axis, i.e. new Axis('X','Y')
return
source?.add_semi_axis this, source_name, pad_index, label, -1
{source, source_name, pad_index, label} = \
@context.input_manager.parse_id plus, false
source?.add_semi_axis this, source_name, pad_index, label, 1
return this
_update: ->
max_plus = max_minus = 0
for {_value, just_pressed} in @_semi_axis_plus
max_plus = Math.max max_plus, _value
if just_pressed then @_priority = 1
for {_value, just_pressed} in @_semi_axis_minus
max_minus = Math.max max_minus, _value
if just_pressed then @_priority = -1
# When both semi axes are digital,
# the last pressed button has the priority
if @_priority > 0
comparison = max_plus >= max_minus
else
comparison = max_plus > max_minus
if comparison
@value = max_plus
else
@value = -max_minus
return
class Axes2
constructor: (@context, minus_x, plus_x, minus_y, plus_y) ->
# vec3 instead of vec2 for convenience
@value = vec3.create()
@x_axis = new Axis @context
@y_axis = new Axis @context
@context.input_manager.all_axes2.push this
@add_inputs minus_x, plus_x, minus_y, plus_y
add_inputs: (minus_x, plus_x, minus_y, plus_y) ->
x = y = x2 = y2 = undefined
if minus_x?
if not plus_x? or minus_y? != plus_y?
throw Error "Invalid parameters. Expected two axes,
four semi axes or none."
if minus_y?
[x, x2] = [minus_x, plus_x]
[y, y2] = [minus_y, plus_y]
else
x = minus_x # actually +X
y = plus_x # actually +Y
@x_axis.add_inputs x, x2
@y_axis.add_inputs y, y2
return this
class InputManager
constructor: (@context) ->
@context.input_manager = this
@input_sources = {}
@input_source_list = []
@pending_reset = []
@all_axis = []
@all_axes2 = []
new KeyboardInputSource @context
new GamepadInputSource @context
update_axes: ->
for source in @input_source_list
source.update_controller()
for axis in @all_axis
axis._update()
for {value, x_axis, y_axis} in @all_axes2
value.x = x_axis.value
value.y = y_axis.value
return
reset_buttons: ->
for button in @pending_reset
button.just_pressed = button.just_released = false
return
parse_id: (id, flip_axis) ->
id = id.toString()
[source_name, label] = id.split ':'
pad_index = 0
if (m = source_name.match /([^\d]*)(\d+)$/)?
source_name = m[1]
pad_index = m[2]|0
source = @input_sources[source_name]
if not source?
console.error "Unknown input source: #{source_name}"
if not label?
if flip_axis
suggest = id
if not @input_sources.Joy.has_semi_axis(id)
suggest = @input_sources.Joy.suggest_semi_axis(id) ? id
console.error "Did you mean 'Joy:#{suggest}'?"
else
suggest = @input_sources.Key.suggest_button(id) ? id
console.error "Did you mean 'Key:#{suggest}'?"
return {}
if flip_axis
label = source.opposite_axis label
if not label?
# opposite_axis() did output an error
return {}
return {source, source_name, pad_index, label}
class InputSource
constructor: (@context) ->
@source_names = []
# Button objects will be referenced here
# For each pad_index, object with label as key, list of buttons as value
# [{label: [Button, Button, ...]}, ...]
# E.g. Joy3:B12 is (button for button in @buttons[3]['B12'])
@buttons = [{}]
# but semi axes will have just values
# and "axis" objects will reference the values
# but only after @ensure_semi_axis(label) has been called
@semi_axes = [{}] # [{label: {_value}}, ...]
register_source: (aliases) ->
for alias in aliases
@source_names.push alias
@context.input_manager.input_sources[alias] = this
@context.input_manager.input_source_list.push this
return
add_button: (button, source_name, pad_index, label) ->
if not @has_button label
sname = source_name + (if pad_index!=0 then pad_index else '')
console.error "Input #{sname} has no button #{label}"
if (suggestion = @suggest_button label)
console.error "Did you mean '#{sname}:#{suggestion}'?"
else
while @buttons.length <= pad_index
@buttons.push {}
buttons = @buttons[pad_index][label]
if not buttons?
buttons = @buttons[pad_index][label] = []
buttons.push button
add_semi_axis: (axis, source_name, pad_index, label, multiplier) ->
if @has_button label
b = new @context.Button
@add_button b, source_name, pad_index, label
if multiplier < 0
axis._semi_axis_minus.push b
else
axis._semi_axis_plus.push b
else if @has_semi_axis label
semi_axis = @ensure_semi_axis pad_index, label
if semi_axis?
if multiplier < 0
axis._semi_axis_minus.push semi_axis
else
axis._semi_axis_plus.push semi_axis
else
sname = source_name + (if pad_index!=0 then pad_index else '')
console.error "Input #{sname} has no semi axis or button '#{label}'"
if (suggestion = @suggest_semi_axis label)?
console.error "Did you mean '#{sname}:#{suggestion}'?"
has_button: (label) ->
throw Error "Abstract method"
has_semi_axis: (label) ->
throw Error "Abstract method"
suggest_button: ->
suggest_semi_axis: ->
update_controller: ->
throw Error "Abstract method"
opposite_axis: (label) ->
suggestion = @context.input_manager.input_sources.Joy.
suggest_semi_axis(label)
console.error "Input source '#{@source_names[0]}' doesn't have
opposite semi axis. Specify all semi axes."
if suggestion
console.error "Did you mean 'Joy:#{suggestion}'?"
ensure_semi_axis: (pad_index, label) ->
while @semi_axes.length <= pad_index
@semi_axes.push {}
semi_axes = @semi_axes[pad_index][label]
if not semi_axes?
semi_axes = @semi_axes[pad_index][label] = {_value: 0}
return semi_axes
ensure_all_existing_semi_axis: ->
for pad,pad_index in @semi_axes
for label of pad
@ensure_semi_axis pad_index, label
return
class KeyboardInputSource extends InputSource
constructor: (context) ->
super context
@register_source ['Key', 'Keyboard']
if 'code' of KeyboardEvent.prototype
window.addEventListener 'keydown', @_keydown
window.addEventListener 'keyup', @_keyup
else if 'key' of KeyboardEvent.prototype
window.addEventListener 'keydown', @_keydown_old
window.addEventListener 'keyup', @_keyup_old
else
console.error "Your browser is too old!"
has_button: (label) ->
# Can we know if a key exists without adding the whole list here?
return label.length > 1 \
and not /(^(Left|Right|Up|Down))|_/i.test(label) \
and not /(^(Control|Alt|Shift|Meta|OS|Command)$)|_/i.test(label) \
and not /^[^A-Z]/.test(label)
has_semi_axis: (label) -> false
suggest_button: (label) ->
# We guess 95% of the mistakes here
if label.length == 1
suggestion = polyfill_keyevent_code label, 0
if label != suggestion
return suggestion
incorrect_side = label.match /^(Left|Right|Up|Down)(.*)/i
if incorrect_side?
[_, side, rest] = incorrect_side
return capital(rest.replace('_','') or 'Arrow') + capital(side)
if label == 'Command'
return 'OSLeft'
keys_that_need_side = label.match /^(Control|Alt|Shift|Meta|OS)$/i
if keys_that_need_side?
return capital label+'Left'
under_scored = label.split '_'
suggestion = (capital x for x in under_scored).join('')
if suggestion != label
return suggestion
return null
suggest_semi_axis: (label) -> @suggest_button label
update_controller: ->
_keydown: (event) =>
buttons = @buttons[0][event.code]
if buttons?
for button in buttons
button.press()
event.preventDefault()
return
_keyup: (event) =>
buttons = @buttons[0][event.code]
if buttons?
for button in buttons
button.release()
return
_keydown_old: (event) =>
{key, location} = event
event.code = polyfill_keyevent_code key, location
@_keydown event
_keyup_old: (event) =>
{key, location} = event
event.code = polyfill_keyevent_code key, location
@_keyup event
class GamepadInputSource extends InputSource
button_mappings =
'A': 0, 'Cross': 0,
'B': 1, 'Circle': 1,
'X': 2, 'Square': 2,
'Y': 3, 'Triangle': 3,
'LB': 4, 'L1': 4,
'RB': 5, 'R1': 5,
# 'LT': 6, 'L2': 6, # These are semi-axes
# 'RT': 7, 'R2': 7,
'Select': 8, 'Back': 8, 'Share': 8,
'Start': 9, 'Forward': 9, 'Options': 9,
'LS': 10, 'L3': 10,
'RS': 11, 'R3': 11,
'Up': 12, 'DPadUp': 12,
'Down': 13, 'DPadDown': 13,
'Left': 14, 'DPadLeft': 14,
'Right': 15, 'DPadRight': 15,
'System': 16, 'Guide': 16, 'PS': 16
'TouchPad': 17,
button_names = [ 'A', 'B', 'X', 'Y', 'L1', 'R1', 'L2', 'R2', 'Select',
'Start', 'L3', 'R3', 'Up', 'Down', 'Left', 'Right', 'System', 'TouchPad'
]
constructor: (context, id) ->
super context
if not navigator.getGamepads?
return
@register_source ['Joy', 'Joystick', 'Gamepad']
@gamepads = []
@buttons_as_semi_axes = []
# @gamepads = navigator.getGamepads()
window.addEventListener 'gamepadconnected', =>
console.log "A gamepad has been connected or detected"
@gamepads = navigator.getGamepads()
@ensure_all_existing_semi_axis()
window.addEventListener 'gamepaddisconnected', =>
console.log "A gamepad has been disconnected"
@gamepads = navigator.getGamepads()
@ensure_all_existing_semi_axis()
add_button: (button, source_name, pad_index, label) ->
# TODO: This is super ugly!!! We need a generic button/semi_axis class
# All buttons are treated as semi axes for now
if (hb = @has_button label)
index = button_mappings[label]
if index?
label = 'B'+index
super(button, source_name, pad_index, label)
if hb
semi_axis = @ensure_semi_axis pad_index, label
@buttons_as_semi_axes.push button, semi_axis
return
has_button: (label) ->
return label of button_mappings or /^B\d+$/.test(label) \
or @has_semi_axis label
has_semi_axis: (label) ->
return /^([+-](X[12]?|Y[12]?|Axis\d+)|LT|RT|L2|R2)$/.test label
suggest_button: (label) ->
if /^\d+$/.test label
return 'B'+label
label_low = label.replace(/button|[^A-Za-z]+/gi, '').toLowerCase()
for name of button_mappings
if label_low == name.toLowerCase()
return name
return
suggest_semi_axis: (label) ->
if /^\d+$/.test label
return '+Axis' + label
if @has_semi_axis '+' + label
return '+' + label
return @suggest_button label
opposite_axis: (label) ->
if /^[+-]/.test label
return {'+': '-', '-': '+'}[label[0]] + label[1...]
console.error "Input '#{label}' has no opposite semi axis."
if /^(X|Y|Axis)\d*$/.test label
console.error "Did you mean '+#{label}'?"
console.error "Otherwise, specify both semi axes."
else
console.error "Specify both semi axes."
ensure_semi_axis: (pad_index, label) ->
semi_axis = super(pad_index, label)
gamepad = semi_axis.gamepad = @gamepads[pad_index]
# TODO: Remap known non-standard gamepads to standard ones
# E.g. PS4 controller is remapped in Chrome but not in Firefox
semi_axis.type = ''
semi_axis.index = 0
semi_axis.multiplier = 1
if gamepad?
type = 'axes'
xy = label.match /^[+-]([XY])([12]?)$/
if xy?
index = 0
if xy[1] == 'Y'
index = 1
if xy[2] == '2'
index += 2
else if /^(LT|L2)$/.test label
type = 'buttons'
index = 6
else if /^(RT|R2)$/.test label
type = 'buttons'
index = 7
else # +AxisN and Bn
match = label.match /^([+-]Axis|B)(\d+)$/
index = match[2]|0
if match[1] == 'B'
type = 'buttons'
semi_axis.type = type
semi_axis.index = index
if label[0] == '-'
semi_axis.multiplier = -1
if gamepad.mapping == 'standard' and (index == 1 or index == 3)
# We invert Y axes on purpose to match handness
semi_axis.multiplier *= -1
return semi_axis
update_controller: ->
# NOTE: Looks like Chrome only updates gamepad values if we call this
if @gamepads.length
# TODO: Investigate why we had to disable this line in Daydream
navigator.getGamepads()
for pad in @semi_axes
for label, semi_axis of pad
{gamepad, type, index, multiplier} = semi_axis
if gamepad?
n = gamepad[type][index]
semi_axis._value = Math.max 0, ((n.value ? n) * multiplier)
# semi_axis.pressed = n.pressed
# TODO: Redo parts relevant to this, preserving the API
# but making more configurable
{buttons_as_semi_axes} = this
for button,i in buttons_as_semi_axes by 2
semi_axis = buttons_as_semi_axes[i+1]
# TODO: This value is rather arbitrary
# TODO: Do we need hysteresis?
{index} = semi_axis
pressed = semi_axis._value > 0.333
# pressed = semi_axis.pressed or semi_axis._value > 0.333
if pressed != button.pressed
if pressed
button.press()
else
button.release()
return
## Helper functions
capital = (str) ->
return str[0].toUpperCase() + str[1...].toLowerCase()
polyfill_keyevent_code = (key, location) ->
switch location
when 0
key = {
' ': 'Space'
',': 'Comma'
'.': 'Period'
'-': 'Minus'
'/': 'Slash'
'\\': 'Backslash'
'+': 'Plus'
'=': 'Equal'
'`': 'Backquote'
}[key] ? key
if /^\d$/.test key
key = 'Digit'+key
else if key.length == 1
key = 'Key'+key.toUpperCase()
when 1
key += 'Left'
when 2
key += 'Right'
when 3
key = 'PI:KEY:<KEY>END_PI' + {
Delete: 'Decimal'
'.': 'Decimal'
Insert: '0'
End: '1'
ArrowDown: '2'
PageDown: '3'
ArrowLeft: '4'
Unidentified: '5'
ArrowRight: '6'
Home: '7'
ArrowUp: '8'
PageUp: '9'
'+': 'Add'
'-': 'Substract'
'*': 'Multiply'
'/': 'Divide'
}[key] ? key
return key
module.exports = {Button, Axis, Axes2, InputSource, InputManager}
|
[
{
"context": "ort Firebase from 'firebase'\n\nconfig =\n apiKey: \"AIzaSyDzofwZagAvn4C22B41ekHs5qTUBUMuitg\"\n authDomain: \"vue-loader-firebase-tutorial.fire",
"end": 92,
"score": 0.999748945236206,
"start": 53,
"tag": "KEY",
"value": "AIzaSyDzofwZagAvn4C22B41ekHs5qTUBUMuitg"
}
] | src/Firebase.coffee | AppSynergy/vue-loader-firebase-tutorial | 0 | import Firebase from 'firebase'
config =
apiKey: "AIzaSyDzofwZagAvn4C22B41ekHs5qTUBUMuitg"
authDomain: "vue-loader-firebase-tutorial.firebaseapp.com"
databaseURL: "https://vue-loader-firebase-tutorial.firebaseio.com"
storageBucket: "vue-loader-firebase-tutorial.appspot.com"
messagingSenderId: "940903474211"
firebaseApp = Firebase.initializeApp config
provider = new Firebase.auth.GoogleAuthProvider()
FirebaseAPI =
database: firebaseApp.database()
googleSignin: () -> Firebase.auth().signInWithPopup(provider)
export default FirebaseAPI
| 25932 | import Firebase from 'firebase'
config =
apiKey: "<KEY>"
authDomain: "vue-loader-firebase-tutorial.firebaseapp.com"
databaseURL: "https://vue-loader-firebase-tutorial.firebaseio.com"
storageBucket: "vue-loader-firebase-tutorial.appspot.com"
messagingSenderId: "940903474211"
firebaseApp = Firebase.initializeApp config
provider = new Firebase.auth.GoogleAuthProvider()
FirebaseAPI =
database: firebaseApp.database()
googleSignin: () -> Firebase.auth().signInWithPopup(provider)
export default FirebaseAPI
| true | import Firebase from 'firebase'
config =
apiKey: "PI:KEY:<KEY>END_PI"
authDomain: "vue-loader-firebase-tutorial.firebaseapp.com"
databaseURL: "https://vue-loader-firebase-tutorial.firebaseio.com"
storageBucket: "vue-loader-firebase-tutorial.appspot.com"
messagingSenderId: "940903474211"
firebaseApp = Firebase.initializeApp config
provider = new Firebase.auth.GoogleAuthProvider()
FirebaseAPI =
database: firebaseApp.database()
googleSignin: () -> Firebase.auth().signInWithPopup(provider)
export default FirebaseAPI
|
[
{
"context": " \n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) \n# ",
"end": 824,
"score": 0.9997925162315369,
"start": 814,
"tag": "NAME",
"value": "Mark Masse"
}
] | wrmldoc/js/app/config/jquery.coffee | wrml/wrml | 47 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# CoffeeScript
do ($) ->
$.fn.toggleWrapper = (obj = {}, init = true) ->
_.defaults obj,
className: ""
backgroundColor: if @css("backgroundColor") isnt "transparent" then @css("backgroundColor") else "white"
zIndex: if @css("zIndex") is "auto" or 0 then 1000 else (Number) @css("zIndex")
$offset = @offset()
$width = @outerWidth(false)
$height = @outerHeight(false)
if init
$("<div>")
.appendTo("body")
.addClass(obj.className)
.attr("data-wrapper", true)
.css
width: $width
height: $height
top: $offset.top
left: $offset.left
position: "absolute"
zIndex: obj.zIndex + 1
backgroundColor: obj.backgroundColor
else
$("[data-wrapper]").remove() | 102368 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 <NAME> (OSS project WRML.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# CoffeeScript
do ($) ->
$.fn.toggleWrapper = (obj = {}, init = true) ->
_.defaults obj,
className: ""
backgroundColor: if @css("backgroundColor") isnt "transparent" then @css("backgroundColor") else "white"
zIndex: if @css("zIndex") is "auto" or 0 then 1000 else (Number) @css("zIndex")
$offset = @offset()
$width = @outerWidth(false)
$height = @outerHeight(false)
if init
$("<div>")
.appendTo("body")
.addClass(obj.className)
.attr("data-wrapper", true)
.css
width: $width
height: $height
top: $offset.top
left: $offset.left
position: "absolute"
zIndex: obj.zIndex + 1
backgroundColor: obj.backgroundColor
else
$("[data-wrapper]").remove() | true | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 PI:NAME:<NAME>END_PI (OSS project WRML.org)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# CoffeeScript
do ($) ->
$.fn.toggleWrapper = (obj = {}, init = true) ->
_.defaults obj,
className: ""
backgroundColor: if @css("backgroundColor") isnt "transparent" then @css("backgroundColor") else "white"
zIndex: if @css("zIndex") is "auto" or 0 then 1000 else (Number) @css("zIndex")
$offset = @offset()
$width = @outerWidth(false)
$height = @outerHeight(false)
if init
$("<div>")
.appendTo("body")
.addClass(obj.className)
.attr("data-wrapper", true)
.css
width: $width
height: $height
top: $offset.top
left: $offset.left
position: "absolute"
zIndex: obj.zIndex + 1
backgroundColor: obj.backgroundColor
else
$("[data-wrapper]").remove() |
[
{
"context": "# Author Marek Pietrucha\n# https://github.com/mareczek/international-phone",
"end": 24,
"score": 0.9998866319656372,
"start": 9,
"tag": "NAME",
"value": "Marek Pietrucha"
},
{
"context": "# Author Marek Pietrucha\n# https://github.com/mareczek/international-phone-number\n\n\"use strict\"\nangular.",
"end": 54,
"score": 0.9996892809867859,
"start": 46,
"tag": "USERNAME",
"value": "mareczek"
}
] | public/bower_components/international-phone-number/src/international-phone-number.coffee | techexplora/techtest | 0 | # Author Marek Pietrucha
# https://github.com/mareczek/international-phone-number
"use strict"
angular.module("internationalPhoneNumber", [])
.constant 'ipnConfig', {
allowExtensions: false
autoFormat: true
autoHideDialCode: true
autoPlaceholder: true
customPlaceholder: null
defaultCountry: ""
geoIpLookup: null
nationalMode: true
numberType: "MOBILE"
onlyCountries: undefined
preferredCountries: ['us', 'gb']
utilsScript: ""
}
.directive 'internationalPhoneNumber', ['$timeout', 'ipnConfig', ($timeout, ipnConfig) ->
restrict: 'A'
require: '^ngModel'
scope:
ngModel: '='
link: (scope, element, attrs, ctrl) ->
if ctrl
if element.val() != ''
$timeout () ->
element.intlTelInput 'setNumber', element.val()
ctrl.$setViewValue element.val()
, 0
read = () ->
ctrl.$setViewValue element.val()
handleWhatsSupposedToBeAnArray = (value) ->
if value instanceof Array
value
else
value.toString().replace(/[ ]/g, '').split(',')
options = angular.copy(ipnConfig)
angular.forEach options, (value, key) ->
return unless attrs.hasOwnProperty(key) and angular.isDefined(attrs[key])
option = attrs[key]
if key == 'preferredCountries'
options.preferredCountries = handleWhatsSupposedToBeAnArray option
else if key == 'onlyCountries'
options.onlyCountries = handleWhatsSupposedToBeAnArray option
else if typeof(value) == "boolean"
options[key] = (option == "true")
else
options[key] = option
# Wait for ngModel to be set
watchOnce = scope.$watch('ngModel', (newValue) ->
# Wait to see if other scope variables were set at the same time
scope.$$postDigest ->
if newValue != null && newValue != undefined && newValue.length > 0
if newValue[0] != '+'
newValue = '+' + newValue
element.val newValue
element.intlTelInput(options)
unless attrs.skipUtilScriptDownload != undefined || options.utilsScript
element.intlTelInput('loadUtils', '/bower_components/intl-tel-input/lib/libphonenumber/build/utils.js')
watchOnce()
)
ctrl.$formatters.push (value) ->
if !value
return value
element.intlTelInput 'setNumber', value
element.val()
ctrl.$parsers.push (value) ->
if !value
return value
value.replace(/[^\d]/g, '')
ctrl.$validators.internationalPhoneNumber = (value) ->
selectedCountry = element.intlTelInput('getSelectedCountryData')
if !value || (selectedCountry && selectedCountry.dialCode == value)
return true
element.intlTelInput("isValidNumber")
element.on 'blur keyup change', (event) ->
scope.$apply read
element.on '$destroy', () ->
element.intlTelInput('destroy');
element.off 'blur keyup change'
]
| 142177 | # Author <NAME>
# https://github.com/mareczek/international-phone-number
"use strict"
angular.module("internationalPhoneNumber", [])
.constant 'ipnConfig', {
allowExtensions: false
autoFormat: true
autoHideDialCode: true
autoPlaceholder: true
customPlaceholder: null
defaultCountry: ""
geoIpLookup: null
nationalMode: true
numberType: "MOBILE"
onlyCountries: undefined
preferredCountries: ['us', 'gb']
utilsScript: ""
}
.directive 'internationalPhoneNumber', ['$timeout', 'ipnConfig', ($timeout, ipnConfig) ->
restrict: 'A'
require: '^ngModel'
scope:
ngModel: '='
link: (scope, element, attrs, ctrl) ->
if ctrl
if element.val() != ''
$timeout () ->
element.intlTelInput 'setNumber', element.val()
ctrl.$setViewValue element.val()
, 0
read = () ->
ctrl.$setViewValue element.val()
handleWhatsSupposedToBeAnArray = (value) ->
if value instanceof Array
value
else
value.toString().replace(/[ ]/g, '').split(',')
options = angular.copy(ipnConfig)
angular.forEach options, (value, key) ->
return unless attrs.hasOwnProperty(key) and angular.isDefined(attrs[key])
option = attrs[key]
if key == 'preferredCountries'
options.preferredCountries = handleWhatsSupposedToBeAnArray option
else if key == 'onlyCountries'
options.onlyCountries = handleWhatsSupposedToBeAnArray option
else if typeof(value) == "boolean"
options[key] = (option == "true")
else
options[key] = option
# Wait for ngModel to be set
watchOnce = scope.$watch('ngModel', (newValue) ->
# Wait to see if other scope variables were set at the same time
scope.$$postDigest ->
if newValue != null && newValue != undefined && newValue.length > 0
if newValue[0] != '+'
newValue = '+' + newValue
element.val newValue
element.intlTelInput(options)
unless attrs.skipUtilScriptDownload != undefined || options.utilsScript
element.intlTelInput('loadUtils', '/bower_components/intl-tel-input/lib/libphonenumber/build/utils.js')
watchOnce()
)
ctrl.$formatters.push (value) ->
if !value
return value
element.intlTelInput 'setNumber', value
element.val()
ctrl.$parsers.push (value) ->
if !value
return value
value.replace(/[^\d]/g, '')
ctrl.$validators.internationalPhoneNumber = (value) ->
selectedCountry = element.intlTelInput('getSelectedCountryData')
if !value || (selectedCountry && selectedCountry.dialCode == value)
return true
element.intlTelInput("isValidNumber")
element.on 'blur keyup change', (event) ->
scope.$apply read
element.on '$destroy', () ->
element.intlTelInput('destroy');
element.off 'blur keyup change'
]
| true | # Author PI:NAME:<NAME>END_PI
# https://github.com/mareczek/international-phone-number
"use strict"
angular.module("internationalPhoneNumber", [])
.constant 'ipnConfig', {
allowExtensions: false
autoFormat: true
autoHideDialCode: true
autoPlaceholder: true
customPlaceholder: null
defaultCountry: ""
geoIpLookup: null
nationalMode: true
numberType: "MOBILE"
onlyCountries: undefined
preferredCountries: ['us', 'gb']
utilsScript: ""
}
.directive 'internationalPhoneNumber', ['$timeout', 'ipnConfig', ($timeout, ipnConfig) ->
restrict: 'A'
require: '^ngModel'
scope:
ngModel: '='
link: (scope, element, attrs, ctrl) ->
if ctrl
if element.val() != ''
$timeout () ->
element.intlTelInput 'setNumber', element.val()
ctrl.$setViewValue element.val()
, 0
read = () ->
ctrl.$setViewValue element.val()
handleWhatsSupposedToBeAnArray = (value) ->
if value instanceof Array
value
else
value.toString().replace(/[ ]/g, '').split(',')
options = angular.copy(ipnConfig)
angular.forEach options, (value, key) ->
return unless attrs.hasOwnProperty(key) and angular.isDefined(attrs[key])
option = attrs[key]
if key == 'preferredCountries'
options.preferredCountries = handleWhatsSupposedToBeAnArray option
else if key == 'onlyCountries'
options.onlyCountries = handleWhatsSupposedToBeAnArray option
else if typeof(value) == "boolean"
options[key] = (option == "true")
else
options[key] = option
# Wait for ngModel to be set
watchOnce = scope.$watch('ngModel', (newValue) ->
# Wait to see if other scope variables were set at the same time
scope.$$postDigest ->
if newValue != null && newValue != undefined && newValue.length > 0
if newValue[0] != '+'
newValue = '+' + newValue
element.val newValue
element.intlTelInput(options)
unless attrs.skipUtilScriptDownload != undefined || options.utilsScript
element.intlTelInput('loadUtils', '/bower_components/intl-tel-input/lib/libphonenumber/build/utils.js')
watchOnce()
)
ctrl.$formatters.push (value) ->
if !value
return value
element.intlTelInput 'setNumber', value
element.val()
ctrl.$parsers.push (value) ->
if !value
return value
value.replace(/[^\d]/g, '')
ctrl.$validators.internationalPhoneNumber = (value) ->
selectedCountry = element.intlTelInput('getSelectedCountryData')
if !value || (selectedCountry && selectedCountry.dialCode == value)
return true
element.intlTelInput("isValidNumber")
element.on 'blur keyup change', (event) ->
scope.$apply read
element.on '$destroy', () ->
element.intlTelInput('destroy');
element.off 'blur keyup change'
]
|
[
{
"context": "s:\n# {\n# hello: \"world\",\n# name: \"mr. Dasde\"\n# }\nqc.objectLike = (template) ->\n (size) -",
"end": 355,
"score": 0.9991492033004761,
"start": 346,
"tag": "NAME",
"value": "mr. Dasde"
}
] | src/generators/object.coffee | gampleman/quick_check.js | 41 | # ### Object generators
# `qc.objectLike` accepts a template of an object with random generators as values,
# and returns a generator of that form of object.
#
# qc.objectLike({
# hello: "world",
# name: qc.string.matching(/^m(r|s)\. [A-Z][a-z]{3,9}$/)
# })(size) // generates:
# {
# hello: "world",
# name: "mr. Dasde"
# }
qc.objectLike = (template) ->
(size) ->
result = {}
for key, value of template
if typeof value == 'function'
result[key] = value(size)
else
result[key] = value
result
# `qc.objectOf` generates an object containing the passed type as its values.
qc.objectOf = (generator, keygen = qc.string) ->
(size) ->
result = {}
for i in [0..qc.intUpto(size)]
result[keygen(size)] = generator(i)
result
# `qc.object` generates an object containing random types
qc.object = (size) -> qc.objectOf(qc.any)(size)
| 163362 | # ### Object generators
# `qc.objectLike` accepts a template of an object with random generators as values,
# and returns a generator of that form of object.
#
# qc.objectLike({
# hello: "world",
# name: qc.string.matching(/^m(r|s)\. [A-Z][a-z]{3,9}$/)
# })(size) // generates:
# {
# hello: "world",
# name: "<NAME>"
# }
qc.objectLike = (template) ->
(size) ->
result = {}
for key, value of template
if typeof value == 'function'
result[key] = value(size)
else
result[key] = value
result
# `qc.objectOf` generates an object containing the passed type as its values.
qc.objectOf = (generator, keygen = qc.string) ->
(size) ->
result = {}
for i in [0..qc.intUpto(size)]
result[keygen(size)] = generator(i)
result
# `qc.object` generates an object containing random types
qc.object = (size) -> qc.objectOf(qc.any)(size)
| true | # ### Object generators
# `qc.objectLike` accepts a template of an object with random generators as values,
# and returns a generator of that form of object.
#
# qc.objectLike({
# hello: "world",
# name: qc.string.matching(/^m(r|s)\. [A-Z][a-z]{3,9}$/)
# })(size) // generates:
# {
# hello: "world",
# name: "PI:NAME:<NAME>END_PI"
# }
qc.objectLike = (template) ->
(size) ->
result = {}
for key, value of template
if typeof value == 'function'
result[key] = value(size)
else
result[key] = value
result
# `qc.objectOf` generates an object containing the passed type as its values.
qc.objectOf = (generator, keygen = qc.string) ->
(size) ->
result = {}
for i in [0..qc.intUpto(size)]
result[keygen(size)] = generator(i)
result
# `qc.object` generates an object containing random types
qc.object = (size) -> qc.objectOf(qc.any)(size)
|
[
{
"context": "###\n @author Gilles Gerlinger\n Copyright 2016. All rights reserved.\n###\n\nexpre",
"end": 30,
"score": 0.9998646378517151,
"start": 14,
"tag": "NAME",
"value": "Gilles Gerlinger"
}
] | test/server.coffee | gigerlin/easyRPC | 1 | ###
@author Gilles Gerlinger
Copyright 2016. All rights reserved.
###
express = require 'express'
#connect = require 'connect'
expressRpc = require('avs-easyrpc').server
store = express()
store.use express.static(__dirname + '/')
process.on 'uncaughtException', (err) -> console.log 'Caught exception: ', err.stack
store.listen port = 4145, ->
console.log "Server started at #{port}", new Date(), '\n'
expressRpc store, { Employee:require('./employee'), Customer:require('./customer') }, timeOut:10 * 60 * 1000
| 127384 | ###
@author <NAME>
Copyright 2016. All rights reserved.
###
express = require 'express'
#connect = require 'connect'
expressRpc = require('avs-easyrpc').server
store = express()
store.use express.static(__dirname + '/')
process.on 'uncaughtException', (err) -> console.log 'Caught exception: ', err.stack
store.listen port = 4145, ->
console.log "Server started at #{port}", new Date(), '\n'
expressRpc store, { Employee:require('./employee'), Customer:require('./customer') }, timeOut:10 * 60 * 1000
| true | ###
@author PI:NAME:<NAME>END_PI
Copyright 2016. All rights reserved.
###
express = require 'express'
#connect = require 'connect'
expressRpc = require('avs-easyrpc').server
store = express()
store.use express.static(__dirname + '/')
process.on 'uncaughtException', (err) -> console.log 'Caught exception: ', err.stack
store.listen port = 4145, ->
console.log "Server started at #{port}", new Date(), '\n'
expressRpc store, { Employee:require('./employee'), Customer:require('./customer') }, timeOut:10 * 60 * 1000
|
[
{
"context": "logs and that sort of stuff\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Modal extends Element\n extend:\n curre",
"end": 106,
"score": 0.9998878836631775,
"start": 89,
"tag": "NAME",
"value": "Nikolay Nemshilov"
},
{
"context": "imeout = new Date()\n Modal.current.limit_size(@size())\n\n\n\n",
"end": 3356,
"score": 0.5297212600708008,
"start": 3352,
"tag": "USERNAME",
"value": "size"
}
] | ui/core/src/modal.coffee | lovely-io/lovely.io-stl | 2 | #
# Generic modal screen unit. for dialogs and that sort of stuff
#
# Copyright (C) 2012 Nikolay Nemshilov
#
class Modal extends Element
extend:
current: null
offsetX: 40
offsetY: 40
#
# Basic constructor
#
# NOTE: the `html` attribute will be inserted into the `inner`
# block, not inside of the main modal container!
#
# @param {Object} html options
# @return {Modal} self
#
constructor: (options)->
options = merge_options(options, { class: 'lui-modal lui-locker' })
html = options.html || '';
options.html = '<div class="lui-inner"></div>'
options['class'] += ' lui-modal-nolock' if options.nolock is true; delete(options.nolock)
options['class'] += ' lui-modal-overlap' if options.overlap is true; delete(options.overlap)
super('div', options)
@_inner = @dialog = @first('.lui-inner')
@_inner.insert(html)
return @
#
# Bypassing the {Element#html} calls to the inner element
#
# @return {Modal} self
#
html: ->
@_inner.html.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#html} calls to the inner element
#
# @return {Modal} self
#
text: ->
@_inner.text.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#insert} calls to the inner element
#
# @return {Modal} self
#
insert: ()->
@_inner.insert.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#update} calls to the inner element
#
# @return {Modal} self
#
update: ()->
@_inner.update.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#clear} calls to the inner element
#
# @return {Modal} self
#
clear: ()->
@_inner.clear()
return @
#
# Automatically inserts the element into the `document.body`
#
# @return {Modal} self
#
show: ()->
hide_all_modals() unless @hasClass('lui-modal-overlap')
@insertTo(document.body)
@$super.apply(@, arguments)
@limit_size(dom_window.size())
Modal.current = @constructor.current = @emit('show')
#
# Removes the whole thing out of the `document.body`
#
# @return {Modal} self
#
hide: ->
Modal.current = @constructor.current = null
@emit('hide').remove()
#
# Sets the size limits for the image
#
# @param {Object} x: N, y: N size
# @return {Zoom} this
#
limit_size: (size)->
@dialog._.style.maxWidth = size.x - (@constructor.offsetX || Modal.offsetX) + 'px'
@dialog._.style.maxHeight = size.y - (@constructor.offsetX || Modal.offsetY) + 'px'
return @
# hides all visible modals on the page
hide_all_modals = ->
modals = dom('div.lui-modal'); last_modal = modals[modals.length - 1]
if last_modal && last_modal.hasClass('lui-modal-overlap')
last_modal.remove()
else
modals.forEach('remove')
# hide all modals when the user presses 'escape'
dom(document).on('esc', hide_all_modals)
dom(document).on 'click', (event)->
if Modal.current && (Modal.current == event.target || !event.find('.lui-modal'))
Modal.current.hide()
Modal.current = dom('div.lui-modal').pop() || null
# setting up the dialog max-sizes with the window
resize_timeout = new Date()
dom_window = dom(window).on 'resize', ->
if Modal.current isnt null && (new Date() - resize_timeout) > 1
resize_timeout = new Date()
Modal.current.limit_size(@size())
| 100341 | #
# Generic modal screen unit. for dialogs and that sort of stuff
#
# Copyright (C) 2012 <NAME>
#
class Modal extends Element
extend:
current: null
offsetX: 40
offsetY: 40
#
# Basic constructor
#
# NOTE: the `html` attribute will be inserted into the `inner`
# block, not inside of the main modal container!
#
# @param {Object} html options
# @return {Modal} self
#
constructor: (options)->
options = merge_options(options, { class: 'lui-modal lui-locker' })
html = options.html || '';
options.html = '<div class="lui-inner"></div>'
options['class'] += ' lui-modal-nolock' if options.nolock is true; delete(options.nolock)
options['class'] += ' lui-modal-overlap' if options.overlap is true; delete(options.overlap)
super('div', options)
@_inner = @dialog = @first('.lui-inner')
@_inner.insert(html)
return @
#
# Bypassing the {Element#html} calls to the inner element
#
# @return {Modal} self
#
html: ->
@_inner.html.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#html} calls to the inner element
#
# @return {Modal} self
#
text: ->
@_inner.text.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#insert} calls to the inner element
#
# @return {Modal} self
#
insert: ()->
@_inner.insert.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#update} calls to the inner element
#
# @return {Modal} self
#
update: ()->
@_inner.update.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#clear} calls to the inner element
#
# @return {Modal} self
#
clear: ()->
@_inner.clear()
return @
#
# Automatically inserts the element into the `document.body`
#
# @return {Modal} self
#
show: ()->
hide_all_modals() unless @hasClass('lui-modal-overlap')
@insertTo(document.body)
@$super.apply(@, arguments)
@limit_size(dom_window.size())
Modal.current = @constructor.current = @emit('show')
#
# Removes the whole thing out of the `document.body`
#
# @return {Modal} self
#
hide: ->
Modal.current = @constructor.current = null
@emit('hide').remove()
#
# Sets the size limits for the image
#
# @param {Object} x: N, y: N size
# @return {Zoom} this
#
limit_size: (size)->
@dialog._.style.maxWidth = size.x - (@constructor.offsetX || Modal.offsetX) + 'px'
@dialog._.style.maxHeight = size.y - (@constructor.offsetX || Modal.offsetY) + 'px'
return @
# hides all visible modals on the page
hide_all_modals = ->
modals = dom('div.lui-modal'); last_modal = modals[modals.length - 1]
if last_modal && last_modal.hasClass('lui-modal-overlap')
last_modal.remove()
else
modals.forEach('remove')
# hide all modals when the user presses 'escape'
dom(document).on('esc', hide_all_modals)
dom(document).on 'click', (event)->
if Modal.current && (Modal.current == event.target || !event.find('.lui-modal'))
Modal.current.hide()
Modal.current = dom('div.lui-modal').pop() || null
# setting up the dialog max-sizes with the window
resize_timeout = new Date()
dom_window = dom(window).on 'resize', ->
if Modal.current isnt null && (new Date() - resize_timeout) > 1
resize_timeout = new Date()
Modal.current.limit_size(@size())
| true | #
# Generic modal screen unit. for dialogs and that sort of stuff
#
# Copyright (C) 2012 PI:NAME:<NAME>END_PI
#
class Modal extends Element
extend:
current: null
offsetX: 40
offsetY: 40
#
# Basic constructor
#
# NOTE: the `html` attribute will be inserted into the `inner`
# block, not inside of the main modal container!
#
# @param {Object} html options
# @return {Modal} self
#
constructor: (options)->
options = merge_options(options, { class: 'lui-modal lui-locker' })
html = options.html || '';
options.html = '<div class="lui-inner"></div>'
options['class'] += ' lui-modal-nolock' if options.nolock is true; delete(options.nolock)
options['class'] += ' lui-modal-overlap' if options.overlap is true; delete(options.overlap)
super('div', options)
@_inner = @dialog = @first('.lui-inner')
@_inner.insert(html)
return @
#
# Bypassing the {Element#html} calls to the inner element
#
# @return {Modal} self
#
html: ->
@_inner.html.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#html} calls to the inner element
#
# @return {Modal} self
#
text: ->
@_inner.text.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#insert} calls to the inner element
#
# @return {Modal} self
#
insert: ()->
@_inner.insert.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#update} calls to the inner element
#
# @return {Modal} self
#
update: ()->
@_inner.update.apply(@_inner, arguments)
return @
#
# Bypassing the {Element#clear} calls to the inner element
#
# @return {Modal} self
#
clear: ()->
@_inner.clear()
return @
#
# Automatically inserts the element into the `document.body`
#
# @return {Modal} self
#
show: ()->
hide_all_modals() unless @hasClass('lui-modal-overlap')
@insertTo(document.body)
@$super.apply(@, arguments)
@limit_size(dom_window.size())
Modal.current = @constructor.current = @emit('show')
#
# Removes the whole thing out of the `document.body`
#
# @return {Modal} self
#
hide: ->
Modal.current = @constructor.current = null
@emit('hide').remove()
#
# Sets the size limits for the image
#
# @param {Object} x: N, y: N size
# @return {Zoom} this
#
limit_size: (size)->
@dialog._.style.maxWidth = size.x - (@constructor.offsetX || Modal.offsetX) + 'px'
@dialog._.style.maxHeight = size.y - (@constructor.offsetX || Modal.offsetY) + 'px'
return @
# hides all visible modals on the page
hide_all_modals = ->
modals = dom('div.lui-modal'); last_modal = modals[modals.length - 1]
if last_modal && last_modal.hasClass('lui-modal-overlap')
last_modal.remove()
else
modals.forEach('remove')
# hide all modals when the user presses 'escape'
dom(document).on('esc', hide_all_modals)
dom(document).on 'click', (event)->
if Modal.current && (Modal.current == event.target || !event.find('.lui-modal'))
Modal.current.hide()
Modal.current = dom('div.lui-modal').pop() || null
# setting up the dialog max-sizes with the window
resize_timeout = new Date()
dom_window = dom(window).on 'resize', ->
if Modal.current isnt null && (new Date() - resize_timeout) > 1
resize_timeout = new Date()
Modal.current.limit_size(@size())
|
[
{
"context": "limit: 15\n\t}, {\n\t\tname: 'spotify',\n\t\tdisplayKey: 'value',\n\t\tsource: tracks.ttAdapter(),\n\t\ttemplates:\n\t\t\ts",
"end": 3763,
"score": 0.5284417867660522,
"start": 3758,
"tag": "KEY",
"value": "value"
},
{
"context": "\nADMIN = false\nfor key in cookie_data\n\tif key == 'chalmersItAuth'\n\t\t$.ajax\n\t\t\turl: 'https://chalmers.it/auth/userI",
"end": 4170,
"score": 0.9910967946052551,
"start": 4156,
"tag": "KEY",
"value": "chalmersItAuth"
},
{
"context": "eed'\n\t$status = $ '#nowPlaying .media'\n\tLS_KEY = 'items'\n\tlist = {}\n\tsent = false\n\tupdates = 0\n\n\tget_list",
"end": 5901,
"score": 0.9921444654464722,
"start": 5896,
"tag": "KEY",
"value": "items"
}
] | client/assets/scripts/application.coffee | cthit/playIT-grails | 0 |
## Settings
SERVER = "http://hubben.chalmers.it:8080/playIT/media"
YOUTUBE = "http://gdata.youtube.com/feeds/api/videos?alt=json&q=%QUERY"
SPOTIFY = "http://ws.spotify.com/search/1/track.json?q=%QUERY"
TIMEOUT = null
TEMPLATES =
spotify: Handlebars.compile $('#spotify-partial').html()
youtube: Handlebars.compile $('#youtube-partial').html()
'spotify-typeahead': Handlebars.compile $('#typeahead-spotify-partial').html()
'youtube-typeahead': Handlebars.compile $('#typeahead-youtube-partial').html()
playing: Handlebars.compile $('#playing').html()
## Handlebars view-helpers
Handlebars.registerHelper 'join', (array) ->
new Handlebars.SafeString array.join(", ")
Handlebars.registerHelper 'ntobr', (string) ->
new Handlebars.SafeString string.replace /\n/g, '<br>'
Handlebars.registerHelper 'desc', (string) ->
index = string.indexOf '\n', 140
string = string.substr 0, index if index != -1
new Handlebars.SafeString string #.replace /\n/g, '<br>'
Handlebars.registerHelper 'url', (type, id) ->
urls =
'spotify': "http://open.spotify.com/track/#{id}"
'youtube': "http://youtu.be/#{id}"
'soundcloud': "http://soundcloud.com/#{id}"
new Handlebars.SafeString urls[type]
Handlebars.registerHelper 'format_time', (seconds) ->
hours = parseInt(seconds / 3600)
seconds -= hours * 3600
minutes = parseInt(seconds / 60)
seconds -= minutes * 60
new Handlebars.SafeString "#{if hours > 0 then hours + ':' else ''}#{(if minutes > 9 then '' else '0') + minutes}:#{(if seconds > 9 then '' else '0') + seconds}"
## Typeahead!
tracks = new Bloodhound
datumTokenizer: (d) -> Bloodhound.tokenizers.whitespace d.value,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote:
url: SPOTIFY,
filter: (json) ->
result = []
for track in json.tracks
result.push
value: track.name,
link: track.href,
artists: track.artists.map( (a) -> a.name).join ', '
album: track.album.name
result
videos = new Bloodhound
datumTokenizer: (d) -> Bloodhound.tokenizers.whitespace d.value,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote:
url: YOUTUBE,
filter: (json) ->
result = []
if json.feed.entry?
for video in json.feed.entry
link = video.id.$t.split('/')
result.push
value: video.title.$t,
link: 'youtu.be/' + link[link.length - 1],
artists: video.author.map( (a) -> a.name.$t).join ', '
result
videos.initialize()
tracks.initialize()
$ '#videofeed'
.on 'click', '.x-button', ->
$el = $(this).parent()
item = $el.data 'item'
if confirm "Confirm deletion of \"#{item.title}\"?"
app.removeItemFromQueue(item)
$el.remove()
.on 'click', '.upvote, .downvote', ->
# If trying to up-/downvote when already up-/downvoted
return if $(this).hasClass 'active'
$el = $(this).parent().parent()
up = $(this).hasClass 'upvote'
item = $el.data 'item'
app.addVote item, up
rate = if item.id of app.get_list() then 2 else 1
$(this).parent().find('.rating').html(item.weight + if up then rate else -rate)
if up
$el.find('.upvote').addClass 'active'
$el.find('.downvote').removeClass 'active'
else
$el.find('.upvote').removeClass 'active'
$el.find('.downvote').addClass 'active'
# Bind events for parsing input url/id
$insert_video = $ '#insert_video'
read_searchfield = (e) ->
value = $insert_video.val()
app.parseInput(value);
$ '#searchfield button'
.on 'click', read_searchfield
$insert_video
.on 'keydown', (e) -> read_searchfield() if e.which == 13
.typeahead {
minLength: 4
}, {
name: 'youtube',
displayKey: 'value',
source: videos.ttAdapter(),
templates:
suggestion: TEMPLATES['youtube-typeahead']
# suggestion: Handlebars.templates.typeahead
limit: 15
}, {
name: 'spotify',
displayKey: 'value',
source: tracks.ttAdapter(),
templates:
suggestion: TEMPLATES['spotify-typeahead']
# suggestion: Handlebars.templates.typeahead
limit: 15
}
.on 'typeahead:selected', (obj, data) ->
if app.parseInput data.link
$(this).val('')
## Basic detction if user has cookie, not fail-safe
cookie_data = document.cookie.split /; |=/
ADMIN = false
for key in cookie_data
if key == 'chalmersItAuth'
$.ajax
url: 'https://chalmers.it/auth/userInfo.php',
xhrFields: { withCredentials: true },
dataType: 'jsonp'
.done (data) ->
ADMIN = 'playITAdmin' in data.groups
$('#videofeed').addClass('admin') if ADMIN
## MediaItem: base class for YouTube- and SpotifyItem
class MediaItem
constructor: (@id, @type) ->
@matches: (id, regex) ->
result = id.match regex
result[result.length - 1] if result?
class YouTubeItem extends MediaItem
@REGEX: /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]+).*/
constructor: (url) ->
@id = YouTubeItem.matches url.trim()
if @id?
super @id, 'youtube'
else
throw new Error "Cannot create YouTubeItem, invalid url: \"#{url}\""
@matches: (id) ->
super id, @REGEX
class SpotifyItem extends MediaItem
@REGEX: /^(.*open\.)?spotify(\.com)?[\/:]track[\/:]([a-zA-Z0-9]+)$/
constructor: (uri) ->
@id = SpotifyItem.matches uri.trim()
if @id?
super @id, 'spotify'
else
throw new Error "Cannot create SpotifyItem, invalid uri: \"#{uri}\""
@matches: (id) ->
super id, @REGEX
class SoundCloudItem extends MediaItem
@REGEX: /^https?:\/\/soundcloud.com\/([\w-]+\/\w+)$/
constructor: (url) ->
temp_id = SoundCloudItem.matches url.trim()
if temp_id?
@resolve temp_id
super @id, 'soundcloud'
else
throw new Error "Cannot create SoundCloudItem, invalid url: \"#{url}\""
resolve: (id) ->
$.getJSON 'http://api.soundcloud.com/resolve.json', {
url: "http://soundcloud.com/#{id}",
client_id: 'a2cfca0784004b38b85829ba183327cb' }, (data) =>
@id = data.id
@matches: (id) ->
super id, @REGEX
## Main class for the application
class App
$feed = $ '#videofeed'
$status = $ '#nowPlaying .media'
LS_KEY = 'items'
list = {}
sent = false
updates = 0
get_list: ->
return list
constructor: ->
if window.localStorage && window.localStorage.hasOwnProperty(LS_KEY)
data = window.localStorage.getItem(LS_KEY)
list = JSON.parse data
parseInput: (string) ->
if YouTubeItem.matches string
@addMediaItem new YouTubeItem string
return true
else if SpotifyItem.matches string
@addMediaItem new SpotifyItem string
return true
else if SoundCloudItem.matches string
@addMediaItem new SoundCloudItem string
return true
else
console.log string
return false
addMediaItem: (item) ->
method = 'addMediaItem'
updates++
query method, {id: item.id, type: item.type}, (body) =>
index = body.indexOf "Fail:"
if index == 0
toaster.err body
else
toaster.toast body
list[item.id] = true
saveList()
@showQueue()
addVote: (item, up) ->
method = 'addVote'
updates++
query method, {id: item.id, upvote: if up then 1 else 0}, (body) =>
console.log body
list[item.id] = up
saveList()
@showQueue()
query = (method, params, callback) ->
url = "#{SERVER}/#{method}"
if typeof params == "function"
callback = params
params = {}
$.ajax
url: url,
xhrFields: { withCredentials: true },
beforeSend: ->
progressJs().start().autoIncrease(4, 500)
data: params
.done (body) ->
progressJs().end()
updates--
callback(body)
nowPlaying: ->
method = 'nowPlaying'
query method, (data) ->
unless data.length > 0
$status.html TEMPLATES.playing(data)
changeLimit: (limit) ->
method = 'changeLimit'
query method, {limit: limit}, (body) ->
console.log body
saveList = ->
window.localStorage.setItem LS_KEY, JSON.stringify list
showQueue: ->
unless TIMEOUT == null
clearTimeout TIMEOUT
TIMEOUT = null
updates++
method = 'showQueue'
query method, (body) =>
return if updates > 0
data = JSON.parse body
$feed.find('div.media').each (index, elem) ->
elem = $(elem)
item = elem.data 'item'
data_item = null
for i in data
if i.externalID == item.id
data_item = i
break
if data_item == null || item.weight == data_item.weight
return
else
item.weight = data_item.weight
elem.find('.rating').html(item.weight)
app.nowPlaying()
if data.length == $feed.find('div.media').length
TIMEOUT = setTimeout(app.showQueue, 10000)
return
items = []
savedIds = []
for item in data
if list[item.externalID]?
element_class = if list[item.externalID] then 'upvoted' else 'downvoted'
# element = Handlebars.templates["#{item.type}-partial"](item)
element = TEMPLATES["#{item.type}"](item)
savedIds.push item.externalID
$el = $ element
.data 'item', id: item.externalID, title: item.title, weight: item.weight
.addClass element_class
items.push $el
$feed.html(items)
for key of list
delete list[key] if key not in savedIds
saveList()
TIMEOUT = setTimeout(app.showQueue, 10000)
removeItemFromQueue: (item) ->
method = 'removeItemFromQueue'
updates++
query method, {id: item.id}, (body) =>
console.log body
# @showQueue()
## Class for displaying messages to the user
class Toaster
toaster = $ '#toaster'
queue = []
constructor: ->
toaster.on 'click', close
close = ->
queue.shift()
if queue.length != 0
toaster.animate height: 10, printNext
return
toaster.animate height: 0, ->
toaster.hide()
queuePrint = (string, err) ->
queue.push {string: string, err: err}
printNext() if queue.length == 1
printNext = ->
{string, err} = queue[0]
if err
string = "<span style=\"color: red\">#{string}</span>"
toaster
.show()
.html "<br>#{string}<br><small>(Click to dismiss)</small>"
.animate height: 100, ->
setTimeout close, 2000
err: (string) ->
console.error string
queuePrint string, true
toast: (string) ->
queuePrint string, false
window.app = new App()
window.toaster = new Toaster()
app.showQueue() #if found
# app.addMediaItem new YouTubeItem 'https://www.youtube.com/watch?v=moSFlvxnbgk'
# app.addMediaItem new SpotifyItem 'spotify:track:10Ip8PpzXoYQe4e3mSgoOy'
| 183370 |
## Settings
SERVER = "http://hubben.chalmers.it:8080/playIT/media"
YOUTUBE = "http://gdata.youtube.com/feeds/api/videos?alt=json&q=%QUERY"
SPOTIFY = "http://ws.spotify.com/search/1/track.json?q=%QUERY"
TIMEOUT = null
TEMPLATES =
spotify: Handlebars.compile $('#spotify-partial').html()
youtube: Handlebars.compile $('#youtube-partial').html()
'spotify-typeahead': Handlebars.compile $('#typeahead-spotify-partial').html()
'youtube-typeahead': Handlebars.compile $('#typeahead-youtube-partial').html()
playing: Handlebars.compile $('#playing').html()
## Handlebars view-helpers
Handlebars.registerHelper 'join', (array) ->
new Handlebars.SafeString array.join(", ")
Handlebars.registerHelper 'ntobr', (string) ->
new Handlebars.SafeString string.replace /\n/g, '<br>'
Handlebars.registerHelper 'desc', (string) ->
index = string.indexOf '\n', 140
string = string.substr 0, index if index != -1
new Handlebars.SafeString string #.replace /\n/g, '<br>'
Handlebars.registerHelper 'url', (type, id) ->
urls =
'spotify': "http://open.spotify.com/track/#{id}"
'youtube': "http://youtu.be/#{id}"
'soundcloud': "http://soundcloud.com/#{id}"
new Handlebars.SafeString urls[type]
Handlebars.registerHelper 'format_time', (seconds) ->
hours = parseInt(seconds / 3600)
seconds -= hours * 3600
minutes = parseInt(seconds / 60)
seconds -= minutes * 60
new Handlebars.SafeString "#{if hours > 0 then hours + ':' else ''}#{(if minutes > 9 then '' else '0') + minutes}:#{(if seconds > 9 then '' else '0') + seconds}"
## Typeahead!
tracks = new Bloodhound
datumTokenizer: (d) -> Bloodhound.tokenizers.whitespace d.value,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote:
url: SPOTIFY,
filter: (json) ->
result = []
for track in json.tracks
result.push
value: track.name,
link: track.href,
artists: track.artists.map( (a) -> a.name).join ', '
album: track.album.name
result
videos = new Bloodhound
datumTokenizer: (d) -> Bloodhound.tokenizers.whitespace d.value,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote:
url: YOUTUBE,
filter: (json) ->
result = []
if json.feed.entry?
for video in json.feed.entry
link = video.id.$t.split('/')
result.push
value: video.title.$t,
link: 'youtu.be/' + link[link.length - 1],
artists: video.author.map( (a) -> a.name.$t).join ', '
result
videos.initialize()
tracks.initialize()
$ '#videofeed'
.on 'click', '.x-button', ->
$el = $(this).parent()
item = $el.data 'item'
if confirm "Confirm deletion of \"#{item.title}\"?"
app.removeItemFromQueue(item)
$el.remove()
.on 'click', '.upvote, .downvote', ->
# If trying to up-/downvote when already up-/downvoted
return if $(this).hasClass 'active'
$el = $(this).parent().parent()
up = $(this).hasClass 'upvote'
item = $el.data 'item'
app.addVote item, up
rate = if item.id of app.get_list() then 2 else 1
$(this).parent().find('.rating').html(item.weight + if up then rate else -rate)
if up
$el.find('.upvote').addClass 'active'
$el.find('.downvote').removeClass 'active'
else
$el.find('.upvote').removeClass 'active'
$el.find('.downvote').addClass 'active'
# Bind events for parsing input url/id
$insert_video = $ '#insert_video'
read_searchfield = (e) ->
value = $insert_video.val()
app.parseInput(value);
$ '#searchfield button'
.on 'click', read_searchfield
$insert_video
.on 'keydown', (e) -> read_searchfield() if e.which == 13
.typeahead {
minLength: 4
}, {
name: 'youtube',
displayKey: 'value',
source: videos.ttAdapter(),
templates:
suggestion: TEMPLATES['youtube-typeahead']
# suggestion: Handlebars.templates.typeahead
limit: 15
}, {
name: 'spotify',
displayKey: '<KEY>',
source: tracks.ttAdapter(),
templates:
suggestion: TEMPLATES['spotify-typeahead']
# suggestion: Handlebars.templates.typeahead
limit: 15
}
.on 'typeahead:selected', (obj, data) ->
if app.parseInput data.link
$(this).val('')
## Basic detction if user has cookie, not fail-safe
cookie_data = document.cookie.split /; |=/
ADMIN = false
for key in cookie_data
if key == '<KEY>'
$.ajax
url: 'https://chalmers.it/auth/userInfo.php',
xhrFields: { withCredentials: true },
dataType: 'jsonp'
.done (data) ->
ADMIN = 'playITAdmin' in data.groups
$('#videofeed').addClass('admin') if ADMIN
## MediaItem: base class for YouTube- and SpotifyItem
class MediaItem
constructor: (@id, @type) ->
@matches: (id, regex) ->
result = id.match regex
result[result.length - 1] if result?
class YouTubeItem extends MediaItem
@REGEX: /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]+).*/
constructor: (url) ->
@id = YouTubeItem.matches url.trim()
if @id?
super @id, 'youtube'
else
throw new Error "Cannot create YouTubeItem, invalid url: \"#{url}\""
@matches: (id) ->
super id, @REGEX
class SpotifyItem extends MediaItem
@REGEX: /^(.*open\.)?spotify(\.com)?[\/:]track[\/:]([a-zA-Z0-9]+)$/
constructor: (uri) ->
@id = SpotifyItem.matches uri.trim()
if @id?
super @id, 'spotify'
else
throw new Error "Cannot create SpotifyItem, invalid uri: \"#{uri}\""
@matches: (id) ->
super id, @REGEX
class SoundCloudItem extends MediaItem
@REGEX: /^https?:\/\/soundcloud.com\/([\w-]+\/\w+)$/
constructor: (url) ->
temp_id = SoundCloudItem.matches url.trim()
if temp_id?
@resolve temp_id
super @id, 'soundcloud'
else
throw new Error "Cannot create SoundCloudItem, invalid url: \"#{url}\""
resolve: (id) ->
$.getJSON 'http://api.soundcloud.com/resolve.json', {
url: "http://soundcloud.com/#{id}",
client_id: 'a2cfca0784004b38b85829ba183327cb' }, (data) =>
@id = data.id
@matches: (id) ->
super id, @REGEX
## Main class for the application
class App
$feed = $ '#videofeed'
$status = $ '#nowPlaying .media'
LS_KEY = '<KEY>'
list = {}
sent = false
updates = 0
get_list: ->
return list
constructor: ->
if window.localStorage && window.localStorage.hasOwnProperty(LS_KEY)
data = window.localStorage.getItem(LS_KEY)
list = JSON.parse data
parseInput: (string) ->
if YouTubeItem.matches string
@addMediaItem new YouTubeItem string
return true
else if SpotifyItem.matches string
@addMediaItem new SpotifyItem string
return true
else if SoundCloudItem.matches string
@addMediaItem new SoundCloudItem string
return true
else
console.log string
return false
addMediaItem: (item) ->
method = 'addMediaItem'
updates++
query method, {id: item.id, type: item.type}, (body) =>
index = body.indexOf "Fail:"
if index == 0
toaster.err body
else
toaster.toast body
list[item.id] = true
saveList()
@showQueue()
addVote: (item, up) ->
method = 'addVote'
updates++
query method, {id: item.id, upvote: if up then 1 else 0}, (body) =>
console.log body
list[item.id] = up
saveList()
@showQueue()
query = (method, params, callback) ->
url = "#{SERVER}/#{method}"
if typeof params == "function"
callback = params
params = {}
$.ajax
url: url,
xhrFields: { withCredentials: true },
beforeSend: ->
progressJs().start().autoIncrease(4, 500)
data: params
.done (body) ->
progressJs().end()
updates--
callback(body)
nowPlaying: ->
method = 'nowPlaying'
query method, (data) ->
unless data.length > 0
$status.html TEMPLATES.playing(data)
changeLimit: (limit) ->
method = 'changeLimit'
query method, {limit: limit}, (body) ->
console.log body
saveList = ->
window.localStorage.setItem LS_KEY, JSON.stringify list
showQueue: ->
unless TIMEOUT == null
clearTimeout TIMEOUT
TIMEOUT = null
updates++
method = 'showQueue'
query method, (body) =>
return if updates > 0
data = JSON.parse body
$feed.find('div.media').each (index, elem) ->
elem = $(elem)
item = elem.data 'item'
data_item = null
for i in data
if i.externalID == item.id
data_item = i
break
if data_item == null || item.weight == data_item.weight
return
else
item.weight = data_item.weight
elem.find('.rating').html(item.weight)
app.nowPlaying()
if data.length == $feed.find('div.media').length
TIMEOUT = setTimeout(app.showQueue, 10000)
return
items = []
savedIds = []
for item in data
if list[item.externalID]?
element_class = if list[item.externalID] then 'upvoted' else 'downvoted'
# element = Handlebars.templates["#{item.type}-partial"](item)
element = TEMPLATES["#{item.type}"](item)
savedIds.push item.externalID
$el = $ element
.data 'item', id: item.externalID, title: item.title, weight: item.weight
.addClass element_class
items.push $el
$feed.html(items)
for key of list
delete list[key] if key not in savedIds
saveList()
TIMEOUT = setTimeout(app.showQueue, 10000)
removeItemFromQueue: (item) ->
method = 'removeItemFromQueue'
updates++
query method, {id: item.id}, (body) =>
console.log body
# @showQueue()
## Class for displaying messages to the user
class Toaster
toaster = $ '#toaster'
queue = []
constructor: ->
toaster.on 'click', close
close = ->
queue.shift()
if queue.length != 0
toaster.animate height: 10, printNext
return
toaster.animate height: 0, ->
toaster.hide()
queuePrint = (string, err) ->
queue.push {string: string, err: err}
printNext() if queue.length == 1
printNext = ->
{string, err} = queue[0]
if err
string = "<span style=\"color: red\">#{string}</span>"
toaster
.show()
.html "<br>#{string}<br><small>(Click to dismiss)</small>"
.animate height: 100, ->
setTimeout close, 2000
err: (string) ->
console.error string
queuePrint string, true
toast: (string) ->
queuePrint string, false
window.app = new App()
window.toaster = new Toaster()
app.showQueue() #if found
# app.addMediaItem new YouTubeItem 'https://www.youtube.com/watch?v=moSFlvxnbgk'
# app.addMediaItem new SpotifyItem 'spotify:track:10Ip8PpzXoYQe4e3mSgoOy'
| true |
## Settings
SERVER = "http://hubben.chalmers.it:8080/playIT/media"
YOUTUBE = "http://gdata.youtube.com/feeds/api/videos?alt=json&q=%QUERY"
SPOTIFY = "http://ws.spotify.com/search/1/track.json?q=%QUERY"
TIMEOUT = null
TEMPLATES =
spotify: Handlebars.compile $('#spotify-partial').html()
youtube: Handlebars.compile $('#youtube-partial').html()
'spotify-typeahead': Handlebars.compile $('#typeahead-spotify-partial').html()
'youtube-typeahead': Handlebars.compile $('#typeahead-youtube-partial').html()
playing: Handlebars.compile $('#playing').html()
## Handlebars view-helpers
Handlebars.registerHelper 'join', (array) ->
new Handlebars.SafeString array.join(", ")
Handlebars.registerHelper 'ntobr', (string) ->
new Handlebars.SafeString string.replace /\n/g, '<br>'
Handlebars.registerHelper 'desc', (string) ->
index = string.indexOf '\n', 140
string = string.substr 0, index if index != -1
new Handlebars.SafeString string #.replace /\n/g, '<br>'
Handlebars.registerHelper 'url', (type, id) ->
urls =
'spotify': "http://open.spotify.com/track/#{id}"
'youtube': "http://youtu.be/#{id}"
'soundcloud': "http://soundcloud.com/#{id}"
new Handlebars.SafeString urls[type]
Handlebars.registerHelper 'format_time', (seconds) ->
hours = parseInt(seconds / 3600)
seconds -= hours * 3600
minutes = parseInt(seconds / 60)
seconds -= minutes * 60
new Handlebars.SafeString "#{if hours > 0 then hours + ':' else ''}#{(if minutes > 9 then '' else '0') + minutes}:#{(if seconds > 9 then '' else '0') + seconds}"
## Typeahead!
tracks = new Bloodhound
datumTokenizer: (d) -> Bloodhound.tokenizers.whitespace d.value,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote:
url: SPOTIFY,
filter: (json) ->
result = []
for track in json.tracks
result.push
value: track.name,
link: track.href,
artists: track.artists.map( (a) -> a.name).join ', '
album: track.album.name
result
videos = new Bloodhound
datumTokenizer: (d) -> Bloodhound.tokenizers.whitespace d.value,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote:
url: YOUTUBE,
filter: (json) ->
result = []
if json.feed.entry?
for video in json.feed.entry
link = video.id.$t.split('/')
result.push
value: video.title.$t,
link: 'youtu.be/' + link[link.length - 1],
artists: video.author.map( (a) -> a.name.$t).join ', '
result
videos.initialize()
tracks.initialize()
$ '#videofeed'
.on 'click', '.x-button', ->
$el = $(this).parent()
item = $el.data 'item'
if confirm "Confirm deletion of \"#{item.title}\"?"
app.removeItemFromQueue(item)
$el.remove()
.on 'click', '.upvote, .downvote', ->
# If trying to up-/downvote when already up-/downvoted
return if $(this).hasClass 'active'
$el = $(this).parent().parent()
up = $(this).hasClass 'upvote'
item = $el.data 'item'
app.addVote item, up
rate = if item.id of app.get_list() then 2 else 1
$(this).parent().find('.rating').html(item.weight + if up then rate else -rate)
if up
$el.find('.upvote').addClass 'active'
$el.find('.downvote').removeClass 'active'
else
$el.find('.upvote').removeClass 'active'
$el.find('.downvote').addClass 'active'
# Bind events for parsing input url/id
$insert_video = $ '#insert_video'
read_searchfield = (e) ->
value = $insert_video.val()
app.parseInput(value);
$ '#searchfield button'
.on 'click', read_searchfield
$insert_video
.on 'keydown', (e) -> read_searchfield() if e.which == 13
.typeahead {
minLength: 4
}, {
name: 'youtube',
displayKey: 'value',
source: videos.ttAdapter(),
templates:
suggestion: TEMPLATES['youtube-typeahead']
# suggestion: Handlebars.templates.typeahead
limit: 15
}, {
name: 'spotify',
displayKey: 'PI:KEY:<KEY>END_PI',
source: tracks.ttAdapter(),
templates:
suggestion: TEMPLATES['spotify-typeahead']
# suggestion: Handlebars.templates.typeahead
limit: 15
}
.on 'typeahead:selected', (obj, data) ->
if app.parseInput data.link
$(this).val('')
## Basic detction if user has cookie, not fail-safe
cookie_data = document.cookie.split /; |=/
ADMIN = false
for key in cookie_data
if key == 'PI:KEY:<KEY>END_PI'
$.ajax
url: 'https://chalmers.it/auth/userInfo.php',
xhrFields: { withCredentials: true },
dataType: 'jsonp'
.done (data) ->
ADMIN = 'playITAdmin' in data.groups
$('#videofeed').addClass('admin') if ADMIN
## MediaItem: base class for YouTube- and SpotifyItem
class MediaItem
constructor: (@id, @type) ->
@matches: (id, regex) ->
result = id.match regex
result[result.length - 1] if result?
class YouTubeItem extends MediaItem
@REGEX: /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]+).*/
constructor: (url) ->
@id = YouTubeItem.matches url.trim()
if @id?
super @id, 'youtube'
else
throw new Error "Cannot create YouTubeItem, invalid url: \"#{url}\""
@matches: (id) ->
super id, @REGEX
class SpotifyItem extends MediaItem
@REGEX: /^(.*open\.)?spotify(\.com)?[\/:]track[\/:]([a-zA-Z0-9]+)$/
constructor: (uri) ->
@id = SpotifyItem.matches uri.trim()
if @id?
super @id, 'spotify'
else
throw new Error "Cannot create SpotifyItem, invalid uri: \"#{uri}\""
@matches: (id) ->
super id, @REGEX
class SoundCloudItem extends MediaItem
@REGEX: /^https?:\/\/soundcloud.com\/([\w-]+\/\w+)$/
constructor: (url) ->
temp_id = SoundCloudItem.matches url.trim()
if temp_id?
@resolve temp_id
super @id, 'soundcloud'
else
throw new Error "Cannot create SoundCloudItem, invalid url: \"#{url}\""
resolve: (id) ->
$.getJSON 'http://api.soundcloud.com/resolve.json', {
url: "http://soundcloud.com/#{id}",
client_id: 'a2cfca0784004b38b85829ba183327cb' }, (data) =>
@id = data.id
@matches: (id) ->
super id, @REGEX
## Main class for the application
class App
$feed = $ '#videofeed'
$status = $ '#nowPlaying .media'
LS_KEY = 'PI:KEY:<KEY>END_PI'
list = {}
sent = false
updates = 0
get_list: ->
return list
constructor: ->
if window.localStorage && window.localStorage.hasOwnProperty(LS_KEY)
data = window.localStorage.getItem(LS_KEY)
list = JSON.parse data
parseInput: (string) ->
if YouTubeItem.matches string
@addMediaItem new YouTubeItem string
return true
else if SpotifyItem.matches string
@addMediaItem new SpotifyItem string
return true
else if SoundCloudItem.matches string
@addMediaItem new SoundCloudItem string
return true
else
console.log string
return false
addMediaItem: (item) ->
method = 'addMediaItem'
updates++
query method, {id: item.id, type: item.type}, (body) =>
index = body.indexOf "Fail:"
if index == 0
toaster.err body
else
toaster.toast body
list[item.id] = true
saveList()
@showQueue()
addVote: (item, up) ->
method = 'addVote'
updates++
query method, {id: item.id, upvote: if up then 1 else 0}, (body) =>
console.log body
list[item.id] = up
saveList()
@showQueue()
query = (method, params, callback) ->
url = "#{SERVER}/#{method}"
if typeof params == "function"
callback = params
params = {}
$.ajax
url: url,
xhrFields: { withCredentials: true },
beforeSend: ->
progressJs().start().autoIncrease(4, 500)
data: params
.done (body) ->
progressJs().end()
updates--
callback(body)
nowPlaying: ->
method = 'nowPlaying'
query method, (data) ->
unless data.length > 0
$status.html TEMPLATES.playing(data)
changeLimit: (limit) ->
method = 'changeLimit'
query method, {limit: limit}, (body) ->
console.log body
saveList = ->
window.localStorage.setItem LS_KEY, JSON.stringify list
showQueue: ->
unless TIMEOUT == null
clearTimeout TIMEOUT
TIMEOUT = null
updates++
method = 'showQueue'
query method, (body) =>
return if updates > 0
data = JSON.parse body
$feed.find('div.media').each (index, elem) ->
elem = $(elem)
item = elem.data 'item'
data_item = null
for i in data
if i.externalID == item.id
data_item = i
break
if data_item == null || item.weight == data_item.weight
return
else
item.weight = data_item.weight
elem.find('.rating').html(item.weight)
app.nowPlaying()
if data.length == $feed.find('div.media').length
TIMEOUT = setTimeout(app.showQueue, 10000)
return
items = []
savedIds = []
for item in data
if list[item.externalID]?
element_class = if list[item.externalID] then 'upvoted' else 'downvoted'
# element = Handlebars.templates["#{item.type}-partial"](item)
element = TEMPLATES["#{item.type}"](item)
savedIds.push item.externalID
$el = $ element
.data 'item', id: item.externalID, title: item.title, weight: item.weight
.addClass element_class
items.push $el
$feed.html(items)
for key of list
delete list[key] if key not in savedIds
saveList()
TIMEOUT = setTimeout(app.showQueue, 10000)
removeItemFromQueue: (item) ->
method = 'removeItemFromQueue'
updates++
query method, {id: item.id}, (body) =>
console.log body
# @showQueue()
## Class for displaying messages to the user
class Toaster
toaster = $ '#toaster'
queue = []
constructor: ->
toaster.on 'click', close
close = ->
queue.shift()
if queue.length != 0
toaster.animate height: 10, printNext
return
toaster.animate height: 0, ->
toaster.hide()
queuePrint = (string, err) ->
queue.push {string: string, err: err}
printNext() if queue.length == 1
printNext = ->
{string, err} = queue[0]
if err
string = "<span style=\"color: red\">#{string}</span>"
toaster
.show()
.html "<br>#{string}<br><small>(Click to dismiss)</small>"
.animate height: 100, ->
setTimeout close, 2000
err: (string) ->
console.error string
queuePrint string, true
toast: (string) ->
queuePrint string, false
window.app = new App()
window.toaster = new Toaster()
app.showQueue() #if found
# app.addMediaItem new YouTubeItem 'https://www.youtube.com/watch?v=moSFlvxnbgk'
# app.addMediaItem new SpotifyItem 'spotify:track:10Ip8PpzXoYQe4e3mSgoOy'
|
[
{
"context": " slight shim for [`changeset`](https://github.com/eugeneware/changeset), an amazing\n(and small!) piece of soft",
"end": 99,
"score": 0.9995845556259155,
"start": 89,
"tag": "USERNAME",
"value": "eugeneware"
},
{
"context": "e, let's consider this MD document:\n\n```md\n<<(.>>@S.COLUMNS.count = 3<<)>>\n<<!columns>>\n<<!yadda>>\n\n<<(.>>@S.COLUMN",
"end": 782,
"score": 0.9567722082138062,
"start": 767,
"tag": "EMAIL",
"value": "S.COLUMNS.count"
},
{
"context": "NS.count = 3<<)>>\n<<!columns>>\n<<!yadda>>\n\n<<(.>>@S.COLUMNS.count = 4<<)>>\n<<!columns>>\n<<!yadda>>\n```\n\nWe want thi",
"end": 839,
"score": 0.9401094317436218,
"start": 824,
"tag": "EMAIL",
"value": "S.COLUMNS.count"
},
{
"context": "da>>`),\nthe first one typeset into three (`<<(.>>@S.COLUMNS.count = 3<<)>>`), and the second one into\nfour (`<<(.>>",
"end": 1035,
"score": 0.8659194111824036,
"start": 1020,
"tag": "EMAIL",
"value": "S.COLUMNS.count"
},
{
"context": "= 3<<)>>`), and the second one into\nfour (`<<(.>>@S.COLUMNS.count = 4<<)>>`) columns (`<<!columns>>`).\n\nIf we were ",
"end": 1101,
"score": 0.9092546701431274,
"start": 1086,
"tag": "EMAIL",
"value": "S.COLUMNS.count"
}
] | src/diffpatch.coffee | loveencounterflow/mingkwai-typesetter | 1 |
###
## Motivation
This module is a slight shim for [`changeset`](https://github.com/eugeneware/changeset), an amazing
(and small!) piece of software that does diffing (i.e. changeset generation) and patching (i.e.
changeset application) for nested JavaScript datastructures.
Chnagesets are implemented as lists of PODs, each detailing one atomic change step and formatted
so they can be directly fit into a (suitably structured) LvelDB instance (using `level`/`levelup`).
It even claims to respect cyclic references, which is great.
We're here less concerned with feeding changesets into a DB; rather, the problem we want
to solve is how to keep track of local state within a processing pipeline.
As an example, let's consider this MD document:
```md
<<(.>>@S.COLUMNS.count = 3<<)>>
<<!columns>>
<<!yadda>>
<<(.>>@S.COLUMNS.count = 4<<)>>
<<!columns>>
<<!yadda>>
```
We want this source to result in a PDF that has two paragraphs of Lore Ipsum mumbo (``<<!yadda>>`),
the first one typeset into three (`<<(.>>@S.COLUMNS.count = 3<<)>>`), and the second one into
four (`<<(.>>@S.COLUMNS.count = 4<<)>>`) columns (`<<!columns>>`).
If we were to use global state—which is communicated via the `S` variable—then that *might* work
out as long as the chain of piped transforms were to act in a strictly lockstep fashion; in other
words, if each event that originates somewhere near the top of the chain were guaranteed to be fully
processed and its consequences all written out to the bottom of the chain before the next event
gets to be processed. However, that is not the case, since some processing steps like footnotes
and TOC compilation need to buffer the entire sequence of events before giving control to the
ensuing step (otherwise you can't have a table of contents in the opening matter of a book).
In the presence of such buffering, a phenomenon reminiscent of a 'failed closure' surfaces: some
step early on knows that the default column count is 2, and may set global state accordingly; at
some later point, a change to 3 is encountered, and S gets changed; still later, a change to 4
is encountered, and S will be modified again. But in the presence of an intermediate buffering
step, that step will only send on events once the document has been finished, and all that remains
in global state is a setting of 4, not 2 or 3 columns per page.
The solution to this problem is to treat changes to local state like any other instructions
from the document source, have them travel down the chain of transforms as events, and require
all interested parties to listen to those change events and rebuild their local copies of local
state themselves. This adds a certain overhead to processing, but the upside is that we can
always be sure that local state will be up to date within each stream transform as long as
events don't get re-ordered.
## Usage
The DIFFPATCH (DP) API is fairly minimal; you get three methods:
```coffee
@snapshot = ( original ) -> LODASH.cloneDeep original
@diff = ( x, y ) -> diff x, y
@patch = ( changeset, x ) -> diff.apply changeset, x
```
`DP.diff x, y` results in a changeset (a list of changes) that tells you which steps are needed
to modify `x` so that it will test deep-equal to `y`. Changesets are what we'll send doen the
pipeline; there'll be a single initial changeset after the document construction stream has started
that allows any interested parties to 'jumpstart', as it were, their local state copy:
you take an empty POD `local = {}`, apply the changeset, and you're good:
`local = DP.patch changeset, local`.
In case a stream transform has to modify local state, it needs a reference point on which to base
its own change events unto, which is what `DO.snapshot` is for:
```coffee
backup = DIFFPATCH.snapshot local # create reference point
local = DIFFPATCH.patch changeset_event, local # update local state
[...]
local.n = 12345678 # modify local state
[...]
changeset_out = DIFFPATCH.diff backup, local # create changeset for
# ensuing transforms to listen to
```
```
#-----------------------------------------------------------------------------------------------------------
test_functions_in_changeset = ->
rpr = ( x ) -> ( ( require 'util' ).inspect x, colors: yes, depth: 2 ).replace /\n * /g, ' '
my_function = -> 108
#.........................................................................................................
changeset_event = null
do =>
sandbox =
n: 42
f: my_function
foo: Array.from 'shrdlu'
bar: { x: 33, y: 54, f: my_function, }
changeset_event = DIFFPATCH.diff {}, sandbox
#.........................................................................................................
do =>
local = DIFFPATCH.patch changeset_event, {}
backup = DIFFPATCH.snapshot local
log CND.truth local[ 'f' ] is my_function
log CND.truth backup[ 'f' ] is my_function
whisper 'A', backup
local.n = 12345678
local.bar[ 'x' ] = 2357
local.foo.push 'ZZ'
changeset_out = DIFFPATCH.diff backup, local
log CND.truth local[ 'f' ] is my_function
log CND.truth backup[ 'f' ] is my_function
# log rpr local
#.........................................................................................................
for change in changeset_out
log 'C', rpr change
#.........................................................................................................
# test_functions_in_changeset()
#-----------------------------------------------------------------------------------------------------------
test_changeset = ->
LODASH = require 'lodash'
D = require 'pipedreams'
$ = D.remit.bind D
$async = D.remit_async.bind D
$observe = D.$observe.bind D
MD_READER = ( require '../mingkwai-typesetter' ).MD_READER
hide = MD_READER.hide.bind MD_READER
copy = MD_READER.copy.bind MD_READER
stamp = MD_READER.stamp.bind MD_READER
unstamp = MD_READER.unstamp.bind MD_READER
select = MD_READER.select.bind MD_READER
is_hidden = MD_READER.is_hidden.bind MD_READER
is_stamped = MD_READER.is_stamped.bind MD_READER
input = D.create_throughstream()
rpr = ( x ) -> ( ( require 'util' ).inspect x, colors: yes, depth: 2 ).replace /\n * /g, ' '
#.........................................................................................................
sandbox =
f: -> 108
n: 42
foo: Array.from 'shrdlu'
bar: { x: 33, y: 54, }
#.........................................................................................................
input
#.......................................................................................................
.pipe do =>
local = {}
backup = null
#.....................................................................................................
return $ ( event, send ) =>
#...................................................................................................
if select event, '~', 'change'
[ _, _, parameters, _, ] = event
[ name, changeset, ] = parameters
#.................................................................................................
if name is 'sandbox'
local = DIFFPATCH.patch changeset, local
#.................................................................................................
send event
#...................................................................................................
else if select event, '~', 'add-ten'
send event
#.................................................................................................
backup = DIFFPATCH.snapshot local
local.n = ( local.n ? 0 ) + 10
changeset = DIFFPATCH.diff backup, local
#.................................................................................................
log 'A', rpr local
send [ '~', 'change', [ 'sandbox', changeset, ], null, ]
#...................................................................................................
else if select event, '~', 'frob'
send event
#.................................................................................................
backup = DIFFPATCH.snapshot local
local.foo.push [ 'X', 'Y', 'Z', ]
changeset = DIFFPATCH.diff backup, local
#.................................................................................................
log 'A', rpr local
send [ '~', 'change', [ 'sandbox', changeset, ], null, ]
#...................................................................................................
else if select event, '~', 'drab'
send event
#.................................................................................................
backup = DIFFPATCH.snapshot local
local.bar[ 'z' ] = local.foo
changeset = DIFFPATCH.diff backup, local
#.................................................................................................
log 'A', rpr local
send [ '~', 'change', [ 'sandbox', changeset, ], null, ]
#...................................................................................................
else
send event
#.......................................................................................................
# .pipe $observe ( event ) => log rpr event
#.......................................................................................................
.pipe $observe ( event ) =>
#.....................................................................................................
if select event, '~', 'change'
[ _, _, parameters, _, ] = event
[ name, changeset, ] = parameters
#.................................................................................................
if name is 'sandbox'
for change in changeset
whisper change
#.......................................................................................................
.pipe do =>
local = {}
#.....................................................................................................
return $observe ( event ) =>
#...................................................................................................
if select event, '~', 'change'
[ _, _, parameters, _, ] = event
[ name, changeset, ] = parameters
#.................................................................................................
if name is 'sandbox'
local = DIFFPATCH.patch changeset, local
log 'B', rpr local
#.........................................................................................................
changeset = DIFFPATCH.diff {}, sandbox
input.write [ '~', 'change', [ 'sandbox', changeset, ], null, ]
input.write [ '~', 'add-ten', null, null, ]
# input.write [ '~', 'frob', null, null, ]
# input.write [ '~', 'drab', null, null, ]
input.end()
test_changeset()
```
###
############################################################################################################
# CND = require 'cnd'
# rpr = CND.rpr
# badge = 'MK/TS/JIZURA/main'
# log = CND.get_logger 'plain', badge
# info = CND.get_logger 'info', badge
# whisper = CND.get_logger 'whisper', badge
# alert = CND.get_logger 'alert', badge
# debug = CND.get_logger 'debug', badge
# warn = CND.get_logger 'warn', badge
# help = CND.get_logger 'help', badge
# urge = CND.get_logger 'urge', badge
# echo = CND.echo.bind CND
diff = require 'changeset'
LODASH = require 'lodash'
#-----------------------------------------------------------------------------------------------------------
@snapshot = ( original ) -> LODASH.cloneDeep original
@diff = ( x, y ) -> diff x, y
@patch = ( changeset, x ) -> diff.apply changeset, x
| 38762 |
###
## Motivation
This module is a slight shim for [`changeset`](https://github.com/eugeneware/changeset), an amazing
(and small!) piece of software that does diffing (i.e. changeset generation) and patching (i.e.
changeset application) for nested JavaScript datastructures.
Chnagesets are implemented as lists of PODs, each detailing one atomic change step and formatted
so they can be directly fit into a (suitably structured) LvelDB instance (using `level`/`levelup`).
It even claims to respect cyclic references, which is great.
We're here less concerned with feeding changesets into a DB; rather, the problem we want
to solve is how to keep track of local state within a processing pipeline.
As an example, let's consider this MD document:
```md
<<(.>>@<EMAIL> = 3<<)>>
<<!columns>>
<<!yadda>>
<<(.>>@<EMAIL> = 4<<)>>
<<!columns>>
<<!yadda>>
```
We want this source to result in a PDF that has two paragraphs of Lore Ipsum mumbo (``<<!yadda>>`),
the first one typeset into three (`<<(.>>@<EMAIL> = 3<<)>>`), and the second one into
four (`<<(.>>@<EMAIL> = 4<<)>>`) columns (`<<!columns>>`).
If we were to use global state—which is communicated via the `S` variable—then that *might* work
out as long as the chain of piped transforms were to act in a strictly lockstep fashion; in other
words, if each event that originates somewhere near the top of the chain were guaranteed to be fully
processed and its consequences all written out to the bottom of the chain before the next event
gets to be processed. However, that is not the case, since some processing steps like footnotes
and TOC compilation need to buffer the entire sequence of events before giving control to the
ensuing step (otherwise you can't have a table of contents in the opening matter of a book).
In the presence of such buffering, a phenomenon reminiscent of a 'failed closure' surfaces: some
step early on knows that the default column count is 2, and may set global state accordingly; at
some later point, a change to 3 is encountered, and S gets changed; still later, a change to 4
is encountered, and S will be modified again. But in the presence of an intermediate buffering
step, that step will only send on events once the document has been finished, and all that remains
in global state is a setting of 4, not 2 or 3 columns per page.
The solution to this problem is to treat changes to local state like any other instructions
from the document source, have them travel down the chain of transforms as events, and require
all interested parties to listen to those change events and rebuild their local copies of local
state themselves. This adds a certain overhead to processing, but the upside is that we can
always be sure that local state will be up to date within each stream transform as long as
events don't get re-ordered.
## Usage
The DIFFPATCH (DP) API is fairly minimal; you get three methods:
```coffee
@snapshot = ( original ) -> LODASH.cloneDeep original
@diff = ( x, y ) -> diff x, y
@patch = ( changeset, x ) -> diff.apply changeset, x
```
`DP.diff x, y` results in a changeset (a list of changes) that tells you which steps are needed
to modify `x` so that it will test deep-equal to `y`. Changesets are what we'll send doen the
pipeline; there'll be a single initial changeset after the document construction stream has started
that allows any interested parties to 'jumpstart', as it were, their local state copy:
you take an empty POD `local = {}`, apply the changeset, and you're good:
`local = DP.patch changeset, local`.
In case a stream transform has to modify local state, it needs a reference point on which to base
its own change events unto, which is what `DO.snapshot` is for:
```coffee
backup = DIFFPATCH.snapshot local # create reference point
local = DIFFPATCH.patch changeset_event, local # update local state
[...]
local.n = 12345678 # modify local state
[...]
changeset_out = DIFFPATCH.diff backup, local # create changeset for
# ensuing transforms to listen to
```
```
#-----------------------------------------------------------------------------------------------------------
test_functions_in_changeset = ->
rpr = ( x ) -> ( ( require 'util' ).inspect x, colors: yes, depth: 2 ).replace /\n * /g, ' '
my_function = -> 108
#.........................................................................................................
changeset_event = null
do =>
sandbox =
n: 42
f: my_function
foo: Array.from 'shrdlu'
bar: { x: 33, y: 54, f: my_function, }
changeset_event = DIFFPATCH.diff {}, sandbox
#.........................................................................................................
do =>
local = DIFFPATCH.patch changeset_event, {}
backup = DIFFPATCH.snapshot local
log CND.truth local[ 'f' ] is my_function
log CND.truth backup[ 'f' ] is my_function
whisper 'A', backup
local.n = 12345678
local.bar[ 'x' ] = 2357
local.foo.push 'ZZ'
changeset_out = DIFFPATCH.diff backup, local
log CND.truth local[ 'f' ] is my_function
log CND.truth backup[ 'f' ] is my_function
# log rpr local
#.........................................................................................................
for change in changeset_out
log 'C', rpr change
#.........................................................................................................
# test_functions_in_changeset()
#-----------------------------------------------------------------------------------------------------------
test_changeset = ->
LODASH = require 'lodash'
D = require 'pipedreams'
$ = D.remit.bind D
$async = D.remit_async.bind D
$observe = D.$observe.bind D
MD_READER = ( require '../mingkwai-typesetter' ).MD_READER
hide = MD_READER.hide.bind MD_READER
copy = MD_READER.copy.bind MD_READER
stamp = MD_READER.stamp.bind MD_READER
unstamp = MD_READER.unstamp.bind MD_READER
select = MD_READER.select.bind MD_READER
is_hidden = MD_READER.is_hidden.bind MD_READER
is_stamped = MD_READER.is_stamped.bind MD_READER
input = D.create_throughstream()
rpr = ( x ) -> ( ( require 'util' ).inspect x, colors: yes, depth: 2 ).replace /\n * /g, ' '
#.........................................................................................................
sandbox =
f: -> 108
n: 42
foo: Array.from 'shrdlu'
bar: { x: 33, y: 54, }
#.........................................................................................................
input
#.......................................................................................................
.pipe do =>
local = {}
backup = null
#.....................................................................................................
return $ ( event, send ) =>
#...................................................................................................
if select event, '~', 'change'
[ _, _, parameters, _, ] = event
[ name, changeset, ] = parameters
#.................................................................................................
if name is 'sandbox'
local = DIFFPATCH.patch changeset, local
#.................................................................................................
send event
#...................................................................................................
else if select event, '~', 'add-ten'
send event
#.................................................................................................
backup = DIFFPATCH.snapshot local
local.n = ( local.n ? 0 ) + 10
changeset = DIFFPATCH.diff backup, local
#.................................................................................................
log 'A', rpr local
send [ '~', 'change', [ 'sandbox', changeset, ], null, ]
#...................................................................................................
else if select event, '~', 'frob'
send event
#.................................................................................................
backup = DIFFPATCH.snapshot local
local.foo.push [ 'X', 'Y', 'Z', ]
changeset = DIFFPATCH.diff backup, local
#.................................................................................................
log 'A', rpr local
send [ '~', 'change', [ 'sandbox', changeset, ], null, ]
#...................................................................................................
else if select event, '~', 'drab'
send event
#.................................................................................................
backup = DIFFPATCH.snapshot local
local.bar[ 'z' ] = local.foo
changeset = DIFFPATCH.diff backup, local
#.................................................................................................
log 'A', rpr local
send [ '~', 'change', [ 'sandbox', changeset, ], null, ]
#...................................................................................................
else
send event
#.......................................................................................................
# .pipe $observe ( event ) => log rpr event
#.......................................................................................................
.pipe $observe ( event ) =>
#.....................................................................................................
if select event, '~', 'change'
[ _, _, parameters, _, ] = event
[ name, changeset, ] = parameters
#.................................................................................................
if name is 'sandbox'
for change in changeset
whisper change
#.......................................................................................................
.pipe do =>
local = {}
#.....................................................................................................
return $observe ( event ) =>
#...................................................................................................
if select event, '~', 'change'
[ _, _, parameters, _, ] = event
[ name, changeset, ] = parameters
#.................................................................................................
if name is 'sandbox'
local = DIFFPATCH.patch changeset, local
log 'B', rpr local
#.........................................................................................................
changeset = DIFFPATCH.diff {}, sandbox
input.write [ '~', 'change', [ 'sandbox', changeset, ], null, ]
input.write [ '~', 'add-ten', null, null, ]
# input.write [ '~', 'frob', null, null, ]
# input.write [ '~', 'drab', null, null, ]
input.end()
test_changeset()
```
###
############################################################################################################
# CND = require 'cnd'
# rpr = CND.rpr
# badge = 'MK/TS/JIZURA/main'
# log = CND.get_logger 'plain', badge
# info = CND.get_logger 'info', badge
# whisper = CND.get_logger 'whisper', badge
# alert = CND.get_logger 'alert', badge
# debug = CND.get_logger 'debug', badge
# warn = CND.get_logger 'warn', badge
# help = CND.get_logger 'help', badge
# urge = CND.get_logger 'urge', badge
# echo = CND.echo.bind CND
diff = require 'changeset'
LODASH = require 'lodash'
#-----------------------------------------------------------------------------------------------------------
@snapshot = ( original ) -> LODASH.cloneDeep original
@diff = ( x, y ) -> diff x, y
@patch = ( changeset, x ) -> diff.apply changeset, x
| true |
###
## Motivation
This module is a slight shim for [`changeset`](https://github.com/eugeneware/changeset), an amazing
(and small!) piece of software that does diffing (i.e. changeset generation) and patching (i.e.
changeset application) for nested JavaScript datastructures.
Chnagesets are implemented as lists of PODs, each detailing one atomic change step and formatted
so they can be directly fit into a (suitably structured) LvelDB instance (using `level`/`levelup`).
It even claims to respect cyclic references, which is great.
We're here less concerned with feeding changesets into a DB; rather, the problem we want
to solve is how to keep track of local state within a processing pipeline.
As an example, let's consider this MD document:
```md
<<(.>>@PI:EMAIL:<EMAIL>END_PI = 3<<)>>
<<!columns>>
<<!yadda>>
<<(.>>@PI:EMAIL:<EMAIL>END_PI = 4<<)>>
<<!columns>>
<<!yadda>>
```
We want this source to result in a PDF that has two paragraphs of Lore Ipsum mumbo (``<<!yadda>>`),
the first one typeset into three (`<<(.>>@PI:EMAIL:<EMAIL>END_PI = 3<<)>>`), and the second one into
four (`<<(.>>@PI:EMAIL:<EMAIL>END_PI = 4<<)>>`) columns (`<<!columns>>`).
If we were to use global state—which is communicated via the `S` variable—then that *might* work
out as long as the chain of piped transforms were to act in a strictly lockstep fashion; in other
words, if each event that originates somewhere near the top of the chain were guaranteed to be fully
processed and its consequences all written out to the bottom of the chain before the next event
gets to be processed. However, that is not the case, since some processing steps like footnotes
and TOC compilation need to buffer the entire sequence of events before giving control to the
ensuing step (otherwise you can't have a table of contents in the opening matter of a book).
In the presence of such buffering, a phenomenon reminiscent of a 'failed closure' surfaces: some
step early on knows that the default column count is 2, and may set global state accordingly; at
some later point, a change to 3 is encountered, and S gets changed; still later, a change to 4
is encountered, and S will be modified again. But in the presence of an intermediate buffering
step, that step will only send on events once the document has been finished, and all that remains
in global state is a setting of 4, not 2 or 3 columns per page.
The solution to this problem is to treat changes to local state like any other instructions
from the document source, have them travel down the chain of transforms as events, and require
all interested parties to listen to those change events and rebuild their local copies of local
state themselves. This adds a certain overhead to processing, but the upside is that we can
always be sure that local state will be up to date within each stream transform as long as
events don't get re-ordered.
## Usage
The DIFFPATCH (DP) API is fairly minimal; you get three methods:
```coffee
@snapshot = ( original ) -> LODASH.cloneDeep original
@diff = ( x, y ) -> diff x, y
@patch = ( changeset, x ) -> diff.apply changeset, x
```
`DP.diff x, y` results in a changeset (a list of changes) that tells you which steps are needed
to modify `x` so that it will test deep-equal to `y`. Changesets are what we'll send doen the
pipeline; there'll be a single initial changeset after the document construction stream has started
that allows any interested parties to 'jumpstart', as it were, their local state copy:
you take an empty POD `local = {}`, apply the changeset, and you're good:
`local = DP.patch changeset, local`.
In case a stream transform has to modify local state, it needs a reference point on which to base
its own change events unto, which is what `DO.snapshot` is for:
```coffee
backup = DIFFPATCH.snapshot local # create reference point
local = DIFFPATCH.patch changeset_event, local # update local state
[...]
local.n = 12345678 # modify local state
[...]
changeset_out = DIFFPATCH.diff backup, local # create changeset for
# ensuing transforms to listen to
```
```
#-----------------------------------------------------------------------------------------------------------
test_functions_in_changeset = ->
rpr = ( x ) -> ( ( require 'util' ).inspect x, colors: yes, depth: 2 ).replace /\n * /g, ' '
my_function = -> 108
#.........................................................................................................
changeset_event = null
do =>
sandbox =
n: 42
f: my_function
foo: Array.from 'shrdlu'
bar: { x: 33, y: 54, f: my_function, }
changeset_event = DIFFPATCH.diff {}, sandbox
#.........................................................................................................
do =>
local = DIFFPATCH.patch changeset_event, {}
backup = DIFFPATCH.snapshot local
log CND.truth local[ 'f' ] is my_function
log CND.truth backup[ 'f' ] is my_function
whisper 'A', backup
local.n = 12345678
local.bar[ 'x' ] = 2357
local.foo.push 'ZZ'
changeset_out = DIFFPATCH.diff backup, local
log CND.truth local[ 'f' ] is my_function
log CND.truth backup[ 'f' ] is my_function
# log rpr local
#.........................................................................................................
for change in changeset_out
log 'C', rpr change
#.........................................................................................................
# test_functions_in_changeset()
#-----------------------------------------------------------------------------------------------------------
test_changeset = ->
LODASH = require 'lodash'
D = require 'pipedreams'
$ = D.remit.bind D
$async = D.remit_async.bind D
$observe = D.$observe.bind D
MD_READER = ( require '../mingkwai-typesetter' ).MD_READER
hide = MD_READER.hide.bind MD_READER
copy = MD_READER.copy.bind MD_READER
stamp = MD_READER.stamp.bind MD_READER
unstamp = MD_READER.unstamp.bind MD_READER
select = MD_READER.select.bind MD_READER
is_hidden = MD_READER.is_hidden.bind MD_READER
is_stamped = MD_READER.is_stamped.bind MD_READER
input = D.create_throughstream()
rpr = ( x ) -> ( ( require 'util' ).inspect x, colors: yes, depth: 2 ).replace /\n * /g, ' '
#.........................................................................................................
sandbox =
f: -> 108
n: 42
foo: Array.from 'shrdlu'
bar: { x: 33, y: 54, }
#.........................................................................................................
input
#.......................................................................................................
.pipe do =>
local = {}
backup = null
#.....................................................................................................
return $ ( event, send ) =>
#...................................................................................................
if select event, '~', 'change'
[ _, _, parameters, _, ] = event
[ name, changeset, ] = parameters
#.................................................................................................
if name is 'sandbox'
local = DIFFPATCH.patch changeset, local
#.................................................................................................
send event
#...................................................................................................
else if select event, '~', 'add-ten'
send event
#.................................................................................................
backup = DIFFPATCH.snapshot local
local.n = ( local.n ? 0 ) + 10
changeset = DIFFPATCH.diff backup, local
#.................................................................................................
log 'A', rpr local
send [ '~', 'change', [ 'sandbox', changeset, ], null, ]
#...................................................................................................
else if select event, '~', 'frob'
send event
#.................................................................................................
backup = DIFFPATCH.snapshot local
local.foo.push [ 'X', 'Y', 'Z', ]
changeset = DIFFPATCH.diff backup, local
#.................................................................................................
log 'A', rpr local
send [ '~', 'change', [ 'sandbox', changeset, ], null, ]
#...................................................................................................
else if select event, '~', 'drab'
send event
#.................................................................................................
backup = DIFFPATCH.snapshot local
local.bar[ 'z' ] = local.foo
changeset = DIFFPATCH.diff backup, local
#.................................................................................................
log 'A', rpr local
send [ '~', 'change', [ 'sandbox', changeset, ], null, ]
#...................................................................................................
else
send event
#.......................................................................................................
# .pipe $observe ( event ) => log rpr event
#.......................................................................................................
.pipe $observe ( event ) =>
#.....................................................................................................
if select event, '~', 'change'
[ _, _, parameters, _, ] = event
[ name, changeset, ] = parameters
#.................................................................................................
if name is 'sandbox'
for change in changeset
whisper change
#.......................................................................................................
.pipe do =>
local = {}
#.....................................................................................................
return $observe ( event ) =>
#...................................................................................................
if select event, '~', 'change'
[ _, _, parameters, _, ] = event
[ name, changeset, ] = parameters
#.................................................................................................
if name is 'sandbox'
local = DIFFPATCH.patch changeset, local
log 'B', rpr local
#.........................................................................................................
changeset = DIFFPATCH.diff {}, sandbox
input.write [ '~', 'change', [ 'sandbox', changeset, ], null, ]
input.write [ '~', 'add-ten', null, null, ]
# input.write [ '~', 'frob', null, null, ]
# input.write [ '~', 'drab', null, null, ]
input.end()
test_changeset()
```
###
############################################################################################################
# CND = require 'cnd'
# rpr = CND.rpr
# badge = 'MK/TS/JIZURA/main'
# log = CND.get_logger 'plain', badge
# info = CND.get_logger 'info', badge
# whisper = CND.get_logger 'whisper', badge
# alert = CND.get_logger 'alert', badge
# debug = CND.get_logger 'debug', badge
# warn = CND.get_logger 'warn', badge
# help = CND.get_logger 'help', badge
# urge = CND.get_logger 'urge', badge
# echo = CND.echo.bind CND
diff = require 'changeset'
LODASH = require 'lodash'
#-----------------------------------------------------------------------------------------------------------
@snapshot = ( original ) -> LODASH.cloneDeep original
@diff = ( x, y ) -> diff x, y
@patch = ( changeset, x ) -> diff.apply changeset, x
|
[
{
"context": "ess', ->\n expect(s3.dnsCompatibleBucketName('1.2.3.4')).toBe(false)\n expect(s3.dnsCompatibleBucke",
"end": 2345,
"score": 0.9995880722999573,
"start": 2338,
"tag": "IP_ADDRESS",
"value": "1.2.3.4"
},
{
"context": "stname\n params = { Bucket: 'bucket', Key: 'a b c', VersionId: 'a&b' }\n req = build('headObj",
"end": 3894,
"score": 0.9981074333190918,
"start": 3889,
"tag": "KEY",
"value": "a b c"
},
{
"context": "h', ->\n params = { Bucket: 'bucket', Key: 'k e/y' }\n req = build('headObject', params)\n ",
"end": 4133,
"score": 0.994423508644104,
"start": 4128,
"tag": "KEY",
"value": "k e/y"
},
{
"context": " = build('headObject', {Bucket:'bucket-name',Key:'abc'})\n expect(req.method).toEqual('HEAD')\n ",
"end": 4866,
"score": 0.9839506149291992,
"start": 4863,
"tag": "KEY",
"value": "abc"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=uefzBaGpqvO9QhGtT%2BbYda0pg",
"end": 17895,
"score": 0.9671981334686279,
"start": 17891,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=60&Signature=ZJKBOuhI99B2OZdkGSOmfG86BOI%",
"end": 18169,
"score": 0.8665775656700134,
"start": 18165,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=60&Signature=ZJKBOuhI99B2OZdkGSOmfG86BOI%",
"end": 18519,
"score": 0.8233869075775146,
"start": 18515,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=uefzBaGpqvO9QhGtT%2BbYda0pg",
"end": 18866,
"score": 0.9274169206619263,
"start": 18862,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=h%2FphNvPoGxx9qq2U7Zhbfqgi0",
"end": 19136,
"score": 0.8573789596557617,
"start": 19132,
"tag": "KEY",
"value": "akid"
},
{
"context": "ttps://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Content-MD5=hBotaJrYa9FhFEdFPCLG%2FA%3D%3D&Expire",
"end": 19434,
"score": 0.90034419298172,
"start": 19430,
"tag": "KEY",
"value": "akid"
},
{
"context": "et.s3.amazonaws.com/?prefix=prefix&AWSAccessKeyId=akid&Expires=900&Signature=fWeCHJBop4LyDXm2%2F%2BvR%2B",
"end": 19782,
"score": 0.938730776309967,
"start": 19778,
"tag": "KEY",
"value": "akid"
}
] | node_modules/Quintus/node_modules/aws-sdk/test/services/s3.spec.coffee | evannara/maze | 2 | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
helpers = require('../helpers')
AWS = helpers.AWS
Stream = require('stream').Stream
require('../../lib/services/s3')
describe 'AWS.S3', ->
s3 = null
oldRegion = null
request = (operation, params) ->
req = new AWS.Request(s3, operation, params || {})
req.service.addAllRequestListeners(req)
req
beforeEach ->
oldRegion = AWS.config.region
AWS.config.update(region: undefined) # use global region
s3 = new AWS.S3()
afterEach ->
AWS.config.update(region: oldRegion)
describe 'dnsCompatibleBucketName', ->
it 'must be at least 3 characters', ->
expect(s3.dnsCompatibleBucketName('aa')).toBe(false)
it 'must not be longer than 63 characters', ->
b = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
expect(s3.dnsCompatibleBucketName(b)).toBe(false)
it 'must start with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('Abc')).toBe(false)
expect(s3.dnsCompatibleBucketName('-bc')).toBe(false)
expect(s3.dnsCompatibleBucketName('abc')).toBe(true)
it 'must end with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('abC')).toBe(false)
expect(s3.dnsCompatibleBucketName('ab-')).toBe(false)
expect(s3.dnsCompatibleBucketName('abc')).toBe(true)
it 'may not contain multiple contiguous dots', ->
expect(s3.dnsCompatibleBucketName('abc.123')).toBe(true)
expect(s3.dnsCompatibleBucketName('abc..123')).toBe(false)
it 'may only contain letters numbers and dots', ->
expect(s3.dnsCompatibleBucketName('abc123')).toBe(true)
expect(s3.dnsCompatibleBucketName('abc_123')).toBe(false)
it 'must not look like an ip address', ->
expect(s3.dnsCompatibleBucketName('1.2.3.4')).toBe(false)
expect(s3.dnsCompatibleBucketName('a.b.c.d')).toBe(true)
describe 'endpoint', ->
it 'sets hostname to s3.amazonaws.com when region is un-specified', ->
s3 = new AWS.S3()
expect(s3.endpoint.hostname).toEqual('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).toEqual('s3.amazonaws.com')
it 'sets region to us-east-1 when unspecified', ->
s3 = new AWS.S3({ region: 'us-east-1' })
expect(s3.config.region).toEqual('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).toEqual('s3-us-west-1.amazonaws.com')
describe 'building a request', ->
build = (operation, params) ->
req = request(operation, params)
req.emit('build', [req])
return req.httpRequest
it 'obeys the configuration for s3ForcePathStyle', ->
config = new AWS.Config({s3ForcePathStyle: true })
s3 = new AWS.S3(config)
expect(s3.config.s3ForcePathStyle).toEqual(true)
req = build('headObject', {Bucket:'bucket', Key:'key'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket/key')
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).toEqual('/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).toEqual('/k%20e/y')
it 'ensures a single forward slash exists', ->
req = build('listObjects', { Bucket: 'bucket' })
expect(req.path).toEqual('/')
req = build('listObjects', { Bucket: 'bucket', MaxKeys:123 })
expect(req.path).toEqual('/?max-keys=123')
it 'ensures a single forward slash exists when querystring is present'
describe 'virtual-hosted vs path-style bucket requests', ->
describe 'HTTPS', ->
beforeEach ->
s3 = new AWS.S3({ sslEnabled: true })
it 'puts dns-compat bucket names in the hostname', ->
req = build('headObject', {Bucket:'bucket-name',Key:'abc'})
expect(req.method).toEqual('HEAD')
expect(req.endpoint.hostname).toEqual('bucket-name.s3.amazonaws.com')
expect(req.path).toEqual('/abc')
it 'ensures the path contains / at a minimum when moving bucket', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).toEqual('bucket-name.s3.amazonaws.com')
expect(req.path).toEqual('/')
it 'puts dns-compat bucket names in path if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket.name')
it 'puts dns-compat bucket names in path if configured to do so', ->
s3 = new AWS.S3({ sslEnabled: true, s3ForcePathStyle: true })
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket-name')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket_name')
describe 'HTTP', ->
beforeEach ->
s3 = new AWS.S3({ sslEnabled: false })
it 'puts dns-compat bucket names in the hostname', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).toEqual('bucket-name.s3.amazonaws.com')
expect(req.path).toEqual('/')
it 'puts dns-compat bucket names in the hostname if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).toEqual('bucket.name.s3.amazonaws.com')
expect(req.path).toEqual('/')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket_name')
# 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', ->
extractError = (statusCode, body) ->
req = request('operation')
resp = new AWS.Response(req)
resp.httpResponse.body = new Buffer(body || '')
resp.httpResponse.statusCode = statusCode
req.emit('extractError', [resp])
resp.error
it 'handles 304 errors', ->
error = extractError(304)
expect(error.code).toEqual('NotModified')
expect(error.message).toEqual(null)
it 'handles 400 errors', ->
error = extractError(400)
expect(error.code).toEqual('BadRequest')
expect(error.message).toEqual(null)
it 'handles 403 errors', ->
error = extractError(403)
expect(error.code).toEqual('Forbidden')
expect(error.message).toEqual(null)
it 'handles 404 errors', ->
error = extractError(404)
expect(error.code).toEqual('NotFound')
expect(error.message).toEqual(null)
it 'misc errors not known to return an empty body', ->
error = extractError(412) # made up
expect(error.code).toEqual(412)
expect(error.message).toEqual(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).toEqual('ErrorCode')
expect(error.message).toEqual('ErrorMessage')
# 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-ruby-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-ruby-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, headers, body
s3.getBucketAcl (error, data) ->
expect(error).toBe(null)
expect(data).toEqual({
Owner:
DisplayName: 'aws-ruby-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser',
DisplayName: 'aws-ruby-sdk'
ID: 'id'
},
{
Permission : 'READ'
Grantee:
Type: 'Group',
URI: 'uri'
}
],
RequestId : 'request-id'
})
describe 'putBucketAcl', ->
it 'correctly builds the ACL XML document', ->
xml =
"""
<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-ruby-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-ruby-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, {}, ''
params =
AccessControlPolicy:
Owner:
DisplayName: 'aws-ruby-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser',
DisplayName: 'aws-ruby-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).toBe(null)
expect(data).toEqual({
Location: 'http://Example-Bucket.s3.amazonaws.com/Example-Object'
Bucket: 'Example-Bucket'
Key: 'Example-Object'
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
RequestId: '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 instanceof Error).toBeTruthy()
expect(error.code).toEqual('InternalError')
expect(error.message).toEqual('We encountered an internal error. Please try again.')
expect(error.statusCode).toEqual(200)
expect(error.retryable).toEqual(true)
expect(data).toEqual(null)
describe 'getBucketLocation', ->
it 'returns null 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).toBe(null)
expect(data).toEqual({})
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).toBe(null)
expect(data).toEqual({
LocationConstraint: 'EU',
RequestId: '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) ->
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(Bucket:'name')
expect(loc).toEqual('eu-west-1')
it 'correctly builds the xml', ->
AWS.util.each AWS.S3.prototype.computableChecksumOperations, (operation) ->
describe operation, ->
it 'forces Content-MD5 header parameter', ->
helpers.mockHttpResponse 200, {}, ''
resp = s3[operation](Bucket: 'bucket', ContentMD5: '000').send()
hash = AWS.util.crypto.md5(resp.request.httpRequest.body, 'base64')
expect(resp.request.httpRequest.headers['Content-MD5']).toEqual(hash)
describe 'willComputeChecksums', ->
beforeEach ->
helpers.mockHttpResponse 200, {}, ''
willCompute = (operation, opts) ->
compute = opts.computeChecksums
s3 = new AWS.S3(computeChecksums: compute)
resp = s3.makeRequest(operation, Bucket: 'example', ContentMD5: opts.hash).send()
checksum = resp.request.httpRequest.headers['Content-MD5']
if opts.hash != undefined
expect(checksum).toEqual(opts.hash)
else
realChecksum = AWS.util.crypto.md5(resp.request.httpRequest.body, 'base64')
expect(checksum).toEqual(realChecksum)
it 'computes checksums if the operation requires it', ->
willCompute 'deleteObjects', computeChecksums: true
willCompute 'putBucketCors', computeChecksums: true
willCompute 'putBucketLifecycle', computeChecksums: true
willCompute 'putBucketTagging', 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 'putBucketTagging', 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 'does not compute checksums for Stream objects', ->
s3 = new AWS.S3(computeChecksums: true)
resp = s3.putObject(Bucket: 'example', Key: 'foo', Body: new Stream).send()
expect(resp.request.httpRequest.headers['Content-MD5']).toEqual(undefined)
it 'computes checksums if computeChecksums is on and ContentMD5 is not provided',->
willCompute 'putBucketAcl', computeChecksums: true
describe 'getSignedUrl', ->
date = null
beforeEach ->
date = AWS.util.date.getDate
AWS.util.date.getDate = -> new Date(0)
afterEach ->
AWS.util.date.getDate = date
it 'gets a signed URL for getObject', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key')
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=uefzBaGpqvO9QhGtT%2BbYda0pgQY%3D')
it 'gets a signed URL with Expires time', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key', Expires: 60)
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=60&Signature=ZJKBOuhI99B2OZdkGSOmfG86BOI%3D')
it 'gets a signed URL with expiration and bound bucket parameters', ->
s3 = new AWS.S3(paramValidation: true, params: Bucket: 'bucket')
url = s3.getSignedUrl('getObject', Key: 'key', Expires: 60)
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=60&Signature=ZJKBOuhI99B2OZdkGSOmfG86BOI%3D')
it 'gets a signed URL with callback', ->
url = null
runs ->
s3.getSignedUrl 'getObject', Bucket: 'bucket', Key: 'key', (err, value) -> url = value
waitsFor -> url
runs ->
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=uefzBaGpqvO9QhGtT%2BbYda0pgQY%3D')
it 'gets a signed URL for putObject with no body', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key')
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Expires=900&Signature=h%2FphNvPoGxx9qq2U7Zhbfqgi0Xs%3D')
it 'gets a signed URL for putObject with a body (and checksum)', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Body: 'body')
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=akid&Content-MD5=hBotaJrYa9FhFEdFPCLG%2FA%3D%3D&Expires=900&Signature=7%2BXiHEwB%2B3nSg2rhTyatSigkGPI%3D')
it 'gets a signed URL and appends to existing query parameters', ->
url = s3.getSignedUrl('listObjects', Bucket: 'bucket', Prefix: 'prefix')
expect(url).toEqual('https://bucket.s3.amazonaws.com/?prefix=prefix&AWSAccessKeyId=akid&Expires=900&Signature=fWeCHJBop4LyDXm2%2F%2BvR%2BqzH5zk%3D')
| 26155 | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
helpers = require('../helpers')
AWS = helpers.AWS
Stream = require('stream').Stream
require('../../lib/services/s3')
describe 'AWS.S3', ->
s3 = null
oldRegion = null
request = (operation, params) ->
req = new AWS.Request(s3, operation, params || {})
req.service.addAllRequestListeners(req)
req
beforeEach ->
oldRegion = AWS.config.region
AWS.config.update(region: undefined) # use global region
s3 = new AWS.S3()
afterEach ->
AWS.config.update(region: oldRegion)
describe 'dnsCompatibleBucketName', ->
it 'must be at least 3 characters', ->
expect(s3.dnsCompatibleBucketName('aa')).toBe(false)
it 'must not be longer than 63 characters', ->
b = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
expect(s3.dnsCompatibleBucketName(b)).toBe(false)
it 'must start with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('Abc')).toBe(false)
expect(s3.dnsCompatibleBucketName('-bc')).toBe(false)
expect(s3.dnsCompatibleBucketName('abc')).toBe(true)
it 'must end with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('abC')).toBe(false)
expect(s3.dnsCompatibleBucketName('ab-')).toBe(false)
expect(s3.dnsCompatibleBucketName('abc')).toBe(true)
it 'may not contain multiple contiguous dots', ->
expect(s3.dnsCompatibleBucketName('abc.123')).toBe(true)
expect(s3.dnsCompatibleBucketName('abc..123')).toBe(false)
it 'may only contain letters numbers and dots', ->
expect(s3.dnsCompatibleBucketName('abc123')).toBe(true)
expect(s3.dnsCompatibleBucketName('abc_123')).toBe(false)
it 'must not look like an ip address', ->
expect(s3.dnsCompatibleBucketName('192.168.127.12')).toBe(false)
expect(s3.dnsCompatibleBucketName('a.b.c.d')).toBe(true)
describe 'endpoint', ->
it 'sets hostname to s3.amazonaws.com when region is un-specified', ->
s3 = new AWS.S3()
expect(s3.endpoint.hostname).toEqual('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).toEqual('s3.amazonaws.com')
it 'sets region to us-east-1 when unspecified', ->
s3 = new AWS.S3({ region: 'us-east-1' })
expect(s3.config.region).toEqual('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).toEqual('s3-us-west-1.amazonaws.com')
describe 'building a request', ->
build = (operation, params) ->
req = request(operation, params)
req.emit('build', [req])
return req.httpRequest
it 'obeys the configuration for s3ForcePathStyle', ->
config = new AWS.Config({s3ForcePathStyle: true })
s3 = new AWS.S3(config)
expect(s3.config.s3ForcePathStyle).toEqual(true)
req = build('headObject', {Bucket:'bucket', Key:'key'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket/key')
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).toEqual('/a%20b%20c?versionId=a%26b')
it 'does not uri-escape forward slashes in the path', ->
params = { Bucket: 'bucket', Key: '<KEY>' }
req = build('headObject', params)
expect(req.path).toEqual('/k%20e/y')
it 'ensures a single forward slash exists', ->
req = build('listObjects', { Bucket: 'bucket' })
expect(req.path).toEqual('/')
req = build('listObjects', { Bucket: 'bucket', MaxKeys:123 })
expect(req.path).toEqual('/?max-keys=123')
it 'ensures a single forward slash exists when querystring is present'
describe 'virtual-hosted vs path-style bucket requests', ->
describe 'HTTPS', ->
beforeEach ->
s3 = new AWS.S3({ sslEnabled: true })
it 'puts dns-compat bucket names in the hostname', ->
req = build('headObject', {Bucket:'bucket-name',Key:'<KEY>'})
expect(req.method).toEqual('HEAD')
expect(req.endpoint.hostname).toEqual('bucket-name.s3.amazonaws.com')
expect(req.path).toEqual('/abc')
it 'ensures the path contains / at a minimum when moving bucket', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).toEqual('bucket-name.s3.amazonaws.com')
expect(req.path).toEqual('/')
it 'puts dns-compat bucket names in path if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket.name')
it 'puts dns-compat bucket names in path if configured to do so', ->
s3 = new AWS.S3({ sslEnabled: true, s3ForcePathStyle: true })
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket-name')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket_name')
describe 'HTTP', ->
beforeEach ->
s3 = new AWS.S3({ sslEnabled: false })
it 'puts dns-compat bucket names in the hostname', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).toEqual('bucket-name.s3.amazonaws.com')
expect(req.path).toEqual('/')
it 'puts dns-compat bucket names in the hostname if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).toEqual('bucket.name.s3.amazonaws.com')
expect(req.path).toEqual('/')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket_name')
# 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', ->
extractError = (statusCode, body) ->
req = request('operation')
resp = new AWS.Response(req)
resp.httpResponse.body = new Buffer(body || '')
resp.httpResponse.statusCode = statusCode
req.emit('extractError', [resp])
resp.error
it 'handles 304 errors', ->
error = extractError(304)
expect(error.code).toEqual('NotModified')
expect(error.message).toEqual(null)
it 'handles 400 errors', ->
error = extractError(400)
expect(error.code).toEqual('BadRequest')
expect(error.message).toEqual(null)
it 'handles 403 errors', ->
error = extractError(403)
expect(error.code).toEqual('Forbidden')
expect(error.message).toEqual(null)
it 'handles 404 errors', ->
error = extractError(404)
expect(error.code).toEqual('NotFound')
expect(error.message).toEqual(null)
it 'misc errors not known to return an empty body', ->
error = extractError(412) # made up
expect(error.code).toEqual(412)
expect(error.message).toEqual(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).toEqual('ErrorCode')
expect(error.message).toEqual('ErrorMessage')
# 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-ruby-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-ruby-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, headers, body
s3.getBucketAcl (error, data) ->
expect(error).toBe(null)
expect(data).toEqual({
Owner:
DisplayName: 'aws-ruby-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser',
DisplayName: 'aws-ruby-sdk'
ID: 'id'
},
{
Permission : 'READ'
Grantee:
Type: 'Group',
URI: 'uri'
}
],
RequestId : 'request-id'
})
describe 'putBucketAcl', ->
it 'correctly builds the ACL XML document', ->
xml =
"""
<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-ruby-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-ruby-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, {}, ''
params =
AccessControlPolicy:
Owner:
DisplayName: 'aws-ruby-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser',
DisplayName: 'aws-ruby-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).toBe(null)
expect(data).toEqual({
Location: 'http://Example-Bucket.s3.amazonaws.com/Example-Object'
Bucket: 'Example-Bucket'
Key: 'Example-Object'
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
RequestId: '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 instanceof Error).toBeTruthy()
expect(error.code).toEqual('InternalError')
expect(error.message).toEqual('We encountered an internal error. Please try again.')
expect(error.statusCode).toEqual(200)
expect(error.retryable).toEqual(true)
expect(data).toEqual(null)
describe 'getBucketLocation', ->
it 'returns null 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).toBe(null)
expect(data).toEqual({})
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).toBe(null)
expect(data).toEqual({
LocationConstraint: 'EU',
RequestId: '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) ->
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(Bucket:'name')
expect(loc).toEqual('eu-west-1')
it 'correctly builds the xml', ->
AWS.util.each AWS.S3.prototype.computableChecksumOperations, (operation) ->
describe operation, ->
it 'forces Content-MD5 header parameter', ->
helpers.mockHttpResponse 200, {}, ''
resp = s3[operation](Bucket: 'bucket', ContentMD5: '000').send()
hash = AWS.util.crypto.md5(resp.request.httpRequest.body, 'base64')
expect(resp.request.httpRequest.headers['Content-MD5']).toEqual(hash)
describe 'willComputeChecksums', ->
beforeEach ->
helpers.mockHttpResponse 200, {}, ''
willCompute = (operation, opts) ->
compute = opts.computeChecksums
s3 = new AWS.S3(computeChecksums: compute)
resp = s3.makeRequest(operation, Bucket: 'example', ContentMD5: opts.hash).send()
checksum = resp.request.httpRequest.headers['Content-MD5']
if opts.hash != undefined
expect(checksum).toEqual(opts.hash)
else
realChecksum = AWS.util.crypto.md5(resp.request.httpRequest.body, 'base64')
expect(checksum).toEqual(realChecksum)
it 'computes checksums if the operation requires it', ->
willCompute 'deleteObjects', computeChecksums: true
willCompute 'putBucketCors', computeChecksums: true
willCompute 'putBucketLifecycle', computeChecksums: true
willCompute 'putBucketTagging', 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 'putBucketTagging', 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 'does not compute checksums for Stream objects', ->
s3 = new AWS.S3(computeChecksums: true)
resp = s3.putObject(Bucket: 'example', Key: 'foo', Body: new Stream).send()
expect(resp.request.httpRequest.headers['Content-MD5']).toEqual(undefined)
it 'computes checksums if computeChecksums is on and ContentMD5 is not provided',->
willCompute 'putBucketAcl', computeChecksums: true
describe 'getSignedUrl', ->
date = null
beforeEach ->
date = AWS.util.date.getDate
AWS.util.date.getDate = -> new Date(0)
afterEach ->
AWS.util.date.getDate = date
it 'gets a signed URL for getObject', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key')
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=900&Signature=uefzBaGpqvO9QhGtT%2BbYda0pgQY%3D')
it 'gets a signed URL with Expires time', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key', Expires: 60)
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=60&Signature=ZJKBOuhI99B2OZdkGSOmfG86BOI%3D')
it 'gets a signed URL with expiration and bound bucket parameters', ->
s3 = new AWS.S3(paramValidation: true, params: Bucket: 'bucket')
url = s3.getSignedUrl('getObject', Key: 'key', Expires: 60)
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=60&Signature=ZJKBOuhI99B2OZdkGSOmfG86BOI%3D')
it 'gets a signed URL with callback', ->
url = null
runs ->
s3.getSignedUrl 'getObject', Bucket: 'bucket', Key: 'key', (err, value) -> url = value
waitsFor -> url
runs ->
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=900&Signature=uefzBaGpqvO9QhGtT%2BbYda0pgQY%3D')
it 'gets a signed URL for putObject with no body', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key')
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Expires=900&Signature=h%2FphNvPoGxx9qq2U7Zhbfqgi0Xs%3D')
it 'gets a signed URL for putObject with a body (and checksum)', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Body: 'body')
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=<KEY>&Content-MD5=hBotaJrYa9FhFEdFPCLG%2FA%3D%3D&Expires=900&Signature=7%2BXiHEwB%2B3nSg2rhTyatSigkGPI%3D')
it 'gets a signed URL and appends to existing query parameters', ->
url = s3.getSignedUrl('listObjects', Bucket: 'bucket', Prefix: 'prefix')
expect(url).toEqual('https://bucket.s3.amazonaws.com/?prefix=prefix&AWSAccessKeyId=<KEY>&Expires=900&Signature=fWeCHJBop4LyDXm2%2F%2BvR%2BqzH5zk%3D')
| true | # Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
helpers = require('../helpers')
AWS = helpers.AWS
Stream = require('stream').Stream
require('../../lib/services/s3')
describe 'AWS.S3', ->
s3 = null
oldRegion = null
request = (operation, params) ->
req = new AWS.Request(s3, operation, params || {})
req.service.addAllRequestListeners(req)
req
beforeEach ->
oldRegion = AWS.config.region
AWS.config.update(region: undefined) # use global region
s3 = new AWS.S3()
afterEach ->
AWS.config.update(region: oldRegion)
describe 'dnsCompatibleBucketName', ->
it 'must be at least 3 characters', ->
expect(s3.dnsCompatibleBucketName('aa')).toBe(false)
it 'must not be longer than 63 characters', ->
b = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
expect(s3.dnsCompatibleBucketName(b)).toBe(false)
it 'must start with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('Abc')).toBe(false)
expect(s3.dnsCompatibleBucketName('-bc')).toBe(false)
expect(s3.dnsCompatibleBucketName('abc')).toBe(true)
it 'must end with a lower-cased letter or number', ->
expect(s3.dnsCompatibleBucketName('abC')).toBe(false)
expect(s3.dnsCompatibleBucketName('ab-')).toBe(false)
expect(s3.dnsCompatibleBucketName('abc')).toBe(true)
it 'may not contain multiple contiguous dots', ->
expect(s3.dnsCompatibleBucketName('abc.123')).toBe(true)
expect(s3.dnsCompatibleBucketName('abc..123')).toBe(false)
it 'may only contain letters numbers and dots', ->
expect(s3.dnsCompatibleBucketName('abc123')).toBe(true)
expect(s3.dnsCompatibleBucketName('abc_123')).toBe(false)
it 'must not look like an ip address', ->
expect(s3.dnsCompatibleBucketName('PI:IP_ADDRESS:192.168.127.12END_PI')).toBe(false)
expect(s3.dnsCompatibleBucketName('a.b.c.d')).toBe(true)
describe 'endpoint', ->
it 'sets hostname to s3.amazonaws.com when region is un-specified', ->
s3 = new AWS.S3()
expect(s3.endpoint.hostname).toEqual('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).toEqual('s3.amazonaws.com')
it 'sets region to us-east-1 when unspecified', ->
s3 = new AWS.S3({ region: 'us-east-1' })
expect(s3.config.region).toEqual('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).toEqual('s3-us-west-1.amazonaws.com')
describe 'building a request', ->
build = (operation, params) ->
req = request(operation, params)
req.emit('build', [req])
return req.httpRequest
it 'obeys the configuration for s3ForcePathStyle', ->
config = new AWS.Config({s3ForcePathStyle: true })
s3 = new AWS.S3(config)
expect(s3.config.s3ForcePathStyle).toEqual(true)
req = build('headObject', {Bucket:'bucket', Key:'key'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket/key')
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).toEqual('/a%20b%20c?versionId=a%26b')
it 'does not uri-escape forward slashes in the path', ->
params = { Bucket: 'bucket', Key: 'PI:KEY:<KEY>END_PI' }
req = build('headObject', params)
expect(req.path).toEqual('/k%20e/y')
it 'ensures a single forward slash exists', ->
req = build('listObjects', { Bucket: 'bucket' })
expect(req.path).toEqual('/')
req = build('listObjects', { Bucket: 'bucket', MaxKeys:123 })
expect(req.path).toEqual('/?max-keys=123')
it 'ensures a single forward slash exists when querystring is present'
describe 'virtual-hosted vs path-style bucket requests', ->
describe 'HTTPS', ->
beforeEach ->
s3 = new AWS.S3({ sslEnabled: 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).toEqual('HEAD')
expect(req.endpoint.hostname).toEqual('bucket-name.s3.amazonaws.com')
expect(req.path).toEqual('/abc')
it 'ensures the path contains / at a minimum when moving bucket', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).toEqual('bucket-name.s3.amazonaws.com')
expect(req.path).toEqual('/')
it 'puts dns-compat bucket names in path if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket.name')
it 'puts dns-compat bucket names in path if configured to do so', ->
s3 = new AWS.S3({ sslEnabled: true, s3ForcePathStyle: true })
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket-name')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket_name')
describe 'HTTP', ->
beforeEach ->
s3 = new AWS.S3({ sslEnabled: false })
it 'puts dns-compat bucket names in the hostname', ->
req = build('listObjects', {Bucket:'bucket-name'})
expect(req.endpoint.hostname).toEqual('bucket-name.s3.amazonaws.com')
expect(req.path).toEqual('/')
it 'puts dns-compat bucket names in the hostname if they contain a dot', ->
req = build('listObjects', {Bucket:'bucket.name'})
expect(req.endpoint.hostname).toEqual('bucket.name.s3.amazonaws.com')
expect(req.path).toEqual('/')
it 'puts dns-incompat bucket names in path', ->
req = build('listObjects', {Bucket:'bucket_name'})
expect(req.endpoint.hostname).toEqual('s3.amazonaws.com')
expect(req.path).toEqual('/bucket_name')
# 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', ->
extractError = (statusCode, body) ->
req = request('operation')
resp = new AWS.Response(req)
resp.httpResponse.body = new Buffer(body || '')
resp.httpResponse.statusCode = statusCode
req.emit('extractError', [resp])
resp.error
it 'handles 304 errors', ->
error = extractError(304)
expect(error.code).toEqual('NotModified')
expect(error.message).toEqual(null)
it 'handles 400 errors', ->
error = extractError(400)
expect(error.code).toEqual('BadRequest')
expect(error.message).toEqual(null)
it 'handles 403 errors', ->
error = extractError(403)
expect(error.code).toEqual('Forbidden')
expect(error.message).toEqual(null)
it 'handles 404 errors', ->
error = extractError(404)
expect(error.code).toEqual('NotFound')
expect(error.message).toEqual(null)
it 'misc errors not known to return an empty body', ->
error = extractError(412) # made up
expect(error.code).toEqual(412)
expect(error.message).toEqual(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).toEqual('ErrorCode')
expect(error.message).toEqual('ErrorMessage')
# 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-ruby-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-ruby-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, headers, body
s3.getBucketAcl (error, data) ->
expect(error).toBe(null)
expect(data).toEqual({
Owner:
DisplayName: 'aws-ruby-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser',
DisplayName: 'aws-ruby-sdk'
ID: 'id'
},
{
Permission : 'READ'
Grantee:
Type: 'Group',
URI: 'uri'
}
],
RequestId : 'request-id'
})
describe 'putBucketAcl', ->
it 'correctly builds the ACL XML document', ->
xml =
"""
<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-ruby-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-ruby-sdk</DisplayName>
<ID>id</ID>
</Owner>
</AccessControlPolicy>
"""
helpers.mockHttpResponse 200, {}, ''
params =
AccessControlPolicy:
Owner:
DisplayName: 'aws-ruby-sdk',
ID: 'id'
Grants: [
{
Permission: 'FULL_CONTROL'
Grantee:
Type: 'CanonicalUser',
DisplayName: 'aws-ruby-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).toBe(null)
expect(data).toEqual({
Location: 'http://Example-Bucket.s3.amazonaws.com/Example-Object'
Bucket: 'Example-Bucket'
Key: 'Example-Object'
ETag: '"3858f62230ac3c915f300c664312c11f-9"'
RequestId: '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 instanceof Error).toBeTruthy()
expect(error.code).toEqual('InternalError')
expect(error.message).toEqual('We encountered an internal error. Please try again.')
expect(error.statusCode).toEqual(200)
expect(error.retryable).toEqual(true)
expect(data).toEqual(null)
describe 'getBucketLocation', ->
it 'returns null 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).toBe(null)
expect(data).toEqual({})
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).toBe(null)
expect(data).toEqual({
LocationConstraint: 'EU',
RequestId: '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) ->
loc = params.CreateBucketConfiguration.LocationConstraint
s3.createBucket(Bucket:'name')
expect(loc).toEqual('eu-west-1')
it 'correctly builds the xml', ->
AWS.util.each AWS.S3.prototype.computableChecksumOperations, (operation) ->
describe operation, ->
it 'forces Content-MD5 header parameter', ->
helpers.mockHttpResponse 200, {}, ''
resp = s3[operation](Bucket: 'bucket', ContentMD5: '000').send()
hash = AWS.util.crypto.md5(resp.request.httpRequest.body, 'base64')
expect(resp.request.httpRequest.headers['Content-MD5']).toEqual(hash)
describe 'willComputeChecksums', ->
beforeEach ->
helpers.mockHttpResponse 200, {}, ''
willCompute = (operation, opts) ->
compute = opts.computeChecksums
s3 = new AWS.S3(computeChecksums: compute)
resp = s3.makeRequest(operation, Bucket: 'example', ContentMD5: opts.hash).send()
checksum = resp.request.httpRequest.headers['Content-MD5']
if opts.hash != undefined
expect(checksum).toEqual(opts.hash)
else
realChecksum = AWS.util.crypto.md5(resp.request.httpRequest.body, 'base64')
expect(checksum).toEqual(realChecksum)
it 'computes checksums if the operation requires it', ->
willCompute 'deleteObjects', computeChecksums: true
willCompute 'putBucketCors', computeChecksums: true
willCompute 'putBucketLifecycle', computeChecksums: true
willCompute 'putBucketTagging', 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 'putBucketTagging', 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 'does not compute checksums for Stream objects', ->
s3 = new AWS.S3(computeChecksums: true)
resp = s3.putObject(Bucket: 'example', Key: 'foo', Body: new Stream).send()
expect(resp.request.httpRequest.headers['Content-MD5']).toEqual(undefined)
it 'computes checksums if computeChecksums is on and ContentMD5 is not provided',->
willCompute 'putBucketAcl', computeChecksums: true
describe 'getSignedUrl', ->
date = null
beforeEach ->
date = AWS.util.date.getDate
AWS.util.date.getDate = -> new Date(0)
afterEach ->
AWS.util.date.getDate = date
it 'gets a signed URL for getObject', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key')
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=uefzBaGpqvO9QhGtT%2BbYda0pgQY%3D')
it 'gets a signed URL with Expires time', ->
url = s3.getSignedUrl('getObject', Bucket: 'bucket', Key: 'key', Expires: 60)
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=60&Signature=ZJKBOuhI99B2OZdkGSOmfG86BOI%3D')
it 'gets a signed URL with expiration and bound bucket parameters', ->
s3 = new AWS.S3(paramValidation: true, params: Bucket: 'bucket')
url = s3.getSignedUrl('getObject', Key: 'key', Expires: 60)
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=60&Signature=ZJKBOuhI99B2OZdkGSOmfG86BOI%3D')
it 'gets a signed URL with callback', ->
url = null
runs ->
s3.getSignedUrl 'getObject', Bucket: 'bucket', Key: 'key', (err, value) -> url = value
waitsFor -> url
runs ->
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=uefzBaGpqvO9QhGtT%2BbYda0pgQY%3D')
it 'gets a signed URL for putObject with no body', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key')
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=h%2FphNvPoGxx9qq2U7Zhbfqgi0Xs%3D')
it 'gets a signed URL for putObject with a body (and checksum)', ->
url = s3.getSignedUrl('putObject', Bucket: 'bucket', Key: 'key', Body: 'body')
expect(url).toEqual('https://bucket.s3.amazonaws.com/key?AWSAccessKeyId=PI:KEY:<KEY>END_PI&Content-MD5=hBotaJrYa9FhFEdFPCLG%2FA%3D%3D&Expires=900&Signature=7%2BXiHEwB%2B3nSg2rhTyatSigkGPI%3D')
it 'gets a signed URL and appends to existing query parameters', ->
url = s3.getSignedUrl('listObjects', Bucket: 'bucket', Prefix: 'prefix')
expect(url).toEqual('https://bucket.s3.amazonaws.com/?prefix=prefix&AWSAccessKeyId=PI:KEY:<KEY>END_PI&Expires=900&Signature=fWeCHJBop4LyDXm2%2F%2BvR%2BqzH5zk%3D')
|
[
{
"context": "#\n# Ui-Core main file\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\n\n# hook up dependencies\ncore = require('cor",
"end": 62,
"score": 0.9998855590820312,
"start": 45,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | ui/core/main.coffee | lovely-io/lovely.io-stl | 2 | #
# Ui-Core main file
#
# Copyright (C) 2012 Nikolay Nemshilov
#
# hook up dependencies
core = require('core')
dom = require('dom')
fx = require('fx')
$ = dom
A = core.A
ext = core.ext
Hash = core.Hash
isObject = core.isObject
Class = core.Class
Event = dom.Event
Element = dom.Element
Document = dom.Document
Window = dom.Window
Input = dom.Input
# glue in the files
include 'src/util'
include 'src/options'
include 'src/event'
include 'src/element'
include 'src/button'
include 'src/icon'
include 'src/spinner'
include 'src/locker'
include 'src/modal'
include 'src/menu'
# export your objects in the module
ext exports,
version: '%{version}'
Options: Options
Button: Button
Icon: Icon
Spinner: Spinner
Locker: Locker
Modal: Modal
Menu: Menu
| 7376 | #
# Ui-Core main file
#
# Copyright (C) 2012 <NAME>
#
# hook up dependencies
core = require('core')
dom = require('dom')
fx = require('fx')
$ = dom
A = core.A
ext = core.ext
Hash = core.Hash
isObject = core.isObject
Class = core.Class
Event = dom.Event
Element = dom.Element
Document = dom.Document
Window = dom.Window
Input = dom.Input
# glue in the files
include 'src/util'
include 'src/options'
include 'src/event'
include 'src/element'
include 'src/button'
include 'src/icon'
include 'src/spinner'
include 'src/locker'
include 'src/modal'
include 'src/menu'
# export your objects in the module
ext exports,
version: '%{version}'
Options: Options
Button: Button
Icon: Icon
Spinner: Spinner
Locker: Locker
Modal: Modal
Menu: Menu
| true | #
# Ui-Core main file
#
# Copyright (C) 2012 PI:NAME:<NAME>END_PI
#
# hook up dependencies
core = require('core')
dom = require('dom')
fx = require('fx')
$ = dom
A = core.A
ext = core.ext
Hash = core.Hash
isObject = core.isObject
Class = core.Class
Event = dom.Event
Element = dom.Element
Document = dom.Document
Window = dom.Window
Input = dom.Input
# glue in the files
include 'src/util'
include 'src/options'
include 'src/event'
include 'src/element'
include 'src/button'
include 'src/icon'
include 'src/spinner'
include 'src/locker'
include 'src/modal'
include 'src/menu'
# export your objects in the module
ext exports,
version: '%{version}'
Options: Options
Button: Button
Icon: Icon
Spinner: Spinner
Locker: Locker
Modal: Modal
Menu: Menu
|
[
{
"context": " Control Spot from campfire. https://github.com/minton/spot\n#\n# Dependencies:\n# None\n#\n# Configuration",
"end": 72,
"score": 0.9996500015258789,
"start": 66,
"tag": "USERNAME",
"value": "minton"
},
{
"context": " current song titles in the queue\n#\n# Authors:\n# mcminton, <Shad Downey> github:andromedado, Eric Stiens - ",
"end": 1655,
"score": 0.9997264742851257,
"start": 1647,
"tag": "USERNAME",
"value": "mcminton"
},
{
"context": "g titles in the queue\n#\n# Authors:\n# mcminton, <Shad Downey> github:andromedado, Eric Stiens - @mutualarising",
"end": 1669,
"score": 0.9998708367347717,
"start": 1658,
"tag": "NAME",
"value": "Shad Downey"
},
{
"context": "e\n#\n# Authors:\n# mcminton, <Shad Downey> github:andromedado, Eric Stiens - @mutualarising\n\nVERSION = '1.4'\n\nU",
"end": 1689,
"score": 0.9995934963226318,
"start": 1678,
"tag": "USERNAME",
"value": "andromedado"
},
{
"context": "s:\n# mcminton, <Shad Downey> github:andromedado, Eric Stiens - @mutualarising\n\nVERSION = '1.4'\n\nURL = process.",
"end": 1702,
"score": 0.9998198747634888,
"start": 1691,
"tag": "NAME",
"value": "Eric Stiens"
},
{
"context": "n, <Shad Downey> github:andromedado, Eric Stiens - @mutualarising\n\nVERSION = '1.4'\n\nURL = process.env.HUBOT_SPOT_UR",
"end": 1719,
"score": 0.9991957545280457,
"start": 1705,
"tag": "USERNAME",
"value": "@mutualarising"
}
] | src/spot.coffee | hubot-scripts/hubot-spot | 0 | # Description:
# Control Spot from campfire. https://github.com/minton/spot
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_SPOT_URL
# HUBOT_SPOT_MENTION_ROOM
#
# Commands:
# hubot play! - Plays current playlist or song.
# hubot pause - Pause the music.
# hubot play next - Plays the next song.
# hubot play back - Plays the previous song.
# hubot playing? - Returns the currently-played song.
# hubot play <song> - Play a particular song. This plays the first most popular result.
# hubot query <song> - Searches Spotify for a particular song, shows what "Play <song>" would play.
# hubot volume? - Returns the current volume level.
# hubot volume [0-100] - Sets the volume.
# hubot volume+ - Bumps the volume.
# hubot volume- - Bumps the volume down.
# hubot mute - Sets the volume to 0.
# hubot [name here] says turn it down - Sets the volume to 15 and blames [name here].
# hubot say <message> - Tells hubot to read a message aloud.
# hubot how much longer? - Hubot tells you how much is left on the current track
# hubot find x music <search> - Searches and pulls up x (or 3) most popular matches
# hubot play #n - Play the nth track from the last search results
# hubot album #n - Pull up album info for the nth track in the last search results
# hubot last find - Pulls up the most recent find query
# hubot airplay <Apple TV> - Tell Spot to broadcast to the specified Apple TV.
# hubot spot - Start or restart the Spotify client.
# hubot queue #n - Queues a song to play up when the current song is done
# hubot queue list - Shows current song titles in the queue
#
# Authors:
# mcminton, <Shad Downey> github:andromedado, Eric Stiens - @mutualarising
VERSION = '1.4'
URL = process.env.HUBOT_SPOT_URL || "http://localhost:5051"
MENTION_ROOM = process.env.HUBOT_SPOT_MENTION_ROOM || "#general"
spotRequest = (message, path, action, options, callback) ->
message.http("#{URL}#{path}")
.query(options)[action]() (err, res, body) ->
callback(err,res,body)
recordUserQueryResults = (message, results) ->
uQ = message.robot.brain.get('userQueries') || {}
uD = uQ[message.message.user.id] = uQ[message.message.user.id] || {}
uD.queries = uD.queries || []
uD.queries.push(
text: message.message.text
time: now()
results: results
)
message.robot.brain.set('userQueries', uQ)
getLastResultsRelevantToUser = (robot, user) ->
uQ = robot.brain.get('userQueries') || {}
uD = uQ[user.id] = uQ[user.id] || {}
uD.queries = uD.queries || []
lastUQTime = 0
if (uD.queries.length)
lastUQTime = uD.queries[uD.queries.length - 1].time
lqT = robot.brain.get('lastQueryTime')
if (lqT && lqT > lastUQTime && lqT - lastUQTime > 60)
return robot.brain.get('lastQueryResults')
if (uD.queries.length)
return uD.queries[uD.queries.length - 1].results
return null
explain = (data) ->
if not data.artists
return 'nothin\''
artists = []
artists.push(a.name) for a in data.artists
A = []
if data.album
album = data.album.name
if data.album.released
album += ' [' + data.album.released + ']'
A = ['Album: ' + album]
return ['Track: ' + data.name].concat(A).concat([
'Artist: ' + artists.join(', '),
'Length: ' + calcLength(data.length)
]).join("\n")
now = () ->
return ~~(Date.now() / 1000)
render = (explanations) ->
str = ""
for exp, i in explanations
str += '#' + (i + 1) + "\n" + exp + "\n"
return str
renderAlbum = (album) ->
artists = []
if not album.artists
artists.push('No one...?')
else
artists.push(a.name) for a in album.artists
pt1 = [
'#ALBUM#',
'Name: ' + album.name,
'Artist: ' + artists.join(', '),
'Released: ' + album.released,
'Tracks:'
].join("\n") + "\n"
explanations = (explain track for track in album.tracks)
return pt1 + render(explanations)
showResults = (robot, message, results) ->
if not results or not results.length
return message.send(':small_blue_diamond: I found nothin\'')
explanations = (explain track for track in results)
message.send(':small_blue_diamond: I found:')
message.send(render(explanations))
calcLength = (seconds) ->
iSeconds = parseInt(seconds, 10)
if (iSeconds < 60)
return (Math.round(iSeconds * 10) / 10) + ' seconds'
rSeconds = iSeconds % 60
if (rSeconds < 10)
rSeconds = '0' + rSeconds
return Math.floor(iSeconds / 60) + ':' + rSeconds
playTrack = (track, message) ->
if not track or not track.uri
message.send(":flushed:")
return
message.send(":small_blue_diamond: Switching to: " + track.name)
spotRequest message, '/play-uri', 'post', {'uri' : track.uri}, (err, res, body) ->
if (err)
message.send(":flushed: " + err)
queueTrack = (track, qL, message) ->
unless track && track.uri
message.send("Sorry, couldn't add that to the queue")
return
qL.push track
message.send(":small_blue_diamond: I'm adding " + track.name + " to the queue")
message.send "Current queue: #{qL.length} songs"
playNextTrackInQueue = (robot) ->
track = robot.brain.data.ql.shift()
robot.messageRoom(MENTION_ROOM, "Switching to " + track.name)
robot.http(URL+'/play-uri')
.query({'uri' : track.uri})['post']() (err,res,body) ->
if (err)
console.log "Error playing Queued Track" + err
sleep(4000) # hacky but otherwise sometimes it plays two tracks in a row
sleep = (ms) ->
start = new Date().getTime()
continue while new Date().getTime() - start < ms
module.exports = (robot) ->
playQueue = (robot) ->
if robot.brain.data.ql && robot.brain.data.ql.length > 0
robot.http(URL+'/seconds-left')
.get() (err, res, body) ->
seconds_left = parseFloat(body)
if seconds_left < 3
playNextTrackInQueue(robot)
setTimeout (->
playQueue(robot)
), 1000
playQueue(robot)
robot.respond /queue list/i, (message) ->
queue_list = []
if robot.brain.data.ql.length > 0
for track in robot.brain.data.ql
queue_list.push(track.name)
message.send "Current Queue: #{queue_list.join(', ')}"
else
message.send "Nothing queued up."
robot.respond /clear queue/i, (message) ->
robot.brain.data.ql = []
message.send "Queue cleared"
robot.respond /queue (.*)/i, (message) ->
robot.brain.data.ql ?= []
qL = robot.brain.data.ql
playNum = message.match[1].match(/#(\d+)\s*$/)
if (playNum)
r = getLastResultsRelevantToUser(robot, message.message.user)
i = parseInt(playNum[1], 10) - 1
if (r && r[i])
queueTrack(r[i], qL, message)
return
robot.respond /play!/i, (message) ->
message.finish()
spotRequest message, '/play', 'put', {}, (err, res, body) ->
message.send(":notes: #{body}")
robot.respond /pause/i, (message) ->
params = {volume: 0}
spotRequest message, '/pause', 'put', params, (err, res, body) ->
message.send("#{body} :cry:")
robot.respond /next/i, (message) ->
if robot.brain.data.ql and robot.brain.data.ql.length > 0
playNextTrackInQueue(robot)
else
spotRequest message, '/next', 'put', {}, (err, res, body) ->
message.send("#{body} :fast_forward:")
robot.respond /back/i, (message) ->
spotRequest message, '/back', 'put', {}, (err, res, body) ->
message.send("#{body} :rewind:")
robot.respond /playing\?/i, (message) ->
spotRequest message, '/playing', 'get', {}, (err, res, body) ->
message.send("#{URL}/playing.png")
message.send(":notes: #{body}")
robot.respond /album art\??/i, (message) ->
spotRequest message, '/playing', 'get', {}, (err, res, body) ->
message.send("#{URL}/playing.png")
robot.respond /volume\?/i, (message) ->
spotRequest message, '/volume', 'get', {}, (err, res, body) ->
message.send("Spot volume is #{body}. :mega:")
robot.respond /volume\+/i, (message) ->
spotRequest message, '/bumpup', 'put', {}, (err, res, body) ->
message.send("Spot volume bumped to #{body}. :mega:")
robot.respond /volume\-/i, (message) ->
spotRequest message, '/bumpdown', 'put', {}, (err, res, body) ->
message.send("Spot volume bumped down to #{body}. :mega:")
robot.respond /mute/i, (message) ->
spotRequest message, '/mute', 'put', {}, (err, res, body) ->
message.send("#{body} :mute:")
robot.respond /volume (.*)/i, (message) ->
params = {volume: message.match[1]}
spotRequest message, '/volume', 'put', params, (err, res, body) ->
message.send("Spot volume set to #{body}. :mega:")
robot.respond /play (.*)/i, (message) ->
playNum = message.match[1].match(/#(\d+)\s*$/)
if (playNum)
r = getLastResultsRelevantToUser(robot, message.message.user)
i = parseInt(playNum[1], 10) - 1
if (r && r[i])
playTrack(r[i], message)
return
if (message.match[1].match(/^that$/i))
lastSingle = robot.brain.get('lastSingleQuery')
if (lastSingle)
playTrack(lastSingle, message)
return
lR = robot.brain.get('lastQueryResults')
if (lR && lR.length)
playTrack(lR[0], message)
return
params = {q: message.match[1]}
spotRequest message, '/find', 'post', params, (err, res, body) ->
message.send(":small_blue_diamond: #{body}")
robot.respond /album .(\d+)/i, (message) ->
r = getLastResultsRelevantToUser(robot, message.message.user)
n = parseInt(message.match[1], 10) - 1
if (!r || !r[n])
message.send(":small_blue_diamon: out of bounds...")
return
spotRequest message, '/album-info', 'get', {'uri' : r[n].album.uri}, (err, res, body) ->
album = JSON.parse(body)
album.tracks.forEach((track) ->
track.album = track.album || {}
track.album.uri = r[n].album.uri
)
recordUserQueryResults(message, album.tracks)
message.send(renderAlbum album)
robot.respond /(how much )?(time )?(remaining|left)\??$/i, (message) ->
spotRequest message, '/how-much-longer', 'get', {}, (err, res, body) ->
message.send(":small_blue_diamond: #{body}")
robot.respond /query (.*)/i, (message) ->
params = {q: message.match[1]}
spotRequest message, '/single-query', 'get', params, (err, res, body) ->
track = JSON.parse(body)
robot.brain.set('lastSingleQuery', track)
message.send(":small_blue_diamond: I found:")
message.send(explain track)
robot.respond /find ?(\d+)? music (.*)/i, (message) ->
limit = message.match[1] || 3
params = {q: message.match[2]}
spotRequest message, '/query', 'get', params, (err, res, body) ->
try
data = JSON.parse(body)
if (data.length > limit)
data = data.slice(0, limit)
robot.brain.set('lastQueryResults', data)
robot.brain.set('lastQueryTime', now())
recordUserQueryResults(message, data)
showResults(robot, message, data)
catch error
message.send(":small_blue_diamond: :flushed: " + error.message)
robot.respond /last find\??/i, (message) ->
data = robot.brain.get 'lastQueryResults'
if (!data || data.length == 0)
message.send(":small_blue_diamond: I got nothin'")
return
recordUserQueryResults(message, data)
showResults(robot, message, data)
robot.respond /say (.*)/i, (message) ->
what = message.match[1]
params = {what: what}
spotRequest message, '/say', 'put', params, (err, res, body) ->
message.send(what)
robot.respond /say me/i, (message) ->
message.send('no way ' + message.message.user.name);
robot.respond /(.*) says.*turn.*down.*/i, (message) ->
name = message.match[1]
message.send("#{name} says, 'Turn down the music and get off my lawn!' :bowtie:")
params = {volume: 15}
spotRequest message, '/volume', 'put', params, (err, res, body) ->
message.send("Spot volume set to #{body}. :mega:")
robot.respond /spot version\??/i, (message) ->
message.send(':small_blue_diamond: Well, ' + message.message.user.name + ', my Spot version is presently ' + VERSION)
robot.respond /airplay (.*)/i, (message) ->
params = {atv: message.match[1]}
spotRequest message, '/airplay', 'put', params, (err, res, body) ->
message.send("#{body} :mega:")
robot.respond /spot/i, (message) ->
spotRequest message, '/spot', 'put', {}, (err, res, body) ->
message.send(body)
robot.respond /respot/i, (message) ->
spotRequest message, '/respot', 'put', {}, (err, res, body) ->
message.send(body)
| 1509 | # Description:
# Control Spot from campfire. https://github.com/minton/spot
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_SPOT_URL
# HUBOT_SPOT_MENTION_ROOM
#
# Commands:
# hubot play! - Plays current playlist or song.
# hubot pause - Pause the music.
# hubot play next - Plays the next song.
# hubot play back - Plays the previous song.
# hubot playing? - Returns the currently-played song.
# hubot play <song> - Play a particular song. This plays the first most popular result.
# hubot query <song> - Searches Spotify for a particular song, shows what "Play <song>" would play.
# hubot volume? - Returns the current volume level.
# hubot volume [0-100] - Sets the volume.
# hubot volume+ - Bumps the volume.
# hubot volume- - Bumps the volume down.
# hubot mute - Sets the volume to 0.
# hubot [name here] says turn it down - Sets the volume to 15 and blames [name here].
# hubot say <message> - Tells hubot to read a message aloud.
# hubot how much longer? - Hubot tells you how much is left on the current track
# hubot find x music <search> - Searches and pulls up x (or 3) most popular matches
# hubot play #n - Play the nth track from the last search results
# hubot album #n - Pull up album info for the nth track in the last search results
# hubot last find - Pulls up the most recent find query
# hubot airplay <Apple TV> - Tell Spot to broadcast to the specified Apple TV.
# hubot spot - Start or restart the Spotify client.
# hubot queue #n - Queues a song to play up when the current song is done
# hubot queue list - Shows current song titles in the queue
#
# Authors:
# mcminton, <<NAME>> github:andromedado, <NAME> - @mutualarising
VERSION = '1.4'
URL = process.env.HUBOT_SPOT_URL || "http://localhost:5051"
MENTION_ROOM = process.env.HUBOT_SPOT_MENTION_ROOM || "#general"
spotRequest = (message, path, action, options, callback) ->
message.http("#{URL}#{path}")
.query(options)[action]() (err, res, body) ->
callback(err,res,body)
recordUserQueryResults = (message, results) ->
uQ = message.robot.brain.get('userQueries') || {}
uD = uQ[message.message.user.id] = uQ[message.message.user.id] || {}
uD.queries = uD.queries || []
uD.queries.push(
text: message.message.text
time: now()
results: results
)
message.robot.brain.set('userQueries', uQ)
getLastResultsRelevantToUser = (robot, user) ->
uQ = robot.brain.get('userQueries') || {}
uD = uQ[user.id] = uQ[user.id] || {}
uD.queries = uD.queries || []
lastUQTime = 0
if (uD.queries.length)
lastUQTime = uD.queries[uD.queries.length - 1].time
lqT = robot.brain.get('lastQueryTime')
if (lqT && lqT > lastUQTime && lqT - lastUQTime > 60)
return robot.brain.get('lastQueryResults')
if (uD.queries.length)
return uD.queries[uD.queries.length - 1].results
return null
explain = (data) ->
if not data.artists
return 'nothin\''
artists = []
artists.push(a.name) for a in data.artists
A = []
if data.album
album = data.album.name
if data.album.released
album += ' [' + data.album.released + ']'
A = ['Album: ' + album]
return ['Track: ' + data.name].concat(A).concat([
'Artist: ' + artists.join(', '),
'Length: ' + calcLength(data.length)
]).join("\n")
now = () ->
return ~~(Date.now() / 1000)
render = (explanations) ->
str = ""
for exp, i in explanations
str += '#' + (i + 1) + "\n" + exp + "\n"
return str
renderAlbum = (album) ->
artists = []
if not album.artists
artists.push('No one...?')
else
artists.push(a.name) for a in album.artists
pt1 = [
'#ALBUM#',
'Name: ' + album.name,
'Artist: ' + artists.join(', '),
'Released: ' + album.released,
'Tracks:'
].join("\n") + "\n"
explanations = (explain track for track in album.tracks)
return pt1 + render(explanations)
showResults = (robot, message, results) ->
if not results or not results.length
return message.send(':small_blue_diamond: I found nothin\'')
explanations = (explain track for track in results)
message.send(':small_blue_diamond: I found:')
message.send(render(explanations))
calcLength = (seconds) ->
iSeconds = parseInt(seconds, 10)
if (iSeconds < 60)
return (Math.round(iSeconds * 10) / 10) + ' seconds'
rSeconds = iSeconds % 60
if (rSeconds < 10)
rSeconds = '0' + rSeconds
return Math.floor(iSeconds / 60) + ':' + rSeconds
playTrack = (track, message) ->
if not track or not track.uri
message.send(":flushed:")
return
message.send(":small_blue_diamond: Switching to: " + track.name)
spotRequest message, '/play-uri', 'post', {'uri' : track.uri}, (err, res, body) ->
if (err)
message.send(":flushed: " + err)
queueTrack = (track, qL, message) ->
unless track && track.uri
message.send("Sorry, couldn't add that to the queue")
return
qL.push track
message.send(":small_blue_diamond: I'm adding " + track.name + " to the queue")
message.send "Current queue: #{qL.length} songs"
playNextTrackInQueue = (robot) ->
track = robot.brain.data.ql.shift()
robot.messageRoom(MENTION_ROOM, "Switching to " + track.name)
robot.http(URL+'/play-uri')
.query({'uri' : track.uri})['post']() (err,res,body) ->
if (err)
console.log "Error playing Queued Track" + err
sleep(4000) # hacky but otherwise sometimes it plays two tracks in a row
sleep = (ms) ->
start = new Date().getTime()
continue while new Date().getTime() - start < ms
module.exports = (robot) ->
playQueue = (robot) ->
if robot.brain.data.ql && robot.brain.data.ql.length > 0
robot.http(URL+'/seconds-left')
.get() (err, res, body) ->
seconds_left = parseFloat(body)
if seconds_left < 3
playNextTrackInQueue(robot)
setTimeout (->
playQueue(robot)
), 1000
playQueue(robot)
robot.respond /queue list/i, (message) ->
queue_list = []
if robot.brain.data.ql.length > 0
for track in robot.brain.data.ql
queue_list.push(track.name)
message.send "Current Queue: #{queue_list.join(', ')}"
else
message.send "Nothing queued up."
robot.respond /clear queue/i, (message) ->
robot.brain.data.ql = []
message.send "Queue cleared"
robot.respond /queue (.*)/i, (message) ->
robot.brain.data.ql ?= []
qL = robot.brain.data.ql
playNum = message.match[1].match(/#(\d+)\s*$/)
if (playNum)
r = getLastResultsRelevantToUser(robot, message.message.user)
i = parseInt(playNum[1], 10) - 1
if (r && r[i])
queueTrack(r[i], qL, message)
return
robot.respond /play!/i, (message) ->
message.finish()
spotRequest message, '/play', 'put', {}, (err, res, body) ->
message.send(":notes: #{body}")
robot.respond /pause/i, (message) ->
params = {volume: 0}
spotRequest message, '/pause', 'put', params, (err, res, body) ->
message.send("#{body} :cry:")
robot.respond /next/i, (message) ->
if robot.brain.data.ql and robot.brain.data.ql.length > 0
playNextTrackInQueue(robot)
else
spotRequest message, '/next', 'put', {}, (err, res, body) ->
message.send("#{body} :fast_forward:")
robot.respond /back/i, (message) ->
spotRequest message, '/back', 'put', {}, (err, res, body) ->
message.send("#{body} :rewind:")
robot.respond /playing\?/i, (message) ->
spotRequest message, '/playing', 'get', {}, (err, res, body) ->
message.send("#{URL}/playing.png")
message.send(":notes: #{body}")
robot.respond /album art\??/i, (message) ->
spotRequest message, '/playing', 'get', {}, (err, res, body) ->
message.send("#{URL}/playing.png")
robot.respond /volume\?/i, (message) ->
spotRequest message, '/volume', 'get', {}, (err, res, body) ->
message.send("Spot volume is #{body}. :mega:")
robot.respond /volume\+/i, (message) ->
spotRequest message, '/bumpup', 'put', {}, (err, res, body) ->
message.send("Spot volume bumped to #{body}. :mega:")
robot.respond /volume\-/i, (message) ->
spotRequest message, '/bumpdown', 'put', {}, (err, res, body) ->
message.send("Spot volume bumped down to #{body}. :mega:")
robot.respond /mute/i, (message) ->
spotRequest message, '/mute', 'put', {}, (err, res, body) ->
message.send("#{body} :mute:")
robot.respond /volume (.*)/i, (message) ->
params = {volume: message.match[1]}
spotRequest message, '/volume', 'put', params, (err, res, body) ->
message.send("Spot volume set to #{body}. :mega:")
robot.respond /play (.*)/i, (message) ->
playNum = message.match[1].match(/#(\d+)\s*$/)
if (playNum)
r = getLastResultsRelevantToUser(robot, message.message.user)
i = parseInt(playNum[1], 10) - 1
if (r && r[i])
playTrack(r[i], message)
return
if (message.match[1].match(/^that$/i))
lastSingle = robot.brain.get('lastSingleQuery')
if (lastSingle)
playTrack(lastSingle, message)
return
lR = robot.brain.get('lastQueryResults')
if (lR && lR.length)
playTrack(lR[0], message)
return
params = {q: message.match[1]}
spotRequest message, '/find', 'post', params, (err, res, body) ->
message.send(":small_blue_diamond: #{body}")
robot.respond /album .(\d+)/i, (message) ->
r = getLastResultsRelevantToUser(robot, message.message.user)
n = parseInt(message.match[1], 10) - 1
if (!r || !r[n])
message.send(":small_blue_diamon: out of bounds...")
return
spotRequest message, '/album-info', 'get', {'uri' : r[n].album.uri}, (err, res, body) ->
album = JSON.parse(body)
album.tracks.forEach((track) ->
track.album = track.album || {}
track.album.uri = r[n].album.uri
)
recordUserQueryResults(message, album.tracks)
message.send(renderAlbum album)
robot.respond /(how much )?(time )?(remaining|left)\??$/i, (message) ->
spotRequest message, '/how-much-longer', 'get', {}, (err, res, body) ->
message.send(":small_blue_diamond: #{body}")
robot.respond /query (.*)/i, (message) ->
params = {q: message.match[1]}
spotRequest message, '/single-query', 'get', params, (err, res, body) ->
track = JSON.parse(body)
robot.brain.set('lastSingleQuery', track)
message.send(":small_blue_diamond: I found:")
message.send(explain track)
robot.respond /find ?(\d+)? music (.*)/i, (message) ->
limit = message.match[1] || 3
params = {q: message.match[2]}
spotRequest message, '/query', 'get', params, (err, res, body) ->
try
data = JSON.parse(body)
if (data.length > limit)
data = data.slice(0, limit)
robot.brain.set('lastQueryResults', data)
robot.brain.set('lastQueryTime', now())
recordUserQueryResults(message, data)
showResults(robot, message, data)
catch error
message.send(":small_blue_diamond: :flushed: " + error.message)
robot.respond /last find\??/i, (message) ->
data = robot.brain.get 'lastQueryResults'
if (!data || data.length == 0)
message.send(":small_blue_diamond: I got nothin'")
return
recordUserQueryResults(message, data)
showResults(robot, message, data)
robot.respond /say (.*)/i, (message) ->
what = message.match[1]
params = {what: what}
spotRequest message, '/say', 'put', params, (err, res, body) ->
message.send(what)
robot.respond /say me/i, (message) ->
message.send('no way ' + message.message.user.name);
robot.respond /(.*) says.*turn.*down.*/i, (message) ->
name = message.match[1]
message.send("#{name} says, 'Turn down the music and get off my lawn!' :bowtie:")
params = {volume: 15}
spotRequest message, '/volume', 'put', params, (err, res, body) ->
message.send("Spot volume set to #{body}. :mega:")
robot.respond /spot version\??/i, (message) ->
message.send(':small_blue_diamond: Well, ' + message.message.user.name + ', my Spot version is presently ' + VERSION)
robot.respond /airplay (.*)/i, (message) ->
params = {atv: message.match[1]}
spotRequest message, '/airplay', 'put', params, (err, res, body) ->
message.send("#{body} :mega:")
robot.respond /spot/i, (message) ->
spotRequest message, '/spot', 'put', {}, (err, res, body) ->
message.send(body)
robot.respond /respot/i, (message) ->
spotRequest message, '/respot', 'put', {}, (err, res, body) ->
message.send(body)
| true | # Description:
# Control Spot from campfire. https://github.com/minton/spot
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_SPOT_URL
# HUBOT_SPOT_MENTION_ROOM
#
# Commands:
# hubot play! - Plays current playlist or song.
# hubot pause - Pause the music.
# hubot play next - Plays the next song.
# hubot play back - Plays the previous song.
# hubot playing? - Returns the currently-played song.
# hubot play <song> - Play a particular song. This plays the first most popular result.
# hubot query <song> - Searches Spotify for a particular song, shows what "Play <song>" would play.
# hubot volume? - Returns the current volume level.
# hubot volume [0-100] - Sets the volume.
# hubot volume+ - Bumps the volume.
# hubot volume- - Bumps the volume down.
# hubot mute - Sets the volume to 0.
# hubot [name here] says turn it down - Sets the volume to 15 and blames [name here].
# hubot say <message> - Tells hubot to read a message aloud.
# hubot how much longer? - Hubot tells you how much is left on the current track
# hubot find x music <search> - Searches and pulls up x (or 3) most popular matches
# hubot play #n - Play the nth track from the last search results
# hubot album #n - Pull up album info for the nth track in the last search results
# hubot last find - Pulls up the most recent find query
# hubot airplay <Apple TV> - Tell Spot to broadcast to the specified Apple TV.
# hubot spot - Start or restart the Spotify client.
# hubot queue #n - Queues a song to play up when the current song is done
# hubot queue list - Shows current song titles in the queue
#
# Authors:
# mcminton, <PI:NAME:<NAME>END_PI> github:andromedado, PI:NAME:<NAME>END_PI - @mutualarising
VERSION = '1.4'
URL = process.env.HUBOT_SPOT_URL || "http://localhost:5051"
MENTION_ROOM = process.env.HUBOT_SPOT_MENTION_ROOM || "#general"
spotRequest = (message, path, action, options, callback) ->
message.http("#{URL}#{path}")
.query(options)[action]() (err, res, body) ->
callback(err,res,body)
recordUserQueryResults = (message, results) ->
uQ = message.robot.brain.get('userQueries') || {}
uD = uQ[message.message.user.id] = uQ[message.message.user.id] || {}
uD.queries = uD.queries || []
uD.queries.push(
text: message.message.text
time: now()
results: results
)
message.robot.brain.set('userQueries', uQ)
getLastResultsRelevantToUser = (robot, user) ->
uQ = robot.brain.get('userQueries') || {}
uD = uQ[user.id] = uQ[user.id] || {}
uD.queries = uD.queries || []
lastUQTime = 0
if (uD.queries.length)
lastUQTime = uD.queries[uD.queries.length - 1].time
lqT = robot.brain.get('lastQueryTime')
if (lqT && lqT > lastUQTime && lqT - lastUQTime > 60)
return robot.brain.get('lastQueryResults')
if (uD.queries.length)
return uD.queries[uD.queries.length - 1].results
return null
explain = (data) ->
if not data.artists
return 'nothin\''
artists = []
artists.push(a.name) for a in data.artists
A = []
if data.album
album = data.album.name
if data.album.released
album += ' [' + data.album.released + ']'
A = ['Album: ' + album]
return ['Track: ' + data.name].concat(A).concat([
'Artist: ' + artists.join(', '),
'Length: ' + calcLength(data.length)
]).join("\n")
now = () ->
return ~~(Date.now() / 1000)
render = (explanations) ->
str = ""
for exp, i in explanations
str += '#' + (i + 1) + "\n" + exp + "\n"
return str
renderAlbum = (album) ->
artists = []
if not album.artists
artists.push('No one...?')
else
artists.push(a.name) for a in album.artists
pt1 = [
'#ALBUM#',
'Name: ' + album.name,
'Artist: ' + artists.join(', '),
'Released: ' + album.released,
'Tracks:'
].join("\n") + "\n"
explanations = (explain track for track in album.tracks)
return pt1 + render(explanations)
showResults = (robot, message, results) ->
if not results or not results.length
return message.send(':small_blue_diamond: I found nothin\'')
explanations = (explain track for track in results)
message.send(':small_blue_diamond: I found:')
message.send(render(explanations))
calcLength = (seconds) ->
iSeconds = parseInt(seconds, 10)
if (iSeconds < 60)
return (Math.round(iSeconds * 10) / 10) + ' seconds'
rSeconds = iSeconds % 60
if (rSeconds < 10)
rSeconds = '0' + rSeconds
return Math.floor(iSeconds / 60) + ':' + rSeconds
playTrack = (track, message) ->
if not track or not track.uri
message.send(":flushed:")
return
message.send(":small_blue_diamond: Switching to: " + track.name)
spotRequest message, '/play-uri', 'post', {'uri' : track.uri}, (err, res, body) ->
if (err)
message.send(":flushed: " + err)
queueTrack = (track, qL, message) ->
unless track && track.uri
message.send("Sorry, couldn't add that to the queue")
return
qL.push track
message.send(":small_blue_diamond: I'm adding " + track.name + " to the queue")
message.send "Current queue: #{qL.length} songs"
playNextTrackInQueue = (robot) ->
track = robot.brain.data.ql.shift()
robot.messageRoom(MENTION_ROOM, "Switching to " + track.name)
robot.http(URL+'/play-uri')
.query({'uri' : track.uri})['post']() (err,res,body) ->
if (err)
console.log "Error playing Queued Track" + err
sleep(4000) # hacky but otherwise sometimes it plays two tracks in a row
sleep = (ms) ->
start = new Date().getTime()
continue while new Date().getTime() - start < ms
module.exports = (robot) ->
playQueue = (robot) ->
if robot.brain.data.ql && robot.brain.data.ql.length > 0
robot.http(URL+'/seconds-left')
.get() (err, res, body) ->
seconds_left = parseFloat(body)
if seconds_left < 3
playNextTrackInQueue(robot)
setTimeout (->
playQueue(robot)
), 1000
playQueue(robot)
robot.respond /queue list/i, (message) ->
queue_list = []
if robot.brain.data.ql.length > 0
for track in robot.brain.data.ql
queue_list.push(track.name)
message.send "Current Queue: #{queue_list.join(', ')}"
else
message.send "Nothing queued up."
robot.respond /clear queue/i, (message) ->
robot.brain.data.ql = []
message.send "Queue cleared"
robot.respond /queue (.*)/i, (message) ->
robot.brain.data.ql ?= []
qL = robot.brain.data.ql
playNum = message.match[1].match(/#(\d+)\s*$/)
if (playNum)
r = getLastResultsRelevantToUser(robot, message.message.user)
i = parseInt(playNum[1], 10) - 1
if (r && r[i])
queueTrack(r[i], qL, message)
return
robot.respond /play!/i, (message) ->
message.finish()
spotRequest message, '/play', 'put', {}, (err, res, body) ->
message.send(":notes: #{body}")
robot.respond /pause/i, (message) ->
params = {volume: 0}
spotRequest message, '/pause', 'put', params, (err, res, body) ->
message.send("#{body} :cry:")
robot.respond /next/i, (message) ->
if robot.brain.data.ql and robot.brain.data.ql.length > 0
playNextTrackInQueue(robot)
else
spotRequest message, '/next', 'put', {}, (err, res, body) ->
message.send("#{body} :fast_forward:")
robot.respond /back/i, (message) ->
spotRequest message, '/back', 'put', {}, (err, res, body) ->
message.send("#{body} :rewind:")
robot.respond /playing\?/i, (message) ->
spotRequest message, '/playing', 'get', {}, (err, res, body) ->
message.send("#{URL}/playing.png")
message.send(":notes: #{body}")
robot.respond /album art\??/i, (message) ->
spotRequest message, '/playing', 'get', {}, (err, res, body) ->
message.send("#{URL}/playing.png")
robot.respond /volume\?/i, (message) ->
spotRequest message, '/volume', 'get', {}, (err, res, body) ->
message.send("Spot volume is #{body}. :mega:")
robot.respond /volume\+/i, (message) ->
spotRequest message, '/bumpup', 'put', {}, (err, res, body) ->
message.send("Spot volume bumped to #{body}. :mega:")
robot.respond /volume\-/i, (message) ->
spotRequest message, '/bumpdown', 'put', {}, (err, res, body) ->
message.send("Spot volume bumped down to #{body}. :mega:")
robot.respond /mute/i, (message) ->
spotRequest message, '/mute', 'put', {}, (err, res, body) ->
message.send("#{body} :mute:")
robot.respond /volume (.*)/i, (message) ->
params = {volume: message.match[1]}
spotRequest message, '/volume', 'put', params, (err, res, body) ->
message.send("Spot volume set to #{body}. :mega:")
robot.respond /play (.*)/i, (message) ->
playNum = message.match[1].match(/#(\d+)\s*$/)
if (playNum)
r = getLastResultsRelevantToUser(robot, message.message.user)
i = parseInt(playNum[1], 10) - 1
if (r && r[i])
playTrack(r[i], message)
return
if (message.match[1].match(/^that$/i))
lastSingle = robot.brain.get('lastSingleQuery')
if (lastSingle)
playTrack(lastSingle, message)
return
lR = robot.brain.get('lastQueryResults')
if (lR && lR.length)
playTrack(lR[0], message)
return
params = {q: message.match[1]}
spotRequest message, '/find', 'post', params, (err, res, body) ->
message.send(":small_blue_diamond: #{body}")
robot.respond /album .(\d+)/i, (message) ->
r = getLastResultsRelevantToUser(robot, message.message.user)
n = parseInt(message.match[1], 10) - 1
if (!r || !r[n])
message.send(":small_blue_diamon: out of bounds...")
return
spotRequest message, '/album-info', 'get', {'uri' : r[n].album.uri}, (err, res, body) ->
album = JSON.parse(body)
album.tracks.forEach((track) ->
track.album = track.album || {}
track.album.uri = r[n].album.uri
)
recordUserQueryResults(message, album.tracks)
message.send(renderAlbum album)
robot.respond /(how much )?(time )?(remaining|left)\??$/i, (message) ->
spotRequest message, '/how-much-longer', 'get', {}, (err, res, body) ->
message.send(":small_blue_diamond: #{body}")
robot.respond /query (.*)/i, (message) ->
params = {q: message.match[1]}
spotRequest message, '/single-query', 'get', params, (err, res, body) ->
track = JSON.parse(body)
robot.brain.set('lastSingleQuery', track)
message.send(":small_blue_diamond: I found:")
message.send(explain track)
robot.respond /find ?(\d+)? music (.*)/i, (message) ->
limit = message.match[1] || 3
params = {q: message.match[2]}
spotRequest message, '/query', 'get', params, (err, res, body) ->
try
data = JSON.parse(body)
if (data.length > limit)
data = data.slice(0, limit)
robot.brain.set('lastQueryResults', data)
robot.brain.set('lastQueryTime', now())
recordUserQueryResults(message, data)
showResults(robot, message, data)
catch error
message.send(":small_blue_diamond: :flushed: " + error.message)
robot.respond /last find\??/i, (message) ->
data = robot.brain.get 'lastQueryResults'
if (!data || data.length == 0)
message.send(":small_blue_diamond: I got nothin'")
return
recordUserQueryResults(message, data)
showResults(robot, message, data)
robot.respond /say (.*)/i, (message) ->
what = message.match[1]
params = {what: what}
spotRequest message, '/say', 'put', params, (err, res, body) ->
message.send(what)
robot.respond /say me/i, (message) ->
message.send('no way ' + message.message.user.name);
robot.respond /(.*) says.*turn.*down.*/i, (message) ->
name = message.match[1]
message.send("#{name} says, 'Turn down the music and get off my lawn!' :bowtie:")
params = {volume: 15}
spotRequest message, '/volume', 'put', params, (err, res, body) ->
message.send("Spot volume set to #{body}. :mega:")
robot.respond /spot version\??/i, (message) ->
message.send(':small_blue_diamond: Well, ' + message.message.user.name + ', my Spot version is presently ' + VERSION)
robot.respond /airplay (.*)/i, (message) ->
params = {atv: message.match[1]}
spotRequest message, '/airplay', 'put', params, (err, res, body) ->
message.send("#{body} :mega:")
robot.respond /spot/i, (message) ->
spotRequest message, '/spot', 'put', {}, (err, res, body) ->
message.send(body)
robot.respond /respot/i, (message) ->
spotRequest message, '/respot', 'put', {}, (err, res, body) ->
message.send(body)
|
[
{
"context": "RT\n user = process.env.HUBOT_CI_USER\n password = process.env.HUBOT_CI_PASSWORD\n auth = new Buffer(user + ",
"end": 425,
"score": 0.8538334369659424,
"start": 414,
"tag": "PASSWORD",
"value": "process.env"
},
{
"context": "path, param, (data) ->\n msg.send(\"I have told Hudson, please wait...\")\n\n robot.respond /ci (.*) (.*)/",
"end": 2490,
"score": 0.7840481996536255,
"start": 2484,
"tag": "NAME",
"value": "Hudson"
}
] | src/scripts/ci.coffee | janx/hubot-scripts | 2 | # Track the status and trigger buid for hudson CI.
#
# ci list all/projects - list all the projects on Hudson
# ci status <project name> - see a project's status
# ci build <project name> - triger a build on hudson
Http = require 'http'
QS = require 'querystring'
module.exports = (robot) ->
host = process.env.HUBOT_CI_HOST
port = process.env.HUBOT_CI_PORT
user = process.env.HUBOT_CI_USER
password = process.env.HUBOT_CI_PASSWORD
auth = new Buffer(user + ':' + password).toString("base64")
headers = 'Authorization': 'Basic ' + auth
error_message = "WTF... Is the Hudson down or it's crazy? I can't parse what it said."
options = (method, path) ->
{host: host, port: port, method: method, path: path, headers: headers}
request = (method, path, params, callback) ->
req = Http.request options(method, path), (response) ->
data = ""
response.setEncoding
response.on "data", (chunk) ->
data += chunk
response.on "end", ->
callback data
req.write params
req.end()
list = (parameter, msg) ->
switch parameter
when "all", "projects"
path = "/api/json"
param = QS.stringify {}
request 'GET', path, param, (data) ->
try
json = JSON.parse(data)
if json
for i of json.jobs
name = json.jobs[i].name
status = if json.jobs[i].color == "red" then "FAILING" else "SUCCESS"
url = json.jobs[i].url
msg.send("name: #{name}, status: #{status}, url: #{url}")
catch e
msg.send error_message
status = (parameter, msg) ->
path = "/api/json"
param = QS.stringify {}
request 'GET', path, param, (data) ->
try
json = JSON.parse(data)
if json
match = false
for i of json.jobs
if parameter == json.jobs[i].name
match = true
status = if json.jobs[i].color == "red" then "FAILING" else "SUCCESS"
url = json.jobs[i].url
msg.send("status: #{status}, url: #{url}")
msg.send("Hmmm... Are you kidding me? Please input the right project name. Or you can use 'ci list projects' to list all projects.") unless match
catch e
msg.send error_message
build = (parameter, msg) ->
path = "/job/#{parameter}/build"
param = QS.stringify {}
request 'GET', path, param, (data) ->
msg.send("I have told Hudson, please wait...")
robot.respond /ci (.*) (.*)/i, (msg) ->
command = msg.match[1]
parameter = msg.match[2]
switch command
when "list" then list(parameter, msg)
when "status" then status(parameter, msg)
when "build" then build(parameter, msg)
| 169152 | # Track the status and trigger buid for hudson CI.
#
# ci list all/projects - list all the projects on Hudson
# ci status <project name> - see a project's status
# ci build <project name> - triger a build on hudson
Http = require 'http'
QS = require 'querystring'
module.exports = (robot) ->
host = process.env.HUBOT_CI_HOST
port = process.env.HUBOT_CI_PORT
user = process.env.HUBOT_CI_USER
password = <PASSWORD>.HUBOT_CI_PASSWORD
auth = new Buffer(user + ':' + password).toString("base64")
headers = 'Authorization': 'Basic ' + auth
error_message = "WTF... Is the Hudson down or it's crazy? I can't parse what it said."
options = (method, path) ->
{host: host, port: port, method: method, path: path, headers: headers}
request = (method, path, params, callback) ->
req = Http.request options(method, path), (response) ->
data = ""
response.setEncoding
response.on "data", (chunk) ->
data += chunk
response.on "end", ->
callback data
req.write params
req.end()
list = (parameter, msg) ->
switch parameter
when "all", "projects"
path = "/api/json"
param = QS.stringify {}
request 'GET', path, param, (data) ->
try
json = JSON.parse(data)
if json
for i of json.jobs
name = json.jobs[i].name
status = if json.jobs[i].color == "red" then "FAILING" else "SUCCESS"
url = json.jobs[i].url
msg.send("name: #{name}, status: #{status}, url: #{url}")
catch e
msg.send error_message
status = (parameter, msg) ->
path = "/api/json"
param = QS.stringify {}
request 'GET', path, param, (data) ->
try
json = JSON.parse(data)
if json
match = false
for i of json.jobs
if parameter == json.jobs[i].name
match = true
status = if json.jobs[i].color == "red" then "FAILING" else "SUCCESS"
url = json.jobs[i].url
msg.send("status: #{status}, url: #{url}")
msg.send("Hmmm... Are you kidding me? Please input the right project name. Or you can use 'ci list projects' to list all projects.") unless match
catch e
msg.send error_message
build = (parameter, msg) ->
path = "/job/#{parameter}/build"
param = QS.stringify {}
request 'GET', path, param, (data) ->
msg.send("I have told <NAME>, please wait...")
robot.respond /ci (.*) (.*)/i, (msg) ->
command = msg.match[1]
parameter = msg.match[2]
switch command
when "list" then list(parameter, msg)
when "status" then status(parameter, msg)
when "build" then build(parameter, msg)
| true | # Track the status and trigger buid for hudson CI.
#
# ci list all/projects - list all the projects on Hudson
# ci status <project name> - see a project's status
# ci build <project name> - triger a build on hudson
Http = require 'http'
QS = require 'querystring'
module.exports = (robot) ->
host = process.env.HUBOT_CI_HOST
port = process.env.HUBOT_CI_PORT
user = process.env.HUBOT_CI_USER
password = PI:PASSWORD:<PASSWORD>END_PI.HUBOT_CI_PASSWORD
auth = new Buffer(user + ':' + password).toString("base64")
headers = 'Authorization': 'Basic ' + auth
error_message = "WTF... Is the Hudson down or it's crazy? I can't parse what it said."
options = (method, path) ->
{host: host, port: port, method: method, path: path, headers: headers}
request = (method, path, params, callback) ->
req = Http.request options(method, path), (response) ->
data = ""
response.setEncoding
response.on "data", (chunk) ->
data += chunk
response.on "end", ->
callback data
req.write params
req.end()
list = (parameter, msg) ->
switch parameter
when "all", "projects"
path = "/api/json"
param = QS.stringify {}
request 'GET', path, param, (data) ->
try
json = JSON.parse(data)
if json
for i of json.jobs
name = json.jobs[i].name
status = if json.jobs[i].color == "red" then "FAILING" else "SUCCESS"
url = json.jobs[i].url
msg.send("name: #{name}, status: #{status}, url: #{url}")
catch e
msg.send error_message
status = (parameter, msg) ->
path = "/api/json"
param = QS.stringify {}
request 'GET', path, param, (data) ->
try
json = JSON.parse(data)
if json
match = false
for i of json.jobs
if parameter == json.jobs[i].name
match = true
status = if json.jobs[i].color == "red" then "FAILING" else "SUCCESS"
url = json.jobs[i].url
msg.send("status: #{status}, url: #{url}")
msg.send("Hmmm... Are you kidding me? Please input the right project name. Or you can use 'ci list projects' to list all projects.") unless match
catch e
msg.send error_message
build = (parameter, msg) ->
path = "/job/#{parameter}/build"
param = QS.stringify {}
request 'GET', path, param, (data) ->
msg.send("I have told PI:NAME:<NAME>END_PI, please wait...")
robot.respond /ci (.*) (.*)/i, (msg) ->
command = msg.match[1]
parameter = msg.match[2]
switch command
when "list" then list(parameter, msg)
when "status" then status(parameter, msg)
when "build" then build(parameter, msg)
|
[
{
"context": "ns if it's the day for your action\n#\n# Author:\n# KuiKui\n \nmodule.exports = (robot) ->\n ",
"end": 193,
"score": 0.8621562123298645,
"start": 192,
"tag": "NAME",
"value": "K"
},
{
"context": " if it's the day for your action\n#\n# Author:\n# KuiKui\n \nmodule.exports = (robot) ->\n robot",
"end": 198,
"score": 0.7189695835113525,
"start": 193,
"tag": "USERNAME",
"value": "uiKui"
}
] | src/scripts/destiny.coffee | neilprosser/hubot-scripts | 1 | # Description:
# Is it the day?
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot is it <action> day ? - Returns if it's the day for your action
#
# Author:
# KuiKui
module.exports = (robot) ->
robot.respond /is it (\w+) day \?/i, (msg) ->
action = msg.match[1]
nbDay = Math.floor(new Date().getTime() / 1000 / 86400)
actionHash = action.length + action.charCodeAt(0) + action.charCodeAt(action.length - 1)
destiny = Math.cos(nbDay + actionHash) + 1
limit = (Math.sin(actionHash) + 1) / 2
if destiny > limit
msg.send "Sorry, it's not " + action + " day. But try tomorrow..."
else
msg.send "Yes, it's " + action + " day !"
| 135544 | # Description:
# Is it the day?
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot is it <action> day ? - Returns if it's the day for your action
#
# Author:
# <NAME>uiKui
module.exports = (robot) ->
robot.respond /is it (\w+) day \?/i, (msg) ->
action = msg.match[1]
nbDay = Math.floor(new Date().getTime() / 1000 / 86400)
actionHash = action.length + action.charCodeAt(0) + action.charCodeAt(action.length - 1)
destiny = Math.cos(nbDay + actionHash) + 1
limit = (Math.sin(actionHash) + 1) / 2
if destiny > limit
msg.send "Sorry, it's not " + action + " day. But try tomorrow..."
else
msg.send "Yes, it's " + action + " day !"
| true | # Description:
# Is it the day?
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot is it <action> day ? - Returns if it's the day for your action
#
# Author:
# PI:NAME:<NAME>END_PIuiKui
module.exports = (robot) ->
robot.respond /is it (\w+) day \?/i, (msg) ->
action = msg.match[1]
nbDay = Math.floor(new Date().getTime() / 1000 / 86400)
actionHash = action.length + action.charCodeAt(0) + action.charCodeAt(action.length - 1)
destiny = Math.cos(nbDay + actionHash) + 1
limit = (Math.sin(actionHash) + 1) / 2
if destiny > limit
msg.send "Sorry, it's not " + action + " day. But try tomorrow..."
else
msg.send "Yes, it's " + action + " day !"
|
[
{
"context": "most recent hubot messages to delete\n#\n# Author:\n# Chris Doughty <cdoughty77@gmail.com>\n#\nmodule.exports = (robot)",
"end": 388,
"score": 0.9998567700386047,
"start": 375,
"tag": "NAME",
"value": "Chris Doughty"
},
{
"context": "t messages to delete\n#\n# Author:\n# Chris Doughty <cdoughty77@gmail.com>\n#\nmodule.exports = (robot) ->\n robot.respond /a",
"end": 410,
"score": 0.9999305009841919,
"start": 390,
"tag": "EMAIL",
"value": "cdoughty77@gmail.com"
},
{
"context": "msgContent)\n robot.logger.info(\"User #{userName} deleted content [#{msg_content[0]}] in flow #{fl",
"end": 2493,
"score": 0.5670214295387268,
"start": 2485,
"tag": "USERNAME",
"value": "userName"
}
] | delete-message.coffee | cdoughty77/hubot-flowdock-delete-message | 2 | # Description
# Tells hubot to delete content of the <N> most recent hubot messages (only deletes message content)
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_FLOWDOCK_API_TOKEN
# HUBOT_NAME
#
# Commands:
# hubot abandon ship <#> - Number of most recent hubot messages to delete
# hubot delete <#> - Number of most recent hubot messages to delete
#
# Author:
# Chris Doughty <cdoughty77@gmail.com>
#
module.exports = (robot) ->
robot.respond /abandon ship|delete(.*)/i, (msg) ->
# Set the default API url
default_url = "https://#{process.env.HUBOT_FLOWDOCK_API_TOKEN}@api.flowdock.com/flows"
hubotName = robot.name
hubotId = robot.brain.userForName(hubotName).id.toString()
flowId = msg.message.user.flow
userName = msg.message.user.name
prefix = "value"
flowName = "#{prefix}.parameterized_name"
orgName = "#{prefix}.organization.parameterized_name"
msgContent = "#{prefix}.content.text"
msgId = "#{prefix}.id"
userId = "#{prefix}.user"
# Parse the json data
parseJson = (body)->
try
JSON.parse(body)
catch error
msg.send("Sorry, I wasn't able to parse the JSON data returned from the API call.")
# Set the counter for messages to delete
delCounter = ()->
if (!isFinite(msg.match[1]) or Math.round(msg.match[1]) == 0) then 1 else Math.round(msg.match[1])
# Search key/values in json response
getValues = (json, keyId, matchingId, searchValue)->
resultArray = []
for key, value of parseJson(json)
if eval(keyId) is matchingId then resultArray.push(eval(searchValue))
resultArray
# Only try if requested in a flow (not 1-on-1 chat)
if flowId
# Get all flows hubot knows about
msg.robot.http(default_url).get() (err, res, body) ->
org = getValues(body, msgId, flowId, orgName)
flow = getValues(body, msgId, flowId, flowName)
# Get 100 (API limit) most recent messages from all users in the current flow
msg.robot.http("#{default_url}/#{org[0]}/#{flow[0]}/messages?limit=100").get() (err, res, mbody) ->
hubot_msg_ids = getValues(mbody, userId, hubotId, msgId).reverse()
# Delete message(s) up to user input or hubot msgs found (whichever is smaller)
for num in [0..(Math.min.apply @, [delCounter(), hubot_msg_ids.length])-1] by 1
msg_content = getValues(mbody, msgId, hubot_msg_ids[num], msgContent)
robot.logger.info("User #{userName} deleted content [#{msg_content[0]}] in flow #{flow[0]}")
msg.robot.http("#{default_url}/#{org[0]}/#{flow[0]}/messages/#{hubot_msg_ids[num]}").delete() (err, res, body) ->
else
msg.send("Sorry, I can't delete messages in 1-on-1 chats.")
| 15088 | # Description
# Tells hubot to delete content of the <N> most recent hubot messages (only deletes message content)
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_FLOWDOCK_API_TOKEN
# HUBOT_NAME
#
# Commands:
# hubot abandon ship <#> - Number of most recent hubot messages to delete
# hubot delete <#> - Number of most recent hubot messages to delete
#
# Author:
# <NAME> <<EMAIL>>
#
module.exports = (robot) ->
robot.respond /abandon ship|delete(.*)/i, (msg) ->
# Set the default API url
default_url = "https://#{process.env.HUBOT_FLOWDOCK_API_TOKEN}@api.flowdock.com/flows"
hubotName = robot.name
hubotId = robot.brain.userForName(hubotName).id.toString()
flowId = msg.message.user.flow
userName = msg.message.user.name
prefix = "value"
flowName = "#{prefix}.parameterized_name"
orgName = "#{prefix}.organization.parameterized_name"
msgContent = "#{prefix}.content.text"
msgId = "#{prefix}.id"
userId = "#{prefix}.user"
# Parse the json data
parseJson = (body)->
try
JSON.parse(body)
catch error
msg.send("Sorry, I wasn't able to parse the JSON data returned from the API call.")
# Set the counter for messages to delete
delCounter = ()->
if (!isFinite(msg.match[1]) or Math.round(msg.match[1]) == 0) then 1 else Math.round(msg.match[1])
# Search key/values in json response
getValues = (json, keyId, matchingId, searchValue)->
resultArray = []
for key, value of parseJson(json)
if eval(keyId) is matchingId then resultArray.push(eval(searchValue))
resultArray
# Only try if requested in a flow (not 1-on-1 chat)
if flowId
# Get all flows hubot knows about
msg.robot.http(default_url).get() (err, res, body) ->
org = getValues(body, msgId, flowId, orgName)
flow = getValues(body, msgId, flowId, flowName)
# Get 100 (API limit) most recent messages from all users in the current flow
msg.robot.http("#{default_url}/#{org[0]}/#{flow[0]}/messages?limit=100").get() (err, res, mbody) ->
hubot_msg_ids = getValues(mbody, userId, hubotId, msgId).reverse()
# Delete message(s) up to user input or hubot msgs found (whichever is smaller)
for num in [0..(Math.min.apply @, [delCounter(), hubot_msg_ids.length])-1] by 1
msg_content = getValues(mbody, msgId, hubot_msg_ids[num], msgContent)
robot.logger.info("User #{userName} deleted content [#{msg_content[0]}] in flow #{flow[0]}")
msg.robot.http("#{default_url}/#{org[0]}/#{flow[0]}/messages/#{hubot_msg_ids[num]}").delete() (err, res, body) ->
else
msg.send("Sorry, I can't delete messages in 1-on-1 chats.")
| true | # Description
# Tells hubot to delete content of the <N> most recent hubot messages (only deletes message content)
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_FLOWDOCK_API_TOKEN
# HUBOT_NAME
#
# Commands:
# hubot abandon ship <#> - Number of most recent hubot messages to delete
# hubot delete <#> - Number of most recent hubot messages to delete
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
module.exports = (robot) ->
robot.respond /abandon ship|delete(.*)/i, (msg) ->
# Set the default API url
default_url = "https://#{process.env.HUBOT_FLOWDOCK_API_TOKEN}@api.flowdock.com/flows"
hubotName = robot.name
hubotId = robot.brain.userForName(hubotName).id.toString()
flowId = msg.message.user.flow
userName = msg.message.user.name
prefix = "value"
flowName = "#{prefix}.parameterized_name"
orgName = "#{prefix}.organization.parameterized_name"
msgContent = "#{prefix}.content.text"
msgId = "#{prefix}.id"
userId = "#{prefix}.user"
# Parse the json data
parseJson = (body)->
try
JSON.parse(body)
catch error
msg.send("Sorry, I wasn't able to parse the JSON data returned from the API call.")
# Set the counter for messages to delete
delCounter = ()->
if (!isFinite(msg.match[1]) or Math.round(msg.match[1]) == 0) then 1 else Math.round(msg.match[1])
# Search key/values in json response
getValues = (json, keyId, matchingId, searchValue)->
resultArray = []
for key, value of parseJson(json)
if eval(keyId) is matchingId then resultArray.push(eval(searchValue))
resultArray
# Only try if requested in a flow (not 1-on-1 chat)
if flowId
# Get all flows hubot knows about
msg.robot.http(default_url).get() (err, res, body) ->
org = getValues(body, msgId, flowId, orgName)
flow = getValues(body, msgId, flowId, flowName)
# Get 100 (API limit) most recent messages from all users in the current flow
msg.robot.http("#{default_url}/#{org[0]}/#{flow[0]}/messages?limit=100").get() (err, res, mbody) ->
hubot_msg_ids = getValues(mbody, userId, hubotId, msgId).reverse()
# Delete message(s) up to user input or hubot msgs found (whichever is smaller)
for num in [0..(Math.min.apply @, [delCounter(), hubot_msg_ids.length])-1] by 1
msg_content = getValues(mbody, msgId, hubot_msg_ids[num], msgContent)
robot.logger.info("User #{userName} deleted content [#{msg_content[0]}] in flow #{flow[0]}")
msg.robot.http("#{default_url}/#{org[0]}/#{flow[0]}/messages/#{hubot_msg_ids[num]}").delete() (err, res, body) ->
else
msg.send("Sorry, I can't delete messages in 1-on-1 chats.")
|
[
{
"context": "================\n#\n# Danbo: Main Class\n#\n# @author Matthew Wagerfield @mwagerfield\n#\n#=================================",
"end": 118,
"score": 0.9998215436935425,
"start": 100,
"tag": "NAME",
"value": "Matthew Wagerfield"
},
{
"context": "# Danbo: Main Class\n#\n# @author Matthew Wagerfield @mwagerfield\n#\n#==============================================",
"end": 131,
"score": 0.999144434928894,
"start": 119,
"tag": "USERNAME",
"value": "@mwagerfield"
}
] | assets/scripts/coffee/project/Main.coffee | wagerfield/danbo | 1 | ###
#============================================================
#
# Danbo: Main Class
#
# @author Matthew Wagerfield @mwagerfield
#
#============================================================
###
class PROJECT.Main extends Class
###
#========================================
# Class Variables
#========================================
###
@class = 'PROJECT.Main'
###
#========================================
# Instance Variables
#========================================
###
$html: null
$body: null
$container: null
$scene: null
# Properties
layout: null
scene: null
raf: null
###
#========================================
# Instance Methods
#========================================
###
constructor: () ->
# Cache selections.
@$html = $ 'html'
@$body = $ 'body'
@$container = @$body.find '#container'
@$scene = @$container.find '#scene'
return
initialise: () =>
super
# Add classes.
@addClasses()
# Kick off the animation loop.
@animate()
return
addClasses: () =>
# Create and initialise the layout.
@layout = new Layout
@layout.initialise()
# Create and initialise the scene.
@scene = new SCENE.Scene
@scene.initialise @$scene
return
animate: () =>
# Call the update method using the requestAnimationFrame callback.
@raf = requestAnimationFrame @animate
# Call the root update method.
@update()
return
update: () =>
# Update the scene.
@scene.update()
return
# Create instance of Main class.
@DANBO = DANBO = new PROJECT.Main
| 39391 | ###
#============================================================
#
# Danbo: Main Class
#
# @author <NAME> @mwagerfield
#
#============================================================
###
class PROJECT.Main extends Class
###
#========================================
# Class Variables
#========================================
###
@class = 'PROJECT.Main'
###
#========================================
# Instance Variables
#========================================
###
$html: null
$body: null
$container: null
$scene: null
# Properties
layout: null
scene: null
raf: null
###
#========================================
# Instance Methods
#========================================
###
constructor: () ->
# Cache selections.
@$html = $ 'html'
@$body = $ 'body'
@$container = @$body.find '#container'
@$scene = @$container.find '#scene'
return
initialise: () =>
super
# Add classes.
@addClasses()
# Kick off the animation loop.
@animate()
return
addClasses: () =>
# Create and initialise the layout.
@layout = new Layout
@layout.initialise()
# Create and initialise the scene.
@scene = new SCENE.Scene
@scene.initialise @$scene
return
animate: () =>
# Call the update method using the requestAnimationFrame callback.
@raf = requestAnimationFrame @animate
# Call the root update method.
@update()
return
update: () =>
# Update the scene.
@scene.update()
return
# Create instance of Main class.
@DANBO = DANBO = new PROJECT.Main
| true | ###
#============================================================
#
# Danbo: Main Class
#
# @author PI:NAME:<NAME>END_PI @mwagerfield
#
#============================================================
###
class PROJECT.Main extends Class
###
#========================================
# Class Variables
#========================================
###
@class = 'PROJECT.Main'
###
#========================================
# Instance Variables
#========================================
###
$html: null
$body: null
$container: null
$scene: null
# Properties
layout: null
scene: null
raf: null
###
#========================================
# Instance Methods
#========================================
###
constructor: () ->
# Cache selections.
@$html = $ 'html'
@$body = $ 'body'
@$container = @$body.find '#container'
@$scene = @$container.find '#scene'
return
initialise: () =>
super
# Add classes.
@addClasses()
# Kick off the animation loop.
@animate()
return
addClasses: () =>
# Create and initialise the layout.
@layout = new Layout
@layout.initialise()
# Create and initialise the scene.
@scene = new SCENE.Scene
@scene.initialise @$scene
return
animate: () =>
# Call the update method using the requestAnimationFrame callback.
@raf = requestAnimationFrame @animate
# Call the root update method.
@update()
return
update: () =>
# Update the scene.
@scene.update()
return
# Create instance of Main class.
@DANBO = DANBO = new PROJECT.Main
|
[
{
"context": "s\n [v, w] = edge\n if v < w\n key = \"#{v},#{w}\"\n else\n key = \"#{w},#{v}\"\n unless",
"end": 3350,
"score": 0.9989563822746277,
"start": 3339,
"tag": "KEY",
"value": "\"#{v},#{w}\""
},
{
"context": " key = \"#{v},#{w}\"\n else\n key = \"#{w},#{v}\"\n unless key of seen\n seen[key] = id\n ",
"end": 3387,
"score": 0.9988710880279541,
"start": 3376,
"tag": "KEY",
"value": "\"#{w},#{v}\""
},
{
"context": "+1]\n for yt in [yr, yr-1, yr+1]\n key = \"#{xt},#{yt}\"\n for v in @hash[key] ? []\n if @ep",
"end": 4414,
"score": 0.9972591400146484,
"start": 4401,
"tag": "KEY",
"value": "\"#{xt},#{yt}\""
},
{
"context": "epsilon\n yr = Math.round y / @epsilon\n key = \"#{xr},#{yr}\"\n\n insert: (coord) ->\n v = @lookup coord\n r",
"end": 4666,
"score": 0.9959251880645752,
"start": 4653,
"tag": "KEY",
"value": "\"#{xr},#{yr}\""
}
] | src/filter.coffee | pimmu1s/fold | 231 | geom = require './geom'
filter = exports
filter.edgesAssigned = (fold, target) ->
i for assignment, i in fold.edges_assignment when assignment == target
filter.mountainEdges = (fold) ->
filter.edgesAssigned fold, 'M'
filter.valleyEdges = (fold) ->
filter.edgesAssigned fold, 'V'
filter.flatEdges = (fold) ->
filter.edgesAssigned fold, 'F'
filter.boundaryEdges = (fold) ->
filter.edgesAssigned fold, 'B'
filter.unassignedEdges = (fold) ->
filter.edgesAssigned fold, 'U'
filter.keysStartingWith = (fold, prefix) ->
key for key of fold when key[...prefix.length] == prefix
filter.keysEndingWith = (fold, suffix) ->
key for key of fold when key[-suffix.length..] == suffix
filter.remapField = (fold, field, old2new) ->
###
old2new: null means throw away that object
###
new2old = []
for j, i in old2new ## later overwrites earlier
new2old[j] = i if j?
for key in filter.keysStartingWith fold, "#{field}_"
fold[key] = (fold[key][old] for old in new2old)
for key in filter.keysEndingWith fold, "_#{field}"
fold[key] = (old2new[old] for old in array for array in fold[key])
fold
filter.remapFieldSubset = (fold, field, keep) ->
id = 0
old2new =
for value in keep
if value
id++
else
null ## remove
filter.remapField fold, field, old2new
old2new
filter.remove = (fold, field, index) ->
###
Remove given index from given field ('vertices', 'edges', 'faces'), in place.
###
filter.remapFieldSubset fold, field,
for i in [0...filter.numType fold, field]
i != index
filter.removeVertex = (fold, index) -> filter.remove fold, 'vertices', index
filter.removeEdge = (fold, index) -> filter.remove fold, 'edges', index
filter.removeFace = (fold, index) -> filter.remove fold, 'faces', index
filter.transform = (fold, matrix) ->
###
Transforms all fields ending in _coords (in particular, vertices_coords)
and all fields ending in FoldTransform (in particular,
faces_flatFoldTransform generated by convert.flat_folded_geometry)
according to the given transformation matrix.
###
for key in filter.keysEndingWith fold, "_coords"
fold[key] = (geom.matrixVector(matrix, coords) for coords in fold[key])
for key in filter.keysEndingWith fold, "FoldTransform" when '_' in key
fold[key] = (geom.matrixMatrix(matrix, transform) for transform in fold[key])
fold
filter.numType = (fold, type) ->
###
Count the maximum number of objects of a given type, by looking at all
fields with key of the form `type_...`, and if that fails, looking at all
fields with key of the form `..._type`. Returns `0` if nothing found.
###
counts =
for key in filter.keysStartingWith fold, "#{type}_"
value = fold[key]
continue unless value.length?
value.length
unless counts.length
counts =
for key in filter.keysEndingWith fold, "_#{type}"
1 + Math.max fold[key]...
if counts.length
Math.max counts...
else
0 ## nothing of this type
filter.numVertices = (fold) -> filter.numType fold, 'vertices'
filter.numEdges = (fold) -> filter.numType fold, 'edges'
filter.numFaces = (fold) -> filter.numType fold, 'faces'
filter.removeDuplicateEdges_vertices = (fold) ->
seen = {}
id = 0
old2new =
for edge in fold.edges_vertices
[v, w] = edge
if v < w
key = "#{v},#{w}"
else
key = "#{w},#{v}"
unless key of seen
seen[key] = id
id += 1
seen[key]
filter.remapField fold, 'edges', old2new
old2new
filter.edges_verticesIncident = (e1, e2) ->
for v in e1
if v in e2
return v
null
## Use hashing to find points within an epsilon > 0 distance from each other.
## Each integer cell will have O(1) distinct points before matching
## (number of disjoint half-unit disks that fit in a unit square).
class RepeatedPointsDS
constructor: (@vertices_coords, @epsilon) ->
## Note: if vertices_coords has some duplicates in the initial state,
## then we will detect them but won't remove them here. Rather,
## future duplicate inserts will return the higher-index vertex.
@hash = {}
for coord, v in @vertices_coords
(@hash[@key coord] ?= []).push v
null
lookup: (coord) ->
[x, y] = coord
xr = Math.round(x / @epsilon)
yr = Math.round(y / @epsilon)
for xt in [xr, xr-1, xr+1]
for yt in [yr, yr-1, yr+1]
key = "#{xt},#{yt}"
for v in @hash[key] ? []
if @epsilon > geom.dist @vertices_coords[v], coord
return v
null
key: (coord) ->
[x, y] = coord
xr = Math.round x / @epsilon
yr = Math.round y / @epsilon
key = "#{xr},#{yr}"
insert: (coord) ->
v = @lookup coord
return v if v?
(@hash[@key coord] ?= []).push v = @vertices_coords.length
@vertices_coords.push coord
v
filter.collapseNearbyVertices = (fold, epsilon) ->
vertices = new RepeatedPointsDS [], epsilon
old2new =
for coords in fold.vertices_coords
vertices.insert coords
filter.remapField fold, 'vertices', old2new
## In particular: fold.vertices_coords = vertices.vertices_coords
filter.maybeAddVertex = (fold, coords, epsilon) ->
###
Add a new vertex at coordinates `coords` and return its (last) index,
unless there is already such a vertex within distance `epsilon`,
in which case return the closest such vertex's index.
###
i = geom.closestIndex coords, fold.vertices_coords
if i? and epsilon >= geom.dist coords, fold.vertices_coords[i]
i ## Closest point is close enough
else
fold.vertices_coords.push(coords) - 1
filter.addVertexLike = (fold, oldVertexIndex) ->
## Add a vertex and copy data from old vertex.
vNew = filter.numVertices fold
for key in filter.keysStartingWith fold, 'vertices_'
switch key[6..]
when 'vertices'
## Leaving these broken
else
fold[key][vNew] = fold[key][oldVertexIndex]
vNew
filter.addEdgeLike = (fold, oldEdgeIndex, v1, v2) ->
## Add an edge between v1 and v2, and copy data from old edge.
## If v1 or v2 are unspecified, defaults to the vertices of the old edge.
## Must have `edges_vertices` property.
eNew = fold.edges_vertices.length
for key in filter.keysStartingWith fold, 'edges_'
switch key[6..]
when 'vertices'
fold.edges_vertices.push [
v1 ? fold.edges_vertices[oldEdgeIndex][0]
v2 ? fold.edges_vertices[oldEdgeIndex][1]
]
when 'edges'
## Leaving these broken
else
fold[key][eNew] = fold[key][oldEdgeIndex]
eNew
filter.addVertexAndSubdivide = (fold, coords, epsilon) ->
v = filter.maybeAddVertex fold, coords, epsilon
changedEdges = []
if v == fold.vertices_coords.length - 1
## Similar to "Handle overlapping edges" case:
for e, i in fold.edges_vertices
continue if v in e # shouldn't happen
s = (fold.vertices_coords[u] for u in e)
if geom.pointStrictlyInSegment coords, s ## implicit epsilon
#console.log coords, 'in', s
iNew = filter.addEdgeLike fold, i, v, e[1]
changedEdges.push i, iNew
e[1] = v
[v, changedEdges]
filter.removeLoopEdges = (fold) ->
###
Remove edges whose endpoints are identical. After collapsing via
`filter.collapseNearbyVertices`, this removes epsilon-length edges.
###
filter.remapFieldSubset fold, 'edges',
for edge in fold.edges_vertices
edge[0] != edge[1]
filter.subdivideCrossingEdges_vertices = (fold, epsilon, involvingEdgesFrom) ->
###
Using just `vertices_coords` and `edges_vertices` and assuming all in 2D,
subdivides all crossing/touching edges to form a planar graph.
In particular, all duplicate and loop edges are also removed.
If called without `involvingEdgesFrom`, does all subdivision in quadratic
time. xxx Should be O(n log n) via plane sweep.
In this case, returns an array of indices of all edges that were subdivided
(both modified old edges and new edges).
If called with `involvingEdgesFrom`, does all subdivision involving an
edge numbered `involvingEdgesFrom` or higher. For example, after adding an
edge with largest number, call with `involvingEdgesFrom =
edges_vertices.length - 1`; then this will run in linear time.
In this case, returns two arrays of edges: the first array are all subdivided
from the "involved" edges, while the second array is the remaining subdivided
edges.
###
changedEdges = [[], []]
addEdge = (v1, v2, oldEdgeIndex, which) ->
#console.log 'adding', oldEdgeIndex, fold.edges_vertices.length, 'to', which
eNew = filter.addEdgeLike fold, oldEdgeIndex, v1, v2
changedEdges[which].push oldEdgeIndex, eNew
## Handle overlapping edges by subdividing edges at any vertices on them.
## We use a while loop instead of a for loop to process newly added edges.
i = involvingEdgesFrom ? 0
while i < fold.edges_vertices.length
e = fold.edges_vertices[i]
s = (fold.vertices_coords[u] for u in e)
for p, v in fold.vertices_coords
continue if v in e
if geom.pointStrictlyInSegment p, s ## implicit epsilon
#console.log p, 'in', s
addEdge v, e[1], i, 0
e[1] = v
i++
## Handle crossing edges
## We use a while loop instead of a for loop to process newly added edges.
vertices = new RepeatedPointsDS fold.vertices_coords, epsilon
i1 = involvingEdgesFrom ? 0
while i1 < fold.edges_vertices.length
e1 = fold.edges_vertices[i1]
s1 = (fold.vertices_coords[v] for v in e1)
for e2, i2 in fold.edges_vertices[...i1]
s2 = (fold.vertices_coords[v] for v in e2)
if not filter.edges_verticesIncident(e1, e2) and geom.segmentsCross s1, s2
## segment intersection is too sensitive a test;
## segmentsCross more reliable
#cross = segmentIntersectSegment s1, s2
cross = geom.lineIntersectLine s1, s2
continue unless cross?
crossI = vertices.insert cross
#console.log e1, s1, 'intersects', e2, s2, 'at', cross, crossI
unless crossI in e1 and crossI in e2 ## don't add endpoint again
#console.log e1, e2, '->'
unless crossI in e1
addEdge crossI, e1[1], i1, 0
e1[1] = crossI
s1[1] = fold.vertices_coords[crossI] # update for future iterations
#console.log '->', e1, fold.edges_vertices[fold.edges_vertices.length-1]
unless crossI in e2
addEdge crossI, e2[1], i2, 1
e2[1] = crossI
#console.log '->', e2, fold.edges_vertices[fold.edges_vertices.length-1]
i1++
old2new = filter.removeDuplicateEdges_vertices fold
for i in [0, 1]
changedEdges[i] = (old2new[e] for e in changedEdges[i])
old2new = filter.removeLoopEdges fold
for i in [0, 1]
changedEdges[i] = (old2new[e] for e in changedEdges[i])
#fold
if involvingEdgesFrom?
changedEdges
else
changedEdges[0].concat changedEdges[1]
filter.addEdgeAndSubdivide = (fold, v1, v2, epsilon) ->
###
Add an edge between vertex indices or points `v1` and `v2`, subdivide
as necessary, and return two arrays: all the subdivided parts of this edge,
and all the other edges that change.
If the edge is a loop or a duplicate, both arrays will be empty.
###
if v1.length?
[v1, changedEdges1] = filter.addVertexAndSubdivide fold, v1, epsilon
if v2.length?
[v2, changedEdges2] = filter.addVertexAndSubdivide fold, v2, epsilon
if v1 == v2 ## Ignore loop edges
return [[], []]
for e, i in fold.edges_vertices
if (e[0] == v1 and e[1] == v2) or
(e[0] == v2 and e[1] == v1)
return [[i], []] ## Ignore duplicate edges
iNew = fold.edges_vertices.push([v1, v2]) - 1
if iNew
changedEdges = filter.subdivideCrossingEdges_vertices(fold, epsilon, iNew)
changedEdges[0].push iNew unless iNew in changedEdges[0]
else
changedEdges = [[iNew], []]
changedEdges[1].push changedEdges1... if changedEdges1?
changedEdges[1].push changedEdges2... if changedEdges2?
changedEdges
filter.cutEdges = (fold, es) ->
###
Given a FOLD object with `edges_vertices`, `edges_assignment`, and
counterclockwise-sorted `vertices_edges`
(see `FOLD.convert.edges_vertices_to_vertices_edges_sorted`),
cuts apart ("unwelds") all edges in `es` into pairs of boundary edges.
When an endpoint of a cut edge ends up on n boundaries,
it splits into n vertices.
Preserves above-mentioned properties (so you can then compute faces via
`FOLD.convert.edges_vertices_to_faces_vertices_edges`),
but ignores face properties and discards `vertices_vertices` if present.
###
vertices_boundaries = []
for e in filter.boundaryEdges fold
for v in fold.edges_vertices[e]
(vertices_boundaries[v] ?= []).push e
for e1 in es
## Split e1 into two edges {e1, e2}
e2 = filter.addEdgeLike fold, e1
for v, i in fold.edges_vertices[e1]
ve = fold.vertices_edges[v]
ve.splice ve.indexOf(e1) + i, 0, e2
## Check for endpoints of {e1, e2} to split, when they're on the boundary
for v1, i in fold.edges_vertices[e1]
u1 = fold.edges_vertices[e1][1-i]
u2 = fold.edges_vertices[e2][1-i]
boundaries = vertices_boundaries[v1]?.length
if boundaries >= 2 ## vertex already on boundary
if boundaries > 2
throw new Error "#{vertices_boundaries[v1].length} boundary edges at vertex #{v1}"
[b1, b2] = vertices_boundaries[v1]
neighbors = fold.vertices_edges[v1]
i1 = neighbors.indexOf b1
i2 = neighbors.indexOf b2
if i2 == (i1+1) % neighbors.length
neighbors = neighbors[i2..].concat neighbors[..i1] unless i2 == 0
else if i1 == (i2+1) % neighbors.length
neighbors = neighbors[i1..].concat neighbors[..i2] unless i1 == 0
else
throw new Error "Nonadjacent boundary edges at vertex #{v1}"
## Find first vertex among e1, e2 among neighbors, so other is next
ie1 = neighbors.indexOf e1
ie2 = neighbors.indexOf e2
ie = Math.min ie1, ie2
fold.vertices_edges[v1] = neighbors[..ie]
v2 = filter.addVertexLike fold, v1
fold.vertices_edges[v2] = neighbors[1+ie..]
#console.log "Split #{neighbors} into #{fold.vertices_edges[v1]} for #{v1} and #{fold.vertices_edges[v2]} for #{v2}"
for neighbor in fold.vertices_edges[v2] # including e2
ev = fold.edges_vertices[neighbor]
ev[ev.indexOf v1] = v2
fold.edges_assignment?[e1] = 'B'
fold.edges_assignment?[e2] = 'B'
for v, i in fold.edges_vertices[e1]
(vertices_boundaries[v] ?= []).push e1
for v, i in fold.edges_vertices[e2]
(vertices_boundaries[v] ?= []).push e2
delete fold.vertices_vertices # would be out-of-date
fold
filter.edges_vertices_to_vertices_vertices = (fold) ->
###
Works for abstract structures, so NOT SORTED.
Use sort_vertices_vertices to sort in counterclockwise order.
###
numVertices = filter.numVertices fold
vertices_vertices = ([] for v in [0...numVertices])
for edge in fold.edges_vertices
[v, w] = edge
while v >= vertices_vertices.length
vertices_vertices.push []
while w >= vertices_vertices.length
vertices_vertices.push []
vertices_vertices[v].push w
vertices_vertices[w].push v
vertices_vertices
| 151545 | geom = require './geom'
filter = exports
filter.edgesAssigned = (fold, target) ->
i for assignment, i in fold.edges_assignment when assignment == target
filter.mountainEdges = (fold) ->
filter.edgesAssigned fold, 'M'
filter.valleyEdges = (fold) ->
filter.edgesAssigned fold, 'V'
filter.flatEdges = (fold) ->
filter.edgesAssigned fold, 'F'
filter.boundaryEdges = (fold) ->
filter.edgesAssigned fold, 'B'
filter.unassignedEdges = (fold) ->
filter.edgesAssigned fold, 'U'
filter.keysStartingWith = (fold, prefix) ->
key for key of fold when key[...prefix.length] == prefix
filter.keysEndingWith = (fold, suffix) ->
key for key of fold when key[-suffix.length..] == suffix
filter.remapField = (fold, field, old2new) ->
###
old2new: null means throw away that object
###
new2old = []
for j, i in old2new ## later overwrites earlier
new2old[j] = i if j?
for key in filter.keysStartingWith fold, "#{field}_"
fold[key] = (fold[key][old] for old in new2old)
for key in filter.keysEndingWith fold, "_#{field}"
fold[key] = (old2new[old] for old in array for array in fold[key])
fold
filter.remapFieldSubset = (fold, field, keep) ->
id = 0
old2new =
for value in keep
if value
id++
else
null ## remove
filter.remapField fold, field, old2new
old2new
filter.remove = (fold, field, index) ->
###
Remove given index from given field ('vertices', 'edges', 'faces'), in place.
###
filter.remapFieldSubset fold, field,
for i in [0...filter.numType fold, field]
i != index
filter.removeVertex = (fold, index) -> filter.remove fold, 'vertices', index
filter.removeEdge = (fold, index) -> filter.remove fold, 'edges', index
filter.removeFace = (fold, index) -> filter.remove fold, 'faces', index
filter.transform = (fold, matrix) ->
###
Transforms all fields ending in _coords (in particular, vertices_coords)
and all fields ending in FoldTransform (in particular,
faces_flatFoldTransform generated by convert.flat_folded_geometry)
according to the given transformation matrix.
###
for key in filter.keysEndingWith fold, "_coords"
fold[key] = (geom.matrixVector(matrix, coords) for coords in fold[key])
for key in filter.keysEndingWith fold, "FoldTransform" when '_' in key
fold[key] = (geom.matrixMatrix(matrix, transform) for transform in fold[key])
fold
filter.numType = (fold, type) ->
###
Count the maximum number of objects of a given type, by looking at all
fields with key of the form `type_...`, and if that fails, looking at all
fields with key of the form `..._type`. Returns `0` if nothing found.
###
counts =
for key in filter.keysStartingWith fold, "#{type}_"
value = fold[key]
continue unless value.length?
value.length
unless counts.length
counts =
for key in filter.keysEndingWith fold, "_#{type}"
1 + Math.max fold[key]...
if counts.length
Math.max counts...
else
0 ## nothing of this type
filter.numVertices = (fold) -> filter.numType fold, 'vertices'
filter.numEdges = (fold) -> filter.numType fold, 'edges'
filter.numFaces = (fold) -> filter.numType fold, 'faces'
filter.removeDuplicateEdges_vertices = (fold) ->
seen = {}
id = 0
old2new =
for edge in fold.edges_vertices
[v, w] = edge
if v < w
key = <KEY>
else
key = <KEY>
unless key of seen
seen[key] = id
id += 1
seen[key]
filter.remapField fold, 'edges', old2new
old2new
filter.edges_verticesIncident = (e1, e2) ->
for v in e1
if v in e2
return v
null
## Use hashing to find points within an epsilon > 0 distance from each other.
## Each integer cell will have O(1) distinct points before matching
## (number of disjoint half-unit disks that fit in a unit square).
class RepeatedPointsDS
constructor: (@vertices_coords, @epsilon) ->
## Note: if vertices_coords has some duplicates in the initial state,
## then we will detect them but won't remove them here. Rather,
## future duplicate inserts will return the higher-index vertex.
@hash = {}
for coord, v in @vertices_coords
(@hash[@key coord] ?= []).push v
null
lookup: (coord) ->
[x, y] = coord
xr = Math.round(x / @epsilon)
yr = Math.round(y / @epsilon)
for xt in [xr, xr-1, xr+1]
for yt in [yr, yr-1, yr+1]
key = <KEY>
for v in @hash[key] ? []
if @epsilon > geom.dist @vertices_coords[v], coord
return v
null
key: (coord) ->
[x, y] = coord
xr = Math.round x / @epsilon
yr = Math.round y / @epsilon
key = <KEY>
insert: (coord) ->
v = @lookup coord
return v if v?
(@hash[@key coord] ?= []).push v = @vertices_coords.length
@vertices_coords.push coord
v
filter.collapseNearbyVertices = (fold, epsilon) ->
vertices = new RepeatedPointsDS [], epsilon
old2new =
for coords in fold.vertices_coords
vertices.insert coords
filter.remapField fold, 'vertices', old2new
## In particular: fold.vertices_coords = vertices.vertices_coords
filter.maybeAddVertex = (fold, coords, epsilon) ->
###
Add a new vertex at coordinates `coords` and return its (last) index,
unless there is already such a vertex within distance `epsilon`,
in which case return the closest such vertex's index.
###
i = geom.closestIndex coords, fold.vertices_coords
if i? and epsilon >= geom.dist coords, fold.vertices_coords[i]
i ## Closest point is close enough
else
fold.vertices_coords.push(coords) - 1
filter.addVertexLike = (fold, oldVertexIndex) ->
## Add a vertex and copy data from old vertex.
vNew = filter.numVertices fold
for key in filter.keysStartingWith fold, 'vertices_'
switch key[6..]
when 'vertices'
## Leaving these broken
else
fold[key][vNew] = fold[key][oldVertexIndex]
vNew
filter.addEdgeLike = (fold, oldEdgeIndex, v1, v2) ->
## Add an edge between v1 and v2, and copy data from old edge.
## If v1 or v2 are unspecified, defaults to the vertices of the old edge.
## Must have `edges_vertices` property.
eNew = fold.edges_vertices.length
for key in filter.keysStartingWith fold, 'edges_'
switch key[6..]
when 'vertices'
fold.edges_vertices.push [
v1 ? fold.edges_vertices[oldEdgeIndex][0]
v2 ? fold.edges_vertices[oldEdgeIndex][1]
]
when 'edges'
## Leaving these broken
else
fold[key][eNew] = fold[key][oldEdgeIndex]
eNew
filter.addVertexAndSubdivide = (fold, coords, epsilon) ->
v = filter.maybeAddVertex fold, coords, epsilon
changedEdges = []
if v == fold.vertices_coords.length - 1
## Similar to "Handle overlapping edges" case:
for e, i in fold.edges_vertices
continue if v in e # shouldn't happen
s = (fold.vertices_coords[u] for u in e)
if geom.pointStrictlyInSegment coords, s ## implicit epsilon
#console.log coords, 'in', s
iNew = filter.addEdgeLike fold, i, v, e[1]
changedEdges.push i, iNew
e[1] = v
[v, changedEdges]
filter.removeLoopEdges = (fold) ->
###
Remove edges whose endpoints are identical. After collapsing via
`filter.collapseNearbyVertices`, this removes epsilon-length edges.
###
filter.remapFieldSubset fold, 'edges',
for edge in fold.edges_vertices
edge[0] != edge[1]
filter.subdivideCrossingEdges_vertices = (fold, epsilon, involvingEdgesFrom) ->
###
Using just `vertices_coords` and `edges_vertices` and assuming all in 2D,
subdivides all crossing/touching edges to form a planar graph.
In particular, all duplicate and loop edges are also removed.
If called without `involvingEdgesFrom`, does all subdivision in quadratic
time. xxx Should be O(n log n) via plane sweep.
In this case, returns an array of indices of all edges that were subdivided
(both modified old edges and new edges).
If called with `involvingEdgesFrom`, does all subdivision involving an
edge numbered `involvingEdgesFrom` or higher. For example, after adding an
edge with largest number, call with `involvingEdgesFrom =
edges_vertices.length - 1`; then this will run in linear time.
In this case, returns two arrays of edges: the first array are all subdivided
from the "involved" edges, while the second array is the remaining subdivided
edges.
###
changedEdges = [[], []]
addEdge = (v1, v2, oldEdgeIndex, which) ->
#console.log 'adding', oldEdgeIndex, fold.edges_vertices.length, 'to', which
eNew = filter.addEdgeLike fold, oldEdgeIndex, v1, v2
changedEdges[which].push oldEdgeIndex, eNew
## Handle overlapping edges by subdividing edges at any vertices on them.
## We use a while loop instead of a for loop to process newly added edges.
i = involvingEdgesFrom ? 0
while i < fold.edges_vertices.length
e = fold.edges_vertices[i]
s = (fold.vertices_coords[u] for u in e)
for p, v in fold.vertices_coords
continue if v in e
if geom.pointStrictlyInSegment p, s ## implicit epsilon
#console.log p, 'in', s
addEdge v, e[1], i, 0
e[1] = v
i++
## Handle crossing edges
## We use a while loop instead of a for loop to process newly added edges.
vertices = new RepeatedPointsDS fold.vertices_coords, epsilon
i1 = involvingEdgesFrom ? 0
while i1 < fold.edges_vertices.length
e1 = fold.edges_vertices[i1]
s1 = (fold.vertices_coords[v] for v in e1)
for e2, i2 in fold.edges_vertices[...i1]
s2 = (fold.vertices_coords[v] for v in e2)
if not filter.edges_verticesIncident(e1, e2) and geom.segmentsCross s1, s2
## segment intersection is too sensitive a test;
## segmentsCross more reliable
#cross = segmentIntersectSegment s1, s2
cross = geom.lineIntersectLine s1, s2
continue unless cross?
crossI = vertices.insert cross
#console.log e1, s1, 'intersects', e2, s2, 'at', cross, crossI
unless crossI in e1 and crossI in e2 ## don't add endpoint again
#console.log e1, e2, '->'
unless crossI in e1
addEdge crossI, e1[1], i1, 0
e1[1] = crossI
s1[1] = fold.vertices_coords[crossI] # update for future iterations
#console.log '->', e1, fold.edges_vertices[fold.edges_vertices.length-1]
unless crossI in e2
addEdge crossI, e2[1], i2, 1
e2[1] = crossI
#console.log '->', e2, fold.edges_vertices[fold.edges_vertices.length-1]
i1++
old2new = filter.removeDuplicateEdges_vertices fold
for i in [0, 1]
changedEdges[i] = (old2new[e] for e in changedEdges[i])
old2new = filter.removeLoopEdges fold
for i in [0, 1]
changedEdges[i] = (old2new[e] for e in changedEdges[i])
#fold
if involvingEdgesFrom?
changedEdges
else
changedEdges[0].concat changedEdges[1]
filter.addEdgeAndSubdivide = (fold, v1, v2, epsilon) ->
###
Add an edge between vertex indices or points `v1` and `v2`, subdivide
as necessary, and return two arrays: all the subdivided parts of this edge,
and all the other edges that change.
If the edge is a loop or a duplicate, both arrays will be empty.
###
if v1.length?
[v1, changedEdges1] = filter.addVertexAndSubdivide fold, v1, epsilon
if v2.length?
[v2, changedEdges2] = filter.addVertexAndSubdivide fold, v2, epsilon
if v1 == v2 ## Ignore loop edges
return [[], []]
for e, i in fold.edges_vertices
if (e[0] == v1 and e[1] == v2) or
(e[0] == v2 and e[1] == v1)
return [[i], []] ## Ignore duplicate edges
iNew = fold.edges_vertices.push([v1, v2]) - 1
if iNew
changedEdges = filter.subdivideCrossingEdges_vertices(fold, epsilon, iNew)
changedEdges[0].push iNew unless iNew in changedEdges[0]
else
changedEdges = [[iNew], []]
changedEdges[1].push changedEdges1... if changedEdges1?
changedEdges[1].push changedEdges2... if changedEdges2?
changedEdges
filter.cutEdges = (fold, es) ->
###
Given a FOLD object with `edges_vertices`, `edges_assignment`, and
counterclockwise-sorted `vertices_edges`
(see `FOLD.convert.edges_vertices_to_vertices_edges_sorted`),
cuts apart ("unwelds") all edges in `es` into pairs of boundary edges.
When an endpoint of a cut edge ends up on n boundaries,
it splits into n vertices.
Preserves above-mentioned properties (so you can then compute faces via
`FOLD.convert.edges_vertices_to_faces_vertices_edges`),
but ignores face properties and discards `vertices_vertices` if present.
###
vertices_boundaries = []
for e in filter.boundaryEdges fold
for v in fold.edges_vertices[e]
(vertices_boundaries[v] ?= []).push e
for e1 in es
## Split e1 into two edges {e1, e2}
e2 = filter.addEdgeLike fold, e1
for v, i in fold.edges_vertices[e1]
ve = fold.vertices_edges[v]
ve.splice ve.indexOf(e1) + i, 0, e2
## Check for endpoints of {e1, e2} to split, when they're on the boundary
for v1, i in fold.edges_vertices[e1]
u1 = fold.edges_vertices[e1][1-i]
u2 = fold.edges_vertices[e2][1-i]
boundaries = vertices_boundaries[v1]?.length
if boundaries >= 2 ## vertex already on boundary
if boundaries > 2
throw new Error "#{vertices_boundaries[v1].length} boundary edges at vertex #{v1}"
[b1, b2] = vertices_boundaries[v1]
neighbors = fold.vertices_edges[v1]
i1 = neighbors.indexOf b1
i2 = neighbors.indexOf b2
if i2 == (i1+1) % neighbors.length
neighbors = neighbors[i2..].concat neighbors[..i1] unless i2 == 0
else if i1 == (i2+1) % neighbors.length
neighbors = neighbors[i1..].concat neighbors[..i2] unless i1 == 0
else
throw new Error "Nonadjacent boundary edges at vertex #{v1}"
## Find first vertex among e1, e2 among neighbors, so other is next
ie1 = neighbors.indexOf e1
ie2 = neighbors.indexOf e2
ie = Math.min ie1, ie2
fold.vertices_edges[v1] = neighbors[..ie]
v2 = filter.addVertexLike fold, v1
fold.vertices_edges[v2] = neighbors[1+ie..]
#console.log "Split #{neighbors} into #{fold.vertices_edges[v1]} for #{v1} and #{fold.vertices_edges[v2]} for #{v2}"
for neighbor in fold.vertices_edges[v2] # including e2
ev = fold.edges_vertices[neighbor]
ev[ev.indexOf v1] = v2
fold.edges_assignment?[e1] = 'B'
fold.edges_assignment?[e2] = 'B'
for v, i in fold.edges_vertices[e1]
(vertices_boundaries[v] ?= []).push e1
for v, i in fold.edges_vertices[e2]
(vertices_boundaries[v] ?= []).push e2
delete fold.vertices_vertices # would be out-of-date
fold
filter.edges_vertices_to_vertices_vertices = (fold) ->
###
Works for abstract structures, so NOT SORTED.
Use sort_vertices_vertices to sort in counterclockwise order.
###
numVertices = filter.numVertices fold
vertices_vertices = ([] for v in [0...numVertices])
for edge in fold.edges_vertices
[v, w] = edge
while v >= vertices_vertices.length
vertices_vertices.push []
while w >= vertices_vertices.length
vertices_vertices.push []
vertices_vertices[v].push w
vertices_vertices[w].push v
vertices_vertices
| true | geom = require './geom'
filter = exports
filter.edgesAssigned = (fold, target) ->
i for assignment, i in fold.edges_assignment when assignment == target
filter.mountainEdges = (fold) ->
filter.edgesAssigned fold, 'M'
filter.valleyEdges = (fold) ->
filter.edgesAssigned fold, 'V'
filter.flatEdges = (fold) ->
filter.edgesAssigned fold, 'F'
filter.boundaryEdges = (fold) ->
filter.edgesAssigned fold, 'B'
filter.unassignedEdges = (fold) ->
filter.edgesAssigned fold, 'U'
filter.keysStartingWith = (fold, prefix) ->
key for key of fold when key[...prefix.length] == prefix
filter.keysEndingWith = (fold, suffix) ->
key for key of fold when key[-suffix.length..] == suffix
filter.remapField = (fold, field, old2new) ->
###
old2new: null means throw away that object
###
new2old = []
for j, i in old2new ## later overwrites earlier
new2old[j] = i if j?
for key in filter.keysStartingWith fold, "#{field}_"
fold[key] = (fold[key][old] for old in new2old)
for key in filter.keysEndingWith fold, "_#{field}"
fold[key] = (old2new[old] for old in array for array in fold[key])
fold
filter.remapFieldSubset = (fold, field, keep) ->
id = 0
old2new =
for value in keep
if value
id++
else
null ## remove
filter.remapField fold, field, old2new
old2new
filter.remove = (fold, field, index) ->
###
Remove given index from given field ('vertices', 'edges', 'faces'), in place.
###
filter.remapFieldSubset fold, field,
for i in [0...filter.numType fold, field]
i != index
filter.removeVertex = (fold, index) -> filter.remove fold, 'vertices', index
filter.removeEdge = (fold, index) -> filter.remove fold, 'edges', index
filter.removeFace = (fold, index) -> filter.remove fold, 'faces', index
filter.transform = (fold, matrix) ->
###
Transforms all fields ending in _coords (in particular, vertices_coords)
and all fields ending in FoldTransform (in particular,
faces_flatFoldTransform generated by convert.flat_folded_geometry)
according to the given transformation matrix.
###
for key in filter.keysEndingWith fold, "_coords"
fold[key] = (geom.matrixVector(matrix, coords) for coords in fold[key])
for key in filter.keysEndingWith fold, "FoldTransform" when '_' in key
fold[key] = (geom.matrixMatrix(matrix, transform) for transform in fold[key])
fold
filter.numType = (fold, type) ->
###
Count the maximum number of objects of a given type, by looking at all
fields with key of the form `type_...`, and if that fails, looking at all
fields with key of the form `..._type`. Returns `0` if nothing found.
###
counts =
for key in filter.keysStartingWith fold, "#{type}_"
value = fold[key]
continue unless value.length?
value.length
unless counts.length
counts =
for key in filter.keysEndingWith fold, "_#{type}"
1 + Math.max fold[key]...
if counts.length
Math.max counts...
else
0 ## nothing of this type
filter.numVertices = (fold) -> filter.numType fold, 'vertices'
filter.numEdges = (fold) -> filter.numType fold, 'edges'
filter.numFaces = (fold) -> filter.numType fold, 'faces'
filter.removeDuplicateEdges_vertices = (fold) ->
seen = {}
id = 0
old2new =
for edge in fold.edges_vertices
[v, w] = edge
if v < w
key = PI:KEY:<KEY>END_PI
else
key = PI:KEY:<KEY>END_PI
unless key of seen
seen[key] = id
id += 1
seen[key]
filter.remapField fold, 'edges', old2new
old2new
filter.edges_verticesIncident = (e1, e2) ->
for v in e1
if v in e2
return v
null
## Use hashing to find points within an epsilon > 0 distance from each other.
## Each integer cell will have O(1) distinct points before matching
## (number of disjoint half-unit disks that fit in a unit square).
class RepeatedPointsDS
constructor: (@vertices_coords, @epsilon) ->
## Note: if vertices_coords has some duplicates in the initial state,
## then we will detect them but won't remove them here. Rather,
## future duplicate inserts will return the higher-index vertex.
@hash = {}
for coord, v in @vertices_coords
(@hash[@key coord] ?= []).push v
null
lookup: (coord) ->
[x, y] = coord
xr = Math.round(x / @epsilon)
yr = Math.round(y / @epsilon)
for xt in [xr, xr-1, xr+1]
for yt in [yr, yr-1, yr+1]
key = PI:KEY:<KEY>END_PI
for v in @hash[key] ? []
if @epsilon > geom.dist @vertices_coords[v], coord
return v
null
key: (coord) ->
[x, y] = coord
xr = Math.round x / @epsilon
yr = Math.round y / @epsilon
key = PI:KEY:<KEY>END_PI
insert: (coord) ->
v = @lookup coord
return v if v?
(@hash[@key coord] ?= []).push v = @vertices_coords.length
@vertices_coords.push coord
v
filter.collapseNearbyVertices = (fold, epsilon) ->
vertices = new RepeatedPointsDS [], epsilon
old2new =
for coords in fold.vertices_coords
vertices.insert coords
filter.remapField fold, 'vertices', old2new
## In particular: fold.vertices_coords = vertices.vertices_coords
filter.maybeAddVertex = (fold, coords, epsilon) ->
###
Add a new vertex at coordinates `coords` and return its (last) index,
unless there is already such a vertex within distance `epsilon`,
in which case return the closest such vertex's index.
###
i = geom.closestIndex coords, fold.vertices_coords
if i? and epsilon >= geom.dist coords, fold.vertices_coords[i]
i ## Closest point is close enough
else
fold.vertices_coords.push(coords) - 1
filter.addVertexLike = (fold, oldVertexIndex) ->
## Add a vertex and copy data from old vertex.
vNew = filter.numVertices fold
for key in filter.keysStartingWith fold, 'vertices_'
switch key[6..]
when 'vertices'
## Leaving these broken
else
fold[key][vNew] = fold[key][oldVertexIndex]
vNew
filter.addEdgeLike = (fold, oldEdgeIndex, v1, v2) ->
## Add an edge between v1 and v2, and copy data from old edge.
## If v1 or v2 are unspecified, defaults to the vertices of the old edge.
## Must have `edges_vertices` property.
eNew = fold.edges_vertices.length
for key in filter.keysStartingWith fold, 'edges_'
switch key[6..]
when 'vertices'
fold.edges_vertices.push [
v1 ? fold.edges_vertices[oldEdgeIndex][0]
v2 ? fold.edges_vertices[oldEdgeIndex][1]
]
when 'edges'
## Leaving these broken
else
fold[key][eNew] = fold[key][oldEdgeIndex]
eNew
filter.addVertexAndSubdivide = (fold, coords, epsilon) ->
v = filter.maybeAddVertex fold, coords, epsilon
changedEdges = []
if v == fold.vertices_coords.length - 1
## Similar to "Handle overlapping edges" case:
for e, i in fold.edges_vertices
continue if v in e # shouldn't happen
s = (fold.vertices_coords[u] for u in e)
if geom.pointStrictlyInSegment coords, s ## implicit epsilon
#console.log coords, 'in', s
iNew = filter.addEdgeLike fold, i, v, e[1]
changedEdges.push i, iNew
e[1] = v
[v, changedEdges]
filter.removeLoopEdges = (fold) ->
###
Remove edges whose endpoints are identical. After collapsing via
`filter.collapseNearbyVertices`, this removes epsilon-length edges.
###
filter.remapFieldSubset fold, 'edges',
for edge in fold.edges_vertices
edge[0] != edge[1]
filter.subdivideCrossingEdges_vertices = (fold, epsilon, involvingEdgesFrom) ->
###
Using just `vertices_coords` and `edges_vertices` and assuming all in 2D,
subdivides all crossing/touching edges to form a planar graph.
In particular, all duplicate and loop edges are also removed.
If called without `involvingEdgesFrom`, does all subdivision in quadratic
time. xxx Should be O(n log n) via plane sweep.
In this case, returns an array of indices of all edges that were subdivided
(both modified old edges and new edges).
If called with `involvingEdgesFrom`, does all subdivision involving an
edge numbered `involvingEdgesFrom` or higher. For example, after adding an
edge with largest number, call with `involvingEdgesFrom =
edges_vertices.length - 1`; then this will run in linear time.
In this case, returns two arrays of edges: the first array are all subdivided
from the "involved" edges, while the second array is the remaining subdivided
edges.
###
changedEdges = [[], []]
addEdge = (v1, v2, oldEdgeIndex, which) ->
#console.log 'adding', oldEdgeIndex, fold.edges_vertices.length, 'to', which
eNew = filter.addEdgeLike fold, oldEdgeIndex, v1, v2
changedEdges[which].push oldEdgeIndex, eNew
## Handle overlapping edges by subdividing edges at any vertices on them.
## We use a while loop instead of a for loop to process newly added edges.
i = involvingEdgesFrom ? 0
while i < fold.edges_vertices.length
e = fold.edges_vertices[i]
s = (fold.vertices_coords[u] for u in e)
for p, v in fold.vertices_coords
continue if v in e
if geom.pointStrictlyInSegment p, s ## implicit epsilon
#console.log p, 'in', s
addEdge v, e[1], i, 0
e[1] = v
i++
## Handle crossing edges
## We use a while loop instead of a for loop to process newly added edges.
vertices = new RepeatedPointsDS fold.vertices_coords, epsilon
i1 = involvingEdgesFrom ? 0
while i1 < fold.edges_vertices.length
e1 = fold.edges_vertices[i1]
s1 = (fold.vertices_coords[v] for v in e1)
for e2, i2 in fold.edges_vertices[...i1]
s2 = (fold.vertices_coords[v] for v in e2)
if not filter.edges_verticesIncident(e1, e2) and geom.segmentsCross s1, s2
## segment intersection is too sensitive a test;
## segmentsCross more reliable
#cross = segmentIntersectSegment s1, s2
cross = geom.lineIntersectLine s1, s2
continue unless cross?
crossI = vertices.insert cross
#console.log e1, s1, 'intersects', e2, s2, 'at', cross, crossI
unless crossI in e1 and crossI in e2 ## don't add endpoint again
#console.log e1, e2, '->'
unless crossI in e1
addEdge crossI, e1[1], i1, 0
e1[1] = crossI
s1[1] = fold.vertices_coords[crossI] # update for future iterations
#console.log '->', e1, fold.edges_vertices[fold.edges_vertices.length-1]
unless crossI in e2
addEdge crossI, e2[1], i2, 1
e2[1] = crossI
#console.log '->', e2, fold.edges_vertices[fold.edges_vertices.length-1]
i1++
old2new = filter.removeDuplicateEdges_vertices fold
for i in [0, 1]
changedEdges[i] = (old2new[e] for e in changedEdges[i])
old2new = filter.removeLoopEdges fold
for i in [0, 1]
changedEdges[i] = (old2new[e] for e in changedEdges[i])
#fold
if involvingEdgesFrom?
changedEdges
else
changedEdges[0].concat changedEdges[1]
filter.addEdgeAndSubdivide = (fold, v1, v2, epsilon) ->
###
Add an edge between vertex indices or points `v1` and `v2`, subdivide
as necessary, and return two arrays: all the subdivided parts of this edge,
and all the other edges that change.
If the edge is a loop or a duplicate, both arrays will be empty.
###
if v1.length?
[v1, changedEdges1] = filter.addVertexAndSubdivide fold, v1, epsilon
if v2.length?
[v2, changedEdges2] = filter.addVertexAndSubdivide fold, v2, epsilon
if v1 == v2 ## Ignore loop edges
return [[], []]
for e, i in fold.edges_vertices
if (e[0] == v1 and e[1] == v2) or
(e[0] == v2 and e[1] == v1)
return [[i], []] ## Ignore duplicate edges
iNew = fold.edges_vertices.push([v1, v2]) - 1
if iNew
changedEdges = filter.subdivideCrossingEdges_vertices(fold, epsilon, iNew)
changedEdges[0].push iNew unless iNew in changedEdges[0]
else
changedEdges = [[iNew], []]
changedEdges[1].push changedEdges1... if changedEdges1?
changedEdges[1].push changedEdges2... if changedEdges2?
changedEdges
filter.cutEdges = (fold, es) ->
###
Given a FOLD object with `edges_vertices`, `edges_assignment`, and
counterclockwise-sorted `vertices_edges`
(see `FOLD.convert.edges_vertices_to_vertices_edges_sorted`),
cuts apart ("unwelds") all edges in `es` into pairs of boundary edges.
When an endpoint of a cut edge ends up on n boundaries,
it splits into n vertices.
Preserves above-mentioned properties (so you can then compute faces via
`FOLD.convert.edges_vertices_to_faces_vertices_edges`),
but ignores face properties and discards `vertices_vertices` if present.
###
vertices_boundaries = []
for e in filter.boundaryEdges fold
for v in fold.edges_vertices[e]
(vertices_boundaries[v] ?= []).push e
for e1 in es
## Split e1 into two edges {e1, e2}
e2 = filter.addEdgeLike fold, e1
for v, i in fold.edges_vertices[e1]
ve = fold.vertices_edges[v]
ve.splice ve.indexOf(e1) + i, 0, e2
## Check for endpoints of {e1, e2} to split, when they're on the boundary
for v1, i in fold.edges_vertices[e1]
u1 = fold.edges_vertices[e1][1-i]
u2 = fold.edges_vertices[e2][1-i]
boundaries = vertices_boundaries[v1]?.length
if boundaries >= 2 ## vertex already on boundary
if boundaries > 2
throw new Error "#{vertices_boundaries[v1].length} boundary edges at vertex #{v1}"
[b1, b2] = vertices_boundaries[v1]
neighbors = fold.vertices_edges[v1]
i1 = neighbors.indexOf b1
i2 = neighbors.indexOf b2
if i2 == (i1+1) % neighbors.length
neighbors = neighbors[i2..].concat neighbors[..i1] unless i2 == 0
else if i1 == (i2+1) % neighbors.length
neighbors = neighbors[i1..].concat neighbors[..i2] unless i1 == 0
else
throw new Error "Nonadjacent boundary edges at vertex #{v1}"
## Find first vertex among e1, e2 among neighbors, so other is next
ie1 = neighbors.indexOf e1
ie2 = neighbors.indexOf e2
ie = Math.min ie1, ie2
fold.vertices_edges[v1] = neighbors[..ie]
v2 = filter.addVertexLike fold, v1
fold.vertices_edges[v2] = neighbors[1+ie..]
#console.log "Split #{neighbors} into #{fold.vertices_edges[v1]} for #{v1} and #{fold.vertices_edges[v2]} for #{v2}"
for neighbor in fold.vertices_edges[v2] # including e2
ev = fold.edges_vertices[neighbor]
ev[ev.indexOf v1] = v2
fold.edges_assignment?[e1] = 'B'
fold.edges_assignment?[e2] = 'B'
for v, i in fold.edges_vertices[e1]
(vertices_boundaries[v] ?= []).push e1
for v, i in fold.edges_vertices[e2]
(vertices_boundaries[v] ?= []).push e2
delete fold.vertices_vertices # would be out-of-date
fold
filter.edges_vertices_to_vertices_vertices = (fold) ->
###
Works for abstract structures, so NOT SORTED.
Use sort_vertices_vertices to sort in counterclockwise order.
###
numVertices = filter.numVertices fold
vertices_vertices = ([] for v in [0...numVertices])
for edge in fold.edges_vertices
[v, w] = edge
while v >= vertices_vertices.length
vertices_vertices.push []
while w >= vertices_vertices.length
vertices_vertices.push []
vertices_vertices[v].push w
vertices_vertices[w].push v
vertices_vertices
|
[
{
"context": ".Complex extends mathJS.Number\n\n PARSE_KEY = \"0c\"\n\n ###########################################",
"end": 46852,
"score": 0.889875590801239,
"start": 46851,
"tag": "KEY",
"value": "c"
}
] | source.coffee | jneuendorf/mathJS | 0 | # from js/init.coffee
###*
* @module mathJS
* @main mathJS
*###
if typeof DEBUG is "undefined"
window.DEBUG = true
# create namespaces
window.mathJS =
Algorithms: {}
Domains: {} # contains instances of sets
Errors: {}
Geometry: {}
Operations: {}
Sets: {}
Utils: {}
# Take namespaces from mathJS
_mathJS = $.extend {}, mathJS
if DEBUG
window._mathJS = _mathJS
startTime = Date.now()
# end js/init.coffee
# from js/prototyping.coffee
# TODO: use object.defineProperties in order to hide methods from enumeration
####################################################################################
Array::reverseCopy = () ->
res = []
res.push(item) for item in @ by -1
return res
Array::unique = () ->
res = []
for elem in @ when elem not in res
res.push elem
return res
Array::sample = (n = 1, forceArray = false) ->
if n is 1
if not forceArray
return @[ Math.floor(Math.random() * @length) ]
return [ @[ Math.floor(Math.random() * @length) ] ]
if n > @length
n = @length
i = 0
res = []
arr = @clone()
while i++ < n
elem = arr.sample(1)
res.push elem
arr.remove elem
return res
Array::shuffle = () ->
arr = @sample(@length)
for elem, i in arr
@[i] = elem
return @
Array::average = () ->
sum = 0
elems = 0
for elem in @ when Math.isNum(elem)
sum += elem
elems++
return sum / elems
# make alias
Array::median = Array::average
Array::clone = Array::slice
# TODO: from http://jsperf.com/array-prototype-slice-call-vs-slice-call/17
# function nonnative_slice(item, start){
# start = ~~start;
# var
# len = item.length, i, newArray;
#
# newArray = new Array(len - start);
#
# for (i = start; i < len; i++){
# newArray[i - start] = item[i];
# }
#
# return newArray;
# }
Array::indexOfNative = Array::indexOf
Array::indexOf = (elem, fromIdx) ->
idx = if fromIdx? then fromIdx else 0
len = @length
while idx < len
if @[idx] is elem
return idx
idx++
return -1
Array::remove = (elem) ->
idx = @indexOf elem
if idx > -1
@splice(idx, 1)
return @
Array::removeAll = (elements = []) ->
for elem in elements
@remove elem
return @
Array::removeAt = (idx) ->
@splice(idx, 1)
return @
# convenient index getters and setters
Object.defineProperties Array::, {
first:
get: () ->
return @[0]
set: (val) ->
@[0] = val
return @
second:
get: () ->
return @[1]
set: (val) ->
@[1] = val
return @
third:
get: () ->
return @[2]
set: (val) ->
@[2] = val
return @
fourth:
get: () ->
return @[3]
set: (val) ->
@[3] = val
return @
last:
get: () ->
return @[@length - 1]
set: (val) ->
@[@length - 1] = val
return @
}
###*
* @method getMax
* @param {Function} propertyGetter
* The passed callback extracts the value being compared from the array elements.
* @return {Array} An array of all maxima.
*###
Array::getMax = (propertyGetter) ->
max = null
res = []
if not propertyGetter?
propertyGetter = (item) ->
return item
for elem in @
val = propertyGetter(elem)
# new max found (or first compare) => restart list with new max value
if val > max or max is null
max = val
res = [elem]
# same as max found => add to list
else if val is max
res.push elem
return res
Array::getMin = (propertyGetter) ->
min = null
res = []
if not propertyGetter?
propertyGetter = (item) ->
return item
for elem in @
val = propertyGetter(elem)
# new min found (or first compare) => restart list with new min value
if val < min or min is null
min = val
res = [elem]
# same as min found => add to list
else if val is min
res.push elem
return res
Array::sortProp = (getProp, order = "asc") ->
if not getProp?
getProp = (item) ->
return item
if order is "asc"
cmpFunc = (a, b) ->
a = getProp(a)
b = getProp(b)
if a < b
return -1
if b > a
return 1
return 0
else
cmpFunc = (a, b) ->
a = getProp(a)
b = getProp(b)
if a > b
return -1
if b < a
return 1
return 0
return @sort cmpFunc
####################################################################################
# STRING
String::camel = (spaces) ->
if not spaces?
spaces = false
str = @toLowerCase()
if spaces
str = str.split(" ")
for i in [1...str.length]
str[i] = str[i].charAt(0).toUpperCase() + str[i].substring(1)
str = str.join("")
return str
String::antiCamel = () ->
res = @charAt(0)
for i in [1...@length]
temp = @charAt(i)
# it is a capital letter -> insert space
if temp is temp.toUpperCase()
res += " "
res += temp
return res
String::firstToUpperCase = () ->
return @charAt(0).toUpperCase() + @slice(1)
String::snakeToCamelCase = () ->
res = ""
for char in @
# not underscore
if char isnt "_"
# previous character was not an underscore => just add character
if prevChar isnt "_"
res += char
# previous character was an underscore => add upper case character
else
res += char.toUpperCase()
prevChar = char
return res
String::camelToSnakeCase = () ->
res = ""
prevChar = null
for char in @
# lower case => just add
if char is char.toLowerCase()
res += char
# upper case
else
# previous character was lower case => add underscore and lower case character
if prevChar is prevChar.toLowerCase()
res += "_" + char.toLowerCase()
# previous character was (also) upper case => just add
else
res += char
prevChar = char
return res
String::lower = String::toLowerCase
String::upper = String::toUpperCase
# convenient index getters and setters
Object.defineProperties String::, {
first:
get: () ->
return @[0]
set: (val) ->
return @
second:
get: () ->
return @[1]
set: (val) ->
return @
third:
get: () ->
return @[2]
set: (val) ->
return @
fourth:
get: () ->
return @[3]
set: (val) ->
return @
last:
get: () ->
return @[@length - 1]
set: (val) ->
return @
}
# implement comparable and orderable interface for primitives
String::equals = (str) ->
return @valueOf() is str.valueOf()
String::lessThan = (str) ->
return @valueOf() < str.valueOf()
String::lt = String::lessThan
String::greaterThan = (str) ->
return @valueOf() > str.valueOf()
String::gt = String::greaterThan
String::lessThanOrEqualTo = (str) ->
return @valueOf() <= str.valueOf()
String::lte = String::lessThanOrEqualTo
String::greaterThanOrEqualTo = (str) ->
return @valueOf() >= str.valueOf()
String::gte
####################################################################################
# BOOLEAN
Boolean::equals = (bool) ->
return @valueOf() is bool.valueOf()
Boolean::lessThan = (bool) ->
return @valueOf() < bool.valueOf()
Boolean::lt = Boolean::lessThan
Boolean::greaterThan = (bool) ->
return @valueOf() > bool.valueOf()
Boolean::gt = Boolean::greaterThan
Boolean::lessThanOrEqualTo = (bool) ->
return @valueOf() <= bool.valueOf()
Boolean::lte = Boolean::lessThanOrEqualTo
Boolean::greaterThanOrEqualTo = (bool) ->
return @valueOf() >= str.valueOf()
Boolean::gte
####################################################################################
# OBJECT
Object.keysLike = (obj, pattern) ->
res = []
for key in Object.keys(obj)
if pattern.test key
res.push key
return res
# end js/prototyping.coffee
# from js/mathJS.coffee
#################################################################################################
# THIS FILE CONTAINS ALL PROPERITES AND FUNCTIONS THAT ARE BOUND DIRECTLY TO mathJS
# CONSTRANTS
Object.defineProperties mathJS, {
e:
value: Math.E
writable: false
pi:
value: Math.PI
writable: false
ln2:
value: Math.LN2
writable: false
ln10:
value: Math.LN10
writable: false
log2e:
value: Math.LOG2E
writable: false
log10e:
value: Math.LOG10E
writable: false
# This value behaves slightly differently than mathematical infinity:
#
# Any positive value, including POSITIVE_INFINITY, multiplied by NEGATIVE_INFINITY is NEGATIVE_INFINITY.
# Any negative value, including NEGATIVE_INFINITY, multiplied by NEGATIVE_INFINITY is POSITIVE_INFINITY.
# Zero multiplied by NEGATIVE_INFINITY is NaN.
# NaN multiplied by NEGATIVE_INFINITY is NaN.
# NEGATIVE_INFINITY, divided by any negative value except NEGATIVE_INFINITY, is POSITIVE_INFINITY.
# NEGATIVE_INFINITY, divided by any positive value except POSITIVE_INFINITY, is NEGATIVE_INFINITY.
# NEGATIVE_INFINITY, divided by either NEGATIVE_INFINITY or POSITIVE_INFINITY, is NaN.
# Any number divided by NEGATIVE_INFINITY is Zero.
infty:
value: Infinity
writable: false
infinity:
value: Infinity
writable: false
epsilon:
value: Number.EPSILON or 2.220446049250313e-16 # 2.220446049250313080847263336181640625e-16
writable: false
maxValue:
value: Number.MAX_VALUE
writable: false
minValue:
value: Number.MIN_VALUE
writable: false
id:
value: (x) ->
return x
writable: false
# number sets / systems
# N:
# value: new mathJS.Set()
# writable: false
}
mathJS.isPrimitive = (x) ->
return typeof x is "string" or typeof x is "number" or typeof x is "boolean"
mathJS.isComparable = (x) ->
# return x instanceof mathJS.Comparable or x.instanceof?(mathJS.Comparable) or mathJS.isPrimitive x
return x.equals instanceof Function or mathJS.isPrimitive x
# mathJS.instanceof = (instance, clss) ->
# return instance instanceof clss or instance.instanceof?(clss)
# mathJS.isA = () ->
mathJS.equals = (x, y) ->
return x.equals?(y) or y.equals?(x) or x is y
mathJS.greaterThan = (x, y) ->
return x.gt?(y) or y.lt?(x) or x > y
mathJS.gt = mathJS.greaterThan
mathJS.lessThan = (x, y) ->
return x.lt?(y) or y.gt?(x) or x < y
mathJS.lt = mathJS.lessThan
mathJS.ggT = () ->
if arguments[0] instanceof Array
vals = arguments[0]
else
vals = Array::slice.apply arguments
if vals.length is 2
if vals[1] is 0
return vals[0]
return mathJS.ggT(vals[1], vals[0] %% vals[1])
else if vals.length > 2
ggt = mathJS.ggT vals[0], vals[1]
for i in [2...vals.length]
ggt = mathJS.ggT(ggt, vals[i])
return ggt
return null
mathJS.gcd = mathJS.ggT
mathJS.kgV = () ->
if arguments[0] instanceof Array
vals = arguments[0]
else
vals = Array::slice.apply arguments
if vals.length is 2
return vals[0] * vals[1] // mathJS.ggT(vals[0], vals[1])
else if vals.length > 2
kgv = mathJS.kgV vals[0], vals[1]
for i in [2...vals.length]
kgv = mathJS.kgV(kgv, vals[i])
return kgv
return null
mathJS.lcm = mathJS.kgV
mathJS.coprime = (x, y) ->
return mathJS.gcd(x, y) is 1
mathJS.ceil = Math.ceil
# faster way of rounding down
mathJS.floor = (n) ->
# if mathJS.isNum(n)
# return ~~n
# return NaN
return ~~n
mathJS.floatToInt = mathJS.floor
mathJS.square = (n) ->
if mathJS.isNum(n)
return n * n
return NaN
mathJS.cube = (n) ->
if mathJS.isNum(n)
return n * n * n
return NaN
# TODO: jsperf
mathJS.pow = Math.pow
# TODO: jsperf
mathJS.sqrt = Math.sqrt
mathJS.curt = (n) ->
if mathJS.isNum(n)
return mathJS.pow(n, 1 / 3)
return NaN
mathJS.root = (n, exp) ->
if mathJS.isNum(n) and mathJS.isNum(exp)
return mathJS.pow(n, 1 / exp)
return NaN
mathJS.factorial = (n) ->
if (n = ~~n) < 0
return NaN
return mathJS.factorial.cache[n] or (mathJS.factorial.cache[n] = n * mathJS.factorial(n - 1))
# initial cache (dynamically growing when exceeded)
mathJS.factorial.cache = [
1
1
2
6
24
120
720
5040
40320
362880
3628800
39916800
4.790016e8
6.2270208e9
8.71782912e10
1.307674368e12
]
# make alias
mathJS.fac = mathJS.factorial
mathJS.parseNumber = (str) ->
# TODO
return null
mathJS.factorialInverse = (n) ->
if (n = ~~n) < 0
return NaN
x = 0
# js: while((y = mathJS.factorial(++x)) < n) {}
while (y = mathJS.factorial(++x)) < n then
if y is n
return parseInt(x, 10)
return NaN
# make alias
mathJS.facInv = mathJS.factorialInverse
###*
* This function checks if a given parameter is a (plain) number.
* @method isNum
* @param {Number} num
* @return {Boolean} Whether the given number is a Number (excluding +/-Infinity)
*###
# mathJS.isNum = (r) ->
# return (typeof r is "number") and not isNaN(r) and r isnt Infinity and r isnt -Infinity
# return not isNaN(r) and -Infinity < r < Infinity
mathJS.isNum = (n) ->
return n? and isFinite(n)
mathJS.isMathJSNum = (n) ->
return n? and (isFinite(n) or n instanceof mathJS.Number or n.instanceof(mathJS.Number))
mathJS.isInt = (r) ->
return mathJS.isNum(r) and ~~r is r
###*
* This function returns a random (plain) integer between max and min (both inclusive). If max is less than min the parameters are swapped.
* @method randInt
* @param {Number} max
* @param {Number} min
* @return {Number} Random integer.
*###
mathJS.randInt = (max = 1, min = 0) ->
# if min > max
# temp = min
# min = max
# max = temp
# return Math.floor(Math.random() * (max + 1 - min)) + min
return ~~mathJS.randNum(max, min)
###*
* This function returns a random number between max and min (both inclusive). If max is less than min the parameters are swapped.
* @method randNum
* @param {Number} max
* @param {Number} min
* Default is 0.
* @return {Integer} Random number.
*###
mathJS.randNum = (max = 1, min = 0) ->
if min > max
temp = min
min = max
max = temp
return Math.random() * (max + 1 - min) + min
mathJS.radToDeg = (rad) ->
return rad * 57.29577951308232 # = rad * (180 / Math.PI)
mathJS.degToRad = (deg) ->
return deg * 0.017453292519943295 # = deg * (Math.PI / 180)
mathJS.sign = (n) ->
n = n.value or n
if mathJS.isNum(n)
if n < 0
return -1
return 1
return NaN
mathJS.min = (elems...) ->
if elems.first instanceof Array
elems = elems.first
propGetter = null
else if elems.first instanceof Function
propGetter = elems.first
elems = elems.slice(1)
if elems.first instanceof Array
elems = elems.first
res = []
min = null
for item in elems
if propGetter?
item = propGetter(item)
if min is null or item.lessThan(min) or item < min
min = item
res = [elem]
# same as min found => add to list
else if item.equals(min) or item is min
res.push elem
return res
mathJS.max = (elems...) ->
if elems.first instanceof Array
elems = elems.first
propGetter = null
else if elems.first instanceof Function
propGetter = elems.first
elems = elems.slice(1)
if elems.first instanceof Array
elems = elems.first
res = []
max = null
for item in elems
if propGetter?
item = propGetter(item)
if max is null or item.greaterThan(max) or item > max
max = item
res = [elem]
# same as max found => add to list
else if item.equals(max) or item is max
res.push elem
return res
mathJS.log = (n, base=10) ->
return Math.log(n) / Math.log(base)
mathJS.logBase = mathJS.log
mathJS.reciprocal = (n) ->
if mathJS.isNum(n)
return 1 / n
return NaN
mathJS.sortFunction = (a, b) ->
if a.lessThan b
return -1
if a.greaterThan b
return 1
return 0
# end js/mathJS.coffee
# from js/settings.coffee
mathJS.settings =
generator:
maxIndex: 1e4
integral:
maxSteps: 1e10
# maxPoolSize is for EACH pool
maxPoolSize: 100
number:
real:
distance: 1e-6
set:
defaultNumberOfElements: 1e3
maxIterations: 1e3
maxMatches: 60
mathJS.config = mathJS.settings
# end js/settings.coffee
# from js/mathJSObject.coffee
###*
* This is the super class of all mathJS classes.
* Therefore all cross-class things are defined here.
* @class Object
*###
class _mathJS.Object
@_implements = []
@_implementedBy = []
@implements = (classes...) ->
if classes.first instanceof Array
classes = classes.first
for clss in classes
# make the class / interface know what classes implement it
if @ not in clss._implementedBy
clss._implementedBy.push @
# implement class / interface
clssPrototype = clss.prototype
# "window." necessary because coffee creates an "Object" variable for this class
prototypeKeys = window.Object.keys(clssPrototype)
# static
for name, method of clss when name not in prototypeKeys
@[name] = method
# non-static (from prototype)
for name, method of clssPrototype
@::[name] = method
@_implements.push clss
return @
isA: (clss) ->
if not clss? or clss not instanceof Function
return false
if @ instanceof clss
return true
for c in @constructor._implements
# direct hit
if c is clss
return true
# check super classes ("__superClass__" is set when coffee extends classes using macros...see macros.js)
while (c = c.__superClass__)?
if c is clss
return true
return false
instanceof: () ->
return @isA.apply(@, arguments)
# end js/mathJSObject.coffee
# from js/Errors/SimpleErrors.coffee
# class _mathJS.Errors.Error extends window.Error
#
# constructor: (message, fileName, lineNumber, misc...) ->
# super(message, fileName, lineNumber)
# @misc = misc
#
# toString: () ->
# return "#{super()}\n more data: #{@misc.toString()}"
class mathJS.Errors.CalculationExceedanceError extends Error
class mathJS.Errors.CycleDetectedError extends Error
class mathJS.Errors.DivisionByZeroError extends Error
class mathJS.Errors.InvalidArityError extends Error
class mathJS.Errors.InvalidParametersError extends Error
class mathJS.Errors.InvalidVariableError extends Error
class mathJS.Errors.NotImplementedError extends Error
class mathJS.Errors.NotParseableError extends Error
# end js/Errors/SimpleErrors.coffee
# from js/Utils/Hash.coffee
###*
* This is an implementation of a dictionary/hash that does not convert its keys into Strings. Keys can therefore actually by anything!
* @class Hash
* @constructor
*###
class mathJS.Utils.Hash
###*
* Creates a new Hash from a given JavaScript object.
* @static
* @method fromObject
* @param object {Object}
*###
@fromObject: (obj) ->
return new mathJS.Utils.Hash(obj)
@new: (obj) ->
return new mathJS.Utils.Hash(obj)
constructor: (obj) ->
@keys = []
@values = []
if obj?
@put key, val for key, val of obj
clone: () ->
res = new mathJS.Utils.Hash()
res.keys = @keys.clone()
res.values = @values.clone()
return res
invert: () ->
res = new mathJS.Utils.Hash()
res.keys = @values.clone()
res.values = @keys.clone()
return res
###*
* Adds a new key-value pair or overwrites an existing one.
* @method put
* @param key {mixed}
* @param val {mixed}
* @return {Hash} This instance.
* @chainable
*###
put: (key, val) ->
idx = @keys.indexOf key
# add new entry
if idx < 0
@keys.push key
@values.push val
# overwrite entry
else
@keys[idx] = key
@values[idx] = val
return @
###*
* Returns the value (or null) for the specified key.
* @method get
* @param key {mixed}
* @param [equalityFunction] {Function}
* This optional function can overwrite the test for equality between keys. This function expects the parameters: (the current key in the key iteration, 'key'). If this parameters is omitted '===' is used.
* @return {mixed}
*###
get: (key) ->
if (idx = @keys.indexOf(key)) >= 0
return @values[idx]
return null
###*
* Indicates whether the Hash has the specified key.
* @method hasKey
* @param key {mixed}
* @return {Boolean}
*###
hasKey: (key) ->
return key in @keys
has: (key) ->
return @hasKey(key)
###*
* Returns the number of entries in the Hash.
* @method size
* @return {Integer}
*###
size: () ->
return @keys.length
empty: () ->
@keys = []
@values = []
return @
remove: (key) ->
if (idx = @keys.indexOf(key)) >= 0
@keys.splice idx, 1
@values.splice idx, 1
else
console.warn "Could not remove key '#{key}'!"
return @
each: (callback) ->
for key, i in @keys when callback(key, @values[i], i) is false
return @
return @
# end js/Utils/Hash.coffee
# from js/Utils/Dispatcher.coffee
class mathJS.Utils.Dispatcher extends _mathJS.Object
# map: receiver -> list of dispatchers
@registeredDispatchers = mathJS.Utils.Hash.new()
# try to detect cyclic dispatching
@registerDispatcher: (newReceiver, newTargets) ->
registrationPossible = newTargets.indexOf(newReceiver) is -1
if registrationPossible
regReceivers = @registeredDispatchers.keys
# IF
# 1. the new receiver is in any of the lists and
# 2. any of the registered receivers is in the new-targets list
# THEN a cycle would be created
@registeredDispatchers.each (regReceiver, regTargets, idx) ->
for regTarget in regTargets when regTarget is newReceiver
for newTarget in newTargets when regReceivers.indexOf(newTarget)
registrationPossible = false
return false
return true
if registrationPossible
@registeredDispatchers.put(newReceiver, newTargets)
return @
throw new mathJS.Errors.CycleDetectedError("Can't register '#{newReceiver}' for dispatching - cycle detected!")
# CONSTRUCTOR
# NOTE: super classes are ignored
constructor: (receiver, targets=[]) ->
@constructor.registerDispatcher(receiver, targets)
@receiver = receiver
@targets = targets
console.log "dispatcher created!"
dispatch: (target, method, params...) ->
dispatch = false
# check instanceof and identity
if @targets.indexOf(target.constructor or target) >= 0
dispatch = true
# check typeof (for primitives)
else
for t in @targets when typeof target is t
dispatch = true
break
if dispatch
if target[method] instanceof Function
return target[method].apply(target, params)
throw new mathJS.Errors.NotImplementedError(
"Can't call '#{method}' on target '#{target}'"
"Dispatcher.coffee"
)
return null
# end js/Utils/Dispatcher.coffee
# from js/Interfaces/Interface.coffee
class _mathJS.Interface extends _mathJS.Object
@implementedBy = []
@isImplementedBy = () ->
return @implementedBy
# end js/Interfaces/Interface.coffee
# from js/Interfaces/Comparable.coffee
class _mathJS.Comparable extends _mathJS.Interface
###*
* This method checks for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2) is true.
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (n) ->
throw new mathJS.Errors.NotImplementedError("equals in #{@contructor.name}")
e: () ->
return @equals.apply(@, arguments)
# end js/Interfaces/Comparable.coffee
# from js/Interfaces/Orderable.coffee
class _mathJS.Orderable extends _mathJS.Comparable
###*
* This method checks for mathmatical "<". This means new mathJS.Double(4.2).lessThan(5.2) is true.
* @method lessThan
* @param {Number} n
* @return {Boolean}
*###
lessThan: (n) ->
throw new mathJS.Errors.NotImplementedError("lessThan in #{@contructor.name}")
###*
* Alias for `lessThan`.
* @method lt
*###
lt: () ->
return @lessThan.apply(@, arguments)
###*
* This method checks for mathmatical ">". This means new mathJS.Double(4.2).greaterThan(3.2) is true.
* @method greaterThan
* @param {Number} n
* @return {Boolean}
*###
greaterThan: (n) ->
throw new mathJS.Errors.NotImplementedError("greaterThan in #{@contructor.name}")
###*
* Alias for `greaterThan`.
* @method gt
*###
gt: () ->
return @greaterThan.apply(@, arguments)
###*
* This method checks for mathmatical "<=". This means new mathJS.Double(4.2).lessThanOrEqualTo(5.2) is true.
* @method lessThanOrEqualTo
* @param {Number} n
* @return {Boolean}
*###
lessThanOrEqualTo: (n) ->
return @lessThan(n) or @equals(n)
###*
* Alias for `lessThanOrEqualTo`.
* @method lte
*###
lte: () ->
return @lessThanOrEqualTo.apply(@, arguments)
###*
* This method checks for mathmatical ">=". This means new mathJS.Double(4.2).greaterThanOrEqualTo(3.2) is true.
* @method greaterThanOrEqualTo
* @param {Number} n
* @return {Boolean}
*###
greaterThanOrEqualTo: (n) ->
return @greaterThan(n) or @equals(n)
###*
* Alias for `greaterThanOrEqualTo`.
* @method gte
*###
gte: () ->
return @greaterThanOrEqualTo.apply(@, arguments)
# end js/Interfaces/Orderable.coffee
# from js/Interfaces/Parseable.coffee
class _mathJS.Parseable extends _mathJS.Interface
@parse: (str) ->
throw new mathJS.Errors.NotImplementedError("static parse in #{@name}")
@fromString: (str) ->
return @parse(str)
toString: (args) ->
throw new mathJS.Errors.NotImplementedError("toString in #{@contructor.name}")
# end js/Interfaces/Parseable.coffee
# from js/Interfaces/Poolable.coffee
class _mathJS.Poolable extends _mathJS.Interface
@_pool = []
@_fromPool: () ->
# implementation should be something like:
# if @_pool.length > 0
# return @_pool.pop()
# return new @()
throw new mathJS.Errors.NotImplementedError("static _fromPool in #{@name}")
###*
* Releases the instance to the pool of its class.
* @method release
* @return This intance
* @chainable
*###
release: () ->
if @constructor._pool.length < mathJS.settings.maxPoolSize
@constructor._pool.push @
if DEBUG
if @constructor._pool.length >= mathJS.settings.maxPoolSize
console.warn "#{@constructor.name}-pool is full:", @constructor._pool
return @
# end js/Interfaces/Poolable.coffee
# from js/Interfaces/Evaluable.coffee
class _mathJS.Evaluable extends _mathJS.Interface
eval: () ->
throw new mathJS.Errors.NotImplementedError("eval() in #{@contructor.name}")
# end js/Interfaces/Evaluable.coffee
# from js/Numbers/AbstractNumber.coffee
# This file defines the Number interface.
# TODO: make number extend expression
class _mathJS.AbstractNumber extends _mathJS.Object
@implements _mathJS.Orderable, _mathJS.Poolable, _mathJS.Parseable
###*
* @Override mathJS.Poolable
* @static
* @method _fromPool
*###
@_fromPool: (value) ->
if @_pool.length > 0
if (val = @_getPrimitive(value))?
number = @_pool.pop()
number.value = val
return number
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{value}'"
"AbstractNumber.coffee"
)
# param check is done in constructor
return new @(value)
###*
* @Override mathJS.Parseable
* @static
* @method parse
*###
@parse: (str) ->
return @_fromPool parseFloat(str)
@getSet: () ->
throw new mathJS.Errors.NotImplementedError("getSet in #{@name}")
@new: (param) ->
return @_fromPool param
@random: (max, min) ->
return @_fromPool mathJS.randNum(max, min)
@dispatcher = new mathJS.Utils.Dispatcher(@, [
# mathJS.Matrix
mathJS.Fraction
])
###*
* This method is used to parse and check a parameter.
* Either a valid value is returned or null (for invalid parameters).
* @static
* @method _getPrimitive
* @param param {Object}
* @param skipCheck {Boolean}
* @return {mathJS.Number}
*###
@_getPrimitive: (param, skipCheck) ->
return null
############################################################################################
# PROTECTED METHODS
_setValue: (value) ->
return @
_getValue: () ->
return @_value
_getPrimitive: (param) ->
return @constructor._getPrimitive(param)
############################################################################################
# PUBLIC METHODS
############################################################################################
# COMPARABLE INTERFACE
###*
* @Override mathJS.Comparable
* This method checks for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2) is true.
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "equals", @))?
return result
if (val = @_getPrimitive(n))?
return @value is val
return false
# END - IMPLEMENTING COMPARABLE
############################################################################################
############################################################################################
# ORDERABLE INTERFACE
###*
* @Override mathJS.Orderable
* This method checks for mathmatical "<". This means new mathJS.Double(4.2).lessThan(5.2) is true.
* @method lessThan
*###
lessThan: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "lessThan", @))?
return result
if (val = @_getPrimitive(n))?
return @value < val
return false
###*
* @Override mathJS.Orderable
* This method checks for mathmatical ">". This means new mathJS.Double(4.2).greaterThan(3.2) is true.
* @method greaterThan
* @param {Number} n
* @return {Boolean}
*###
greaterThan: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "greaterThan", @))?
return result
if (val = @_getPrimitive(n))?
return @value > val
return false
# END - IMPLEMENTING ORDERABLE
############################################################################################
###*
* This method adds 2 numbers and returns a new one.
* @method plus
* @param {Number} n
* @return {mathJS.Number} Calculated Number.
*###
plus: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "plus", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value + val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method substracts 2 numbers and returns a new one.
* @method minus
* @param {Number} n
* @return {mathJS.Number} Calculated Number.
*###
minus: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "minus", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value - val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method multiplies 2 numbers and returns a new one.
* @method times
* @param {Number} n
* @return {mathJS.Number} Calculated Number.
*###
times: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "times", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value * val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method divides 2 numbers and returns a new one.
* @method divide
* @param {Number} n
* @return {Number} Calculated Number.
*###
divide: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "divide", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value / val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method squares this instance and returns a new one.
* @method square
* @return {Number} Calculated Number.
*###
square: () ->
return mathJS.Number.new(@value * @value)
###*
* This method cubes this instance and returns a new one.
* @method cube
* @return {Number} Calculated Number.
*###
cube: () ->
return mathJS.Number.new(@value * @value * @value)
###*
* This method calculates the square root of this instance and returns a new one.
* @method sqrt
* @return {Number} Calculated Number.
*###
sqrt: () ->
return mathJS.Number.new(mathJS.sqrt(@value))
###*
* This method calculates the cubic root of this instance and returns a new one.
* @method curt
* @return {Number} Calculated Number.
*###
curt: () ->
return @pow(0.3333333333333333)
###*
* This method calculates any root of this instance and returns a new one.
* @method root
* @param {Number} exponent
* @return {Number} Calculated Number.
*###
root: (exp) ->
if (val = @_getPrimitive(exp))?
return @pow(1 / val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{exp}'"
"AbstractNumber.coffee"
)
###*
* This method returns the reciprocal (1/n) of this number.
* @method reciprocal
* @return {Number} Calculated Number.
*###
reciprocal: () ->
return mathJS.Number.new(1 / @value)
###*
* This method returns this' value the the n-th power (this^n).
* @method pow
* @param {Number} n
* @return {Number} Calculated Number.
*###
pow: (n) ->
if (val = @_getPrimitive(n))?
return mathJS.Number.new(mathJS.pow(@value, val))
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method returns the sign of this number (sign(this)).
* @method sign
* @param plain {Boolean}
* Indicates whether the return value is wrapped in a mathJS.Number or not (-> primitive value).
* @return {Number|mathJS.Number}
*###
sign: (plain=true) ->
val = @value
if plain is true
if val < 0
return -1
return 1
# else:
if val < 0
return mathJS.Number.new(-1)
return mathJS.Number.new(1)
negate: () ->
return mathJS.Number.new(-@value)
toInt: () ->
return mathJS.Int.new(@value)
toNumber: () ->
return mathJS.Number.new(@value)
toString: (format) ->
if not format?
return "#{@value}"
return numeral(@value).format(format)
clone: () ->
return mathJS.Number.new(@value)
# EVALUABLE INTERFACE
eval: (values) ->
return @
_getSet: () ->
return new mathJS.Set(@)
############################################################################################
# SETS...
in: (set) ->
return set.contains(@)
# end js/Numbers/AbstractNumber.coffee
# from js/Numbers/Number.coffee
# TODO: mathJS.Number should also somehow be a mathJS.Expression!!!
###*
* @abstract
* @class Number
* @constructor
* @param {Number} value
* @extends Object
*###
class mathJS.Number extends _mathJS.AbstractNumber
###########################################################################################
# STATIC
@_getPrimitive: (param, skipCheck) ->
if skipCheck is true
return param
if param instanceof mathJS.Number
return param.value
if param instanceof Number
return param.valueOf()
if mathJS.isNum(param)
return param
return null
@getSet: () ->
return mathJS.Domains.R
# moved to AbstractNumber
# @new: (value) ->
# return @_fromPool value
###########################################################################################
# CONSTRUCTOR
constructor: (value) ->
@_value = null
Object.defineProperties @, {
value:
get: @_getValue
set: @_setValue
}
if (val = @_getPrimitive(value))?
@_value = val
else
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{value}'"
"Number.coffee"
)
###########################################################################################
# PRIVATE METHODS
###########################################################################################
# PROTECTED METHODS
###########################################################################################
# PUBLIC METHODS
########################################################
# IMPLEMENTING COMPARABLE
# see AbstractNumber
# END - IMPLEMENTING COMPARABLE
########################################################
# IMPLEMENTING BASIC OPERATIONS
# see AbstractNumber
# END - IMPLEMENTING BASIC OPERATIONS
# EVALUABLE INTERFACE
eval: (values) ->
return @
# TODO: intercept destructor
# .....
_getSet: () ->
return new mathJS.Set(@)
in: (set) ->
return set.contains(@)
valueOf: @::_getValue
# end js/Numbers/Number.coffee
# from js/Numbers/Double.coffee
class mathJS.Double extends mathJS.Number
# end js/Numbers/Double.coffee
# from js/Numbers/Int.coffee
###*
* @class Int
* @constructor
* @param {Number} value
* @extends Number
*###
class mathJS.Int extends mathJS.Number
###########################################################################
# STATIC
@parse: (str) ->
if mathJS.isNum(parsed = parseInt(str, 10))
return @_fromPool parsed
return parsed
@random: (max, min) ->
return @_fromPool mathJS.randInt(max, min)
@getSet: () ->
return mathJS.Domains.N
###*
* @Override mathJS.Poolable
* @static
* @protected
* @method _fromPool
*###
@_fromPool: (value) ->
if @_pool.length > 0
if (val = @_getPrimitiveInt(value))?
number = @_pool.pop()
number.value = val.value or val
return number
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{value}'"
"Int.coffee"
undefined
value
)
# param check is done in constructor
return new @(value)
@_getPrimitiveInt: (param, skipCheck) ->
if skipCheck is true
return param
if param instanceof mathJS.Int
return param.value
if param instanceof mathJS.Number
return ~~param.value
if param instanceof Number
return ~~param.valueOf()
if mathJS.isNum(param)
return ~~param
return null
###########################################################################
# CONSTRUCTOR
constructor: (value) ->
super(value)
if (val = @_getPrimitiveInt(value))?
@_value = val
else
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate integer from given '#{value}'"
"Int.coffee"
)
###########################################################################
# PRIVATE METHODS
###########################################################################
# PROTECTED METHODS
_getPrimitiveInt: (param) ->
return @constructor._getPrimitiveInt(param)
###########################################################################
# PUBLIC METHODS
isEven: () ->
return @value %% 2 is 0
isOdd: () ->
return @value %% 2 is 1
toInt: () ->
return mathJS.Int._fromPool @value
getSet: () ->
return mathJS.Domains.N
# end js/Numbers/Int.coffee
# from js/Numbers/Fraction.coffee
class mathJS.Fraction extends mathJS.Number
###*
* @Override mathJS.Number
* @static
* @method _fromPool
*###
@_fromPool: (numerator, denominator) ->
if @_pool.length > 0
if (e = @_getPrimitiveFrac(numerator))? and (d = @_getPrimitiveFrac(denominator))?
frac = @_pool.pop()
frac.numerator = e
frac.denominator = d
return frac
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate fraction from given '#{numerator}, #{denominator}'"
"Fraction.coffee"
)
else
# param check is done in constructor
return new @(numerator, denominator)
###*
* This method parses strings of the form "x / y" or "x : y".
* @Override mathJS.Number
* @static
* @method parse
*###
@parse: (str) ->
if "/" in str
parts = str.split "/"
return @new parts.first, parts.second
num = parseFloat(str)
if not isNaN(num)
# TODO
numerator = num
denominator = 1
# 123.456 = 123456 / 1000
while numerator % 1 isnt 0
numerator *= 10
denominator *= 10
return @new(numerator, denominator)
throw new mathJS.Errors.NotParseableError("Can't parse '#{str}' as fraction!")
###*
* @Override mathJS.Number
* @static
* @method getSet
*###
@getSet: () ->
return mathJS.Domains.Q
###*
* @Override mathJS.Number
* @static
* @method new
*###
@new: (e, d) ->
return @_fromPool e, d
@_getPrimitiveFrac: (param, skipCheck) ->
return mathJS.Int._getPrimitiveInt(param, skipCheck)
###########################################################################
# CONSTRUCTOR
constructor: (numerator, denominator) ->
@_numerator = null
@_denominator = null
Object.defineProperties @, {
numerator:
get: () ->
return @_numerator
set: @_setValue
denominator:
get: () ->
return @_denominator
set: @_setValue
}
if (e = @_getPrimitiveFrac(numerator))? and (d = @_getPrimitiveFrac(denominator))?
# TODO: when sth. like 12.55 / 0.8 is given => create 12.55*100 / 0.8*100 = 1255 / 80
if d is 0
throw new mathJS.Error.DivisionByZeroError("Denominator is 0 (when creating fraction)!")
@_numerator = e
@_denominator = d
else
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate fraction from given '#{numerator}, #{denominator}'"
"Fraction.coffee"
)
############################################################################################
# PROTECTED METHODS
_getPrimitiveFrac: (param) ->
return @constructor._getPrimitiveFrac(param)
############################################################################################
# PUBLIC METHODS
# end js/Numbers/Fraction.coffee
# from js/Numbers/Complex.coffee
###*
* @abstract
* @class Complex
* @constructor
* @param {Number} real
* Real part of the number. Either a mathJS.Number or primitive number.
* @param {Number} image
* Real part of the number. Either a mathJS.Number or primitive number.
* @extends Number
*###
# TODO: maybe extend mathJS.Vector instead?! or mix them
class mathJS.Complex extends mathJS.Number
PARSE_KEY = "0c"
###########################################################################
# STATIC
# ###*
# * @Override
# *###
# @_valueIsValid: (value) ->
# return value instanceof mathJS.Number or mathJS.isNum(value)
###*
* @Override
* This method creates an object with the keys "real" and "img" which have primitive numbers as their values.
* @static
* @method _getValueFromParam
* @param {Complex|Number} real
* @param {Number} img
* @return {Object}
*###
@_getValueFromParam: (real, img) ->
if real instanceof mathJS.Complex
return {
real: real.real
img: real.img
}
if real instanceof mathJS.Number and img instanceof mathJS.Number
return {
real: real.value
img: img.value
}
if mathJS.isNum(real) and mathJS.isNum(img)
return {
real: real
img: img
}
return null
@_fromPool: (real, img) ->
if @_pool.length > 0
if @_valueIsValid(real) and @_valueIsValid(img)
number = @_pool.pop()
number.real = real
number.img = img
return number
return null
else
return new @(real, img)
@parse: (str) ->
idx = str.toLowerCase().indexOf(PARSE_KEY)
if idx >= 0
parts = str.substring(idx + PARSE_KEY.length).split ","
if mathJS.isNum(real = parseFloat(parts[0])) and mathJS.isNum(img = parseFloat(parts[1]))
return @_fromPool real, img
return NaN
@random: (max1, min1, max2, min2) ->
return @_fromPool mathJS.randNum(max1, min1), mathJS.randNum(max2, min2)
###########################################################################
# CONSTRUCTOR
constructor: (real, img) ->
values = @_getValueFromParam(real, img)
# if not values?
# fStr = arguments.callee.caller.toString()
# throw new Error("mathJS: Expected 2 numbers or a complex number! Given (#{real}, #{img}) in \"#{fStr.substring(0, fStr.indexOf(")") + 1)}\"")
Object.defineProperties @, {
real:
get: @_getReal
set: @_setReal
img:
get: @_getImg
set: @_setImg
_fromPool:
value: @constructor._fromPool.bind(@constructor)
writable: false
enumarable: false
configurable: false
}
@real = values.real
@img = values.img
###########################################################################
# PRIVATE METHODS
###########################################################################
# PROTECTED METHODS
_setReal: (value) ->
if @_valueIsValid(value)
@_real = value.value or value.real or value
return @
_getReal: () ->
return @_real
_setImg: (value) ->
if @_valueIsValid(value)
@_img = value.value or value.img or value
return @
_getImg: () ->
return @_img
_getValueFromParam: @_getValueFromParam
###########################################################################
# PUBLIC METHODS
###*
* This method check for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2)
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @real is values.real and @img is values.img
return false
plus: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real + values.real, @img + values.img)
return NaN
increase: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
@real += values.real
@img += values.img
return @
plusSelf: @increase
minus: (n) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real - values.real, @img - values.img)
return NaN
decrease: (n) ->
values = @_getValueFromParam(r, i)
if values?
@real -= values.real
@img -= values.img
return @
minusSelf: @decrease
# TODO: adjust last functions for complex numbers
times: (r, i) ->
# return @_fromPool(@value * _getValueFromParam(n))
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real * values.real, @img * values.img)
return NaN
timesSelf: (n) ->
@value *= _getValueFromParam(n)
return @
divide: (n) ->
return @_fromPool(@value / _getValueFromParam(n))
divideSelf: (n) ->
@value /= _getValueFromParam(n)
return @
square: () ->
return @_fromPool(@value * @value)
squareSelf: () ->
@value *= @value
return @
cube: () ->
return @_fromPool(@value * @value * @value)
squareSelf: () ->
@value *= @value * @value
return @
sqrt: () ->
return @_fromPool(mathJS.sqrt @value)
sqrtSelf: () ->
@value = mathJS.sqrt @value
return @
pow: (n) ->
return @_fromPool(mathJS.pow @value, _getValueFromParam(n))
powSelf: (n) ->
@value = mathJS.pow @value, _getValueFromParam(n)
return @
sign: () ->
return mathJS.sign @value
toInt: () ->
return mathJS.Int._fromPool mathJS.floor(@value)
toDouble: () ->
return mathJS.Double._fromPool @value
toString: () ->
return "#{PARSE_KEY}#{@real.toString()},#{@img.toString()}"
clone: () ->
return @_fromPool(@value)
# add instance to pool
release: () ->
@constructor._pool.push @
return @constructor
# end js/Numbers/Complex.coffee
# from js/Algorithms/ShuntingYard.coffee
# from http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
class mathJS.Algorithms.ShuntingYard
CLASS = @
@specialOperators =
# unary plus/minus
"+" : "#"
"-" : "_"
@init = () ->
@specialOperations =
"#": mathJS.Operations.neutralPlus
"_": mathJS.Operations.negate
constructor: (settings) ->
@ops = ""
@precedence = {}
@associativity = {}
for op, opSettings of settings
@ops += op
@precedence[op] = opSettings.precedence
@associativity[op] = opSettings.associativity
isOperand = (token) ->
return mathJS.isNum(token)
toPostfix: (str) ->
# remove spaces
str = str.replace /\s+/g, ""
# make implicit multiplication explicit (3x=> 3*x, xy => x*y)
# TODO: what if a variable/function has more than 1 character: 3*abs(-3)
str = str.replace /(\d+|\w)(\w)/g,"$1*$2"
stack = []
ops = @ops
precedence = @precedence
associativity = @associativity
postfix = ""
# set string property to indicate format
postfix.postfix = true
for token, i in str
# if token is an operator
if token in ops
o1 = token
o2 = stack.last()
# handle unary plus/minus => just add special char
if i is 0 or prevToken is "("
if CLASS.specialOperators[token]?
postfix += "#{CLASS.specialOperators[token]} "
else
# while operator token, o2, on top of the stack
# and o1 is left-associative and its precedence is less than or equal to that of o2
# (the algorithm on wikipedia says: or o1 precedence < o2 precedence, but I think it should be)
# or o1 is right-associative and its precedence is less than that of o2
while o2 in ops and (associativity[o1] is "left" and precedence[o1] <= precedence[o2]) or (associativity[o1] is "right" and precedence[o1] < precedence[o2])
# add o2 to output queue
postfix += "#{o2} "
# pop o2 of the stack
stack.pop()
# next round
o2 = stack.last()
# push o1 onto the stack
stack.push(o1)
# if token is left parenthesis
else if token is "("
# then push it onto the stack
stack.push(token)
# if token is right parenthesis
else if token is ")"
# until token at top is (
while stack.last() isnt "("
postfix += "#{stack.pop()} "
# pop (, but not onto the output queue
stack.pop()
# token is an operand or a variable
else
postfix += "#{token} "
prevToken = token
# console.log token, stack
while stack.length > 0
postfix += "#{stack.pop()} "
return postfix.trim()
toExpression: (str) ->
if not str.postfix?
postfix = @toPostfix(str)
else
postfix = str
postfix = postfix.split " "
# gather all operators
ops = @ops
for k, v of CLASS.specialOperators
ops += v
i = 0
# while expression tree is not complete
while postfix.length > 1
token = postfix[i]
idxOffset = 0
if token in ops
if (op = mathJS.Operations[token])
startIdx = i - op.arity
endIdx = i
else if (op = CLASS.specialOperations[token])
startIdx = i + 1
endIdx = i + op.arity + 1
idxOffset = -1
params = postfix.slice(startIdx, endIdx)
startIdx += idxOffset
# # convert parameter strings to mathJS objects
for param, j in params when typeof param is "string"
if isOperand(param)
params[j] = new mathJS.Expression(parseFloat(param))
else
params[j] = new mathJS.Variable(param)
# create expression from parameters
exp = new mathJS.Expression(op, params...)
# this expression replaces the operation and its parameters
postfix.splice(startIdx, params.length + 1, exp)
# reset i to the first replaced element index -> increase in next iteration -> new element
i = startIdx + 1
# constants
else if isOperand(token)
postfix[i++] = new mathJS.Expression(parseFloat(token))
# variables
else
postfix[i++] = new mathJS.Variable(token)
return postfix.first
# end js/Algorithms/ShuntingYard.coffee
# from js/Formals/Operation.coffee
class mathJS.Operation
constructor: (name, precedence, associativity="left", commutative, func, inverse, setEquivalent) ->
@name = name
@precedence = precedence
@associativity = associativity
@commutative = commutative
@func = func
@arity = func.length # number of parameters => unary, binary, ternary...
@inverse = inverse or null
@setEquivalent = setEquivalent or null
eval: (args) ->
return @func.apply(@, args)
invert: () ->
if @inverse?
return @inverse.apply(@, arguments)
return null
# ABSTRACT OPERATIONS
# Those functions make sure primitives are converted correctly and calls the according operation on it"s first argument.
# They are the actual functions of the operations.
# TODO: no DRY
mathJS.Abstract =
Operations:
# arithmetical
divide: (x, y) ->
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
return x.divide(y)
minus: (x, y) ->
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
return x.minus(y)
plus: (x, y) ->
# numbers -> convert to mathJS.Number
# => int to real
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
# else if x instanceof mathJS.Variable or y instanceof mathJS.Variable
# return new mathJS.Expression(mathJS.Operations.plus, x, y)
# else if x.plus?
# return x.plus(y)
return x.plus(y)
# throw new mathJS.Errors.InvalidParametersError("...")
times: (x, y) ->
# numbers -> convert to mathJS.Number
# => int to real
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
return x.times(y)
negate: (x) ->
if mathJS.Number.valueIsValid(x)
x = new mathJS.Number(x)
return x.negate()
unaryPlus: (x) ->
if mathJS.Number.valueIsValid(x)
x = new mathJS.Number(x)
return x.clone()
# boolean / logical (converting from primitives to numbers doesn"t make sense because 3 and 4 is not defined)
and: (x, y) ->
return x.and(y)
or: (x, y) ->
return x.or(y)
not: (x) ->
return x.not()
nand: (x, y) ->
return x.nand(y)
nor: (x, y) ->
return x.nor(y)
xor: (x, y) ->
return x.xor(y)
equals: (x, y) ->
return x.equals(y)
###
PRECEDENCE (top to bottom):
(...)
factorial
unary +/-
exponents, roots
multiplication, division
addition, subtraction
###
cached =
division: new mathJS.Operation(
"divide"
1
"left"
false
mathJS.pow
mathJS.root
)
addition: new mathJS.Operation(
"plus"
1
"left"
true
mathJS.Abstract.Operations.plus
mathJS.Abstract.Operations.minus
)
subtraction: new mathJS.Operation(
"plus"
1
"left"
false
mathJS.Abstract.Operations.minus
mathJS.Abstract.Operations.plus
)
multiplication: new mathJS.Operation(
"times"
1
"left"
true
mathJS.Abstract.Operations.times
mathJS.Abstract.Operations.divide
)
exponentiation: new mathJS.Operation(
"pow"
1
"right"
false
mathJS.pow
mathJS.root
)
factorial: new mathJS.Operation(
"factorial"
10
"right"
false
mathJS.factorial
mathJS.factorialInverse
)
negate: new mathJS.Operation(
"negate"
11
"none"
false
mathJS.Abstract.Operations.negate
mathJS.Abstract.Operations.negate
)
unaryPlus: new mathJS.Operation(
"unaryPlus"
11
"none"
false
mathJS.Abstract.Operations.unaryPlus
mathJS.Abstract.Operations.unaryPlus
)
and: new mathJS.Operation(
"and"
1
"left"
true
mathJS.Abstract.Operations.and
null
"intersection"
)
or: new mathJS.Operation(
"or"
1
"left"
true
mathJS.Abstract.Operations.or
null
"union"
)
not: new mathJS.Operation(
"not"
5
"none"
false
mathJS.Abstract.Operations.not
mathJS.Abstract.Operations.not
"complement"
)
nand: new mathJS.Operation(
"nand"
1
"left"
true
mathJS.Abstract.Operations.nand
null
)
nor: new mathJS.Operation(
"nor"
1
"left"
true
mathJS.Abstract.Operations.nor
null
)
xor: new mathJS.Operation(
"xor"
1
"left"
true
mathJS.Abstract.Operations.xor
null
)
equals: new mathJS.Operation(
"equals"
1
"left"
true
mathJS.Abstract.Operations.equals
null
"intersection"
)
mathJS.Operations =
# arithmetical
"+": cached.addition
"plus": cached.addition
"-": cached.subtraction
"minus": cached.subtraction
"*": cached.multiplication
"times": cached.multiplication
"/": cached.division
":": cached.division
"divide": cached.division
"^": cached.exponentiation
"pow": cached.exponentiation
"!": cached.factorial
"negate": cached.negate
"-u": cached.negate
"u-": cached.negate
"unaryMinus": cached.negate
"neutralMinus": cached.negate
"+u": cached.unaryPlus
"u+": cached.unaryPlus
"unaryPlus": cached.unaryPlus
"neutralPlus": cached.unaryPlus
# logical
"and": cached.and
"or": cached.or
"not": cached.not
"nand": cached.nand
"nor": cached.nor
"xor": cached.xor
"equals": cached.equals
"=": cached.equals
"xnor": cached.equals
# end js/Formals/Operation.coffee
# from js/Formals/Expression.coffee
###*
* Tree structure of expressions. It consists of 2 expression and 1 operation.
* @class Expression
* @constructor
* @param operation {Operation|String}
* @param expressions... {Expression}
*###
class mathJS.Expression
CLASS = @
@fromString: (str) ->
# TODO: parse string
return new mathJS.Expression()
@parse = @fromString
@parser = new mathJS.Algorithms.ShuntingYard(
# TODO: use operations from operation class
"!":
precedence: 5
associativity: "right"
"^":
precedence: 4
associativity: "right"
"*":
precedence: 3
associativity: "left"
"/":
precedence: 3
associativity: "left"
"+":
precedence: 2
associativity: "left"
"-":
precedence: 2
associativity: "left"
)
# TODO: make those meaningful: eg. adjusted parameter lists?!
@new: (operation, expressions...) ->
return new CLASS(operation, expressions)
constructor: (operation, expressions...) ->
# map op string to actual operation object
if typeof operation is "string"
if mathJS.Operations[operation]?
operation = mathJS.Operations[operation]
else
throw new mathJS.Errors.InvalidParametersError("Invalid operation string given: \"#{operation}\".")
# if constructor was called from static .new()
if expressions.first instanceof Array
expressions = expressions.first
# just 1 parameter => constant/value or hash given
if expressions.length is 0
# constant/variable value given => leaf in expression tree
if mathJS.Number.valueIsValid(operation)
@operation = null
@expressions = [new mathJS.Number(operation)]
else
if operation instanceof mathJS.Variable
@operation = null
@expressions = [operation]
# variable string. eg. "x"
else
@operation = null
@expressions = [new mathJS.Variable(operation)]
# else
# throw new mathJS.Errors.InvalidParametersError("...")
else if operation.arity is expressions.length
@operation = operation
@expressions = expressions
else
throw new mathJS.Errors.InvalidArityError("Invalid number of parameters (#{expressions.length}) for Operation \"#{operation.name}\". Expected number of parameters is #{operation.arity}.")
###*
* This method tests for the equality of structure. So 2*3x does not equal 6x!
* For that see mathEquals().
* @method equals
*###
equals: (expression) ->
# immediate return if different number of sub expressions
if @expressions.length isnt expression.expressions.length
return false
# leaf -> anchor
if not @operation?
return not expression.operation? and expression.expressions.first.equals(@expressions.first)
# order of expressions doesnt matter
if @operation.commutative is true
doneExpressions = []
for exp, i in @expressions
res = false
for x, j in expression.expressions when j not in doneExpressions and x.equals(exp)
doneExpressions.push j
res = true
break
# exp does not equals any of the expressions => return false
if not res
return false
return true
# order of expressions matters
else
# res = true
for e1, i in @expressions
e2 = expression.expressions[i]
# res = res and e1.equals(e2)
if not e1.equals(e2)
return false
# return res
return true
###*
* This method tests for the logical/mathematical equality of 2 expressions.
*###
# TODO: change naming here! equals should always be mathematical!!!
mathEquals: (expression) ->
return @simplify().equals expression.simplify()
###*
* @method eval
* @param values {Object}
* An object of the form {varKey: varVal}.
* @returns The value of the expression (specified by the values).
*###
eval: (values) ->
# replace primitives with mathJS objects
for k, v of values
if mathJS.isPrimitive(v) and mathJS.Number.valueIsValid(v)
values[k] = new mathJS.Number(v)
# leaf => first expression is either a mathJS.Variable or a constant (-> Number)
if not @operation?
return @expressions.first.eval(values)
# no leaf => eval substrees
args = []
for expression in @expressions
# evaluated expression is a variable => stop because this and the "above" expression cant be evaluated further
value = expression.eval(values)
if value instanceof mathJS.Variable
return @
# evaluation succeeded => add to list of evaluated values (which will be passed to the operation)
args.push value
return @operation.eval(args)
simplify: () ->
# simplify numeric values aka. non-variable arithmetics
evaluated = @eval()
# actual simplification: less ops!
# TODO: gather simplification patterns
return @
getVariables: () ->
if not @operation?
if (val = @expressions.first) instanceof mathJS.Variable
return [val]
return []
res = []
for expression in @expressions
res = res.concat expression.getVariables()
return res
_getSet: () ->
# leaf
if not @operation?
return @expressions.first._getSet()
# no leaf
res = null
for expression in @expressions
if res?
res = res[@operation.setEquivalent] expression._getSet()
else
res = expression._getSet()
# TODO: the "or new mathJS.Set()" should be unnecessary
return res or new mathJS.Set()
###*
* Get the "range" of the expression (the set of all possible results).
* @method getSet
*###
getSet: () ->
return @eval()._getSet()
# MAKE ALIASES
evaluatesTo: @::getSet
if DEBUG
@test = () ->
e1 = new CLASS(5)
e2 = new CLASS(new mathJS.Variable("x", mathJS.Number))
e4 = new CLASS("+", e1, e2)
console.log e4.getVariables()
# console.log e4.eval({x: new mathJS.Number(5)})
# console.log e4.eval()
# e5 = e4.eval()
# console.log e5.eval({x: new mathJS.Number(5)})
str = "(5x - 3) ^ 2 * 2 / (4y + 3!)"
# (5x-3)^2 * 2 / (4y + 6)
return "test done"
# end js/Formals/Expression.coffee
# from js/Formals/Variable.coffee
###*
* @class Variable
* @constructor
* @param {String} name
* This is name name of the variable (mathematically)
* @param {mathJS.Set} type
*###
# TODO: make interfaces meta: eg. have a Variable@Evaluable.coffee file that contains the interface and inset on build
# class mathJS.Variable extends mathJS.Evaluable
class mathJS.Variable extends mathJS.Expression
# TODO: change this to mathJS.Domains.R when R is implemented
constructor: (name, elementOf=mathJS.Domains.N) ->
@name = name
if elementOf.getSet?
@elementOf = elementOf.getSet()
else
@elementOf = elementOf
_getSet: () ->
return @elementOf
equals: (variable) ->
return @name is variable.name and @elementOf.equals variable.elementOf
plus: (n) ->
return new mathJS.Expression("+", @, n)
minus: (n) ->
return new mathJS.Expression("-", @, n)
times: (n) ->
return new mathJS.Expression("*", @, n)
divide: (n) ->
return new mathJS.Expression("/", @, n)
eval: (values) ->
if values? and (val = values[@name])?
if @elementOf.contains val
return val
console.warn "Given value \"#{val}\" is not in the set \"#{@elementOf.name}\"."
return @
# end js/Formals/Variable.coffee
# from js/Formals/Equation.coffee
class mathJS.Equation
constructor: (left, right) ->
# if left.mathEquals(right)
# @left = left
# @right = right
# else
# # TODO: only if no variables are contained
# throw new mathJS.Errors.InvalidParametersError("The 2 expressions are not (mathematically) equal!")
@left = left
@right = right
solve: (variable) ->
left = @left.simplify()
right = @right.simplify()
solutions = new mathJS.Set()
# convert to actual variable if only the name was given
if variable not instanceof mathJS.Variable
variables = left.getVariables().concat right.getVariables()
variable = (v for v in variables when v.name is variable).first
return solutions
eval: (values) ->
return @left.eval(values).equals @right.eval(values)
simplify: () ->
@left = @left.simplify()
@right = @right.simplify()
return @
# MAKE ALIASES
# ...
# end js/Formals/Equation.coffee
# from js/Sets/AbstractSet.coffee
class _mathJS.AbstractSet extends _mathJS.Object
@implements _mathJS.Orderable, _mathJS.Poolable, _mathJS.Parseable
@fromString: (str) ->
@parse: () ->
return @fromString.apply(@, arguments)
cartesianProduct: (set) ->
clone: () ->
contains: (elem) ->
equals: (set) ->
getElements: () ->
infimum: () ->
intersection: (set) ->
isSubsetOf: (set) ->
min: () ->
max: () ->
# PRE-IMPLEMENTED (may be inherited)
size: () ->
return Infinity
supremum: () ->
union: (set) ->
intersection: (set) ->
without: (set) ->
###########################################################################
# PRE-IMPLEMENTED (to be inherited)
complement: (universe) ->
return universe.minus(@)
disjoint: (set) ->
return @intersection(set).size() is 0
intersects: (set) ->
return not @disjoint(set)
isEmpty: () ->
return @size() is 0
isSupersetOf: (set) ->
return set.isSubsetOf @
pow: (exponent) ->
sets = []
for i in [0...exponent]
sets.push @
return @cartesianProduct.apply(@, sets)
###########################################################################
# ALIASES
@_makeAliases: () ->
aliasesData =
size: ["cardinality"]
without: ["difference", "except", "minus"]
contains: ["has"]
intersection: ["intersect"]
isSubsetOf: ["subsetOf"]
isSupersetOf: ["supersetOf"]
cartesianProduct: ["times"]
for orig, aliases of aliasesData
for alias in aliases
@::[alias] = @::[orig]
return @
@_makeAliases()
# end js/Sets/AbstractSet.coffee
# from js/Sets/Set.coffee
###*
* @class Set
* @constructor
* @param {mixed} specifications
* To create an empty set pass no parameters.
* To create a discrete set list the elements. Those elements must implement the comparable interface and must not be arrays. Non-comparable elements will be ignored unless they are primitives.
* To create a set from set-builder notation pass the parameters must have the following types:
* mathJS.Expression|mathJS.Tuple|mathJS.Number, mathJS.Predicate
# TODO: package all those types (expression-like) into 1 prototype (Variable already is)
*###
class mathJS.Set extends _mathJS.AbstractSet
###########################################################################
# STATIC
###*
* Optionally the left and right configuration can be passed directly (each with an open- and value-property) or the Interval can be parsed from String (like "(2, 6 ]").
* @static
* @method createInterval
* @param leftOpen {Boolean}
* @param leftValue {Number|mathJS.Number}
* @param rightValue {Number|mathJS.Number}
* @param rightOpen {Boolean}
*###
@createInterval: (parameters...) ->
if typeof (str = parameters.first) is "string"
# remove spaces
str = str.replace /\s+/g, ""
.split ","
left =
open: str.first[0] is "("
value: new mathJS.Number(parseInt(str.first.slice(1), 10))
right =
open: str.second.last is ")"
value: new mathJS.Number(parseInt(str.second.slice(0, -1), 10))
# # first parameter has an .open property => assume ctor called from fromString()
# else if parameters.first.open?
# left = parameters.first
# right = parameters.second
else
second = parameters.second
fourth = parameters.fourth
left =
open: parameters.first
value: (if second instanceof mathJS.Number then second else new mathJS.Number(second))
right =
open: parameters.third
value: (if fourth instanceof mathJS.Number then fourth else new mathJS.Number(fourth))
# an interval can be expressed with a conditional set: (a,b) = {x | x in R, a < x < b}
expression = new mathJS.Variable("x", mathJS.Domains.N)
predicate = null
return new mathJS.Set(expression, predicate)
###########################################################################
# CONSTRUCTOR
constructor: (parameters...) ->
# ANALYSE PARAMETERS
# nothing passed => empty set
if parameters.length is 0
@discreteSet = new _mathJS.DiscreteSet()
@conditionalSet = new _mathJS.ConditionalSet()
# discrete and conditional set given (from internal calls like union())
else if parameters.first instanceof _mathJS.DiscreteSet and parameters.second instanceof _mathJS.ConditionalSet
@discreteSet = parameters.first
@conditionalSet = parameters.second
# set-builder notation
else if parameters.first instanceof mathJS.Expression and parameters.second instanceof mathJS.Expression
console.log "set builder"
@discreteSet = new _mathJS.DiscreteSet()
@conditionalSet = new _mathJS.ConditionalSet(parameters.first, parameters.slice(1))
# discrete set
else
# array given -> make its elements the set elements
if parameters.first instanceof Array
parameters = parameters.first
console.log "params:", parameters
@discreteSet = new _mathJS.DiscreteSet(parameters)
@conditionalSet = new _mathJS.ConditionalSet()
###########################################################################
# PRIVATE METHODS
# TODO: inline the following 2 if used nowhere else
newFromDiscrete = (set) ->
return new mathJS.Set(set.getElements())
newFromConditional = (set) ->
return new mathJS.Set(set.expression, set.domains, set.predicate)
###########################################################################
# PROTECTED METHODS
###########################################################################
# PUBLIC METHODS
getElements: (n=mathJS.config.set.defaultNumberOfElements, sorted=false) ->
res = @discreteSet.elems.concat(@conditionalSet.getElements(n, sorted))
if sorted isnt true
return res
return res.sort(mathJS.sortFunction)
size: () ->
return @discreteSet.size() + @conditionalSet.size()
clone: () ->
return newFromDiscrete(@discreteSet).union(newFromConditional(@conditionalSet))
equals: (set) ->
if set.size() isnt @size()
return false
return set.discreteSet.equals(@discreteSet) and set.conditionalSet.equals(@conditionalSet)
getSet: () ->
return @
isSubsetOf: (set) ->
return @conditionalSet.isSubsetOf(set) or @discreteSet.isSubsetOf(set)
isSupersetOf: (set) ->
return @conditionalSet.isSupersetOf(set) or @discreteSet.isSupersetOf(set)
contains: (elem) ->
return @conditionalSet.contains(@conditionalSet) or @discreteSet.contains(@discreteSet)
union: (set) ->
# if domain (N, Z, Q, R, C) let it handle the union because it knows know more about itself than this does
# also domains have neither discrete nor conditional sets
if set.isDomain
return set.union(@)
return new mathJS.Set(@discreteSet.union(set.discreteSet), @conditionalSet.union(set.conditionalSet))
intersection: (set) ->
if set.isDomain
return set.intersection(@)
return new mathJS.Set(@discreteSet.intersection(set.discreteSet), @conditionalSet.intersection(set.conditionalSet))
complement: () ->
if @universe?
return asdf
return new mathJS.EmptySet()
without: (set) ->
cartesianProduct: (set) ->
min: () ->
return mathJS.min(@discreteSet.min().concat @conditionalSet.min())
max: () ->
return mathJS.max(@discreteSet.max().concat @conditionalSet.max())
infimum: () ->
supremum: () ->
# end js/Sets/Set.coffee
# from js/Sets/DiscreteSet.coffee
###*
* This class is a Setof explicitely listed elements (with no needed logic).
* @class DiscreteSet
* @constructor
* @param {Function|Class} type
* @param {Set} universe
* Optional. If given, the created Set will be interpreted as a sub set of the universe.
* @param {mixed} elems...
* Optional. This and the following parameters serve as elements for the new Set. They will be in the new Set immediately.
* @extends Set
*###
class _mathJS.DiscreteSet extends mathJS.Set
###########################################################################
# CONSTRUCTOR
constructor: (elems...) ->
if elems.first instanceof Array
elems = elems.first
@elems = []
for elem in elems when not @contains(elem)
if not mathJS.isNum(elem)
@elems.push elem
else
@elems.push new mathJS.Number(elem)
###########################################################################
# PROTECTED METHODS
###########################################################################
# PUBLIC METHODS
# discrete sets only!
cartesianProduct: (set) ->
elements = []
for e in @elems
for x in set.elems
elements.push new mathJS.Tuple(e, x)
return new _mathJS.DiscreteSet(elements)
clone: () ->
return new _mathJS.DiscreteSet(@elems)
contains: (elem) ->
for e in @elems when elem.equals e
return true
return false
# discrete sets only!
equals: (set) ->
# return @isSubsetOf(set) and set.isSubsetOf(@)
for e in @elems when not set.contains e
return false
for e in set.elems when not @contains e
return false
return true
###*
* Get the elements of the set.
* @method getElements
* @param sorted {Boolean}
* Optional. If set to `true` returns the elements in ascending order.
*###
getElements: (sorted) ->
if sorted isnt true
return @elems.clone()
return @elems.clone().sort(mathJS.sortFunction)
# discrete sets only!
intersection: (set) ->
elems = []
for x in @elems
for y in set.elems when x.equals y
elems.push x
return new _mathJS.DiscreteSet(elems)
isSubsetOf: (set) ->
for e in @elems when not set.contains e
return false
return true
size: () ->
# TODO: cache size
return @elems.length
# discrete sets only!
union: (set) ->
return new _mathJS.DiscreteSet(set.elems.concat(@elems))
without: (set) ->
return (elem for elem in @elems when not set.contains elem)
min: () ->
return mathJS.min @elems
max: () ->
return mathJS.max @elems
infimum: () ->
supremum: () ->
@_makeAliases()
# end js/Sets/DiscreteSet.coffee
# from js/Sets/ConditionalSet.coffee
class _mathJS.ConditionalSet extends mathJS.Set
CLASS = @
###
{2x^2 | x in R and 0 <= x < 20 and x = x^2} ==> {0, 1}
x in R and 0 <= x < 20 and x = x^2 <=> R intersect [0, 20) intersect {0,1} (where 0 and 1 have to be part of the previous set)
do the following:
1. map domains to domains
2. map unequations to intervals
3. map equations to (discrete?!) sets
4. create intersection of all!
simplifications:
1. domains intersect interval = interval (because in this notation the domain is the superset)
so it wouldnt make sense to say: x in N and x in [0, 10] and expect the set to be infinite!!
the order does not matter (otherwise (x in [0, 10] and x in N) would be infinite!!)
2. when trying to get equation solutions numerically (should this ever happen??) look for interval first to get boundaries
###
# predicate is an boolean expression
# TODO: try to find out if the set is actually discrete!
# TODO: maybe a 3rd parameter "baseSet" should be passed to indicate where the generator comes from
# TODO: predicate could also be the base set itself. if not it must be derived from the (boolean) predicate
# TODO: predicate's type is Expression.Boolean
constructor: (expression, predicate) ->
# empty set
if arguments.length is 0
@generator = null
# non-empty set
else if expression instanceof mathJS.Generator
@generator = expression
# no generator passed => standard parameters
else
if predicate instanceof mathJS.Expression
predicate = predicate.getSet()
# f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple
@generator = new mathJS.Generator(
# f: predicate -> ?? (expression.getSet())
# x |-> expression(x)
new mathJS.Function("f", expression, predicate, expression.getSet())
predicate.min()
predicate.max()
)
cartesianProduct: (sets...) ->
generators = [@generator].concat(set.generator for set in sets)
return new _mathJS.ConditionalSet(mathJS.Generator.product(generators...))
clone: () ->
return new CLASS()
contains: (elem) ->
if mathJS.isComparable elem
if @condition?.check(elem) is true
return true
return false
equals: (set) ->
if set instanceof CLASS
return @generator.f.equals set.generator.f
# normal set
return set.discreteSet.isEmpty() and @generator.f.equals set.conditionSet.generator.f
getElements: (n, sorted) ->
res = []
# TODO
return res
# TODO: "and" generators
intersection: (set) ->
isSubsetOf: (set) ->
isSupersetOf: (set) ->
size: () ->
return @generator.f.range.size()
# TODO: "or" generators
union: (set) ->
without: (set) ->
@_makeAliases()
if DEBUG
@test = () ->
e1 = new mathJS.Expression(5)
e2 = new mathJS.Expression(new mathJS.Variable("x", mathJS.Number))
e3 = new mathJS.Expression("+", e1, e2)
p1 = new mathJS.Expression(new mathJS.Variable("x", mathJS.Number))
p2 = new mathJS.Expression(4)
p3 = new mathJS.Expression("=", p1, p2)
console.log p3.eval(x: 4)
console.log p3.getSet()
console.log AAA
# set = new _mathJS.ConditionalSet(e3, p3)
# console.log set
return "done"
# end js/Sets/ConditionalSet.coffee
# from js/Sets/Tuple.coffee
class mathJS.Tuple
###########################################################################
# CONSTRUCTOR
constructor: (elems...) ->
if elems.first instanceof Array
elems = elems.first
temp = []
for elem in elems
if not mathJS.isNum(elem)
temp.push elem
else
temp.push new mathJS.Number(elem)
@elems = temp
@_size = temp.length
###########################################################################
# PUBLIC METHODS
Object.defineProperties @::, {
first:
get: () ->
return @at(0)
set: () ->
return @
length:
get: () ->
return @_size
set: () ->
return @
}
add: (elems...) ->
return new mathJS.Tuple(@elems.concat(elems))
at: (idx) ->
return @elems[idx]
clone: () ->
return new mathJS.Tuple(@elems)
contains: (elem) ->
for e in @elems when e.equals elem
return true
return false
equals: (tuple) ->
if @_size isnt tuple._size
return false
elements = tuple.elems
for elem, idx in @elems when not elem.equals elements[idx]
return false
return true
###*
* Evaluates the tuple.
* @param values {Array}
* # TODO: also enables hash of vars
* A value for each tuple element.
*###
eval: (values) ->
elems = (elem.eval(values[i]) for elem, i in @elems)
return new mathJS.Tuple(elems)
###*
* Get the elements of the Tuple.
* @method getElements
*###
getElements: () ->
return @elems.clone()
insert: (idx, elems...) ->
elements = []
for elem, i in @elems
if i is idx
elements = elements.concat(elems)
elements.push elem
return new mathJS.Tuple(elements)
isEmpty: () ->
return @_size() is 0
###*
* Removes the first occurences of the given elements.
*###
remove: (elems...) ->
elements = @elems.clone()
for e in elems
for elem, i in elements when elem.equals e
elements.splice i, 1
break
return new mathJS.Tuple(elements)
removeAt: (idx, n=1) ->
elems = []
for elem, i in @elems when i < idx or i >= idx + n
elems.push elem
return new mathJS.Tuple(elems)
size: () ->
return @_size
slice: (startIdx, endIdx=@_size) ->
return new mathJS.Tuple(@elems.slice(startIdx, endIdx))
###########################################################################
# ALIASES
cardinality: @::size
extendBy: @::add
get: @::at
has: @::contains
addAt: @::insert
insertAt: @::insert
reduceBy: @::remove
# end js/Sets/Tuple.coffee
# from js/Sets/Function.coffee
class mathJS.Function extends mathJS.Set
# EQUAL!
# function:
# f: X -> Y, f(x) = 3x^2 - 5x + 7
# set:
# {(x, 3x^2 - 5x + 7) | x in X}
# domain is implicit by variables" types contained in the expression
# range is implicit by the expression
# constructor: (name, domain, range, expression) ->
constructor: (name, expression, domain, range) ->
@name = name
@expression = expression
if domain instanceof mathJS.Set
@domain = domain
else
@domain = new mathJS.Set(expression.getVariables())
if range instanceof mathJS.Set
@range = range
else
@range = expression.getSet()
@_cache = {}
@caching = true
super()
###*
* Empty the cache or reset to given cache.
* @method clearCache
* @param cache {Object}
* @return mathJS.Function
* @chainable
*###
clearCache: (cache) ->
if not cache?
@_cache = {}
else
@_cache = cache
return @
###*
* Evaluate the function for given values.
* @method get
* @param values {Array|Object}
* If an array the first value will be associated with the first variable name. Otherwise an object like {x: 42} is expected.
* @return
*###
eval: (values...) ->
tmp = {}
if values instanceof Array
for value, i in values
tmp[@variableNames[i]] = value
values = tmp
# check if values are in domain
for varName, val of values
if not domain.contains(val)
return null
return @expression.eval(values)
# make alias
at: @eval
get: @eval
# end js/Sets/Function.coffee
# from js/Sets/Generators/AbstractGenerator.coffee
class _mathJS.AbstractGenerator extends _mathJS.Object
###########################################################################
# CONSTRUCTOR
constructor: (f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple) ->
@f = f
@inverseF = f.getInverse()
@minX = minX
@maxX = maxX
@stepSize = stepSize
@maxIndex = maxIndex
@tuple = tuple
@x = minX
@overflowed = false
@index = 0
###########################################################################
# DEFINED PROPS
Object.defineProperties @::, {
function:
get: () ->
return @f
set: (f) ->
@f = f
@inverseF = f.getInverse()
return @
}
###########################################################################
# STATIC
@product: (generators...) ->
@or: (gen1, gen2) ->
@and: (gen1, gen2) ->
###########################################################################
# PUBLIC
###*
* Indicates whether the set the generator creates contains the given value or not.
* @method generates
*###
generates: (y) ->
if @f.range.contains(y)
#
if @inverseF?
return @inverseF.eval(y)
return
return false
eval: (n) ->
# eval each tuple element individually (the tuple knows how to do that)
if @tuple?
return @tuple.eval(n)
# eval expression
if @f.eval?
@f.eval(n)
# eval js function
return @f.call(@, n)
hasNext: () ->
if @tuple?
for g, i in @tuple.elems when g.hasNext()
return true
return false
return not @overflowed and @x < @maxX and @index < @maxIndex
_incX: () ->
@index++
# more calculation than just "@x += @stepSize" but more precise!
@x = @minX + @index * @stepSize
if @x > @maxX
@x = @minX
@index = 0
@overflowed = true
return @x
next: () ->
if @tuple?
res = @eval(g.x for g in @tuple.elems)
###
0 0
0 1
1 0
1 1
###
# start binary-like counting (so all possibilities are done)
i = 0
maxI = @tuple.length
generator = @tuple.first
generator._incX()
while i < maxI and generator.overflowed
generator.overflowed = false
generator = @tuple.at(++i)
# # "if" needed for very last value -> i should theoretically overflow
# => i refers to the (n+1)st tuple element (which only has n elements)
if generator?
generator._incX()
return res
# no tuple => simple generator
res = @eval(@x)
@_incX()
return res
reset: () ->
@x = @minX
@index = 0
return @
if DEBUG
@test = () ->
# simple
g = new mathJS.Generator(
(x) ->
return 3*x*x+2*x-5
-10
10
0.2
)
res = []
while g.hasNext()
tmp = g.next()
# console.log tmp
res.push tmp
tmp = g.next()
# console.log tmp
res.push tmp
console.log "simple test:", (if res.length is ((g.maxX - g.minX) / g.stepSize + 1) then "successful" else "failed")
# "nested"
g1 = new mathJS.Generator(
(x) -> x,
0,
5,
0.5
)
g2 = new mathJS.Generator(
(x) -> 2*x,
-2,
10,
2
)
g = mathJS.Generator.product(g1, g2)
res = []
while g.hasNext()
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
console.log "tuple test:", (if res.length is ((g1.maxX - g1.minX) / g1.stepSize + 1) * ((g2.maxX - g2.minX) / g2.stepSize + 1) then "successful" else "failed")
g = new mathJS.Generator((x) -> x)
while g.hasNext()
tmp = g.next()
# console.log tmp
tmp = g.next()
# console.log tmp
return "done"
# end js/Sets/Generators/AbstractGenerator.coffee
# from js/Sets/Generators/DiscreteGenerator.coffee
class mathJS.DiscreteGenerator extends _mathJS.AbstractGenerator
###########################################################################
# CONSTRUCTOR
constructor: (f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple) ->
@f = f
@inverseF = f.getInverse()
@minX = minX
@maxX = maxX
@stepSize = stepSize
@maxIndex = maxIndex
@tuple = tuple
@x = minX
@overflowed = false
@index = 0
###########################################################################
# DEFINED PROPS
Object.defineProperties @::, {
function:
get: () ->
return @f
set: (f) ->
@f = f
@inverseF = f.getInverse()
return @
}
###########################################################################
# STATIC
@product: (generators...) ->
return new mathJS.Generator(null, 0, Infinity, null, null, new mathJS.Tuple(generators))
@or: () ->
@and: () ->
###########################################################################
# PUBLIC
###*
* Indicates whether the set the generator creates contains the given value or not.
* @method generates
*###
generates: (y) ->
if @f.range.contains(y)
#
if @inverseF?
return @inverseF.eval(y)
return
return false
eval: (n) ->
# eval each tuple element individually (the tuple knows how to do that)
if @tuple?
return @tuple.eval(n)
# eval expression
if @f.eval?
@f.eval(n)
# eval js function
return @f.call(@, n)
hasNext: () ->
if @tuple?
for g, i in @tuple.elems when g.hasNext()
return true
return false
return not @overflowed and @x < @maxX and @index < @maxIndex
_incX: () ->
@index++
# more calculation than just "@x += @stepSize" but more precise!
@x = @minX + @index * @stepSize
if @x > @maxX
@x = @minX
@index = 0
@overflowed = true
return @x
next: () ->
if @tuple?
res = @eval(g.x for g in @tuple.elems)
###
0 0
0 1
1 0
1 1
###
# start binary-like counting (so all possibilities are done)
i = 0
maxI = @tuple.length
generator = @tuple.first
generator._incX()
while i < maxI and generator.overflowed
generator.overflowed = false
generator = @tuple.at(++i)
# # "if" needed for very last value -> i should theoretically overflow
# => i refers to the (n+1)st tuple element (which only has n elements)
if generator?
generator._incX()
return res
# no tuple => simple generator
res = @eval(@x)
@_incX()
return res
reset: () ->
@x = @minX
@index = 0
return @
if DEBUG
@test = () ->
# simple
g = new mathJS.Generator(
(x) ->
return 3*x*x+2*x-5
-10
10
0.2
)
res = []
while g.hasNext()
tmp = g.next()
# console.log tmp
res.push tmp
tmp = g.next()
# console.log tmp
res.push tmp
console.log "simple test:", (if res.length is ((g.maxX - g.minX) / g.stepSize + 1) then "successful" else "failed")
# "nested"
g1 = new mathJS.Generator(
(x) -> x,
0,
5,
0.5
)
g2 = new mathJS.Generator(
(x) -> 2*x,
-2,
10,
2
)
g = mathJS.Generator.product(g1, g2)
res = []
while g.hasNext()
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
console.log "tuple test:", (if res.length is ((g1.maxX - g1.minX) / g1.stepSize + 1) * ((g2.maxX - g2.minX) / g2.stepSize + 1) then "successful" else "failed")
g = new mathJS.Generator((x) -> x)
while g.hasNext()
tmp = g.next()
# console.log tmp
tmp = g.next()
# console.log tmp
return "done"
# end js/Sets/Generators/DiscreteGenerator.coffee
# from js/Sets/Generators/ContinuousGenerator.coffee
class mathJS.ContinuousGenerator extends _mathJS.AbstractGenerator
###########################################################################
# CONSTRUCTOR
constructor: (f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple) ->
@f = f
@inverseF = f.getInverse()
@minX = minX
@maxX = maxX
@stepSize = stepSize
@maxIndex = maxIndex
@tuple = tuple
@x = minX
@overflowed = false
@index = 0
###########################################################################
# DEFINED PROPS
Object.defineProperties @::, {
function:
get: () ->
return @f
set: (f) ->
@f = f
@inverseF = f.getInverse()
return @
}
###########################################################################
# STATIC
@product: (generators...) ->
return new mathJS.Generator(null, 0, Infinity, null, null, new mathJS.Tuple(generators))
@or: () ->
@and: () ->
###########################################################################
# PUBLIC
###*
* Indicates whether the set the generator creates contains the given value or not.
* @method generates
*###
generates: (y) ->
if @f.range.contains(y)
#
if @inverseF?
return @inverseF.eval(y)
return
return false
eval: (n) ->
# eval each tuple element individually (the tuple knows how to do that)
if @tuple?
return @tuple.eval(n)
# eval expression
if @f.eval?
@f.eval(n)
# eval js function
return @f.call(@, n)
hasNext: () ->
if @tuple?
for g, i in @tuple.elems when g.hasNext()
return true
return false
return not @overflowed and @x < @maxX and @index < @maxIndex
_incX: () ->
@index++
# more calculation than just "@x += @stepSize" but more precise!
@x = @minX + @index * @stepSize
if @x > @maxX
@x = @minX
@index = 0
@overflowed = true
return @x
next: () ->
if @tuple?
res = @eval(g.x for g in @tuple.elems)
###
0 0
0 1
1 0
1 1
###
# start binary-like counting (so all possibilities are done)
i = 0
maxI = @tuple.length
generator = @tuple.first
generator._incX()
while i < maxI and generator.overflowed
generator.overflowed = false
generator = @tuple.at(++i)
# # "if" needed for very last value -> i should theoretically overflow
# => i refers to the (n+1)st tuple element (which only has n elements)
if generator?
generator._incX()
return res
# no tuple => simple generator
res = @eval(@x)
@_incX()
return res
reset: () ->
@x = @minX
@index = 0
return @
if DEBUG
@test = () ->
# simple
g = new mathJS.Generator(
(x) ->
return 3*x*x+2*x-5
-10
10
0.2
)
res = []
while g.hasNext()
tmp = g.next()
# console.log tmp
res.push tmp
tmp = g.next()
# console.log tmp
res.push tmp
console.log "simple test:", (if res.length is ((g.maxX - g.minX) / g.stepSize + 1) then "successful" else "failed")
# "nested"
g1 = new mathJS.Generator(
(x) -> x,
0,
5,
0.5
)
g2 = new mathJS.Generator(
(x) -> 2*x,
-2,
10,
2
)
g = mathJS.Generator.product(g1, g2)
res = []
while g.hasNext()
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
console.log "tuple test:", (if res.length is ((g1.maxX - g1.minX) / g1.stepSize + 1) * ((g2.maxX - g2.minX) / g2.stepSize + 1) then "successful" else "failed")
g = new mathJS.Generator((x) -> x)
while g.hasNext()
tmp = g.next()
# console.log tmp
tmp = g.next()
# console.log tmp
return "done"
# end js/Sets/Generators/ContinuousGenerator.coffee
# from js/Sets/Domains/Domain.coffee
###*
* Domain ranks are like so:
* N -> 0
* Z -> 1
* Q -> 2
* I -> 2
* R -> 3
* C -> 4
* ==> union: take greater rank (if equal (and unequal names) take next greater rank)
* ==> intersection: take smaller rank (if equal (and unequal names) take empty set)
*###
class _mathJS.Sets.Domain extends _mathJS.AbstractSet
CLASS = @
@new: () ->
return new CLASS()
@_byRank: (rank) ->
for name, domain of mathJS.Domains when domain.rank is rank
return domain
return null
constructor: (name, rank, isCountable) ->
@isDomain = true
@name = name
@rank = rank
@isCountable = isCountable
clone: () ->
return @constructor.new()
size: () ->
return Infinity
equals: (set) ->
return set instanceof @constructor
intersection: (set) ->
if set.isDomain
if @name is set.name
return @
if @rank < set.rank
return @
if @rank > set.rank
return set
return new mathJS.Set()
# TODO !!
return false
union: (set) ->
if set.isDomain
if @name is set.name
return @
if @rank > set.rank
return @
if @rank < set.rank
return set
return CLASS._byRank(@rank + 1)
# TODO !!
return false
@_makeAliases()
# end js/Sets/Domains/Domain.coffee
# from js/Sets/Domains/N.coffee
class mathJS.Sets.N extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("N", 0, true)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return mathJS.isInt(x) or new mathJS.Int(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
union: (set, n = mathJS.settings.set.maxIterations, matches = mathJS.settings.set.maxMatches) ->
# AND both checker functions
checker = (elem) ->
return self.checker(elem) or set.checker(elem)
generator = () ->
# TODO: how to avoid doubles? implementations that use boolean arrays => XOR operations on elements
# discrete set
if set instanceof mathJS.DiscreteSet or set.instanceof?(mathJS.DiscreteSet)
# non-discrete set (empty or conditional set, or domain)
else if set instanceof mathJS.Set or set.instanceof?(mathJS.Set)
# check for domains. if set is a domain this or the set can directly be returned because they are immutable
# N
if mathJS.instanceof(set, mathJS.Set.N)
return @
# Q, R # TODO: other domains like I, C
if mathJS.instanceof(set, mathJS.Domains.Q) or mathJS.instanceof(set, mathJS.Domains.R)
return set
self = @
# param was no set
return null
intersect: (set) ->
# AND both checker functions
checker = (elem) ->
return self.checker(elem) and set.checker(elem)
# if the f2-invert of the y-value of f1 lies within f2" domain/universe both ranges include that value
# or vice versa
# we know this generator function has N as domain (and as range of course)
# we even know the set"s generator function also has N as domain as we assume that (because the mapping is always a bijection from N -> X)
# so we can only check a single value at a time so we have to have to boundaries for the number of iterations and the number of matches
# after x matches we try to find a series that produces those matches (otherwise a discrete set will be created)
commonElements = []
x = 0 # current iteration = current x value
m = 0 # current matches
f1 = @generator
f2 = set.generator
f1Elems = [] # in ascending order because generators are increasing
f2Elems = [] # in ascending order because generators are increasing
while x < n and m < matches
y1 = f1(x) # TODO: maybe inline generator function here?? but that would mean every sub class has to overwrite
y2 = f2(x)
# f1 is bigger than f2 at current x => check for y2 in f1Elems
if mathJS.gt(y1, y2)
found = false
for f1Elem, i in f1Elems when mathJS.equals(y2, f1Elem)
# new match!
m++
found = true
# y2 found in f1Elems => add to common elements
commonElements.push y2
# because both functions are increasing dispose of earlier elements
# remove all unneeded elements from f1Elems incl. (current) y1
f1Elems = f1Elems.slice(i + 1)
# y2 was a match (the last in f2Elems) and y1 is bigger than y2 so we can forget everything in f2Elems
f2Elems = []
# exit loop
break
if not found
f1Elems.push y1
f2Elems.push y2
# f2 is bigger than f1 at current x => check for y1 in f2Elems
else if mathJS.lt(y1, y2)
found = false
for f2Elem, i in f2Elems when mathJS.equals(y1, f2Elem)
# new match!
m++
found = true
# y1 found in f2Elems => add to common elements
commonElements.push y1
# because both functions are increasing dispose of earlier elements
# remove all unneeded elements from f2Elems incl. (current) y1
f2Elems = f2Elems.slice(i + 1)
# y1 was a match (the last in f2Elems) and y1 is bigger than y1 so we can forget everything in f1Elems
f1Elems = []
# exit loop
break
if not found
f1Elems.push y1
f2Elems.push y2
# equal
else
m++
commonElements.push y1
# all previous values are unimportant because in the next iteration the new values will BOTH be greater than y1=y2 and the 2 lists contain only smaller elements than y1=y2 so there can"t be a match with the next elements
f1Elems = []
f2Elems = []
# increment
x++
console.log "x=#{x}", "m=#{m}", commonElements
# try to find formular from series (supported is: +,-,*,/)
ops = []
for elem in commonElements
true
# example: c1 = x^2, c2 = 2x+1
# c1: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81...
# c2: 1, 3, 5, 7, 9, 11, 13, 15, 17, ...
# => 1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089, 1225, 1369, 1521, 1681, 1849
# this is all odd squares (all odd numbers squared!) ==> f(x) = (2x + 1)^2
# ==> slower increasing function = f, faster increasing function = g -> new-f(x) = g(f(x)) = (g o f)(x)
# actually it is the "bigger function" with a constraint
# inserting smaller in bigger works also for 2x, 3x
# what about 2x, 3x+1 -> 3(2x) + 1 = 6x+1
# but 2x, 2x => 2(2x) = 4x wrong!
# series like *2, +1, *3, -1, *4, +1, *5, -1, *6, +1, ...
# would create 1, 2, 3, 9, 8, 32, 33, 165, 164, 984, 985
# indices: 0 1 2 3 4 5 6 7 8 9 10
# f would be y = x^2 + (-1)^x
return
intersects: (set) ->
return @intersection(set).size > 0
disjoint: (set) ->
return @intersection(set).size is 0
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
times: @::cartesianProduct
# inherited
# isEmpty: () ->
# return @size is 0
# MAKE MATHJS.DOMAINS.N AN INSTANCE
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
N:
value: new mathJS.Sets.N()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/N.coffee
# from js/Sets/Domains/Z.coffee
class mathJS.Sets.Z extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("Z", 1, true)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
Z:
value: new mathJS.Sets.Z()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/Z.coffee
# from js/Sets/Domains/Q.coffee
class mathJS.Sets.Q extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("Q", 2, true)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
Q:
value: new mathJS.Sets.Q()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/Q.coffee
# from js/Sets/Domains/I.coffee
class mathJS.Sets.I extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("I", 2, false)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
I:
value: new mathJS.Sets.I()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/I.coffee
# from js/Sets/Domains/R.coffee
class mathJS.Sets.R extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("R", 3, false)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
R:
value: new mathJS.Sets.R()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/R.coffee
# from js/Sets/Domains/C.coffee
class mathJS.Sets.C extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("C", 4, false)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
C:
value: new mathJS.Sets.C()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/C.coffee
# from js/Calculus/Integral.coffee
class mathJS.Integral
CLASS = @
if DEBUG
@test = () ->
i = new mathJS.Integral(
(x) ->
return -2*x*x-3*x+10
-3
1
)
start = Date.now()
console.log i.solve(false, 0.00000000000001), Date.now() - start
start = Date.now()
i.solveAsync(
(res) ->
console.log res, "async took:", Date.now() - start
false
0.0000001
)
start2 = Date.now()
console.log i.solve(), Date.now() - start2
return "test done"
constructor: (integrand, leftBoundary=-Infinity, rightBoundary=Infinity, integrationVariable=new mathJS.Variable("x")) ->
@integrand = integrand
@leftBoundary = leftBoundary
@rightBoundary = rightBoundary
@integrationVariable = integrationVariable
@settings = null
# PRIVATE
_solvePrepareVars = (from, to, abs, stepSize) ->
# absolute integral?
if abs is false
modVal = mathJS.id
else
modVal = (x) ->
return Math.abs(x)
# get primitives
from = from.value or from
to = to.value or to
# swap if in wrong order
if to < from
tmp = to
to = from
from = tmp
if (diff = to - from) < stepSize
# stepSize = diff * stepSize * 0.1
stepSize = diff * 0.001
return {
modVal: modVal
from: from
to: to
stepSize: stepSize
}
# STATIC
@solve = (integrand, from, to, abs=false, stepSize=0.01, settings={}) ->
vars = _solvePrepareVars(from, to, abs, stepSize)
modVal = vars.modVal
from = vars.from
to = vars.to
stepSize = vars.stepSize
if (steps = (to - from) / stepSize) > settings.maxSteps or mathJS.settings.integral.maxSteps
throw new mathJS.Errors.CalculationExceedanceError("Too many calculations (#{steps.toExponential()}) ahead! Either adjust mathJS.Integral.settings.maxSteps, set the Integral\"s instance\"s settings or pass settings to mathJS.Integral.solve() if you really need that many calculations.")
res = 0
# cache 0.5 * stepSize
halfStepSize = 0.5 * stepSize
y1 = integrand(from)
if DEBUG
i = 0
for x2 in [(from + stepSize)..to] by stepSize
if DEBUG
i++
y2 = integrand(x2)
if mathJS.sign(y1) is mathJS.sign(y2)
# trapezoid formula
res += modVal((y1 + y2) * halfStepSize)
# else: round to zero -> no calculation needed
y1 = y2
if DEBUG
console.log "made", i, "calculations"
return res
###*
* For better calculation performance of the integral decrease delay and numBlocks.
* For better overall performance increase them.
* @public
* @static
* @method solveAsync
* @param integrand {Function}
* @param from {Number}
* @param to {Number}
* @param callback {Function}
* @param abs {Boolean}
* Optional. Indicates whether areas below the graph are negative or not.
* Default is false.
* @param stepSize {Number}
* Optional. Defines the width of each trapezoid. Default is 0.01.
* @param delay {Number}
* Optional. Defines the time to pass between blocks of calculations.
* Default is 2ms.
* @param numBlocks {Number}
* Optional. Defines the number of calculation blocks.
* Default is 100.
*###
@solveAsync: (integrand, from, to, callback, abs, stepSize, delay=2, numBlocks=100) ->
if not callback?
return false
# split calculation into numBlocks blocks
blockSize = (to - from) / numBlocks
block = 0
res = 0
f = (from, to) ->
# done with all blocks => return result to callback
if block++ is numBlocks
return callback(res)
res += CLASS.solve(integrand, from, to, abs, stepSize)
setTimeout () ->
f(to, to + blockSize)
, delay
return true
f(from, from + blockSize)
return @
# PUBLIC
solve: (abs, stepSize) ->
return CLASS.solve(@integrand, @leftBoundary, @rightBoundary, abs, stepSize)
solveAsync: (callback, abs, stepSize) ->
return CLASS.solveAsync(@integrand, @leftBoundary, @rightBoundary, callback, abs, stepSize)
# end js/Calculus/Integral.coffee
# from js/LinearAlgebra/Vector.coffee
class mathJS.Vector
_isVectorLike: (v) ->
return v instanceof mathJS.Vector or v.instanceof?(mathJS.Vector)# or v instanceof mathJS.Tuple or v.instanceof?(mathJS.Tuple)
@_isVectorLike: @::_isVectorLike
# CONSTRUCTOR
constructor: (values) ->
# check values for
@values = values
if DEBUG
for val in values when not mathJS.isMathJSNum(val)
console.warn "invalid value:", val
equals: (v) ->
if not @_isVectorLike(v)
return false
for val, i in @values
vValue = v.values[i]
if not val.equals?(vValue) and val isnt vValue
return false
return true
clone: () ->
return new TD.Vector(@values)
move: (v) ->
if not @_isVectorLike v
return @
for val, i in v.values
vValue = v.values[i]
@values[i] = vValue.plus?(val) or val.plus?(vValue) or (vValue + val)
return @
moveBy: @move
moveTo: (p) ->
if not @_isVectorLike v
return @
for val, i in v.values
vValue = v.values[i]
@values[i] = vValue.value or vValue
return @
multiply: (r) ->
if Math.isNum r
return new TD.Point(@x * r, @y * r)
return null
# make alias
times: @multiply
magnitude: () ->
sum = 0
for val, i in @values
sum += val * val
return Math.sqrt(sum)
###*
* This method calculates the distance between 2 points.
* It"s a shortcut for substracting 2 vectors and getting that vector"s magnitude (because no new object is created).
* For that reason this method should be used for pure distance calculations.
*
* @method distanceTo
* @param {Point} p
* @return {Number} Distance between this point and p.
*###
distanceTo: (v) ->
sum = 0
for val, i in @values
sum += (val - v.values[i]) * (val - v.values[i])
return Math.sqrt(sum)
add: (v) ->
if not @_isVectorLike v
return null
values = []
for val, i in v.values
vValue = v.values[i]
values.push(vValue.plus?(val) or val.plus?(vValue) or (vValue + val))
return new mathJS.Vector(values)
# make alias
plus: @add
substract: (p) ->
if isPointLike p
return new TD.Point(@x - p.x, @y - p.y)
return null
# make alias
minus: @substract
xyRatio: () ->
return @x / @y
toArray: () ->
return [@x, @y]
isPositive: () ->
return @x >= 0 and @y >= 0
###*
* Returns the angle of a vector. Beware that the angle is measured in counter clockwise direction beginning at 0˚ which equals the x axis in positive direction.
* So on a computer grid the angle won"t be what you expect! Use anglePC() in that case!
*
* @method angle
* @return {Number} Angle of the vector in degrees. 0 degrees means pointing to the right.
*###
angle: () ->
# 1st quadrant (and zero)
if @x >= 0 and @y >= 0
return Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) ) % 360
# 2nd quadrant
if @x < 0 and @y > 0
return (90 + Math.radToDeg( Math.atan( Math.abs(@x) / Math.abs(@y) ) )) % 360
# 3rd quadrant
if @x < 0 and @y < 0
return (180 + Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) )) % 360
# 4th quadrant
return (270 + Math.radToDeg( Math.atan( Math.abs(@x) / Math.abs(@y) ) )) % 360
###*
* Returns the angle of a vector. 0˚ means pointing to the top. Clockwise.
*
* @method anglePC
* @return {Number} Angle of the vector in degrees. 0 degrees means pointing to the right.
*###
anglePC: () ->
# 1st quadrant: pointing to bottom right
if @x >= 0 and @y >= 0
return (90 + Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) )) % 360
# 2nd quadrant: pointing to bottom left
if @x < 0 and @y > 0
return (180 + Math.radToDeg( Math.atan( Math.abs(@x) / Math.abs(@y) ) )) % 360
# 3rd quadrant: pointing to top left
if @x < 0 and @y < 0
return (270 + Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) )) % 360
# 4th quadrant: pointing to top right
return Math.radToDeg(Math.atan( Math.abs(@x) / Math.abs(@y) ) ) % 360
###*
* Returns a random Point within a given radius.
*
* @method randPointInRadius
* @param {Number} radius
* Default is 10 (pixels). Must not be smaller than 0.
* @param {Boolean} random
* Indicates whether the given radius is the maximum or exact distance between the 2 points.
* @return {Number} Random Point.
*###
randPointInRadius: (radius = 5, random = false) ->
angle = Math.degToRad(Math.randNum(0, 360))
if random is true
radius = Math.randNum(0, radius)
x = radius * Math.cos angle
y = radius * Math.sin angle
return @add( new TD.Point(x, y) )
# end js/LinearAlgebra/Vector.coffee
# from js/Initializer.coffee
class mathJS.Initializer
@start: () ->
mathJS.Algorithms.ShuntingYard.init()
# end js/Initializer.coffee
# from js/start.coffee
mathJS.Initializer.start()
if DEBUG
diff = Date.now() - startTime
console.log "time to load mathJS: ", diff, "ms"
if diff > 100
console.warn "LOADING TIME CRITICAL!"
# end js/start.coffee
| 1110 | # from js/init.coffee
###*
* @module mathJS
* @main mathJS
*###
if typeof DEBUG is "undefined"
window.DEBUG = true
# create namespaces
window.mathJS =
Algorithms: {}
Domains: {} # contains instances of sets
Errors: {}
Geometry: {}
Operations: {}
Sets: {}
Utils: {}
# Take namespaces from mathJS
_mathJS = $.extend {}, mathJS
if DEBUG
window._mathJS = _mathJS
startTime = Date.now()
# end js/init.coffee
# from js/prototyping.coffee
# TODO: use object.defineProperties in order to hide methods from enumeration
####################################################################################
Array::reverseCopy = () ->
res = []
res.push(item) for item in @ by -1
return res
Array::unique = () ->
res = []
for elem in @ when elem not in res
res.push elem
return res
Array::sample = (n = 1, forceArray = false) ->
if n is 1
if not forceArray
return @[ Math.floor(Math.random() * @length) ]
return [ @[ Math.floor(Math.random() * @length) ] ]
if n > @length
n = @length
i = 0
res = []
arr = @clone()
while i++ < n
elem = arr.sample(1)
res.push elem
arr.remove elem
return res
Array::shuffle = () ->
arr = @sample(@length)
for elem, i in arr
@[i] = elem
return @
Array::average = () ->
sum = 0
elems = 0
for elem in @ when Math.isNum(elem)
sum += elem
elems++
return sum / elems
# make alias
Array::median = Array::average
Array::clone = Array::slice
# TODO: from http://jsperf.com/array-prototype-slice-call-vs-slice-call/17
# function nonnative_slice(item, start){
# start = ~~start;
# var
# len = item.length, i, newArray;
#
# newArray = new Array(len - start);
#
# for (i = start; i < len; i++){
# newArray[i - start] = item[i];
# }
#
# return newArray;
# }
Array::indexOfNative = Array::indexOf
Array::indexOf = (elem, fromIdx) ->
idx = if fromIdx? then fromIdx else 0
len = @length
while idx < len
if @[idx] is elem
return idx
idx++
return -1
Array::remove = (elem) ->
idx = @indexOf elem
if idx > -1
@splice(idx, 1)
return @
Array::removeAll = (elements = []) ->
for elem in elements
@remove elem
return @
Array::removeAt = (idx) ->
@splice(idx, 1)
return @
# convenient index getters and setters
Object.defineProperties Array::, {
first:
get: () ->
return @[0]
set: (val) ->
@[0] = val
return @
second:
get: () ->
return @[1]
set: (val) ->
@[1] = val
return @
third:
get: () ->
return @[2]
set: (val) ->
@[2] = val
return @
fourth:
get: () ->
return @[3]
set: (val) ->
@[3] = val
return @
last:
get: () ->
return @[@length - 1]
set: (val) ->
@[@length - 1] = val
return @
}
###*
* @method getMax
* @param {Function} propertyGetter
* The passed callback extracts the value being compared from the array elements.
* @return {Array} An array of all maxima.
*###
Array::getMax = (propertyGetter) ->
max = null
res = []
if not propertyGetter?
propertyGetter = (item) ->
return item
for elem in @
val = propertyGetter(elem)
# new max found (or first compare) => restart list with new max value
if val > max or max is null
max = val
res = [elem]
# same as max found => add to list
else if val is max
res.push elem
return res
Array::getMin = (propertyGetter) ->
min = null
res = []
if not propertyGetter?
propertyGetter = (item) ->
return item
for elem in @
val = propertyGetter(elem)
# new min found (or first compare) => restart list with new min value
if val < min or min is null
min = val
res = [elem]
# same as min found => add to list
else if val is min
res.push elem
return res
Array::sortProp = (getProp, order = "asc") ->
if not getProp?
getProp = (item) ->
return item
if order is "asc"
cmpFunc = (a, b) ->
a = getProp(a)
b = getProp(b)
if a < b
return -1
if b > a
return 1
return 0
else
cmpFunc = (a, b) ->
a = getProp(a)
b = getProp(b)
if a > b
return -1
if b < a
return 1
return 0
return @sort cmpFunc
####################################################################################
# STRING
String::camel = (spaces) ->
if not spaces?
spaces = false
str = @toLowerCase()
if spaces
str = str.split(" ")
for i in [1...str.length]
str[i] = str[i].charAt(0).toUpperCase() + str[i].substring(1)
str = str.join("")
return str
String::antiCamel = () ->
res = @charAt(0)
for i in [1...@length]
temp = @charAt(i)
# it is a capital letter -> insert space
if temp is temp.toUpperCase()
res += " "
res += temp
return res
String::firstToUpperCase = () ->
return @charAt(0).toUpperCase() + @slice(1)
String::snakeToCamelCase = () ->
res = ""
for char in @
# not underscore
if char isnt "_"
# previous character was not an underscore => just add character
if prevChar isnt "_"
res += char
# previous character was an underscore => add upper case character
else
res += char.toUpperCase()
prevChar = char
return res
String::camelToSnakeCase = () ->
res = ""
prevChar = null
for char in @
# lower case => just add
if char is char.toLowerCase()
res += char
# upper case
else
# previous character was lower case => add underscore and lower case character
if prevChar is prevChar.toLowerCase()
res += "_" + char.toLowerCase()
# previous character was (also) upper case => just add
else
res += char
prevChar = char
return res
String::lower = String::toLowerCase
String::upper = String::toUpperCase
# convenient index getters and setters
Object.defineProperties String::, {
first:
get: () ->
return @[0]
set: (val) ->
return @
second:
get: () ->
return @[1]
set: (val) ->
return @
third:
get: () ->
return @[2]
set: (val) ->
return @
fourth:
get: () ->
return @[3]
set: (val) ->
return @
last:
get: () ->
return @[@length - 1]
set: (val) ->
return @
}
# implement comparable and orderable interface for primitives
String::equals = (str) ->
return @valueOf() is str.valueOf()
String::lessThan = (str) ->
return @valueOf() < str.valueOf()
String::lt = String::lessThan
String::greaterThan = (str) ->
return @valueOf() > str.valueOf()
String::gt = String::greaterThan
String::lessThanOrEqualTo = (str) ->
return @valueOf() <= str.valueOf()
String::lte = String::lessThanOrEqualTo
String::greaterThanOrEqualTo = (str) ->
return @valueOf() >= str.valueOf()
String::gte
####################################################################################
# BOOLEAN
Boolean::equals = (bool) ->
return @valueOf() is bool.valueOf()
Boolean::lessThan = (bool) ->
return @valueOf() < bool.valueOf()
Boolean::lt = Boolean::lessThan
Boolean::greaterThan = (bool) ->
return @valueOf() > bool.valueOf()
Boolean::gt = Boolean::greaterThan
Boolean::lessThanOrEqualTo = (bool) ->
return @valueOf() <= bool.valueOf()
Boolean::lte = Boolean::lessThanOrEqualTo
Boolean::greaterThanOrEqualTo = (bool) ->
return @valueOf() >= str.valueOf()
Boolean::gte
####################################################################################
# OBJECT
Object.keysLike = (obj, pattern) ->
res = []
for key in Object.keys(obj)
if pattern.test key
res.push key
return res
# end js/prototyping.coffee
# from js/mathJS.coffee
#################################################################################################
# THIS FILE CONTAINS ALL PROPERITES AND FUNCTIONS THAT ARE BOUND DIRECTLY TO mathJS
# CONSTRANTS
Object.defineProperties mathJS, {
e:
value: Math.E
writable: false
pi:
value: Math.PI
writable: false
ln2:
value: Math.LN2
writable: false
ln10:
value: Math.LN10
writable: false
log2e:
value: Math.LOG2E
writable: false
log10e:
value: Math.LOG10E
writable: false
# This value behaves slightly differently than mathematical infinity:
#
# Any positive value, including POSITIVE_INFINITY, multiplied by NEGATIVE_INFINITY is NEGATIVE_INFINITY.
# Any negative value, including NEGATIVE_INFINITY, multiplied by NEGATIVE_INFINITY is POSITIVE_INFINITY.
# Zero multiplied by NEGATIVE_INFINITY is NaN.
# NaN multiplied by NEGATIVE_INFINITY is NaN.
# NEGATIVE_INFINITY, divided by any negative value except NEGATIVE_INFINITY, is POSITIVE_INFINITY.
# NEGATIVE_INFINITY, divided by any positive value except POSITIVE_INFINITY, is NEGATIVE_INFINITY.
# NEGATIVE_INFINITY, divided by either NEGATIVE_INFINITY or POSITIVE_INFINITY, is NaN.
# Any number divided by NEGATIVE_INFINITY is Zero.
infty:
value: Infinity
writable: false
infinity:
value: Infinity
writable: false
epsilon:
value: Number.EPSILON or 2.220446049250313e-16 # 2.220446049250313080847263336181640625e-16
writable: false
maxValue:
value: Number.MAX_VALUE
writable: false
minValue:
value: Number.MIN_VALUE
writable: false
id:
value: (x) ->
return x
writable: false
# number sets / systems
# N:
# value: new mathJS.Set()
# writable: false
}
mathJS.isPrimitive = (x) ->
return typeof x is "string" or typeof x is "number" or typeof x is "boolean"
mathJS.isComparable = (x) ->
# return x instanceof mathJS.Comparable or x.instanceof?(mathJS.Comparable) or mathJS.isPrimitive x
return x.equals instanceof Function or mathJS.isPrimitive x
# mathJS.instanceof = (instance, clss) ->
# return instance instanceof clss or instance.instanceof?(clss)
# mathJS.isA = () ->
mathJS.equals = (x, y) ->
return x.equals?(y) or y.equals?(x) or x is y
mathJS.greaterThan = (x, y) ->
return x.gt?(y) or y.lt?(x) or x > y
mathJS.gt = mathJS.greaterThan
mathJS.lessThan = (x, y) ->
return x.lt?(y) or y.gt?(x) or x < y
mathJS.lt = mathJS.lessThan
mathJS.ggT = () ->
if arguments[0] instanceof Array
vals = arguments[0]
else
vals = Array::slice.apply arguments
if vals.length is 2
if vals[1] is 0
return vals[0]
return mathJS.ggT(vals[1], vals[0] %% vals[1])
else if vals.length > 2
ggt = mathJS.ggT vals[0], vals[1]
for i in [2...vals.length]
ggt = mathJS.ggT(ggt, vals[i])
return ggt
return null
mathJS.gcd = mathJS.ggT
mathJS.kgV = () ->
if arguments[0] instanceof Array
vals = arguments[0]
else
vals = Array::slice.apply arguments
if vals.length is 2
return vals[0] * vals[1] // mathJS.ggT(vals[0], vals[1])
else if vals.length > 2
kgv = mathJS.kgV vals[0], vals[1]
for i in [2...vals.length]
kgv = mathJS.kgV(kgv, vals[i])
return kgv
return null
mathJS.lcm = mathJS.kgV
mathJS.coprime = (x, y) ->
return mathJS.gcd(x, y) is 1
mathJS.ceil = Math.ceil
# faster way of rounding down
mathJS.floor = (n) ->
# if mathJS.isNum(n)
# return ~~n
# return NaN
return ~~n
mathJS.floatToInt = mathJS.floor
mathJS.square = (n) ->
if mathJS.isNum(n)
return n * n
return NaN
mathJS.cube = (n) ->
if mathJS.isNum(n)
return n * n * n
return NaN
# TODO: jsperf
mathJS.pow = Math.pow
# TODO: jsperf
mathJS.sqrt = Math.sqrt
mathJS.curt = (n) ->
if mathJS.isNum(n)
return mathJS.pow(n, 1 / 3)
return NaN
mathJS.root = (n, exp) ->
if mathJS.isNum(n) and mathJS.isNum(exp)
return mathJS.pow(n, 1 / exp)
return NaN
mathJS.factorial = (n) ->
if (n = ~~n) < 0
return NaN
return mathJS.factorial.cache[n] or (mathJS.factorial.cache[n] = n * mathJS.factorial(n - 1))
# initial cache (dynamically growing when exceeded)
mathJS.factorial.cache = [
1
1
2
6
24
120
720
5040
40320
362880
3628800
39916800
4.790016e8
6.2270208e9
8.71782912e10
1.307674368e12
]
# make alias
mathJS.fac = mathJS.factorial
mathJS.parseNumber = (str) ->
# TODO
return null
mathJS.factorialInverse = (n) ->
if (n = ~~n) < 0
return NaN
x = 0
# js: while((y = mathJS.factorial(++x)) < n) {}
while (y = mathJS.factorial(++x)) < n then
if y is n
return parseInt(x, 10)
return NaN
# make alias
mathJS.facInv = mathJS.factorialInverse
###*
* This function checks if a given parameter is a (plain) number.
* @method isNum
* @param {Number} num
* @return {Boolean} Whether the given number is a Number (excluding +/-Infinity)
*###
# mathJS.isNum = (r) ->
# return (typeof r is "number") and not isNaN(r) and r isnt Infinity and r isnt -Infinity
# return not isNaN(r) and -Infinity < r < Infinity
mathJS.isNum = (n) ->
return n? and isFinite(n)
mathJS.isMathJSNum = (n) ->
return n? and (isFinite(n) or n instanceof mathJS.Number or n.instanceof(mathJS.Number))
mathJS.isInt = (r) ->
return mathJS.isNum(r) and ~~r is r
###*
* This function returns a random (plain) integer between max and min (both inclusive). If max is less than min the parameters are swapped.
* @method randInt
* @param {Number} max
* @param {Number} min
* @return {Number} Random integer.
*###
mathJS.randInt = (max = 1, min = 0) ->
# if min > max
# temp = min
# min = max
# max = temp
# return Math.floor(Math.random() * (max + 1 - min)) + min
return ~~mathJS.randNum(max, min)
###*
* This function returns a random number between max and min (both inclusive). If max is less than min the parameters are swapped.
* @method randNum
* @param {Number} max
* @param {Number} min
* Default is 0.
* @return {Integer} Random number.
*###
mathJS.randNum = (max = 1, min = 0) ->
if min > max
temp = min
min = max
max = temp
return Math.random() * (max + 1 - min) + min
mathJS.radToDeg = (rad) ->
return rad * 57.29577951308232 # = rad * (180 / Math.PI)
mathJS.degToRad = (deg) ->
return deg * 0.017453292519943295 # = deg * (Math.PI / 180)
mathJS.sign = (n) ->
n = n.value or n
if mathJS.isNum(n)
if n < 0
return -1
return 1
return NaN
mathJS.min = (elems...) ->
if elems.first instanceof Array
elems = elems.first
propGetter = null
else if elems.first instanceof Function
propGetter = elems.first
elems = elems.slice(1)
if elems.first instanceof Array
elems = elems.first
res = []
min = null
for item in elems
if propGetter?
item = propGetter(item)
if min is null or item.lessThan(min) or item < min
min = item
res = [elem]
# same as min found => add to list
else if item.equals(min) or item is min
res.push elem
return res
mathJS.max = (elems...) ->
if elems.first instanceof Array
elems = elems.first
propGetter = null
else if elems.first instanceof Function
propGetter = elems.first
elems = elems.slice(1)
if elems.first instanceof Array
elems = elems.first
res = []
max = null
for item in elems
if propGetter?
item = propGetter(item)
if max is null or item.greaterThan(max) or item > max
max = item
res = [elem]
# same as max found => add to list
else if item.equals(max) or item is max
res.push elem
return res
mathJS.log = (n, base=10) ->
return Math.log(n) / Math.log(base)
mathJS.logBase = mathJS.log
mathJS.reciprocal = (n) ->
if mathJS.isNum(n)
return 1 / n
return NaN
mathJS.sortFunction = (a, b) ->
if a.lessThan b
return -1
if a.greaterThan b
return 1
return 0
# end js/mathJS.coffee
# from js/settings.coffee
mathJS.settings =
generator:
maxIndex: 1e4
integral:
maxSteps: 1e10
# maxPoolSize is for EACH pool
maxPoolSize: 100
number:
real:
distance: 1e-6
set:
defaultNumberOfElements: 1e3
maxIterations: 1e3
maxMatches: 60
mathJS.config = mathJS.settings
# end js/settings.coffee
# from js/mathJSObject.coffee
###*
* This is the super class of all mathJS classes.
* Therefore all cross-class things are defined here.
* @class Object
*###
class _mathJS.Object
@_implements = []
@_implementedBy = []
@implements = (classes...) ->
if classes.first instanceof Array
classes = classes.first
for clss in classes
# make the class / interface know what classes implement it
if @ not in clss._implementedBy
clss._implementedBy.push @
# implement class / interface
clssPrototype = clss.prototype
# "window." necessary because coffee creates an "Object" variable for this class
prototypeKeys = window.Object.keys(clssPrototype)
# static
for name, method of clss when name not in prototypeKeys
@[name] = method
# non-static (from prototype)
for name, method of clssPrototype
@::[name] = method
@_implements.push clss
return @
isA: (clss) ->
if not clss? or clss not instanceof Function
return false
if @ instanceof clss
return true
for c in @constructor._implements
# direct hit
if c is clss
return true
# check super classes ("__superClass__" is set when coffee extends classes using macros...see macros.js)
while (c = c.__superClass__)?
if c is clss
return true
return false
instanceof: () ->
return @isA.apply(@, arguments)
# end js/mathJSObject.coffee
# from js/Errors/SimpleErrors.coffee
# class _mathJS.Errors.Error extends window.Error
#
# constructor: (message, fileName, lineNumber, misc...) ->
# super(message, fileName, lineNumber)
# @misc = misc
#
# toString: () ->
# return "#{super()}\n more data: #{@misc.toString()}"
class mathJS.Errors.CalculationExceedanceError extends Error
class mathJS.Errors.CycleDetectedError extends Error
class mathJS.Errors.DivisionByZeroError extends Error
class mathJS.Errors.InvalidArityError extends Error
class mathJS.Errors.InvalidParametersError extends Error
class mathJS.Errors.InvalidVariableError extends Error
class mathJS.Errors.NotImplementedError extends Error
class mathJS.Errors.NotParseableError extends Error
# end js/Errors/SimpleErrors.coffee
# from js/Utils/Hash.coffee
###*
* This is an implementation of a dictionary/hash that does not convert its keys into Strings. Keys can therefore actually by anything!
* @class Hash
* @constructor
*###
class mathJS.Utils.Hash
###*
* Creates a new Hash from a given JavaScript object.
* @static
* @method fromObject
* @param object {Object}
*###
@fromObject: (obj) ->
return new mathJS.Utils.Hash(obj)
@new: (obj) ->
return new mathJS.Utils.Hash(obj)
constructor: (obj) ->
@keys = []
@values = []
if obj?
@put key, val for key, val of obj
clone: () ->
res = new mathJS.Utils.Hash()
res.keys = @keys.clone()
res.values = @values.clone()
return res
invert: () ->
res = new mathJS.Utils.Hash()
res.keys = @values.clone()
res.values = @keys.clone()
return res
###*
* Adds a new key-value pair or overwrites an existing one.
* @method put
* @param key {mixed}
* @param val {mixed}
* @return {Hash} This instance.
* @chainable
*###
put: (key, val) ->
idx = @keys.indexOf key
# add new entry
if idx < 0
@keys.push key
@values.push val
# overwrite entry
else
@keys[idx] = key
@values[idx] = val
return @
###*
* Returns the value (or null) for the specified key.
* @method get
* @param key {mixed}
* @param [equalityFunction] {Function}
* This optional function can overwrite the test for equality between keys. This function expects the parameters: (the current key in the key iteration, 'key'). If this parameters is omitted '===' is used.
* @return {mixed}
*###
get: (key) ->
if (idx = @keys.indexOf(key)) >= 0
return @values[idx]
return null
###*
* Indicates whether the Hash has the specified key.
* @method hasKey
* @param key {mixed}
* @return {Boolean}
*###
hasKey: (key) ->
return key in @keys
has: (key) ->
return @hasKey(key)
###*
* Returns the number of entries in the Hash.
* @method size
* @return {Integer}
*###
size: () ->
return @keys.length
empty: () ->
@keys = []
@values = []
return @
remove: (key) ->
if (idx = @keys.indexOf(key)) >= 0
@keys.splice idx, 1
@values.splice idx, 1
else
console.warn "Could not remove key '#{key}'!"
return @
each: (callback) ->
for key, i in @keys when callback(key, @values[i], i) is false
return @
return @
# end js/Utils/Hash.coffee
# from js/Utils/Dispatcher.coffee
class mathJS.Utils.Dispatcher extends _mathJS.Object
# map: receiver -> list of dispatchers
@registeredDispatchers = mathJS.Utils.Hash.new()
# try to detect cyclic dispatching
@registerDispatcher: (newReceiver, newTargets) ->
registrationPossible = newTargets.indexOf(newReceiver) is -1
if registrationPossible
regReceivers = @registeredDispatchers.keys
# IF
# 1. the new receiver is in any of the lists and
# 2. any of the registered receivers is in the new-targets list
# THEN a cycle would be created
@registeredDispatchers.each (regReceiver, regTargets, idx) ->
for regTarget in regTargets when regTarget is newReceiver
for newTarget in newTargets when regReceivers.indexOf(newTarget)
registrationPossible = false
return false
return true
if registrationPossible
@registeredDispatchers.put(newReceiver, newTargets)
return @
throw new mathJS.Errors.CycleDetectedError("Can't register '#{newReceiver}' for dispatching - cycle detected!")
# CONSTRUCTOR
# NOTE: super classes are ignored
constructor: (receiver, targets=[]) ->
@constructor.registerDispatcher(receiver, targets)
@receiver = receiver
@targets = targets
console.log "dispatcher created!"
dispatch: (target, method, params...) ->
dispatch = false
# check instanceof and identity
if @targets.indexOf(target.constructor or target) >= 0
dispatch = true
# check typeof (for primitives)
else
for t in @targets when typeof target is t
dispatch = true
break
if dispatch
if target[method] instanceof Function
return target[method].apply(target, params)
throw new mathJS.Errors.NotImplementedError(
"Can't call '#{method}' on target '#{target}'"
"Dispatcher.coffee"
)
return null
# end js/Utils/Dispatcher.coffee
# from js/Interfaces/Interface.coffee
class _mathJS.Interface extends _mathJS.Object
@implementedBy = []
@isImplementedBy = () ->
return @implementedBy
# end js/Interfaces/Interface.coffee
# from js/Interfaces/Comparable.coffee
class _mathJS.Comparable extends _mathJS.Interface
###*
* This method checks for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2) is true.
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (n) ->
throw new mathJS.Errors.NotImplementedError("equals in #{@contructor.name}")
e: () ->
return @equals.apply(@, arguments)
# end js/Interfaces/Comparable.coffee
# from js/Interfaces/Orderable.coffee
class _mathJS.Orderable extends _mathJS.Comparable
###*
* This method checks for mathmatical "<". This means new mathJS.Double(4.2).lessThan(5.2) is true.
* @method lessThan
* @param {Number} n
* @return {Boolean}
*###
lessThan: (n) ->
throw new mathJS.Errors.NotImplementedError("lessThan in #{@contructor.name}")
###*
* Alias for `lessThan`.
* @method lt
*###
lt: () ->
return @lessThan.apply(@, arguments)
###*
* This method checks for mathmatical ">". This means new mathJS.Double(4.2).greaterThan(3.2) is true.
* @method greaterThan
* @param {Number} n
* @return {Boolean}
*###
greaterThan: (n) ->
throw new mathJS.Errors.NotImplementedError("greaterThan in #{@contructor.name}")
###*
* Alias for `greaterThan`.
* @method gt
*###
gt: () ->
return @greaterThan.apply(@, arguments)
###*
* This method checks for mathmatical "<=". This means new mathJS.Double(4.2).lessThanOrEqualTo(5.2) is true.
* @method lessThanOrEqualTo
* @param {Number} n
* @return {Boolean}
*###
lessThanOrEqualTo: (n) ->
return @lessThan(n) or @equals(n)
###*
* Alias for `lessThanOrEqualTo`.
* @method lte
*###
lte: () ->
return @lessThanOrEqualTo.apply(@, arguments)
###*
* This method checks for mathmatical ">=". This means new mathJS.Double(4.2).greaterThanOrEqualTo(3.2) is true.
* @method greaterThanOrEqualTo
* @param {Number} n
* @return {Boolean}
*###
greaterThanOrEqualTo: (n) ->
return @greaterThan(n) or @equals(n)
###*
* Alias for `greaterThanOrEqualTo`.
* @method gte
*###
gte: () ->
return @greaterThanOrEqualTo.apply(@, arguments)
# end js/Interfaces/Orderable.coffee
# from js/Interfaces/Parseable.coffee
class _mathJS.Parseable extends _mathJS.Interface
@parse: (str) ->
throw new mathJS.Errors.NotImplementedError("static parse in #{@name}")
@fromString: (str) ->
return @parse(str)
toString: (args) ->
throw new mathJS.Errors.NotImplementedError("toString in #{@contructor.name}")
# end js/Interfaces/Parseable.coffee
# from js/Interfaces/Poolable.coffee
class _mathJS.Poolable extends _mathJS.Interface
@_pool = []
@_fromPool: () ->
# implementation should be something like:
# if @_pool.length > 0
# return @_pool.pop()
# return new @()
throw new mathJS.Errors.NotImplementedError("static _fromPool in #{@name}")
###*
* Releases the instance to the pool of its class.
* @method release
* @return This intance
* @chainable
*###
release: () ->
if @constructor._pool.length < mathJS.settings.maxPoolSize
@constructor._pool.push @
if DEBUG
if @constructor._pool.length >= mathJS.settings.maxPoolSize
console.warn "#{@constructor.name}-pool is full:", @constructor._pool
return @
# end js/Interfaces/Poolable.coffee
# from js/Interfaces/Evaluable.coffee
class _mathJS.Evaluable extends _mathJS.Interface
eval: () ->
throw new mathJS.Errors.NotImplementedError("eval() in #{@contructor.name}")
# end js/Interfaces/Evaluable.coffee
# from js/Numbers/AbstractNumber.coffee
# This file defines the Number interface.
# TODO: make number extend expression
class _mathJS.AbstractNumber extends _mathJS.Object
@implements _mathJS.Orderable, _mathJS.Poolable, _mathJS.Parseable
###*
* @Override mathJS.Poolable
* @static
* @method _fromPool
*###
@_fromPool: (value) ->
if @_pool.length > 0
if (val = @_getPrimitive(value))?
number = @_pool.pop()
number.value = val
return number
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{value}'"
"AbstractNumber.coffee"
)
# param check is done in constructor
return new @(value)
###*
* @Override mathJS.Parseable
* @static
* @method parse
*###
@parse: (str) ->
return @_fromPool parseFloat(str)
@getSet: () ->
throw new mathJS.Errors.NotImplementedError("getSet in #{@name}")
@new: (param) ->
return @_fromPool param
@random: (max, min) ->
return @_fromPool mathJS.randNum(max, min)
@dispatcher = new mathJS.Utils.Dispatcher(@, [
# mathJS.Matrix
mathJS.Fraction
])
###*
* This method is used to parse and check a parameter.
* Either a valid value is returned or null (for invalid parameters).
* @static
* @method _getPrimitive
* @param param {Object}
* @param skipCheck {Boolean}
* @return {mathJS.Number}
*###
@_getPrimitive: (param, skipCheck) ->
return null
############################################################################################
# PROTECTED METHODS
_setValue: (value) ->
return @
_getValue: () ->
return @_value
_getPrimitive: (param) ->
return @constructor._getPrimitive(param)
############################################################################################
# PUBLIC METHODS
############################################################################################
# COMPARABLE INTERFACE
###*
* @Override mathJS.Comparable
* This method checks for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2) is true.
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "equals", @))?
return result
if (val = @_getPrimitive(n))?
return @value is val
return false
# END - IMPLEMENTING COMPARABLE
############################################################################################
############################################################################################
# ORDERABLE INTERFACE
###*
* @Override mathJS.Orderable
* This method checks for mathmatical "<". This means new mathJS.Double(4.2).lessThan(5.2) is true.
* @method lessThan
*###
lessThan: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "lessThan", @))?
return result
if (val = @_getPrimitive(n))?
return @value < val
return false
###*
* @Override mathJS.Orderable
* This method checks for mathmatical ">". This means new mathJS.Double(4.2).greaterThan(3.2) is true.
* @method greaterThan
* @param {Number} n
* @return {Boolean}
*###
greaterThan: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "greaterThan", @))?
return result
if (val = @_getPrimitive(n))?
return @value > val
return false
# END - IMPLEMENTING ORDERABLE
############################################################################################
###*
* This method adds 2 numbers and returns a new one.
* @method plus
* @param {Number} n
* @return {mathJS.Number} Calculated Number.
*###
plus: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "plus", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value + val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method substracts 2 numbers and returns a new one.
* @method minus
* @param {Number} n
* @return {mathJS.Number} Calculated Number.
*###
minus: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "minus", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value - val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method multiplies 2 numbers and returns a new one.
* @method times
* @param {Number} n
* @return {mathJS.Number} Calculated Number.
*###
times: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "times", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value * val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method divides 2 numbers and returns a new one.
* @method divide
* @param {Number} n
* @return {Number} Calculated Number.
*###
divide: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "divide", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value / val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method squares this instance and returns a new one.
* @method square
* @return {Number} Calculated Number.
*###
square: () ->
return mathJS.Number.new(@value * @value)
###*
* This method cubes this instance and returns a new one.
* @method cube
* @return {Number} Calculated Number.
*###
cube: () ->
return mathJS.Number.new(@value * @value * @value)
###*
* This method calculates the square root of this instance and returns a new one.
* @method sqrt
* @return {Number} Calculated Number.
*###
sqrt: () ->
return mathJS.Number.new(mathJS.sqrt(@value))
###*
* This method calculates the cubic root of this instance and returns a new one.
* @method curt
* @return {Number} Calculated Number.
*###
curt: () ->
return @pow(0.3333333333333333)
###*
* This method calculates any root of this instance and returns a new one.
* @method root
* @param {Number} exponent
* @return {Number} Calculated Number.
*###
root: (exp) ->
if (val = @_getPrimitive(exp))?
return @pow(1 / val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{exp}'"
"AbstractNumber.coffee"
)
###*
* This method returns the reciprocal (1/n) of this number.
* @method reciprocal
* @return {Number} Calculated Number.
*###
reciprocal: () ->
return mathJS.Number.new(1 / @value)
###*
* This method returns this' value the the n-th power (this^n).
* @method pow
* @param {Number} n
* @return {Number} Calculated Number.
*###
pow: (n) ->
if (val = @_getPrimitive(n))?
return mathJS.Number.new(mathJS.pow(@value, val))
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method returns the sign of this number (sign(this)).
* @method sign
* @param plain {Boolean}
* Indicates whether the return value is wrapped in a mathJS.Number or not (-> primitive value).
* @return {Number|mathJS.Number}
*###
sign: (plain=true) ->
val = @value
if plain is true
if val < 0
return -1
return 1
# else:
if val < 0
return mathJS.Number.new(-1)
return mathJS.Number.new(1)
negate: () ->
return mathJS.Number.new(-@value)
toInt: () ->
return mathJS.Int.new(@value)
toNumber: () ->
return mathJS.Number.new(@value)
toString: (format) ->
if not format?
return "#{@value}"
return numeral(@value).format(format)
clone: () ->
return mathJS.Number.new(@value)
# EVALUABLE INTERFACE
eval: (values) ->
return @
_getSet: () ->
return new mathJS.Set(@)
############################################################################################
# SETS...
in: (set) ->
return set.contains(@)
# end js/Numbers/AbstractNumber.coffee
# from js/Numbers/Number.coffee
# TODO: mathJS.Number should also somehow be a mathJS.Expression!!!
###*
* @abstract
* @class Number
* @constructor
* @param {Number} value
* @extends Object
*###
class mathJS.Number extends _mathJS.AbstractNumber
###########################################################################################
# STATIC
@_getPrimitive: (param, skipCheck) ->
if skipCheck is true
return param
if param instanceof mathJS.Number
return param.value
if param instanceof Number
return param.valueOf()
if mathJS.isNum(param)
return param
return null
@getSet: () ->
return mathJS.Domains.R
# moved to AbstractNumber
# @new: (value) ->
# return @_fromPool value
###########################################################################################
# CONSTRUCTOR
constructor: (value) ->
@_value = null
Object.defineProperties @, {
value:
get: @_getValue
set: @_setValue
}
if (val = @_getPrimitive(value))?
@_value = val
else
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{value}'"
"Number.coffee"
)
###########################################################################################
# PRIVATE METHODS
###########################################################################################
# PROTECTED METHODS
###########################################################################################
# PUBLIC METHODS
########################################################
# IMPLEMENTING COMPARABLE
# see AbstractNumber
# END - IMPLEMENTING COMPARABLE
########################################################
# IMPLEMENTING BASIC OPERATIONS
# see AbstractNumber
# END - IMPLEMENTING BASIC OPERATIONS
# EVALUABLE INTERFACE
eval: (values) ->
return @
# TODO: intercept destructor
# .....
_getSet: () ->
return new mathJS.Set(@)
in: (set) ->
return set.contains(@)
valueOf: @::_getValue
# end js/Numbers/Number.coffee
# from js/Numbers/Double.coffee
class mathJS.Double extends mathJS.Number
# end js/Numbers/Double.coffee
# from js/Numbers/Int.coffee
###*
* @class Int
* @constructor
* @param {Number} value
* @extends Number
*###
class mathJS.Int extends mathJS.Number
###########################################################################
# STATIC
@parse: (str) ->
if mathJS.isNum(parsed = parseInt(str, 10))
return @_fromPool parsed
return parsed
@random: (max, min) ->
return @_fromPool mathJS.randInt(max, min)
@getSet: () ->
return mathJS.Domains.N
###*
* @Override mathJS.Poolable
* @static
* @protected
* @method _fromPool
*###
@_fromPool: (value) ->
if @_pool.length > 0
if (val = @_getPrimitiveInt(value))?
number = @_pool.pop()
number.value = val.value or val
return number
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{value}'"
"Int.coffee"
undefined
value
)
# param check is done in constructor
return new @(value)
@_getPrimitiveInt: (param, skipCheck) ->
if skipCheck is true
return param
if param instanceof mathJS.Int
return param.value
if param instanceof mathJS.Number
return ~~param.value
if param instanceof Number
return ~~param.valueOf()
if mathJS.isNum(param)
return ~~param
return null
###########################################################################
# CONSTRUCTOR
constructor: (value) ->
super(value)
if (val = @_getPrimitiveInt(value))?
@_value = val
else
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate integer from given '#{value}'"
"Int.coffee"
)
###########################################################################
# PRIVATE METHODS
###########################################################################
# PROTECTED METHODS
_getPrimitiveInt: (param) ->
return @constructor._getPrimitiveInt(param)
###########################################################################
# PUBLIC METHODS
isEven: () ->
return @value %% 2 is 0
isOdd: () ->
return @value %% 2 is 1
toInt: () ->
return mathJS.Int._fromPool @value
getSet: () ->
return mathJS.Domains.N
# end js/Numbers/Int.coffee
# from js/Numbers/Fraction.coffee
class mathJS.Fraction extends mathJS.Number
###*
* @Override mathJS.Number
* @static
* @method _fromPool
*###
@_fromPool: (numerator, denominator) ->
if @_pool.length > 0
if (e = @_getPrimitiveFrac(numerator))? and (d = @_getPrimitiveFrac(denominator))?
frac = @_pool.pop()
frac.numerator = e
frac.denominator = d
return frac
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate fraction from given '#{numerator}, #{denominator}'"
"Fraction.coffee"
)
else
# param check is done in constructor
return new @(numerator, denominator)
###*
* This method parses strings of the form "x / y" or "x : y".
* @Override mathJS.Number
* @static
* @method parse
*###
@parse: (str) ->
if "/" in str
parts = str.split "/"
return @new parts.first, parts.second
num = parseFloat(str)
if not isNaN(num)
# TODO
numerator = num
denominator = 1
# 123.456 = 123456 / 1000
while numerator % 1 isnt 0
numerator *= 10
denominator *= 10
return @new(numerator, denominator)
throw new mathJS.Errors.NotParseableError("Can't parse '#{str}' as fraction!")
###*
* @Override mathJS.Number
* @static
* @method getSet
*###
@getSet: () ->
return mathJS.Domains.Q
###*
* @Override mathJS.Number
* @static
* @method new
*###
@new: (e, d) ->
return @_fromPool e, d
@_getPrimitiveFrac: (param, skipCheck) ->
return mathJS.Int._getPrimitiveInt(param, skipCheck)
###########################################################################
# CONSTRUCTOR
constructor: (numerator, denominator) ->
@_numerator = null
@_denominator = null
Object.defineProperties @, {
numerator:
get: () ->
return @_numerator
set: @_setValue
denominator:
get: () ->
return @_denominator
set: @_setValue
}
if (e = @_getPrimitiveFrac(numerator))? and (d = @_getPrimitiveFrac(denominator))?
# TODO: when sth. like 12.55 / 0.8 is given => create 12.55*100 / 0.8*100 = 1255 / 80
if d is 0
throw new mathJS.Error.DivisionByZeroError("Denominator is 0 (when creating fraction)!")
@_numerator = e
@_denominator = d
else
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate fraction from given '#{numerator}, #{denominator}'"
"Fraction.coffee"
)
############################################################################################
# PROTECTED METHODS
_getPrimitiveFrac: (param) ->
return @constructor._getPrimitiveFrac(param)
############################################################################################
# PUBLIC METHODS
# end js/Numbers/Fraction.coffee
# from js/Numbers/Complex.coffee
###*
* @abstract
* @class Complex
* @constructor
* @param {Number} real
* Real part of the number. Either a mathJS.Number or primitive number.
* @param {Number} image
* Real part of the number. Either a mathJS.Number or primitive number.
* @extends Number
*###
# TODO: maybe extend mathJS.Vector instead?! or mix them
class mathJS.Complex extends mathJS.Number
PARSE_KEY = "0<KEY>"
###########################################################################
# STATIC
# ###*
# * @Override
# *###
# @_valueIsValid: (value) ->
# return value instanceof mathJS.Number or mathJS.isNum(value)
###*
* @Override
* This method creates an object with the keys "real" and "img" which have primitive numbers as their values.
* @static
* @method _getValueFromParam
* @param {Complex|Number} real
* @param {Number} img
* @return {Object}
*###
@_getValueFromParam: (real, img) ->
if real instanceof mathJS.Complex
return {
real: real.real
img: real.img
}
if real instanceof mathJS.Number and img instanceof mathJS.Number
return {
real: real.value
img: img.value
}
if mathJS.isNum(real) and mathJS.isNum(img)
return {
real: real
img: img
}
return null
@_fromPool: (real, img) ->
if @_pool.length > 0
if @_valueIsValid(real) and @_valueIsValid(img)
number = @_pool.pop()
number.real = real
number.img = img
return number
return null
else
return new @(real, img)
@parse: (str) ->
idx = str.toLowerCase().indexOf(PARSE_KEY)
if idx >= 0
parts = str.substring(idx + PARSE_KEY.length).split ","
if mathJS.isNum(real = parseFloat(parts[0])) and mathJS.isNum(img = parseFloat(parts[1]))
return @_fromPool real, img
return NaN
@random: (max1, min1, max2, min2) ->
return @_fromPool mathJS.randNum(max1, min1), mathJS.randNum(max2, min2)
###########################################################################
# CONSTRUCTOR
constructor: (real, img) ->
values = @_getValueFromParam(real, img)
# if not values?
# fStr = arguments.callee.caller.toString()
# throw new Error("mathJS: Expected 2 numbers or a complex number! Given (#{real}, #{img}) in \"#{fStr.substring(0, fStr.indexOf(")") + 1)}\"")
Object.defineProperties @, {
real:
get: @_getReal
set: @_setReal
img:
get: @_getImg
set: @_setImg
_fromPool:
value: @constructor._fromPool.bind(@constructor)
writable: false
enumarable: false
configurable: false
}
@real = values.real
@img = values.img
###########################################################################
# PRIVATE METHODS
###########################################################################
# PROTECTED METHODS
_setReal: (value) ->
if @_valueIsValid(value)
@_real = value.value or value.real or value
return @
_getReal: () ->
return @_real
_setImg: (value) ->
if @_valueIsValid(value)
@_img = value.value or value.img or value
return @
_getImg: () ->
return @_img
_getValueFromParam: @_getValueFromParam
###########################################################################
# PUBLIC METHODS
###*
* This method check for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2)
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @real is values.real and @img is values.img
return false
plus: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real + values.real, @img + values.img)
return NaN
increase: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
@real += values.real
@img += values.img
return @
plusSelf: @increase
minus: (n) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real - values.real, @img - values.img)
return NaN
decrease: (n) ->
values = @_getValueFromParam(r, i)
if values?
@real -= values.real
@img -= values.img
return @
minusSelf: @decrease
# TODO: adjust last functions for complex numbers
times: (r, i) ->
# return @_fromPool(@value * _getValueFromParam(n))
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real * values.real, @img * values.img)
return NaN
timesSelf: (n) ->
@value *= _getValueFromParam(n)
return @
divide: (n) ->
return @_fromPool(@value / _getValueFromParam(n))
divideSelf: (n) ->
@value /= _getValueFromParam(n)
return @
square: () ->
return @_fromPool(@value * @value)
squareSelf: () ->
@value *= @value
return @
cube: () ->
return @_fromPool(@value * @value * @value)
squareSelf: () ->
@value *= @value * @value
return @
sqrt: () ->
return @_fromPool(mathJS.sqrt @value)
sqrtSelf: () ->
@value = mathJS.sqrt @value
return @
pow: (n) ->
return @_fromPool(mathJS.pow @value, _getValueFromParam(n))
powSelf: (n) ->
@value = mathJS.pow @value, _getValueFromParam(n)
return @
sign: () ->
return mathJS.sign @value
toInt: () ->
return mathJS.Int._fromPool mathJS.floor(@value)
toDouble: () ->
return mathJS.Double._fromPool @value
toString: () ->
return "#{PARSE_KEY}#{@real.toString()},#{@img.toString()}"
clone: () ->
return @_fromPool(@value)
# add instance to pool
release: () ->
@constructor._pool.push @
return @constructor
# end js/Numbers/Complex.coffee
# from js/Algorithms/ShuntingYard.coffee
# from http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
class mathJS.Algorithms.ShuntingYard
CLASS = @
@specialOperators =
# unary plus/minus
"+" : "#"
"-" : "_"
@init = () ->
@specialOperations =
"#": mathJS.Operations.neutralPlus
"_": mathJS.Operations.negate
constructor: (settings) ->
@ops = ""
@precedence = {}
@associativity = {}
for op, opSettings of settings
@ops += op
@precedence[op] = opSettings.precedence
@associativity[op] = opSettings.associativity
isOperand = (token) ->
return mathJS.isNum(token)
toPostfix: (str) ->
# remove spaces
str = str.replace /\s+/g, ""
# make implicit multiplication explicit (3x=> 3*x, xy => x*y)
# TODO: what if a variable/function has more than 1 character: 3*abs(-3)
str = str.replace /(\d+|\w)(\w)/g,"$1*$2"
stack = []
ops = @ops
precedence = @precedence
associativity = @associativity
postfix = ""
# set string property to indicate format
postfix.postfix = true
for token, i in str
# if token is an operator
if token in ops
o1 = token
o2 = stack.last()
# handle unary plus/minus => just add special char
if i is 0 or prevToken is "("
if CLASS.specialOperators[token]?
postfix += "#{CLASS.specialOperators[token]} "
else
# while operator token, o2, on top of the stack
# and o1 is left-associative and its precedence is less than or equal to that of o2
# (the algorithm on wikipedia says: or o1 precedence < o2 precedence, but I think it should be)
# or o1 is right-associative and its precedence is less than that of o2
while o2 in ops and (associativity[o1] is "left" and precedence[o1] <= precedence[o2]) or (associativity[o1] is "right" and precedence[o1] < precedence[o2])
# add o2 to output queue
postfix += "#{o2} "
# pop o2 of the stack
stack.pop()
# next round
o2 = stack.last()
# push o1 onto the stack
stack.push(o1)
# if token is left parenthesis
else if token is "("
# then push it onto the stack
stack.push(token)
# if token is right parenthesis
else if token is ")"
# until token at top is (
while stack.last() isnt "("
postfix += "#{stack.pop()} "
# pop (, but not onto the output queue
stack.pop()
# token is an operand or a variable
else
postfix += "#{token} "
prevToken = token
# console.log token, stack
while stack.length > 0
postfix += "#{stack.pop()} "
return postfix.trim()
toExpression: (str) ->
if not str.postfix?
postfix = @toPostfix(str)
else
postfix = str
postfix = postfix.split " "
# gather all operators
ops = @ops
for k, v of CLASS.specialOperators
ops += v
i = 0
# while expression tree is not complete
while postfix.length > 1
token = postfix[i]
idxOffset = 0
if token in ops
if (op = mathJS.Operations[token])
startIdx = i - op.arity
endIdx = i
else if (op = CLASS.specialOperations[token])
startIdx = i + 1
endIdx = i + op.arity + 1
idxOffset = -1
params = postfix.slice(startIdx, endIdx)
startIdx += idxOffset
# # convert parameter strings to mathJS objects
for param, j in params when typeof param is "string"
if isOperand(param)
params[j] = new mathJS.Expression(parseFloat(param))
else
params[j] = new mathJS.Variable(param)
# create expression from parameters
exp = new mathJS.Expression(op, params...)
# this expression replaces the operation and its parameters
postfix.splice(startIdx, params.length + 1, exp)
# reset i to the first replaced element index -> increase in next iteration -> new element
i = startIdx + 1
# constants
else if isOperand(token)
postfix[i++] = new mathJS.Expression(parseFloat(token))
# variables
else
postfix[i++] = new mathJS.Variable(token)
return postfix.first
# end js/Algorithms/ShuntingYard.coffee
# from js/Formals/Operation.coffee
class mathJS.Operation
constructor: (name, precedence, associativity="left", commutative, func, inverse, setEquivalent) ->
@name = name
@precedence = precedence
@associativity = associativity
@commutative = commutative
@func = func
@arity = func.length # number of parameters => unary, binary, ternary...
@inverse = inverse or null
@setEquivalent = setEquivalent or null
eval: (args) ->
return @func.apply(@, args)
invert: () ->
if @inverse?
return @inverse.apply(@, arguments)
return null
# ABSTRACT OPERATIONS
# Those functions make sure primitives are converted correctly and calls the according operation on it"s first argument.
# They are the actual functions of the operations.
# TODO: no DRY
mathJS.Abstract =
Operations:
# arithmetical
divide: (x, y) ->
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
return x.divide(y)
minus: (x, y) ->
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
return x.minus(y)
plus: (x, y) ->
# numbers -> convert to mathJS.Number
# => int to real
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
# else if x instanceof mathJS.Variable or y instanceof mathJS.Variable
# return new mathJS.Expression(mathJS.Operations.plus, x, y)
# else if x.plus?
# return x.plus(y)
return x.plus(y)
# throw new mathJS.Errors.InvalidParametersError("...")
times: (x, y) ->
# numbers -> convert to mathJS.Number
# => int to real
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
return x.times(y)
negate: (x) ->
if mathJS.Number.valueIsValid(x)
x = new mathJS.Number(x)
return x.negate()
unaryPlus: (x) ->
if mathJS.Number.valueIsValid(x)
x = new mathJS.Number(x)
return x.clone()
# boolean / logical (converting from primitives to numbers doesn"t make sense because 3 and 4 is not defined)
and: (x, y) ->
return x.and(y)
or: (x, y) ->
return x.or(y)
not: (x) ->
return x.not()
nand: (x, y) ->
return x.nand(y)
nor: (x, y) ->
return x.nor(y)
xor: (x, y) ->
return x.xor(y)
equals: (x, y) ->
return x.equals(y)
###
PRECEDENCE (top to bottom):
(...)
factorial
unary +/-
exponents, roots
multiplication, division
addition, subtraction
###
cached =
division: new mathJS.Operation(
"divide"
1
"left"
false
mathJS.pow
mathJS.root
)
addition: new mathJS.Operation(
"plus"
1
"left"
true
mathJS.Abstract.Operations.plus
mathJS.Abstract.Operations.minus
)
subtraction: new mathJS.Operation(
"plus"
1
"left"
false
mathJS.Abstract.Operations.minus
mathJS.Abstract.Operations.plus
)
multiplication: new mathJS.Operation(
"times"
1
"left"
true
mathJS.Abstract.Operations.times
mathJS.Abstract.Operations.divide
)
exponentiation: new mathJS.Operation(
"pow"
1
"right"
false
mathJS.pow
mathJS.root
)
factorial: new mathJS.Operation(
"factorial"
10
"right"
false
mathJS.factorial
mathJS.factorialInverse
)
negate: new mathJS.Operation(
"negate"
11
"none"
false
mathJS.Abstract.Operations.negate
mathJS.Abstract.Operations.negate
)
unaryPlus: new mathJS.Operation(
"unaryPlus"
11
"none"
false
mathJS.Abstract.Operations.unaryPlus
mathJS.Abstract.Operations.unaryPlus
)
and: new mathJS.Operation(
"and"
1
"left"
true
mathJS.Abstract.Operations.and
null
"intersection"
)
or: new mathJS.Operation(
"or"
1
"left"
true
mathJS.Abstract.Operations.or
null
"union"
)
not: new mathJS.Operation(
"not"
5
"none"
false
mathJS.Abstract.Operations.not
mathJS.Abstract.Operations.not
"complement"
)
nand: new mathJS.Operation(
"nand"
1
"left"
true
mathJS.Abstract.Operations.nand
null
)
nor: new mathJS.Operation(
"nor"
1
"left"
true
mathJS.Abstract.Operations.nor
null
)
xor: new mathJS.Operation(
"xor"
1
"left"
true
mathJS.Abstract.Operations.xor
null
)
equals: new mathJS.Operation(
"equals"
1
"left"
true
mathJS.Abstract.Operations.equals
null
"intersection"
)
mathJS.Operations =
# arithmetical
"+": cached.addition
"plus": cached.addition
"-": cached.subtraction
"minus": cached.subtraction
"*": cached.multiplication
"times": cached.multiplication
"/": cached.division
":": cached.division
"divide": cached.division
"^": cached.exponentiation
"pow": cached.exponentiation
"!": cached.factorial
"negate": cached.negate
"-u": cached.negate
"u-": cached.negate
"unaryMinus": cached.negate
"neutralMinus": cached.negate
"+u": cached.unaryPlus
"u+": cached.unaryPlus
"unaryPlus": cached.unaryPlus
"neutralPlus": cached.unaryPlus
# logical
"and": cached.and
"or": cached.or
"not": cached.not
"nand": cached.nand
"nor": cached.nor
"xor": cached.xor
"equals": cached.equals
"=": cached.equals
"xnor": cached.equals
# end js/Formals/Operation.coffee
# from js/Formals/Expression.coffee
###*
* Tree structure of expressions. It consists of 2 expression and 1 operation.
* @class Expression
* @constructor
* @param operation {Operation|String}
* @param expressions... {Expression}
*###
class mathJS.Expression
CLASS = @
@fromString: (str) ->
# TODO: parse string
return new mathJS.Expression()
@parse = @fromString
@parser = new mathJS.Algorithms.ShuntingYard(
# TODO: use operations from operation class
"!":
precedence: 5
associativity: "right"
"^":
precedence: 4
associativity: "right"
"*":
precedence: 3
associativity: "left"
"/":
precedence: 3
associativity: "left"
"+":
precedence: 2
associativity: "left"
"-":
precedence: 2
associativity: "left"
)
# TODO: make those meaningful: eg. adjusted parameter lists?!
@new: (operation, expressions...) ->
return new CLASS(operation, expressions)
constructor: (operation, expressions...) ->
# map op string to actual operation object
if typeof operation is "string"
if mathJS.Operations[operation]?
operation = mathJS.Operations[operation]
else
throw new mathJS.Errors.InvalidParametersError("Invalid operation string given: \"#{operation}\".")
# if constructor was called from static .new()
if expressions.first instanceof Array
expressions = expressions.first
# just 1 parameter => constant/value or hash given
if expressions.length is 0
# constant/variable value given => leaf in expression tree
if mathJS.Number.valueIsValid(operation)
@operation = null
@expressions = [new mathJS.Number(operation)]
else
if operation instanceof mathJS.Variable
@operation = null
@expressions = [operation]
# variable string. eg. "x"
else
@operation = null
@expressions = [new mathJS.Variable(operation)]
# else
# throw new mathJS.Errors.InvalidParametersError("...")
else if operation.arity is expressions.length
@operation = operation
@expressions = expressions
else
throw new mathJS.Errors.InvalidArityError("Invalid number of parameters (#{expressions.length}) for Operation \"#{operation.name}\". Expected number of parameters is #{operation.arity}.")
###*
* This method tests for the equality of structure. So 2*3x does not equal 6x!
* For that see mathEquals().
* @method equals
*###
equals: (expression) ->
# immediate return if different number of sub expressions
if @expressions.length isnt expression.expressions.length
return false
# leaf -> anchor
if not @operation?
return not expression.operation? and expression.expressions.first.equals(@expressions.first)
# order of expressions doesnt matter
if @operation.commutative is true
doneExpressions = []
for exp, i in @expressions
res = false
for x, j in expression.expressions when j not in doneExpressions and x.equals(exp)
doneExpressions.push j
res = true
break
# exp does not equals any of the expressions => return false
if not res
return false
return true
# order of expressions matters
else
# res = true
for e1, i in @expressions
e2 = expression.expressions[i]
# res = res and e1.equals(e2)
if not e1.equals(e2)
return false
# return res
return true
###*
* This method tests for the logical/mathematical equality of 2 expressions.
*###
# TODO: change naming here! equals should always be mathematical!!!
mathEquals: (expression) ->
return @simplify().equals expression.simplify()
###*
* @method eval
* @param values {Object}
* An object of the form {varKey: varVal}.
* @returns The value of the expression (specified by the values).
*###
eval: (values) ->
# replace primitives with mathJS objects
for k, v of values
if mathJS.isPrimitive(v) and mathJS.Number.valueIsValid(v)
values[k] = new mathJS.Number(v)
# leaf => first expression is either a mathJS.Variable or a constant (-> Number)
if not @operation?
return @expressions.first.eval(values)
# no leaf => eval substrees
args = []
for expression in @expressions
# evaluated expression is a variable => stop because this and the "above" expression cant be evaluated further
value = expression.eval(values)
if value instanceof mathJS.Variable
return @
# evaluation succeeded => add to list of evaluated values (which will be passed to the operation)
args.push value
return @operation.eval(args)
simplify: () ->
# simplify numeric values aka. non-variable arithmetics
evaluated = @eval()
# actual simplification: less ops!
# TODO: gather simplification patterns
return @
getVariables: () ->
if not @operation?
if (val = @expressions.first) instanceof mathJS.Variable
return [val]
return []
res = []
for expression in @expressions
res = res.concat expression.getVariables()
return res
_getSet: () ->
# leaf
if not @operation?
return @expressions.first._getSet()
# no leaf
res = null
for expression in @expressions
if res?
res = res[@operation.setEquivalent] expression._getSet()
else
res = expression._getSet()
# TODO: the "or new mathJS.Set()" should be unnecessary
return res or new mathJS.Set()
###*
* Get the "range" of the expression (the set of all possible results).
* @method getSet
*###
getSet: () ->
return @eval()._getSet()
# MAKE ALIASES
evaluatesTo: @::getSet
if DEBUG
@test = () ->
e1 = new CLASS(5)
e2 = new CLASS(new mathJS.Variable("x", mathJS.Number))
e4 = new CLASS("+", e1, e2)
console.log e4.getVariables()
# console.log e4.eval({x: new mathJS.Number(5)})
# console.log e4.eval()
# e5 = e4.eval()
# console.log e5.eval({x: new mathJS.Number(5)})
str = "(5x - 3) ^ 2 * 2 / (4y + 3!)"
# (5x-3)^2 * 2 / (4y + 6)
return "test done"
# end js/Formals/Expression.coffee
# from js/Formals/Variable.coffee
###*
* @class Variable
* @constructor
* @param {String} name
* This is name name of the variable (mathematically)
* @param {mathJS.Set} type
*###
# TODO: make interfaces meta: eg. have a Variable@Evaluable.coffee file that contains the interface and inset on build
# class mathJS.Variable extends mathJS.Evaluable
class mathJS.Variable extends mathJS.Expression
# TODO: change this to mathJS.Domains.R when R is implemented
constructor: (name, elementOf=mathJS.Domains.N) ->
@name = name
if elementOf.getSet?
@elementOf = elementOf.getSet()
else
@elementOf = elementOf
_getSet: () ->
return @elementOf
equals: (variable) ->
return @name is variable.name and @elementOf.equals variable.elementOf
plus: (n) ->
return new mathJS.Expression("+", @, n)
minus: (n) ->
return new mathJS.Expression("-", @, n)
times: (n) ->
return new mathJS.Expression("*", @, n)
divide: (n) ->
return new mathJS.Expression("/", @, n)
eval: (values) ->
if values? and (val = values[@name])?
if @elementOf.contains val
return val
console.warn "Given value \"#{val}\" is not in the set \"#{@elementOf.name}\"."
return @
# end js/Formals/Variable.coffee
# from js/Formals/Equation.coffee
class mathJS.Equation
constructor: (left, right) ->
# if left.mathEquals(right)
# @left = left
# @right = right
# else
# # TODO: only if no variables are contained
# throw new mathJS.Errors.InvalidParametersError("The 2 expressions are not (mathematically) equal!")
@left = left
@right = right
solve: (variable) ->
left = @left.simplify()
right = @right.simplify()
solutions = new mathJS.Set()
# convert to actual variable if only the name was given
if variable not instanceof mathJS.Variable
variables = left.getVariables().concat right.getVariables()
variable = (v for v in variables when v.name is variable).first
return solutions
eval: (values) ->
return @left.eval(values).equals @right.eval(values)
simplify: () ->
@left = @left.simplify()
@right = @right.simplify()
return @
# MAKE ALIASES
# ...
# end js/Formals/Equation.coffee
# from js/Sets/AbstractSet.coffee
class _mathJS.AbstractSet extends _mathJS.Object
@implements _mathJS.Orderable, _mathJS.Poolable, _mathJS.Parseable
@fromString: (str) ->
@parse: () ->
return @fromString.apply(@, arguments)
cartesianProduct: (set) ->
clone: () ->
contains: (elem) ->
equals: (set) ->
getElements: () ->
infimum: () ->
intersection: (set) ->
isSubsetOf: (set) ->
min: () ->
max: () ->
# PRE-IMPLEMENTED (may be inherited)
size: () ->
return Infinity
supremum: () ->
union: (set) ->
intersection: (set) ->
without: (set) ->
###########################################################################
# PRE-IMPLEMENTED (to be inherited)
complement: (universe) ->
return universe.minus(@)
disjoint: (set) ->
return @intersection(set).size() is 0
intersects: (set) ->
return not @disjoint(set)
isEmpty: () ->
return @size() is 0
isSupersetOf: (set) ->
return set.isSubsetOf @
pow: (exponent) ->
sets = []
for i in [0...exponent]
sets.push @
return @cartesianProduct.apply(@, sets)
###########################################################################
# ALIASES
@_makeAliases: () ->
aliasesData =
size: ["cardinality"]
without: ["difference", "except", "minus"]
contains: ["has"]
intersection: ["intersect"]
isSubsetOf: ["subsetOf"]
isSupersetOf: ["supersetOf"]
cartesianProduct: ["times"]
for orig, aliases of aliasesData
for alias in aliases
@::[alias] = @::[orig]
return @
@_makeAliases()
# end js/Sets/AbstractSet.coffee
# from js/Sets/Set.coffee
###*
* @class Set
* @constructor
* @param {mixed} specifications
* To create an empty set pass no parameters.
* To create a discrete set list the elements. Those elements must implement the comparable interface and must not be arrays. Non-comparable elements will be ignored unless they are primitives.
* To create a set from set-builder notation pass the parameters must have the following types:
* mathJS.Expression|mathJS.Tuple|mathJS.Number, mathJS.Predicate
# TODO: package all those types (expression-like) into 1 prototype (Variable already is)
*###
class mathJS.Set extends _mathJS.AbstractSet
###########################################################################
# STATIC
###*
* Optionally the left and right configuration can be passed directly (each with an open- and value-property) or the Interval can be parsed from String (like "(2, 6 ]").
* @static
* @method createInterval
* @param leftOpen {Boolean}
* @param leftValue {Number|mathJS.Number}
* @param rightValue {Number|mathJS.Number}
* @param rightOpen {Boolean}
*###
@createInterval: (parameters...) ->
if typeof (str = parameters.first) is "string"
# remove spaces
str = str.replace /\s+/g, ""
.split ","
left =
open: str.first[0] is "("
value: new mathJS.Number(parseInt(str.first.slice(1), 10))
right =
open: str.second.last is ")"
value: new mathJS.Number(parseInt(str.second.slice(0, -1), 10))
# # first parameter has an .open property => assume ctor called from fromString()
# else if parameters.first.open?
# left = parameters.first
# right = parameters.second
else
second = parameters.second
fourth = parameters.fourth
left =
open: parameters.first
value: (if second instanceof mathJS.Number then second else new mathJS.Number(second))
right =
open: parameters.third
value: (if fourth instanceof mathJS.Number then fourth else new mathJS.Number(fourth))
# an interval can be expressed with a conditional set: (a,b) = {x | x in R, a < x < b}
expression = new mathJS.Variable("x", mathJS.Domains.N)
predicate = null
return new mathJS.Set(expression, predicate)
###########################################################################
# CONSTRUCTOR
constructor: (parameters...) ->
# ANALYSE PARAMETERS
# nothing passed => empty set
if parameters.length is 0
@discreteSet = new _mathJS.DiscreteSet()
@conditionalSet = new _mathJS.ConditionalSet()
# discrete and conditional set given (from internal calls like union())
else if parameters.first instanceof _mathJS.DiscreteSet and parameters.second instanceof _mathJS.ConditionalSet
@discreteSet = parameters.first
@conditionalSet = parameters.second
# set-builder notation
else if parameters.first instanceof mathJS.Expression and parameters.second instanceof mathJS.Expression
console.log "set builder"
@discreteSet = new _mathJS.DiscreteSet()
@conditionalSet = new _mathJS.ConditionalSet(parameters.first, parameters.slice(1))
# discrete set
else
# array given -> make its elements the set elements
if parameters.first instanceof Array
parameters = parameters.first
console.log "params:", parameters
@discreteSet = new _mathJS.DiscreteSet(parameters)
@conditionalSet = new _mathJS.ConditionalSet()
###########################################################################
# PRIVATE METHODS
# TODO: inline the following 2 if used nowhere else
newFromDiscrete = (set) ->
return new mathJS.Set(set.getElements())
newFromConditional = (set) ->
return new mathJS.Set(set.expression, set.domains, set.predicate)
###########################################################################
# PROTECTED METHODS
###########################################################################
# PUBLIC METHODS
getElements: (n=mathJS.config.set.defaultNumberOfElements, sorted=false) ->
res = @discreteSet.elems.concat(@conditionalSet.getElements(n, sorted))
if sorted isnt true
return res
return res.sort(mathJS.sortFunction)
size: () ->
return @discreteSet.size() + @conditionalSet.size()
clone: () ->
return newFromDiscrete(@discreteSet).union(newFromConditional(@conditionalSet))
equals: (set) ->
if set.size() isnt @size()
return false
return set.discreteSet.equals(@discreteSet) and set.conditionalSet.equals(@conditionalSet)
getSet: () ->
return @
isSubsetOf: (set) ->
return @conditionalSet.isSubsetOf(set) or @discreteSet.isSubsetOf(set)
isSupersetOf: (set) ->
return @conditionalSet.isSupersetOf(set) or @discreteSet.isSupersetOf(set)
contains: (elem) ->
return @conditionalSet.contains(@conditionalSet) or @discreteSet.contains(@discreteSet)
union: (set) ->
# if domain (N, Z, Q, R, C) let it handle the union because it knows know more about itself than this does
# also domains have neither discrete nor conditional sets
if set.isDomain
return set.union(@)
return new mathJS.Set(@discreteSet.union(set.discreteSet), @conditionalSet.union(set.conditionalSet))
intersection: (set) ->
if set.isDomain
return set.intersection(@)
return new mathJS.Set(@discreteSet.intersection(set.discreteSet), @conditionalSet.intersection(set.conditionalSet))
complement: () ->
if @universe?
return asdf
return new mathJS.EmptySet()
without: (set) ->
cartesianProduct: (set) ->
min: () ->
return mathJS.min(@discreteSet.min().concat @conditionalSet.min())
max: () ->
return mathJS.max(@discreteSet.max().concat @conditionalSet.max())
infimum: () ->
supremum: () ->
# end js/Sets/Set.coffee
# from js/Sets/DiscreteSet.coffee
###*
* This class is a Setof explicitely listed elements (with no needed logic).
* @class DiscreteSet
* @constructor
* @param {Function|Class} type
* @param {Set} universe
* Optional. If given, the created Set will be interpreted as a sub set of the universe.
* @param {mixed} elems...
* Optional. This and the following parameters serve as elements for the new Set. They will be in the new Set immediately.
* @extends Set
*###
class _mathJS.DiscreteSet extends mathJS.Set
###########################################################################
# CONSTRUCTOR
constructor: (elems...) ->
if elems.first instanceof Array
elems = elems.first
@elems = []
for elem in elems when not @contains(elem)
if not mathJS.isNum(elem)
@elems.push elem
else
@elems.push new mathJS.Number(elem)
###########################################################################
# PROTECTED METHODS
###########################################################################
# PUBLIC METHODS
# discrete sets only!
cartesianProduct: (set) ->
elements = []
for e in @elems
for x in set.elems
elements.push new mathJS.Tuple(e, x)
return new _mathJS.DiscreteSet(elements)
clone: () ->
return new _mathJS.DiscreteSet(@elems)
contains: (elem) ->
for e in @elems when elem.equals e
return true
return false
# discrete sets only!
equals: (set) ->
# return @isSubsetOf(set) and set.isSubsetOf(@)
for e in @elems when not set.contains e
return false
for e in set.elems when not @contains e
return false
return true
###*
* Get the elements of the set.
* @method getElements
* @param sorted {Boolean}
* Optional. If set to `true` returns the elements in ascending order.
*###
getElements: (sorted) ->
if sorted isnt true
return @elems.clone()
return @elems.clone().sort(mathJS.sortFunction)
# discrete sets only!
intersection: (set) ->
elems = []
for x in @elems
for y in set.elems when x.equals y
elems.push x
return new _mathJS.DiscreteSet(elems)
isSubsetOf: (set) ->
for e in @elems when not set.contains e
return false
return true
size: () ->
# TODO: cache size
return @elems.length
# discrete sets only!
union: (set) ->
return new _mathJS.DiscreteSet(set.elems.concat(@elems))
without: (set) ->
return (elem for elem in @elems when not set.contains elem)
min: () ->
return mathJS.min @elems
max: () ->
return mathJS.max @elems
infimum: () ->
supremum: () ->
@_makeAliases()
# end js/Sets/DiscreteSet.coffee
# from js/Sets/ConditionalSet.coffee
class _mathJS.ConditionalSet extends mathJS.Set
CLASS = @
###
{2x^2 | x in R and 0 <= x < 20 and x = x^2} ==> {0, 1}
x in R and 0 <= x < 20 and x = x^2 <=> R intersect [0, 20) intersect {0,1} (where 0 and 1 have to be part of the previous set)
do the following:
1. map domains to domains
2. map unequations to intervals
3. map equations to (discrete?!) sets
4. create intersection of all!
simplifications:
1. domains intersect interval = interval (because in this notation the domain is the superset)
so it wouldnt make sense to say: x in N and x in [0, 10] and expect the set to be infinite!!
the order does not matter (otherwise (x in [0, 10] and x in N) would be infinite!!)
2. when trying to get equation solutions numerically (should this ever happen??) look for interval first to get boundaries
###
# predicate is an boolean expression
# TODO: try to find out if the set is actually discrete!
# TODO: maybe a 3rd parameter "baseSet" should be passed to indicate where the generator comes from
# TODO: predicate could also be the base set itself. if not it must be derived from the (boolean) predicate
# TODO: predicate's type is Expression.Boolean
constructor: (expression, predicate) ->
# empty set
if arguments.length is 0
@generator = null
# non-empty set
else if expression instanceof mathJS.Generator
@generator = expression
# no generator passed => standard parameters
else
if predicate instanceof mathJS.Expression
predicate = predicate.getSet()
# f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple
@generator = new mathJS.Generator(
# f: predicate -> ?? (expression.getSet())
# x |-> expression(x)
new mathJS.Function("f", expression, predicate, expression.getSet())
predicate.min()
predicate.max()
)
cartesianProduct: (sets...) ->
generators = [@generator].concat(set.generator for set in sets)
return new _mathJS.ConditionalSet(mathJS.Generator.product(generators...))
clone: () ->
return new CLASS()
contains: (elem) ->
if mathJS.isComparable elem
if @condition?.check(elem) is true
return true
return false
equals: (set) ->
if set instanceof CLASS
return @generator.f.equals set.generator.f
# normal set
return set.discreteSet.isEmpty() and @generator.f.equals set.conditionSet.generator.f
getElements: (n, sorted) ->
res = []
# TODO
return res
# TODO: "and" generators
intersection: (set) ->
isSubsetOf: (set) ->
isSupersetOf: (set) ->
size: () ->
return @generator.f.range.size()
# TODO: "or" generators
union: (set) ->
without: (set) ->
@_makeAliases()
if DEBUG
@test = () ->
e1 = new mathJS.Expression(5)
e2 = new mathJS.Expression(new mathJS.Variable("x", mathJS.Number))
e3 = new mathJS.Expression("+", e1, e2)
p1 = new mathJS.Expression(new mathJS.Variable("x", mathJS.Number))
p2 = new mathJS.Expression(4)
p3 = new mathJS.Expression("=", p1, p2)
console.log p3.eval(x: 4)
console.log p3.getSet()
console.log AAA
# set = new _mathJS.ConditionalSet(e3, p3)
# console.log set
return "done"
# end js/Sets/ConditionalSet.coffee
# from js/Sets/Tuple.coffee
class mathJS.Tuple
###########################################################################
# CONSTRUCTOR
constructor: (elems...) ->
if elems.first instanceof Array
elems = elems.first
temp = []
for elem in elems
if not mathJS.isNum(elem)
temp.push elem
else
temp.push new mathJS.Number(elem)
@elems = temp
@_size = temp.length
###########################################################################
# PUBLIC METHODS
Object.defineProperties @::, {
first:
get: () ->
return @at(0)
set: () ->
return @
length:
get: () ->
return @_size
set: () ->
return @
}
add: (elems...) ->
return new mathJS.Tuple(@elems.concat(elems))
at: (idx) ->
return @elems[idx]
clone: () ->
return new mathJS.Tuple(@elems)
contains: (elem) ->
for e in @elems when e.equals elem
return true
return false
equals: (tuple) ->
if @_size isnt tuple._size
return false
elements = tuple.elems
for elem, idx in @elems when not elem.equals elements[idx]
return false
return true
###*
* Evaluates the tuple.
* @param values {Array}
* # TODO: also enables hash of vars
* A value for each tuple element.
*###
eval: (values) ->
elems = (elem.eval(values[i]) for elem, i in @elems)
return new mathJS.Tuple(elems)
###*
* Get the elements of the Tuple.
* @method getElements
*###
getElements: () ->
return @elems.clone()
insert: (idx, elems...) ->
elements = []
for elem, i in @elems
if i is idx
elements = elements.concat(elems)
elements.push elem
return new mathJS.Tuple(elements)
isEmpty: () ->
return @_size() is 0
###*
* Removes the first occurences of the given elements.
*###
remove: (elems...) ->
elements = @elems.clone()
for e in elems
for elem, i in elements when elem.equals e
elements.splice i, 1
break
return new mathJS.Tuple(elements)
removeAt: (idx, n=1) ->
elems = []
for elem, i in @elems when i < idx or i >= idx + n
elems.push elem
return new mathJS.Tuple(elems)
size: () ->
return @_size
slice: (startIdx, endIdx=@_size) ->
return new mathJS.Tuple(@elems.slice(startIdx, endIdx))
###########################################################################
# ALIASES
cardinality: @::size
extendBy: @::add
get: @::at
has: @::contains
addAt: @::insert
insertAt: @::insert
reduceBy: @::remove
# end js/Sets/Tuple.coffee
# from js/Sets/Function.coffee
class mathJS.Function extends mathJS.Set
# EQUAL!
# function:
# f: X -> Y, f(x) = 3x^2 - 5x + 7
# set:
# {(x, 3x^2 - 5x + 7) | x in X}
# domain is implicit by variables" types contained in the expression
# range is implicit by the expression
# constructor: (name, domain, range, expression) ->
constructor: (name, expression, domain, range) ->
@name = name
@expression = expression
if domain instanceof mathJS.Set
@domain = domain
else
@domain = new mathJS.Set(expression.getVariables())
if range instanceof mathJS.Set
@range = range
else
@range = expression.getSet()
@_cache = {}
@caching = true
super()
###*
* Empty the cache or reset to given cache.
* @method clearCache
* @param cache {Object}
* @return mathJS.Function
* @chainable
*###
clearCache: (cache) ->
if not cache?
@_cache = {}
else
@_cache = cache
return @
###*
* Evaluate the function for given values.
* @method get
* @param values {Array|Object}
* If an array the first value will be associated with the first variable name. Otherwise an object like {x: 42} is expected.
* @return
*###
eval: (values...) ->
tmp = {}
if values instanceof Array
for value, i in values
tmp[@variableNames[i]] = value
values = tmp
# check if values are in domain
for varName, val of values
if not domain.contains(val)
return null
return @expression.eval(values)
# make alias
at: @eval
get: @eval
# end js/Sets/Function.coffee
# from js/Sets/Generators/AbstractGenerator.coffee
class _mathJS.AbstractGenerator extends _mathJS.Object
###########################################################################
# CONSTRUCTOR
constructor: (f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple) ->
@f = f
@inverseF = f.getInverse()
@minX = minX
@maxX = maxX
@stepSize = stepSize
@maxIndex = maxIndex
@tuple = tuple
@x = minX
@overflowed = false
@index = 0
###########################################################################
# DEFINED PROPS
Object.defineProperties @::, {
function:
get: () ->
return @f
set: (f) ->
@f = f
@inverseF = f.getInverse()
return @
}
###########################################################################
# STATIC
@product: (generators...) ->
@or: (gen1, gen2) ->
@and: (gen1, gen2) ->
###########################################################################
# PUBLIC
###*
* Indicates whether the set the generator creates contains the given value or not.
* @method generates
*###
generates: (y) ->
if @f.range.contains(y)
#
if @inverseF?
return @inverseF.eval(y)
return
return false
eval: (n) ->
# eval each tuple element individually (the tuple knows how to do that)
if @tuple?
return @tuple.eval(n)
# eval expression
if @f.eval?
@f.eval(n)
# eval js function
return @f.call(@, n)
hasNext: () ->
if @tuple?
for g, i in @tuple.elems when g.hasNext()
return true
return false
return not @overflowed and @x < @maxX and @index < @maxIndex
_incX: () ->
@index++
# more calculation than just "@x += @stepSize" but more precise!
@x = @minX + @index * @stepSize
if @x > @maxX
@x = @minX
@index = 0
@overflowed = true
return @x
next: () ->
if @tuple?
res = @eval(g.x for g in @tuple.elems)
###
0 0
0 1
1 0
1 1
###
# start binary-like counting (so all possibilities are done)
i = 0
maxI = @tuple.length
generator = @tuple.first
generator._incX()
while i < maxI and generator.overflowed
generator.overflowed = false
generator = @tuple.at(++i)
# # "if" needed for very last value -> i should theoretically overflow
# => i refers to the (n+1)st tuple element (which only has n elements)
if generator?
generator._incX()
return res
# no tuple => simple generator
res = @eval(@x)
@_incX()
return res
reset: () ->
@x = @minX
@index = 0
return @
if DEBUG
@test = () ->
# simple
g = new mathJS.Generator(
(x) ->
return 3*x*x+2*x-5
-10
10
0.2
)
res = []
while g.hasNext()
tmp = g.next()
# console.log tmp
res.push tmp
tmp = g.next()
# console.log tmp
res.push tmp
console.log "simple test:", (if res.length is ((g.maxX - g.minX) / g.stepSize + 1) then "successful" else "failed")
# "nested"
g1 = new mathJS.Generator(
(x) -> x,
0,
5,
0.5
)
g2 = new mathJS.Generator(
(x) -> 2*x,
-2,
10,
2
)
g = mathJS.Generator.product(g1, g2)
res = []
while g.hasNext()
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
console.log "tuple test:", (if res.length is ((g1.maxX - g1.minX) / g1.stepSize + 1) * ((g2.maxX - g2.minX) / g2.stepSize + 1) then "successful" else "failed")
g = new mathJS.Generator((x) -> x)
while g.hasNext()
tmp = g.next()
# console.log tmp
tmp = g.next()
# console.log tmp
return "done"
# end js/Sets/Generators/AbstractGenerator.coffee
# from js/Sets/Generators/DiscreteGenerator.coffee
class mathJS.DiscreteGenerator extends _mathJS.AbstractGenerator
###########################################################################
# CONSTRUCTOR
constructor: (f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple) ->
@f = f
@inverseF = f.getInverse()
@minX = minX
@maxX = maxX
@stepSize = stepSize
@maxIndex = maxIndex
@tuple = tuple
@x = minX
@overflowed = false
@index = 0
###########################################################################
# DEFINED PROPS
Object.defineProperties @::, {
function:
get: () ->
return @f
set: (f) ->
@f = f
@inverseF = f.getInverse()
return @
}
###########################################################################
# STATIC
@product: (generators...) ->
return new mathJS.Generator(null, 0, Infinity, null, null, new mathJS.Tuple(generators))
@or: () ->
@and: () ->
###########################################################################
# PUBLIC
###*
* Indicates whether the set the generator creates contains the given value or not.
* @method generates
*###
generates: (y) ->
if @f.range.contains(y)
#
if @inverseF?
return @inverseF.eval(y)
return
return false
eval: (n) ->
# eval each tuple element individually (the tuple knows how to do that)
if @tuple?
return @tuple.eval(n)
# eval expression
if @f.eval?
@f.eval(n)
# eval js function
return @f.call(@, n)
hasNext: () ->
if @tuple?
for g, i in @tuple.elems when g.hasNext()
return true
return false
return not @overflowed and @x < @maxX and @index < @maxIndex
_incX: () ->
@index++
# more calculation than just "@x += @stepSize" but more precise!
@x = @minX + @index * @stepSize
if @x > @maxX
@x = @minX
@index = 0
@overflowed = true
return @x
next: () ->
if @tuple?
res = @eval(g.x for g in @tuple.elems)
###
0 0
0 1
1 0
1 1
###
# start binary-like counting (so all possibilities are done)
i = 0
maxI = @tuple.length
generator = @tuple.first
generator._incX()
while i < maxI and generator.overflowed
generator.overflowed = false
generator = @tuple.at(++i)
# # "if" needed for very last value -> i should theoretically overflow
# => i refers to the (n+1)st tuple element (which only has n elements)
if generator?
generator._incX()
return res
# no tuple => simple generator
res = @eval(@x)
@_incX()
return res
reset: () ->
@x = @minX
@index = 0
return @
if DEBUG
@test = () ->
# simple
g = new mathJS.Generator(
(x) ->
return 3*x*x+2*x-5
-10
10
0.2
)
res = []
while g.hasNext()
tmp = g.next()
# console.log tmp
res.push tmp
tmp = g.next()
# console.log tmp
res.push tmp
console.log "simple test:", (if res.length is ((g.maxX - g.minX) / g.stepSize + 1) then "successful" else "failed")
# "nested"
g1 = new mathJS.Generator(
(x) -> x,
0,
5,
0.5
)
g2 = new mathJS.Generator(
(x) -> 2*x,
-2,
10,
2
)
g = mathJS.Generator.product(g1, g2)
res = []
while g.hasNext()
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
console.log "tuple test:", (if res.length is ((g1.maxX - g1.minX) / g1.stepSize + 1) * ((g2.maxX - g2.minX) / g2.stepSize + 1) then "successful" else "failed")
g = new mathJS.Generator((x) -> x)
while g.hasNext()
tmp = g.next()
# console.log tmp
tmp = g.next()
# console.log tmp
return "done"
# end js/Sets/Generators/DiscreteGenerator.coffee
# from js/Sets/Generators/ContinuousGenerator.coffee
class mathJS.ContinuousGenerator extends _mathJS.AbstractGenerator
###########################################################################
# CONSTRUCTOR
constructor: (f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple) ->
@f = f
@inverseF = f.getInverse()
@minX = minX
@maxX = maxX
@stepSize = stepSize
@maxIndex = maxIndex
@tuple = tuple
@x = minX
@overflowed = false
@index = 0
###########################################################################
# DEFINED PROPS
Object.defineProperties @::, {
function:
get: () ->
return @f
set: (f) ->
@f = f
@inverseF = f.getInverse()
return @
}
###########################################################################
# STATIC
@product: (generators...) ->
return new mathJS.Generator(null, 0, Infinity, null, null, new mathJS.Tuple(generators))
@or: () ->
@and: () ->
###########################################################################
# PUBLIC
###*
* Indicates whether the set the generator creates contains the given value or not.
* @method generates
*###
generates: (y) ->
if @f.range.contains(y)
#
if @inverseF?
return @inverseF.eval(y)
return
return false
eval: (n) ->
# eval each tuple element individually (the tuple knows how to do that)
if @tuple?
return @tuple.eval(n)
# eval expression
if @f.eval?
@f.eval(n)
# eval js function
return @f.call(@, n)
hasNext: () ->
if @tuple?
for g, i in @tuple.elems when g.hasNext()
return true
return false
return not @overflowed and @x < @maxX and @index < @maxIndex
_incX: () ->
@index++
# more calculation than just "@x += @stepSize" but more precise!
@x = @minX + @index * @stepSize
if @x > @maxX
@x = @minX
@index = 0
@overflowed = true
return @x
next: () ->
if @tuple?
res = @eval(g.x for g in @tuple.elems)
###
0 0
0 1
1 0
1 1
###
# start binary-like counting (so all possibilities are done)
i = 0
maxI = @tuple.length
generator = @tuple.first
generator._incX()
while i < maxI and generator.overflowed
generator.overflowed = false
generator = @tuple.at(++i)
# # "if" needed for very last value -> i should theoretically overflow
# => i refers to the (n+1)st tuple element (which only has n elements)
if generator?
generator._incX()
return res
# no tuple => simple generator
res = @eval(@x)
@_incX()
return res
reset: () ->
@x = @minX
@index = 0
return @
if DEBUG
@test = () ->
# simple
g = new mathJS.Generator(
(x) ->
return 3*x*x+2*x-5
-10
10
0.2
)
res = []
while g.hasNext()
tmp = g.next()
# console.log tmp
res.push tmp
tmp = g.next()
# console.log tmp
res.push tmp
console.log "simple test:", (if res.length is ((g.maxX - g.minX) / g.stepSize + 1) then "successful" else "failed")
# "nested"
g1 = new mathJS.Generator(
(x) -> x,
0,
5,
0.5
)
g2 = new mathJS.Generator(
(x) -> 2*x,
-2,
10,
2
)
g = mathJS.Generator.product(g1, g2)
res = []
while g.hasNext()
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
console.log "tuple test:", (if res.length is ((g1.maxX - g1.minX) / g1.stepSize + 1) * ((g2.maxX - g2.minX) / g2.stepSize + 1) then "successful" else "failed")
g = new mathJS.Generator((x) -> x)
while g.hasNext()
tmp = g.next()
# console.log tmp
tmp = g.next()
# console.log tmp
return "done"
# end js/Sets/Generators/ContinuousGenerator.coffee
# from js/Sets/Domains/Domain.coffee
###*
* Domain ranks are like so:
* N -> 0
* Z -> 1
* Q -> 2
* I -> 2
* R -> 3
* C -> 4
* ==> union: take greater rank (if equal (and unequal names) take next greater rank)
* ==> intersection: take smaller rank (if equal (and unequal names) take empty set)
*###
class _mathJS.Sets.Domain extends _mathJS.AbstractSet
CLASS = @
@new: () ->
return new CLASS()
@_byRank: (rank) ->
for name, domain of mathJS.Domains when domain.rank is rank
return domain
return null
constructor: (name, rank, isCountable) ->
@isDomain = true
@name = name
@rank = rank
@isCountable = isCountable
clone: () ->
return @constructor.new()
size: () ->
return Infinity
equals: (set) ->
return set instanceof @constructor
intersection: (set) ->
if set.isDomain
if @name is set.name
return @
if @rank < set.rank
return @
if @rank > set.rank
return set
return new mathJS.Set()
# TODO !!
return false
union: (set) ->
if set.isDomain
if @name is set.name
return @
if @rank > set.rank
return @
if @rank < set.rank
return set
return CLASS._byRank(@rank + 1)
# TODO !!
return false
@_makeAliases()
# end js/Sets/Domains/Domain.coffee
# from js/Sets/Domains/N.coffee
class mathJS.Sets.N extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("N", 0, true)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return mathJS.isInt(x) or new mathJS.Int(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
union: (set, n = mathJS.settings.set.maxIterations, matches = mathJS.settings.set.maxMatches) ->
# AND both checker functions
checker = (elem) ->
return self.checker(elem) or set.checker(elem)
generator = () ->
# TODO: how to avoid doubles? implementations that use boolean arrays => XOR operations on elements
# discrete set
if set instanceof mathJS.DiscreteSet or set.instanceof?(mathJS.DiscreteSet)
# non-discrete set (empty or conditional set, or domain)
else if set instanceof mathJS.Set or set.instanceof?(mathJS.Set)
# check for domains. if set is a domain this or the set can directly be returned because they are immutable
# N
if mathJS.instanceof(set, mathJS.Set.N)
return @
# Q, R # TODO: other domains like I, C
if mathJS.instanceof(set, mathJS.Domains.Q) or mathJS.instanceof(set, mathJS.Domains.R)
return set
self = @
# param was no set
return null
intersect: (set) ->
# AND both checker functions
checker = (elem) ->
return self.checker(elem) and set.checker(elem)
# if the f2-invert of the y-value of f1 lies within f2" domain/universe both ranges include that value
# or vice versa
# we know this generator function has N as domain (and as range of course)
# we even know the set"s generator function also has N as domain as we assume that (because the mapping is always a bijection from N -> X)
# so we can only check a single value at a time so we have to have to boundaries for the number of iterations and the number of matches
# after x matches we try to find a series that produces those matches (otherwise a discrete set will be created)
commonElements = []
x = 0 # current iteration = current x value
m = 0 # current matches
f1 = @generator
f2 = set.generator
f1Elems = [] # in ascending order because generators are increasing
f2Elems = [] # in ascending order because generators are increasing
while x < n and m < matches
y1 = f1(x) # TODO: maybe inline generator function here?? but that would mean every sub class has to overwrite
y2 = f2(x)
# f1 is bigger than f2 at current x => check for y2 in f1Elems
if mathJS.gt(y1, y2)
found = false
for f1Elem, i in f1Elems when mathJS.equals(y2, f1Elem)
# new match!
m++
found = true
# y2 found in f1Elems => add to common elements
commonElements.push y2
# because both functions are increasing dispose of earlier elements
# remove all unneeded elements from f1Elems incl. (current) y1
f1Elems = f1Elems.slice(i + 1)
# y2 was a match (the last in f2Elems) and y1 is bigger than y2 so we can forget everything in f2Elems
f2Elems = []
# exit loop
break
if not found
f1Elems.push y1
f2Elems.push y2
# f2 is bigger than f1 at current x => check for y1 in f2Elems
else if mathJS.lt(y1, y2)
found = false
for f2Elem, i in f2Elems when mathJS.equals(y1, f2Elem)
# new match!
m++
found = true
# y1 found in f2Elems => add to common elements
commonElements.push y1
# because both functions are increasing dispose of earlier elements
# remove all unneeded elements from f2Elems incl. (current) y1
f2Elems = f2Elems.slice(i + 1)
# y1 was a match (the last in f2Elems) and y1 is bigger than y1 so we can forget everything in f1Elems
f1Elems = []
# exit loop
break
if not found
f1Elems.push y1
f2Elems.push y2
# equal
else
m++
commonElements.push y1
# all previous values are unimportant because in the next iteration the new values will BOTH be greater than y1=y2 and the 2 lists contain only smaller elements than y1=y2 so there can"t be a match with the next elements
f1Elems = []
f2Elems = []
# increment
x++
console.log "x=#{x}", "m=#{m}", commonElements
# try to find formular from series (supported is: +,-,*,/)
ops = []
for elem in commonElements
true
# example: c1 = x^2, c2 = 2x+1
# c1: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81...
# c2: 1, 3, 5, 7, 9, 11, 13, 15, 17, ...
# => 1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089, 1225, 1369, 1521, 1681, 1849
# this is all odd squares (all odd numbers squared!) ==> f(x) = (2x + 1)^2
# ==> slower increasing function = f, faster increasing function = g -> new-f(x) = g(f(x)) = (g o f)(x)
# actually it is the "bigger function" with a constraint
# inserting smaller in bigger works also for 2x, 3x
# what about 2x, 3x+1 -> 3(2x) + 1 = 6x+1
# but 2x, 2x => 2(2x) = 4x wrong!
# series like *2, +1, *3, -1, *4, +1, *5, -1, *6, +1, ...
# would create 1, 2, 3, 9, 8, 32, 33, 165, 164, 984, 985
# indices: 0 1 2 3 4 5 6 7 8 9 10
# f would be y = x^2 + (-1)^x
return
intersects: (set) ->
return @intersection(set).size > 0
disjoint: (set) ->
return @intersection(set).size is 0
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
times: @::cartesianProduct
# inherited
# isEmpty: () ->
# return @size is 0
# MAKE MATHJS.DOMAINS.N AN INSTANCE
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
N:
value: new mathJS.Sets.N()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/N.coffee
# from js/Sets/Domains/Z.coffee
class mathJS.Sets.Z extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("Z", 1, true)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
Z:
value: new mathJS.Sets.Z()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/Z.coffee
# from js/Sets/Domains/Q.coffee
class mathJS.Sets.Q extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("Q", 2, true)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
Q:
value: new mathJS.Sets.Q()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/Q.coffee
# from js/Sets/Domains/I.coffee
class mathJS.Sets.I extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("I", 2, false)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
I:
value: new mathJS.Sets.I()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/I.coffee
# from js/Sets/Domains/R.coffee
class mathJS.Sets.R extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("R", 3, false)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
R:
value: new mathJS.Sets.R()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/R.coffee
# from js/Sets/Domains/C.coffee
class mathJS.Sets.C extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("C", 4, false)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
C:
value: new mathJS.Sets.C()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/C.coffee
# from js/Calculus/Integral.coffee
class mathJS.Integral
CLASS = @
if DEBUG
@test = () ->
i = new mathJS.Integral(
(x) ->
return -2*x*x-3*x+10
-3
1
)
start = Date.now()
console.log i.solve(false, 0.00000000000001), Date.now() - start
start = Date.now()
i.solveAsync(
(res) ->
console.log res, "async took:", Date.now() - start
false
0.0000001
)
start2 = Date.now()
console.log i.solve(), Date.now() - start2
return "test done"
constructor: (integrand, leftBoundary=-Infinity, rightBoundary=Infinity, integrationVariable=new mathJS.Variable("x")) ->
@integrand = integrand
@leftBoundary = leftBoundary
@rightBoundary = rightBoundary
@integrationVariable = integrationVariable
@settings = null
# PRIVATE
_solvePrepareVars = (from, to, abs, stepSize) ->
# absolute integral?
if abs is false
modVal = mathJS.id
else
modVal = (x) ->
return Math.abs(x)
# get primitives
from = from.value or from
to = to.value or to
# swap if in wrong order
if to < from
tmp = to
to = from
from = tmp
if (diff = to - from) < stepSize
# stepSize = diff * stepSize * 0.1
stepSize = diff * 0.001
return {
modVal: modVal
from: from
to: to
stepSize: stepSize
}
# STATIC
@solve = (integrand, from, to, abs=false, stepSize=0.01, settings={}) ->
vars = _solvePrepareVars(from, to, abs, stepSize)
modVal = vars.modVal
from = vars.from
to = vars.to
stepSize = vars.stepSize
if (steps = (to - from) / stepSize) > settings.maxSteps or mathJS.settings.integral.maxSteps
throw new mathJS.Errors.CalculationExceedanceError("Too many calculations (#{steps.toExponential()}) ahead! Either adjust mathJS.Integral.settings.maxSteps, set the Integral\"s instance\"s settings or pass settings to mathJS.Integral.solve() if you really need that many calculations.")
res = 0
# cache 0.5 * stepSize
halfStepSize = 0.5 * stepSize
y1 = integrand(from)
if DEBUG
i = 0
for x2 in [(from + stepSize)..to] by stepSize
if DEBUG
i++
y2 = integrand(x2)
if mathJS.sign(y1) is mathJS.sign(y2)
# trapezoid formula
res += modVal((y1 + y2) * halfStepSize)
# else: round to zero -> no calculation needed
y1 = y2
if DEBUG
console.log "made", i, "calculations"
return res
###*
* For better calculation performance of the integral decrease delay and numBlocks.
* For better overall performance increase them.
* @public
* @static
* @method solveAsync
* @param integrand {Function}
* @param from {Number}
* @param to {Number}
* @param callback {Function}
* @param abs {Boolean}
* Optional. Indicates whether areas below the graph are negative or not.
* Default is false.
* @param stepSize {Number}
* Optional. Defines the width of each trapezoid. Default is 0.01.
* @param delay {Number}
* Optional. Defines the time to pass between blocks of calculations.
* Default is 2ms.
* @param numBlocks {Number}
* Optional. Defines the number of calculation blocks.
* Default is 100.
*###
@solveAsync: (integrand, from, to, callback, abs, stepSize, delay=2, numBlocks=100) ->
if not callback?
return false
# split calculation into numBlocks blocks
blockSize = (to - from) / numBlocks
block = 0
res = 0
f = (from, to) ->
# done with all blocks => return result to callback
if block++ is numBlocks
return callback(res)
res += CLASS.solve(integrand, from, to, abs, stepSize)
setTimeout () ->
f(to, to + blockSize)
, delay
return true
f(from, from + blockSize)
return @
# PUBLIC
solve: (abs, stepSize) ->
return CLASS.solve(@integrand, @leftBoundary, @rightBoundary, abs, stepSize)
solveAsync: (callback, abs, stepSize) ->
return CLASS.solveAsync(@integrand, @leftBoundary, @rightBoundary, callback, abs, stepSize)
# end js/Calculus/Integral.coffee
# from js/LinearAlgebra/Vector.coffee
class mathJS.Vector
_isVectorLike: (v) ->
return v instanceof mathJS.Vector or v.instanceof?(mathJS.Vector)# or v instanceof mathJS.Tuple or v.instanceof?(mathJS.Tuple)
@_isVectorLike: @::_isVectorLike
# CONSTRUCTOR
constructor: (values) ->
# check values for
@values = values
if DEBUG
for val in values when not mathJS.isMathJSNum(val)
console.warn "invalid value:", val
equals: (v) ->
if not @_isVectorLike(v)
return false
for val, i in @values
vValue = v.values[i]
if not val.equals?(vValue) and val isnt vValue
return false
return true
clone: () ->
return new TD.Vector(@values)
move: (v) ->
if not @_isVectorLike v
return @
for val, i in v.values
vValue = v.values[i]
@values[i] = vValue.plus?(val) or val.plus?(vValue) or (vValue + val)
return @
moveBy: @move
moveTo: (p) ->
if not @_isVectorLike v
return @
for val, i in v.values
vValue = v.values[i]
@values[i] = vValue.value or vValue
return @
multiply: (r) ->
if Math.isNum r
return new TD.Point(@x * r, @y * r)
return null
# make alias
times: @multiply
magnitude: () ->
sum = 0
for val, i in @values
sum += val * val
return Math.sqrt(sum)
###*
* This method calculates the distance between 2 points.
* It"s a shortcut for substracting 2 vectors and getting that vector"s magnitude (because no new object is created).
* For that reason this method should be used for pure distance calculations.
*
* @method distanceTo
* @param {Point} p
* @return {Number} Distance between this point and p.
*###
distanceTo: (v) ->
sum = 0
for val, i in @values
sum += (val - v.values[i]) * (val - v.values[i])
return Math.sqrt(sum)
add: (v) ->
if not @_isVectorLike v
return null
values = []
for val, i in v.values
vValue = v.values[i]
values.push(vValue.plus?(val) or val.plus?(vValue) or (vValue + val))
return new mathJS.Vector(values)
# make alias
plus: @add
substract: (p) ->
if isPointLike p
return new TD.Point(@x - p.x, @y - p.y)
return null
# make alias
minus: @substract
xyRatio: () ->
return @x / @y
toArray: () ->
return [@x, @y]
isPositive: () ->
return @x >= 0 and @y >= 0
###*
* Returns the angle of a vector. Beware that the angle is measured in counter clockwise direction beginning at 0˚ which equals the x axis in positive direction.
* So on a computer grid the angle won"t be what you expect! Use anglePC() in that case!
*
* @method angle
* @return {Number} Angle of the vector in degrees. 0 degrees means pointing to the right.
*###
angle: () ->
# 1st quadrant (and zero)
if @x >= 0 and @y >= 0
return Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) ) % 360
# 2nd quadrant
if @x < 0 and @y > 0
return (90 + Math.radToDeg( Math.atan( Math.abs(@x) / Math.abs(@y) ) )) % 360
# 3rd quadrant
if @x < 0 and @y < 0
return (180 + Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) )) % 360
# 4th quadrant
return (270 + Math.radToDeg( Math.atan( Math.abs(@x) / Math.abs(@y) ) )) % 360
###*
* Returns the angle of a vector. 0˚ means pointing to the top. Clockwise.
*
* @method anglePC
* @return {Number} Angle of the vector in degrees. 0 degrees means pointing to the right.
*###
anglePC: () ->
# 1st quadrant: pointing to bottom right
if @x >= 0 and @y >= 0
return (90 + Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) )) % 360
# 2nd quadrant: pointing to bottom left
if @x < 0 and @y > 0
return (180 + Math.radToDeg( Math.atan( Math.abs(@x) / Math.abs(@y) ) )) % 360
# 3rd quadrant: pointing to top left
if @x < 0 and @y < 0
return (270 + Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) )) % 360
# 4th quadrant: pointing to top right
return Math.radToDeg(Math.atan( Math.abs(@x) / Math.abs(@y) ) ) % 360
###*
* Returns a random Point within a given radius.
*
* @method randPointInRadius
* @param {Number} radius
* Default is 10 (pixels). Must not be smaller than 0.
* @param {Boolean} random
* Indicates whether the given radius is the maximum or exact distance between the 2 points.
* @return {Number} Random Point.
*###
randPointInRadius: (radius = 5, random = false) ->
angle = Math.degToRad(Math.randNum(0, 360))
if random is true
radius = Math.randNum(0, radius)
x = radius * Math.cos angle
y = radius * Math.sin angle
return @add( new TD.Point(x, y) )
# end js/LinearAlgebra/Vector.coffee
# from js/Initializer.coffee
class mathJS.Initializer
@start: () ->
mathJS.Algorithms.ShuntingYard.init()
# end js/Initializer.coffee
# from js/start.coffee
mathJS.Initializer.start()
if DEBUG
diff = Date.now() - startTime
console.log "time to load mathJS: ", diff, "ms"
if diff > 100
console.warn "LOADING TIME CRITICAL!"
# end js/start.coffee
| true | # from js/init.coffee
###*
* @module mathJS
* @main mathJS
*###
if typeof DEBUG is "undefined"
window.DEBUG = true
# create namespaces
window.mathJS =
Algorithms: {}
Domains: {} # contains instances of sets
Errors: {}
Geometry: {}
Operations: {}
Sets: {}
Utils: {}
# Take namespaces from mathJS
_mathJS = $.extend {}, mathJS
if DEBUG
window._mathJS = _mathJS
startTime = Date.now()
# end js/init.coffee
# from js/prototyping.coffee
# TODO: use object.defineProperties in order to hide methods from enumeration
####################################################################################
Array::reverseCopy = () ->
res = []
res.push(item) for item in @ by -1
return res
Array::unique = () ->
res = []
for elem in @ when elem not in res
res.push elem
return res
Array::sample = (n = 1, forceArray = false) ->
if n is 1
if not forceArray
return @[ Math.floor(Math.random() * @length) ]
return [ @[ Math.floor(Math.random() * @length) ] ]
if n > @length
n = @length
i = 0
res = []
arr = @clone()
while i++ < n
elem = arr.sample(1)
res.push elem
arr.remove elem
return res
Array::shuffle = () ->
arr = @sample(@length)
for elem, i in arr
@[i] = elem
return @
Array::average = () ->
sum = 0
elems = 0
for elem in @ when Math.isNum(elem)
sum += elem
elems++
return sum / elems
# make alias
Array::median = Array::average
Array::clone = Array::slice
# TODO: from http://jsperf.com/array-prototype-slice-call-vs-slice-call/17
# function nonnative_slice(item, start){
# start = ~~start;
# var
# len = item.length, i, newArray;
#
# newArray = new Array(len - start);
#
# for (i = start; i < len; i++){
# newArray[i - start] = item[i];
# }
#
# return newArray;
# }
Array::indexOfNative = Array::indexOf
Array::indexOf = (elem, fromIdx) ->
idx = if fromIdx? then fromIdx else 0
len = @length
while idx < len
if @[idx] is elem
return idx
idx++
return -1
Array::remove = (elem) ->
idx = @indexOf elem
if idx > -1
@splice(idx, 1)
return @
Array::removeAll = (elements = []) ->
for elem in elements
@remove elem
return @
Array::removeAt = (idx) ->
@splice(idx, 1)
return @
# convenient index getters and setters
Object.defineProperties Array::, {
first:
get: () ->
return @[0]
set: (val) ->
@[0] = val
return @
second:
get: () ->
return @[1]
set: (val) ->
@[1] = val
return @
third:
get: () ->
return @[2]
set: (val) ->
@[2] = val
return @
fourth:
get: () ->
return @[3]
set: (val) ->
@[3] = val
return @
last:
get: () ->
return @[@length - 1]
set: (val) ->
@[@length - 1] = val
return @
}
###*
* @method getMax
* @param {Function} propertyGetter
* The passed callback extracts the value being compared from the array elements.
* @return {Array} An array of all maxima.
*###
Array::getMax = (propertyGetter) ->
max = null
res = []
if not propertyGetter?
propertyGetter = (item) ->
return item
for elem in @
val = propertyGetter(elem)
# new max found (or first compare) => restart list with new max value
if val > max or max is null
max = val
res = [elem]
# same as max found => add to list
else if val is max
res.push elem
return res
Array::getMin = (propertyGetter) ->
min = null
res = []
if not propertyGetter?
propertyGetter = (item) ->
return item
for elem in @
val = propertyGetter(elem)
# new min found (or first compare) => restart list with new min value
if val < min or min is null
min = val
res = [elem]
# same as min found => add to list
else if val is min
res.push elem
return res
Array::sortProp = (getProp, order = "asc") ->
if not getProp?
getProp = (item) ->
return item
if order is "asc"
cmpFunc = (a, b) ->
a = getProp(a)
b = getProp(b)
if a < b
return -1
if b > a
return 1
return 0
else
cmpFunc = (a, b) ->
a = getProp(a)
b = getProp(b)
if a > b
return -1
if b < a
return 1
return 0
return @sort cmpFunc
####################################################################################
# STRING
String::camel = (spaces) ->
if not spaces?
spaces = false
str = @toLowerCase()
if spaces
str = str.split(" ")
for i in [1...str.length]
str[i] = str[i].charAt(0).toUpperCase() + str[i].substring(1)
str = str.join("")
return str
String::antiCamel = () ->
res = @charAt(0)
for i in [1...@length]
temp = @charAt(i)
# it is a capital letter -> insert space
if temp is temp.toUpperCase()
res += " "
res += temp
return res
String::firstToUpperCase = () ->
return @charAt(0).toUpperCase() + @slice(1)
String::snakeToCamelCase = () ->
res = ""
for char in @
# not underscore
if char isnt "_"
# previous character was not an underscore => just add character
if prevChar isnt "_"
res += char
# previous character was an underscore => add upper case character
else
res += char.toUpperCase()
prevChar = char
return res
String::camelToSnakeCase = () ->
res = ""
prevChar = null
for char in @
# lower case => just add
if char is char.toLowerCase()
res += char
# upper case
else
# previous character was lower case => add underscore and lower case character
if prevChar is prevChar.toLowerCase()
res += "_" + char.toLowerCase()
# previous character was (also) upper case => just add
else
res += char
prevChar = char
return res
String::lower = String::toLowerCase
String::upper = String::toUpperCase
# convenient index getters and setters
Object.defineProperties String::, {
first:
get: () ->
return @[0]
set: (val) ->
return @
second:
get: () ->
return @[1]
set: (val) ->
return @
third:
get: () ->
return @[2]
set: (val) ->
return @
fourth:
get: () ->
return @[3]
set: (val) ->
return @
last:
get: () ->
return @[@length - 1]
set: (val) ->
return @
}
# implement comparable and orderable interface for primitives
String::equals = (str) ->
return @valueOf() is str.valueOf()
String::lessThan = (str) ->
return @valueOf() < str.valueOf()
String::lt = String::lessThan
String::greaterThan = (str) ->
return @valueOf() > str.valueOf()
String::gt = String::greaterThan
String::lessThanOrEqualTo = (str) ->
return @valueOf() <= str.valueOf()
String::lte = String::lessThanOrEqualTo
String::greaterThanOrEqualTo = (str) ->
return @valueOf() >= str.valueOf()
String::gte
####################################################################################
# BOOLEAN
Boolean::equals = (bool) ->
return @valueOf() is bool.valueOf()
Boolean::lessThan = (bool) ->
return @valueOf() < bool.valueOf()
Boolean::lt = Boolean::lessThan
Boolean::greaterThan = (bool) ->
return @valueOf() > bool.valueOf()
Boolean::gt = Boolean::greaterThan
Boolean::lessThanOrEqualTo = (bool) ->
return @valueOf() <= bool.valueOf()
Boolean::lte = Boolean::lessThanOrEqualTo
Boolean::greaterThanOrEqualTo = (bool) ->
return @valueOf() >= str.valueOf()
Boolean::gte
####################################################################################
# OBJECT
Object.keysLike = (obj, pattern) ->
res = []
for key in Object.keys(obj)
if pattern.test key
res.push key
return res
# end js/prototyping.coffee
# from js/mathJS.coffee
#################################################################################################
# THIS FILE CONTAINS ALL PROPERITES AND FUNCTIONS THAT ARE BOUND DIRECTLY TO mathJS
# CONSTRANTS
Object.defineProperties mathJS, {
e:
value: Math.E
writable: false
pi:
value: Math.PI
writable: false
ln2:
value: Math.LN2
writable: false
ln10:
value: Math.LN10
writable: false
log2e:
value: Math.LOG2E
writable: false
log10e:
value: Math.LOG10E
writable: false
# This value behaves slightly differently than mathematical infinity:
#
# Any positive value, including POSITIVE_INFINITY, multiplied by NEGATIVE_INFINITY is NEGATIVE_INFINITY.
# Any negative value, including NEGATIVE_INFINITY, multiplied by NEGATIVE_INFINITY is POSITIVE_INFINITY.
# Zero multiplied by NEGATIVE_INFINITY is NaN.
# NaN multiplied by NEGATIVE_INFINITY is NaN.
# NEGATIVE_INFINITY, divided by any negative value except NEGATIVE_INFINITY, is POSITIVE_INFINITY.
# NEGATIVE_INFINITY, divided by any positive value except POSITIVE_INFINITY, is NEGATIVE_INFINITY.
# NEGATIVE_INFINITY, divided by either NEGATIVE_INFINITY or POSITIVE_INFINITY, is NaN.
# Any number divided by NEGATIVE_INFINITY is Zero.
infty:
value: Infinity
writable: false
infinity:
value: Infinity
writable: false
epsilon:
value: Number.EPSILON or 2.220446049250313e-16 # 2.220446049250313080847263336181640625e-16
writable: false
maxValue:
value: Number.MAX_VALUE
writable: false
minValue:
value: Number.MIN_VALUE
writable: false
id:
value: (x) ->
return x
writable: false
# number sets / systems
# N:
# value: new mathJS.Set()
# writable: false
}
mathJS.isPrimitive = (x) ->
return typeof x is "string" or typeof x is "number" or typeof x is "boolean"
mathJS.isComparable = (x) ->
# return x instanceof mathJS.Comparable or x.instanceof?(mathJS.Comparable) or mathJS.isPrimitive x
return x.equals instanceof Function or mathJS.isPrimitive x
# mathJS.instanceof = (instance, clss) ->
# return instance instanceof clss or instance.instanceof?(clss)
# mathJS.isA = () ->
mathJS.equals = (x, y) ->
return x.equals?(y) or y.equals?(x) or x is y
mathJS.greaterThan = (x, y) ->
return x.gt?(y) or y.lt?(x) or x > y
mathJS.gt = mathJS.greaterThan
mathJS.lessThan = (x, y) ->
return x.lt?(y) or y.gt?(x) or x < y
mathJS.lt = mathJS.lessThan
mathJS.ggT = () ->
if arguments[0] instanceof Array
vals = arguments[0]
else
vals = Array::slice.apply arguments
if vals.length is 2
if vals[1] is 0
return vals[0]
return mathJS.ggT(vals[1], vals[0] %% vals[1])
else if vals.length > 2
ggt = mathJS.ggT vals[0], vals[1]
for i in [2...vals.length]
ggt = mathJS.ggT(ggt, vals[i])
return ggt
return null
mathJS.gcd = mathJS.ggT
mathJS.kgV = () ->
if arguments[0] instanceof Array
vals = arguments[0]
else
vals = Array::slice.apply arguments
if vals.length is 2
return vals[0] * vals[1] // mathJS.ggT(vals[0], vals[1])
else if vals.length > 2
kgv = mathJS.kgV vals[0], vals[1]
for i in [2...vals.length]
kgv = mathJS.kgV(kgv, vals[i])
return kgv
return null
mathJS.lcm = mathJS.kgV
mathJS.coprime = (x, y) ->
return mathJS.gcd(x, y) is 1
mathJS.ceil = Math.ceil
# faster way of rounding down
mathJS.floor = (n) ->
# if mathJS.isNum(n)
# return ~~n
# return NaN
return ~~n
mathJS.floatToInt = mathJS.floor
mathJS.square = (n) ->
if mathJS.isNum(n)
return n * n
return NaN
mathJS.cube = (n) ->
if mathJS.isNum(n)
return n * n * n
return NaN
# TODO: jsperf
mathJS.pow = Math.pow
# TODO: jsperf
mathJS.sqrt = Math.sqrt
mathJS.curt = (n) ->
if mathJS.isNum(n)
return mathJS.pow(n, 1 / 3)
return NaN
mathJS.root = (n, exp) ->
if mathJS.isNum(n) and mathJS.isNum(exp)
return mathJS.pow(n, 1 / exp)
return NaN
mathJS.factorial = (n) ->
if (n = ~~n) < 0
return NaN
return mathJS.factorial.cache[n] or (mathJS.factorial.cache[n] = n * mathJS.factorial(n - 1))
# initial cache (dynamically growing when exceeded)
mathJS.factorial.cache = [
1
1
2
6
24
120
720
5040
40320
362880
3628800
39916800
4.790016e8
6.2270208e9
8.71782912e10
1.307674368e12
]
# make alias
mathJS.fac = mathJS.factorial
mathJS.parseNumber = (str) ->
# TODO
return null
mathJS.factorialInverse = (n) ->
if (n = ~~n) < 0
return NaN
x = 0
# js: while((y = mathJS.factorial(++x)) < n) {}
while (y = mathJS.factorial(++x)) < n then
if y is n
return parseInt(x, 10)
return NaN
# make alias
mathJS.facInv = mathJS.factorialInverse
###*
* This function checks if a given parameter is a (plain) number.
* @method isNum
* @param {Number} num
* @return {Boolean} Whether the given number is a Number (excluding +/-Infinity)
*###
# mathJS.isNum = (r) ->
# return (typeof r is "number") and not isNaN(r) and r isnt Infinity and r isnt -Infinity
# return not isNaN(r) and -Infinity < r < Infinity
mathJS.isNum = (n) ->
return n? and isFinite(n)
mathJS.isMathJSNum = (n) ->
return n? and (isFinite(n) or n instanceof mathJS.Number or n.instanceof(mathJS.Number))
mathJS.isInt = (r) ->
return mathJS.isNum(r) and ~~r is r
###*
* This function returns a random (plain) integer between max and min (both inclusive). If max is less than min the parameters are swapped.
* @method randInt
* @param {Number} max
* @param {Number} min
* @return {Number} Random integer.
*###
mathJS.randInt = (max = 1, min = 0) ->
# if min > max
# temp = min
# min = max
# max = temp
# return Math.floor(Math.random() * (max + 1 - min)) + min
return ~~mathJS.randNum(max, min)
###*
* This function returns a random number between max and min (both inclusive). If max is less than min the parameters are swapped.
* @method randNum
* @param {Number} max
* @param {Number} min
* Default is 0.
* @return {Integer} Random number.
*###
mathJS.randNum = (max = 1, min = 0) ->
if min > max
temp = min
min = max
max = temp
return Math.random() * (max + 1 - min) + min
mathJS.radToDeg = (rad) ->
return rad * 57.29577951308232 # = rad * (180 / Math.PI)
mathJS.degToRad = (deg) ->
return deg * 0.017453292519943295 # = deg * (Math.PI / 180)
mathJS.sign = (n) ->
n = n.value or n
if mathJS.isNum(n)
if n < 0
return -1
return 1
return NaN
mathJS.min = (elems...) ->
if elems.first instanceof Array
elems = elems.first
propGetter = null
else if elems.first instanceof Function
propGetter = elems.first
elems = elems.slice(1)
if elems.first instanceof Array
elems = elems.first
res = []
min = null
for item in elems
if propGetter?
item = propGetter(item)
if min is null or item.lessThan(min) or item < min
min = item
res = [elem]
# same as min found => add to list
else if item.equals(min) or item is min
res.push elem
return res
mathJS.max = (elems...) ->
if elems.first instanceof Array
elems = elems.first
propGetter = null
else if elems.first instanceof Function
propGetter = elems.first
elems = elems.slice(1)
if elems.first instanceof Array
elems = elems.first
res = []
max = null
for item in elems
if propGetter?
item = propGetter(item)
if max is null or item.greaterThan(max) or item > max
max = item
res = [elem]
# same as max found => add to list
else if item.equals(max) or item is max
res.push elem
return res
mathJS.log = (n, base=10) ->
return Math.log(n) / Math.log(base)
mathJS.logBase = mathJS.log
mathJS.reciprocal = (n) ->
if mathJS.isNum(n)
return 1 / n
return NaN
mathJS.sortFunction = (a, b) ->
if a.lessThan b
return -1
if a.greaterThan b
return 1
return 0
# end js/mathJS.coffee
# from js/settings.coffee
mathJS.settings =
generator:
maxIndex: 1e4
integral:
maxSteps: 1e10
# maxPoolSize is for EACH pool
maxPoolSize: 100
number:
real:
distance: 1e-6
set:
defaultNumberOfElements: 1e3
maxIterations: 1e3
maxMatches: 60
mathJS.config = mathJS.settings
# end js/settings.coffee
# from js/mathJSObject.coffee
###*
* This is the super class of all mathJS classes.
* Therefore all cross-class things are defined here.
* @class Object
*###
class _mathJS.Object
@_implements = []
@_implementedBy = []
@implements = (classes...) ->
if classes.first instanceof Array
classes = classes.first
for clss in classes
# make the class / interface know what classes implement it
if @ not in clss._implementedBy
clss._implementedBy.push @
# implement class / interface
clssPrototype = clss.prototype
# "window." necessary because coffee creates an "Object" variable for this class
prototypeKeys = window.Object.keys(clssPrototype)
# static
for name, method of clss when name not in prototypeKeys
@[name] = method
# non-static (from prototype)
for name, method of clssPrototype
@::[name] = method
@_implements.push clss
return @
isA: (clss) ->
if not clss? or clss not instanceof Function
return false
if @ instanceof clss
return true
for c in @constructor._implements
# direct hit
if c is clss
return true
# check super classes ("__superClass__" is set when coffee extends classes using macros...see macros.js)
while (c = c.__superClass__)?
if c is clss
return true
return false
instanceof: () ->
return @isA.apply(@, arguments)
# end js/mathJSObject.coffee
# from js/Errors/SimpleErrors.coffee
# class _mathJS.Errors.Error extends window.Error
#
# constructor: (message, fileName, lineNumber, misc...) ->
# super(message, fileName, lineNumber)
# @misc = misc
#
# toString: () ->
# return "#{super()}\n more data: #{@misc.toString()}"
class mathJS.Errors.CalculationExceedanceError extends Error
class mathJS.Errors.CycleDetectedError extends Error
class mathJS.Errors.DivisionByZeroError extends Error
class mathJS.Errors.InvalidArityError extends Error
class mathJS.Errors.InvalidParametersError extends Error
class mathJS.Errors.InvalidVariableError extends Error
class mathJS.Errors.NotImplementedError extends Error
class mathJS.Errors.NotParseableError extends Error
# end js/Errors/SimpleErrors.coffee
# from js/Utils/Hash.coffee
###*
* This is an implementation of a dictionary/hash that does not convert its keys into Strings. Keys can therefore actually by anything!
* @class Hash
* @constructor
*###
class mathJS.Utils.Hash
###*
* Creates a new Hash from a given JavaScript object.
* @static
* @method fromObject
* @param object {Object}
*###
@fromObject: (obj) ->
return new mathJS.Utils.Hash(obj)
@new: (obj) ->
return new mathJS.Utils.Hash(obj)
constructor: (obj) ->
@keys = []
@values = []
if obj?
@put key, val for key, val of obj
clone: () ->
res = new mathJS.Utils.Hash()
res.keys = @keys.clone()
res.values = @values.clone()
return res
invert: () ->
res = new mathJS.Utils.Hash()
res.keys = @values.clone()
res.values = @keys.clone()
return res
###*
* Adds a new key-value pair or overwrites an existing one.
* @method put
* @param key {mixed}
* @param val {mixed}
* @return {Hash} This instance.
* @chainable
*###
put: (key, val) ->
idx = @keys.indexOf key
# add new entry
if idx < 0
@keys.push key
@values.push val
# overwrite entry
else
@keys[idx] = key
@values[idx] = val
return @
###*
* Returns the value (or null) for the specified key.
* @method get
* @param key {mixed}
* @param [equalityFunction] {Function}
* This optional function can overwrite the test for equality between keys. This function expects the parameters: (the current key in the key iteration, 'key'). If this parameters is omitted '===' is used.
* @return {mixed}
*###
get: (key) ->
if (idx = @keys.indexOf(key)) >= 0
return @values[idx]
return null
###*
* Indicates whether the Hash has the specified key.
* @method hasKey
* @param key {mixed}
* @return {Boolean}
*###
hasKey: (key) ->
return key in @keys
has: (key) ->
return @hasKey(key)
###*
* Returns the number of entries in the Hash.
* @method size
* @return {Integer}
*###
size: () ->
return @keys.length
empty: () ->
@keys = []
@values = []
return @
remove: (key) ->
if (idx = @keys.indexOf(key)) >= 0
@keys.splice idx, 1
@values.splice idx, 1
else
console.warn "Could not remove key '#{key}'!"
return @
each: (callback) ->
for key, i in @keys when callback(key, @values[i], i) is false
return @
return @
# end js/Utils/Hash.coffee
# from js/Utils/Dispatcher.coffee
class mathJS.Utils.Dispatcher extends _mathJS.Object
# map: receiver -> list of dispatchers
@registeredDispatchers = mathJS.Utils.Hash.new()
# try to detect cyclic dispatching
@registerDispatcher: (newReceiver, newTargets) ->
registrationPossible = newTargets.indexOf(newReceiver) is -1
if registrationPossible
regReceivers = @registeredDispatchers.keys
# IF
# 1. the new receiver is in any of the lists and
# 2. any of the registered receivers is in the new-targets list
# THEN a cycle would be created
@registeredDispatchers.each (regReceiver, regTargets, idx) ->
for regTarget in regTargets when regTarget is newReceiver
for newTarget in newTargets when regReceivers.indexOf(newTarget)
registrationPossible = false
return false
return true
if registrationPossible
@registeredDispatchers.put(newReceiver, newTargets)
return @
throw new mathJS.Errors.CycleDetectedError("Can't register '#{newReceiver}' for dispatching - cycle detected!")
# CONSTRUCTOR
# NOTE: super classes are ignored
constructor: (receiver, targets=[]) ->
@constructor.registerDispatcher(receiver, targets)
@receiver = receiver
@targets = targets
console.log "dispatcher created!"
dispatch: (target, method, params...) ->
dispatch = false
# check instanceof and identity
if @targets.indexOf(target.constructor or target) >= 0
dispatch = true
# check typeof (for primitives)
else
for t in @targets when typeof target is t
dispatch = true
break
if dispatch
if target[method] instanceof Function
return target[method].apply(target, params)
throw new mathJS.Errors.NotImplementedError(
"Can't call '#{method}' on target '#{target}'"
"Dispatcher.coffee"
)
return null
# end js/Utils/Dispatcher.coffee
# from js/Interfaces/Interface.coffee
class _mathJS.Interface extends _mathJS.Object
@implementedBy = []
@isImplementedBy = () ->
return @implementedBy
# end js/Interfaces/Interface.coffee
# from js/Interfaces/Comparable.coffee
class _mathJS.Comparable extends _mathJS.Interface
###*
* This method checks for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2) is true.
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (n) ->
throw new mathJS.Errors.NotImplementedError("equals in #{@contructor.name}")
e: () ->
return @equals.apply(@, arguments)
# end js/Interfaces/Comparable.coffee
# from js/Interfaces/Orderable.coffee
class _mathJS.Orderable extends _mathJS.Comparable
###*
* This method checks for mathmatical "<". This means new mathJS.Double(4.2).lessThan(5.2) is true.
* @method lessThan
* @param {Number} n
* @return {Boolean}
*###
lessThan: (n) ->
throw new mathJS.Errors.NotImplementedError("lessThan in #{@contructor.name}")
###*
* Alias for `lessThan`.
* @method lt
*###
lt: () ->
return @lessThan.apply(@, arguments)
###*
* This method checks for mathmatical ">". This means new mathJS.Double(4.2).greaterThan(3.2) is true.
* @method greaterThan
* @param {Number} n
* @return {Boolean}
*###
greaterThan: (n) ->
throw new mathJS.Errors.NotImplementedError("greaterThan in #{@contructor.name}")
###*
* Alias for `greaterThan`.
* @method gt
*###
gt: () ->
return @greaterThan.apply(@, arguments)
###*
* This method checks for mathmatical "<=". This means new mathJS.Double(4.2).lessThanOrEqualTo(5.2) is true.
* @method lessThanOrEqualTo
* @param {Number} n
* @return {Boolean}
*###
lessThanOrEqualTo: (n) ->
return @lessThan(n) or @equals(n)
###*
* Alias for `lessThanOrEqualTo`.
* @method lte
*###
lte: () ->
return @lessThanOrEqualTo.apply(@, arguments)
###*
* This method checks for mathmatical ">=". This means new mathJS.Double(4.2).greaterThanOrEqualTo(3.2) is true.
* @method greaterThanOrEqualTo
* @param {Number} n
* @return {Boolean}
*###
greaterThanOrEqualTo: (n) ->
return @greaterThan(n) or @equals(n)
###*
* Alias for `greaterThanOrEqualTo`.
* @method gte
*###
gte: () ->
return @greaterThanOrEqualTo.apply(@, arguments)
# end js/Interfaces/Orderable.coffee
# from js/Interfaces/Parseable.coffee
class _mathJS.Parseable extends _mathJS.Interface
@parse: (str) ->
throw new mathJS.Errors.NotImplementedError("static parse in #{@name}")
@fromString: (str) ->
return @parse(str)
toString: (args) ->
throw new mathJS.Errors.NotImplementedError("toString in #{@contructor.name}")
# end js/Interfaces/Parseable.coffee
# from js/Interfaces/Poolable.coffee
class _mathJS.Poolable extends _mathJS.Interface
@_pool = []
@_fromPool: () ->
# implementation should be something like:
# if @_pool.length > 0
# return @_pool.pop()
# return new @()
throw new mathJS.Errors.NotImplementedError("static _fromPool in #{@name}")
###*
* Releases the instance to the pool of its class.
* @method release
* @return This intance
* @chainable
*###
release: () ->
if @constructor._pool.length < mathJS.settings.maxPoolSize
@constructor._pool.push @
if DEBUG
if @constructor._pool.length >= mathJS.settings.maxPoolSize
console.warn "#{@constructor.name}-pool is full:", @constructor._pool
return @
# end js/Interfaces/Poolable.coffee
# from js/Interfaces/Evaluable.coffee
class _mathJS.Evaluable extends _mathJS.Interface
eval: () ->
throw new mathJS.Errors.NotImplementedError("eval() in #{@contructor.name}")
# end js/Interfaces/Evaluable.coffee
# from js/Numbers/AbstractNumber.coffee
# This file defines the Number interface.
# TODO: make number extend expression
class _mathJS.AbstractNumber extends _mathJS.Object
@implements _mathJS.Orderable, _mathJS.Poolable, _mathJS.Parseable
###*
* @Override mathJS.Poolable
* @static
* @method _fromPool
*###
@_fromPool: (value) ->
if @_pool.length > 0
if (val = @_getPrimitive(value))?
number = @_pool.pop()
number.value = val
return number
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{value}'"
"AbstractNumber.coffee"
)
# param check is done in constructor
return new @(value)
###*
* @Override mathJS.Parseable
* @static
* @method parse
*###
@parse: (str) ->
return @_fromPool parseFloat(str)
@getSet: () ->
throw new mathJS.Errors.NotImplementedError("getSet in #{@name}")
@new: (param) ->
return @_fromPool param
@random: (max, min) ->
return @_fromPool mathJS.randNum(max, min)
@dispatcher = new mathJS.Utils.Dispatcher(@, [
# mathJS.Matrix
mathJS.Fraction
])
###*
* This method is used to parse and check a parameter.
* Either a valid value is returned or null (for invalid parameters).
* @static
* @method _getPrimitive
* @param param {Object}
* @param skipCheck {Boolean}
* @return {mathJS.Number}
*###
@_getPrimitive: (param, skipCheck) ->
return null
############################################################################################
# PROTECTED METHODS
_setValue: (value) ->
return @
_getValue: () ->
return @_value
_getPrimitive: (param) ->
return @constructor._getPrimitive(param)
############################################################################################
# PUBLIC METHODS
############################################################################################
# COMPARABLE INTERFACE
###*
* @Override mathJS.Comparable
* This method checks for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2) is true.
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "equals", @))?
return result
if (val = @_getPrimitive(n))?
return @value is val
return false
# END - IMPLEMENTING COMPARABLE
############################################################################################
############################################################################################
# ORDERABLE INTERFACE
###*
* @Override mathJS.Orderable
* This method checks for mathmatical "<". This means new mathJS.Double(4.2).lessThan(5.2) is true.
* @method lessThan
*###
lessThan: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "lessThan", @))?
return result
if (val = @_getPrimitive(n))?
return @value < val
return false
###*
* @Override mathJS.Orderable
* This method checks for mathmatical ">". This means new mathJS.Double(4.2).greaterThan(3.2) is true.
* @method greaterThan
* @param {Number} n
* @return {Boolean}
*###
greaterThan: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "greaterThan", @))?
return result
if (val = @_getPrimitive(n))?
return @value > val
return false
# END - IMPLEMENTING ORDERABLE
############################################################################################
###*
* This method adds 2 numbers and returns a new one.
* @method plus
* @param {Number} n
* @return {mathJS.Number} Calculated Number.
*###
plus: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "plus", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value + val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method substracts 2 numbers and returns a new one.
* @method minus
* @param {Number} n
* @return {mathJS.Number} Calculated Number.
*###
minus: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "minus", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value - val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method multiplies 2 numbers and returns a new one.
* @method times
* @param {Number} n
* @return {mathJS.Number} Calculated Number.
*###
times: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "times", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value * val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method divides 2 numbers and returns a new one.
* @method divide
* @param {Number} n
* @return {Number} Calculated Number.
*###
divide: (n) ->
if (result = @constructor.dispatcher.dispatch(n, "divide", @))?
return result
if (val = @_getPrimitive(n))?
return mathJS.Number.new(@value / val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method squares this instance and returns a new one.
* @method square
* @return {Number} Calculated Number.
*###
square: () ->
return mathJS.Number.new(@value * @value)
###*
* This method cubes this instance and returns a new one.
* @method cube
* @return {Number} Calculated Number.
*###
cube: () ->
return mathJS.Number.new(@value * @value * @value)
###*
* This method calculates the square root of this instance and returns a new one.
* @method sqrt
* @return {Number} Calculated Number.
*###
sqrt: () ->
return mathJS.Number.new(mathJS.sqrt(@value))
###*
* This method calculates the cubic root of this instance and returns a new one.
* @method curt
* @return {Number} Calculated Number.
*###
curt: () ->
return @pow(0.3333333333333333)
###*
* This method calculates any root of this instance and returns a new one.
* @method root
* @param {Number} exponent
* @return {Number} Calculated Number.
*###
root: (exp) ->
if (val = @_getPrimitive(exp))?
return @pow(1 / val)
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{exp}'"
"AbstractNumber.coffee"
)
###*
* This method returns the reciprocal (1/n) of this number.
* @method reciprocal
* @return {Number} Calculated Number.
*###
reciprocal: () ->
return mathJS.Number.new(1 / @value)
###*
* This method returns this' value the the n-th power (this^n).
* @method pow
* @param {Number} n
* @return {Number} Calculated Number.
*###
pow: (n) ->
if (val = @_getPrimitive(n))?
return mathJS.Number.new(mathJS.pow(@value, val))
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{n}'"
"AbstractNumber.coffee"
)
###*
* This method returns the sign of this number (sign(this)).
* @method sign
* @param plain {Boolean}
* Indicates whether the return value is wrapped in a mathJS.Number or not (-> primitive value).
* @return {Number|mathJS.Number}
*###
sign: (plain=true) ->
val = @value
if plain is true
if val < 0
return -1
return 1
# else:
if val < 0
return mathJS.Number.new(-1)
return mathJS.Number.new(1)
negate: () ->
return mathJS.Number.new(-@value)
toInt: () ->
return mathJS.Int.new(@value)
toNumber: () ->
return mathJS.Number.new(@value)
toString: (format) ->
if not format?
return "#{@value}"
return numeral(@value).format(format)
clone: () ->
return mathJS.Number.new(@value)
# EVALUABLE INTERFACE
eval: (values) ->
return @
_getSet: () ->
return new mathJS.Set(@)
############################################################################################
# SETS...
in: (set) ->
return set.contains(@)
# end js/Numbers/AbstractNumber.coffee
# from js/Numbers/Number.coffee
# TODO: mathJS.Number should also somehow be a mathJS.Expression!!!
###*
* @abstract
* @class Number
* @constructor
* @param {Number} value
* @extends Object
*###
class mathJS.Number extends _mathJS.AbstractNumber
###########################################################################################
# STATIC
@_getPrimitive: (param, skipCheck) ->
if skipCheck is true
return param
if param instanceof mathJS.Number
return param.value
if param instanceof Number
return param.valueOf()
if mathJS.isNum(param)
return param
return null
@getSet: () ->
return mathJS.Domains.R
# moved to AbstractNumber
# @new: (value) ->
# return @_fromPool value
###########################################################################################
# CONSTRUCTOR
constructor: (value) ->
@_value = null
Object.defineProperties @, {
value:
get: @_getValue
set: @_setValue
}
if (val = @_getPrimitive(value))?
@_value = val
else
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{value}'"
"Number.coffee"
)
###########################################################################################
# PRIVATE METHODS
###########################################################################################
# PROTECTED METHODS
###########################################################################################
# PUBLIC METHODS
########################################################
# IMPLEMENTING COMPARABLE
# see AbstractNumber
# END - IMPLEMENTING COMPARABLE
########################################################
# IMPLEMENTING BASIC OPERATIONS
# see AbstractNumber
# END - IMPLEMENTING BASIC OPERATIONS
# EVALUABLE INTERFACE
eval: (values) ->
return @
# TODO: intercept destructor
# .....
_getSet: () ->
return new mathJS.Set(@)
in: (set) ->
return set.contains(@)
valueOf: @::_getValue
# end js/Numbers/Number.coffee
# from js/Numbers/Double.coffee
class mathJS.Double extends mathJS.Number
# end js/Numbers/Double.coffee
# from js/Numbers/Int.coffee
###*
* @class Int
* @constructor
* @param {Number} value
* @extends Number
*###
class mathJS.Int extends mathJS.Number
###########################################################################
# STATIC
@parse: (str) ->
if mathJS.isNum(parsed = parseInt(str, 10))
return @_fromPool parsed
return parsed
@random: (max, min) ->
return @_fromPool mathJS.randInt(max, min)
@getSet: () ->
return mathJS.Domains.N
###*
* @Override mathJS.Poolable
* @static
* @protected
* @method _fromPool
*###
@_fromPool: (value) ->
if @_pool.length > 0
if (val = @_getPrimitiveInt(value))?
number = @_pool.pop()
number.value = val.value or val
return number
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate number from given '#{value}'"
"Int.coffee"
undefined
value
)
# param check is done in constructor
return new @(value)
@_getPrimitiveInt: (param, skipCheck) ->
if skipCheck is true
return param
if param instanceof mathJS.Int
return param.value
if param instanceof mathJS.Number
return ~~param.value
if param instanceof Number
return ~~param.valueOf()
if mathJS.isNum(param)
return ~~param
return null
###########################################################################
# CONSTRUCTOR
constructor: (value) ->
super(value)
if (val = @_getPrimitiveInt(value))?
@_value = val
else
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate integer from given '#{value}'"
"Int.coffee"
)
###########################################################################
# PRIVATE METHODS
###########################################################################
# PROTECTED METHODS
_getPrimitiveInt: (param) ->
return @constructor._getPrimitiveInt(param)
###########################################################################
# PUBLIC METHODS
isEven: () ->
return @value %% 2 is 0
isOdd: () ->
return @value %% 2 is 1
toInt: () ->
return mathJS.Int._fromPool @value
getSet: () ->
return mathJS.Domains.N
# end js/Numbers/Int.coffee
# from js/Numbers/Fraction.coffee
class mathJS.Fraction extends mathJS.Number
###*
* @Override mathJS.Number
* @static
* @method _fromPool
*###
@_fromPool: (numerator, denominator) ->
if @_pool.length > 0
if (e = @_getPrimitiveFrac(numerator))? and (d = @_getPrimitiveFrac(denominator))?
frac = @_pool.pop()
frac.numerator = e
frac.denominator = d
return frac
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate fraction from given '#{numerator}, #{denominator}'"
"Fraction.coffee"
)
else
# param check is done in constructor
return new @(numerator, denominator)
###*
* This method parses strings of the form "x / y" or "x : y".
* @Override mathJS.Number
* @static
* @method parse
*###
@parse: (str) ->
if "/" in str
parts = str.split "/"
return @new parts.first, parts.second
num = parseFloat(str)
if not isNaN(num)
# TODO
numerator = num
denominator = 1
# 123.456 = 123456 / 1000
while numerator % 1 isnt 0
numerator *= 10
denominator *= 10
return @new(numerator, denominator)
throw new mathJS.Errors.NotParseableError("Can't parse '#{str}' as fraction!")
###*
* @Override mathJS.Number
* @static
* @method getSet
*###
@getSet: () ->
return mathJS.Domains.Q
###*
* @Override mathJS.Number
* @static
* @method new
*###
@new: (e, d) ->
return @_fromPool e, d
@_getPrimitiveFrac: (param, skipCheck) ->
return mathJS.Int._getPrimitiveInt(param, skipCheck)
###########################################################################
# CONSTRUCTOR
constructor: (numerator, denominator) ->
@_numerator = null
@_denominator = null
Object.defineProperties @, {
numerator:
get: () ->
return @_numerator
set: @_setValue
denominator:
get: () ->
return @_denominator
set: @_setValue
}
if (e = @_getPrimitiveFrac(numerator))? and (d = @_getPrimitiveFrac(denominator))?
# TODO: when sth. like 12.55 / 0.8 is given => create 12.55*100 / 0.8*100 = 1255 / 80
if d is 0
throw new mathJS.Error.DivisionByZeroError("Denominator is 0 (when creating fraction)!")
@_numerator = e
@_denominator = d
else
throw new mathJS.Errors.InvalidParametersError(
"Can't instatiate fraction from given '#{numerator}, #{denominator}'"
"Fraction.coffee"
)
############################################################################################
# PROTECTED METHODS
_getPrimitiveFrac: (param) ->
return @constructor._getPrimitiveFrac(param)
############################################################################################
# PUBLIC METHODS
# end js/Numbers/Fraction.coffee
# from js/Numbers/Complex.coffee
###*
* @abstract
* @class Complex
* @constructor
* @param {Number} real
* Real part of the number. Either a mathJS.Number or primitive number.
* @param {Number} image
* Real part of the number. Either a mathJS.Number or primitive number.
* @extends Number
*###
# TODO: maybe extend mathJS.Vector instead?! or mix them
class mathJS.Complex extends mathJS.Number
PARSE_KEY = "0PI:KEY:<KEY>END_PI"
###########################################################################
# STATIC
# ###*
# * @Override
# *###
# @_valueIsValid: (value) ->
# return value instanceof mathJS.Number or mathJS.isNum(value)
###*
* @Override
* This method creates an object with the keys "real" and "img" which have primitive numbers as their values.
* @static
* @method _getValueFromParam
* @param {Complex|Number} real
* @param {Number} img
* @return {Object}
*###
@_getValueFromParam: (real, img) ->
if real instanceof mathJS.Complex
return {
real: real.real
img: real.img
}
if real instanceof mathJS.Number and img instanceof mathJS.Number
return {
real: real.value
img: img.value
}
if mathJS.isNum(real) and mathJS.isNum(img)
return {
real: real
img: img
}
return null
@_fromPool: (real, img) ->
if @_pool.length > 0
if @_valueIsValid(real) and @_valueIsValid(img)
number = @_pool.pop()
number.real = real
number.img = img
return number
return null
else
return new @(real, img)
@parse: (str) ->
idx = str.toLowerCase().indexOf(PARSE_KEY)
if idx >= 0
parts = str.substring(idx + PARSE_KEY.length).split ","
if mathJS.isNum(real = parseFloat(parts[0])) and mathJS.isNum(img = parseFloat(parts[1]))
return @_fromPool real, img
return NaN
@random: (max1, min1, max2, min2) ->
return @_fromPool mathJS.randNum(max1, min1), mathJS.randNum(max2, min2)
###########################################################################
# CONSTRUCTOR
constructor: (real, img) ->
values = @_getValueFromParam(real, img)
# if not values?
# fStr = arguments.callee.caller.toString()
# throw new Error("mathJS: Expected 2 numbers or a complex number! Given (#{real}, #{img}) in \"#{fStr.substring(0, fStr.indexOf(")") + 1)}\"")
Object.defineProperties @, {
real:
get: @_getReal
set: @_setReal
img:
get: @_getImg
set: @_setImg
_fromPool:
value: @constructor._fromPool.bind(@constructor)
writable: false
enumarable: false
configurable: false
}
@real = values.real
@img = values.img
###########################################################################
# PRIVATE METHODS
###########################################################################
# PROTECTED METHODS
_setReal: (value) ->
if @_valueIsValid(value)
@_real = value.value or value.real or value
return @
_getReal: () ->
return @_real
_setImg: (value) ->
if @_valueIsValid(value)
@_img = value.value or value.img or value
return @
_getImg: () ->
return @_img
_getValueFromParam: @_getValueFromParam
###########################################################################
# PUBLIC METHODS
###*
* This method check for mathmatical equality. This means new mathJS.Double(4.2).equals(4.2)
* @method equals
* @param {Number} n
* @return {Boolean}
*###
equals: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @real is values.real and @img is values.img
return false
plus: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real + values.real, @img + values.img)
return NaN
increase: (r, i) ->
values = @_getValueFromParam(r, i)
if values?
@real += values.real
@img += values.img
return @
plusSelf: @increase
minus: (n) ->
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real - values.real, @img - values.img)
return NaN
decrease: (n) ->
values = @_getValueFromParam(r, i)
if values?
@real -= values.real
@img -= values.img
return @
minusSelf: @decrease
# TODO: adjust last functions for complex numbers
times: (r, i) ->
# return @_fromPool(@value * _getValueFromParam(n))
values = @_getValueFromParam(r, i)
if values?
return @_fromPool(@real * values.real, @img * values.img)
return NaN
timesSelf: (n) ->
@value *= _getValueFromParam(n)
return @
divide: (n) ->
return @_fromPool(@value / _getValueFromParam(n))
divideSelf: (n) ->
@value /= _getValueFromParam(n)
return @
square: () ->
return @_fromPool(@value * @value)
squareSelf: () ->
@value *= @value
return @
cube: () ->
return @_fromPool(@value * @value * @value)
squareSelf: () ->
@value *= @value * @value
return @
sqrt: () ->
return @_fromPool(mathJS.sqrt @value)
sqrtSelf: () ->
@value = mathJS.sqrt @value
return @
pow: (n) ->
return @_fromPool(mathJS.pow @value, _getValueFromParam(n))
powSelf: (n) ->
@value = mathJS.pow @value, _getValueFromParam(n)
return @
sign: () ->
return mathJS.sign @value
toInt: () ->
return mathJS.Int._fromPool mathJS.floor(@value)
toDouble: () ->
return mathJS.Double._fromPool @value
toString: () ->
return "#{PARSE_KEY}#{@real.toString()},#{@img.toString()}"
clone: () ->
return @_fromPool(@value)
# add instance to pool
release: () ->
@constructor._pool.push @
return @constructor
# end js/Numbers/Complex.coffee
# from js/Algorithms/ShuntingYard.coffee
# from http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
class mathJS.Algorithms.ShuntingYard
CLASS = @
@specialOperators =
# unary plus/minus
"+" : "#"
"-" : "_"
@init = () ->
@specialOperations =
"#": mathJS.Operations.neutralPlus
"_": mathJS.Operations.negate
constructor: (settings) ->
@ops = ""
@precedence = {}
@associativity = {}
for op, opSettings of settings
@ops += op
@precedence[op] = opSettings.precedence
@associativity[op] = opSettings.associativity
isOperand = (token) ->
return mathJS.isNum(token)
toPostfix: (str) ->
# remove spaces
str = str.replace /\s+/g, ""
# make implicit multiplication explicit (3x=> 3*x, xy => x*y)
# TODO: what if a variable/function has more than 1 character: 3*abs(-3)
str = str.replace /(\d+|\w)(\w)/g,"$1*$2"
stack = []
ops = @ops
precedence = @precedence
associativity = @associativity
postfix = ""
# set string property to indicate format
postfix.postfix = true
for token, i in str
# if token is an operator
if token in ops
o1 = token
o2 = stack.last()
# handle unary plus/minus => just add special char
if i is 0 or prevToken is "("
if CLASS.specialOperators[token]?
postfix += "#{CLASS.specialOperators[token]} "
else
# while operator token, o2, on top of the stack
# and o1 is left-associative and its precedence is less than or equal to that of o2
# (the algorithm on wikipedia says: or o1 precedence < o2 precedence, but I think it should be)
# or o1 is right-associative and its precedence is less than that of o2
while o2 in ops and (associativity[o1] is "left" and precedence[o1] <= precedence[o2]) or (associativity[o1] is "right" and precedence[o1] < precedence[o2])
# add o2 to output queue
postfix += "#{o2} "
# pop o2 of the stack
stack.pop()
# next round
o2 = stack.last()
# push o1 onto the stack
stack.push(o1)
# if token is left parenthesis
else if token is "("
# then push it onto the stack
stack.push(token)
# if token is right parenthesis
else if token is ")"
# until token at top is (
while stack.last() isnt "("
postfix += "#{stack.pop()} "
# pop (, but not onto the output queue
stack.pop()
# token is an operand or a variable
else
postfix += "#{token} "
prevToken = token
# console.log token, stack
while stack.length > 0
postfix += "#{stack.pop()} "
return postfix.trim()
toExpression: (str) ->
if not str.postfix?
postfix = @toPostfix(str)
else
postfix = str
postfix = postfix.split " "
# gather all operators
ops = @ops
for k, v of CLASS.specialOperators
ops += v
i = 0
# while expression tree is not complete
while postfix.length > 1
token = postfix[i]
idxOffset = 0
if token in ops
if (op = mathJS.Operations[token])
startIdx = i - op.arity
endIdx = i
else if (op = CLASS.specialOperations[token])
startIdx = i + 1
endIdx = i + op.arity + 1
idxOffset = -1
params = postfix.slice(startIdx, endIdx)
startIdx += idxOffset
# # convert parameter strings to mathJS objects
for param, j in params when typeof param is "string"
if isOperand(param)
params[j] = new mathJS.Expression(parseFloat(param))
else
params[j] = new mathJS.Variable(param)
# create expression from parameters
exp = new mathJS.Expression(op, params...)
# this expression replaces the operation and its parameters
postfix.splice(startIdx, params.length + 1, exp)
# reset i to the first replaced element index -> increase in next iteration -> new element
i = startIdx + 1
# constants
else if isOperand(token)
postfix[i++] = new mathJS.Expression(parseFloat(token))
# variables
else
postfix[i++] = new mathJS.Variable(token)
return postfix.first
# end js/Algorithms/ShuntingYard.coffee
# from js/Formals/Operation.coffee
class mathJS.Operation
constructor: (name, precedence, associativity="left", commutative, func, inverse, setEquivalent) ->
@name = name
@precedence = precedence
@associativity = associativity
@commutative = commutative
@func = func
@arity = func.length # number of parameters => unary, binary, ternary...
@inverse = inverse or null
@setEquivalent = setEquivalent or null
eval: (args) ->
return @func.apply(@, args)
invert: () ->
if @inverse?
return @inverse.apply(@, arguments)
return null
# ABSTRACT OPERATIONS
# Those functions make sure primitives are converted correctly and calls the according operation on it"s first argument.
# They are the actual functions of the operations.
# TODO: no DRY
mathJS.Abstract =
Operations:
# arithmetical
divide: (x, y) ->
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
return x.divide(y)
minus: (x, y) ->
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
return x.minus(y)
plus: (x, y) ->
# numbers -> convert to mathJS.Number
# => int to real
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
# else if x instanceof mathJS.Variable or y instanceof mathJS.Variable
# return new mathJS.Expression(mathJS.Operations.plus, x, y)
# else if x.plus?
# return x.plus(y)
return x.plus(y)
# throw new mathJS.Errors.InvalidParametersError("...")
times: (x, y) ->
# numbers -> convert to mathJS.Number
# => int to real
if mathJS.Number.valueIsValid(x) and mathJS.Number.valueIsValid(y)
x = new mathJS.Number(x)
y = new mathJS.Number(y)
return x.times(y)
negate: (x) ->
if mathJS.Number.valueIsValid(x)
x = new mathJS.Number(x)
return x.negate()
unaryPlus: (x) ->
if mathJS.Number.valueIsValid(x)
x = new mathJS.Number(x)
return x.clone()
# boolean / logical (converting from primitives to numbers doesn"t make sense because 3 and 4 is not defined)
and: (x, y) ->
return x.and(y)
or: (x, y) ->
return x.or(y)
not: (x) ->
return x.not()
nand: (x, y) ->
return x.nand(y)
nor: (x, y) ->
return x.nor(y)
xor: (x, y) ->
return x.xor(y)
equals: (x, y) ->
return x.equals(y)
###
PRECEDENCE (top to bottom):
(...)
factorial
unary +/-
exponents, roots
multiplication, division
addition, subtraction
###
cached =
division: new mathJS.Operation(
"divide"
1
"left"
false
mathJS.pow
mathJS.root
)
addition: new mathJS.Operation(
"plus"
1
"left"
true
mathJS.Abstract.Operations.plus
mathJS.Abstract.Operations.minus
)
subtraction: new mathJS.Operation(
"plus"
1
"left"
false
mathJS.Abstract.Operations.minus
mathJS.Abstract.Operations.plus
)
multiplication: new mathJS.Operation(
"times"
1
"left"
true
mathJS.Abstract.Operations.times
mathJS.Abstract.Operations.divide
)
exponentiation: new mathJS.Operation(
"pow"
1
"right"
false
mathJS.pow
mathJS.root
)
factorial: new mathJS.Operation(
"factorial"
10
"right"
false
mathJS.factorial
mathJS.factorialInverse
)
negate: new mathJS.Operation(
"negate"
11
"none"
false
mathJS.Abstract.Operations.negate
mathJS.Abstract.Operations.negate
)
unaryPlus: new mathJS.Operation(
"unaryPlus"
11
"none"
false
mathJS.Abstract.Operations.unaryPlus
mathJS.Abstract.Operations.unaryPlus
)
and: new mathJS.Operation(
"and"
1
"left"
true
mathJS.Abstract.Operations.and
null
"intersection"
)
or: new mathJS.Operation(
"or"
1
"left"
true
mathJS.Abstract.Operations.or
null
"union"
)
not: new mathJS.Operation(
"not"
5
"none"
false
mathJS.Abstract.Operations.not
mathJS.Abstract.Operations.not
"complement"
)
nand: new mathJS.Operation(
"nand"
1
"left"
true
mathJS.Abstract.Operations.nand
null
)
nor: new mathJS.Operation(
"nor"
1
"left"
true
mathJS.Abstract.Operations.nor
null
)
xor: new mathJS.Operation(
"xor"
1
"left"
true
mathJS.Abstract.Operations.xor
null
)
equals: new mathJS.Operation(
"equals"
1
"left"
true
mathJS.Abstract.Operations.equals
null
"intersection"
)
mathJS.Operations =
# arithmetical
"+": cached.addition
"plus": cached.addition
"-": cached.subtraction
"minus": cached.subtraction
"*": cached.multiplication
"times": cached.multiplication
"/": cached.division
":": cached.division
"divide": cached.division
"^": cached.exponentiation
"pow": cached.exponentiation
"!": cached.factorial
"negate": cached.negate
"-u": cached.negate
"u-": cached.negate
"unaryMinus": cached.negate
"neutralMinus": cached.negate
"+u": cached.unaryPlus
"u+": cached.unaryPlus
"unaryPlus": cached.unaryPlus
"neutralPlus": cached.unaryPlus
# logical
"and": cached.and
"or": cached.or
"not": cached.not
"nand": cached.nand
"nor": cached.nor
"xor": cached.xor
"equals": cached.equals
"=": cached.equals
"xnor": cached.equals
# end js/Formals/Operation.coffee
# from js/Formals/Expression.coffee
###*
* Tree structure of expressions. It consists of 2 expression and 1 operation.
* @class Expression
* @constructor
* @param operation {Operation|String}
* @param expressions... {Expression}
*###
class mathJS.Expression
CLASS = @
@fromString: (str) ->
# TODO: parse string
return new mathJS.Expression()
@parse = @fromString
@parser = new mathJS.Algorithms.ShuntingYard(
# TODO: use operations from operation class
"!":
precedence: 5
associativity: "right"
"^":
precedence: 4
associativity: "right"
"*":
precedence: 3
associativity: "left"
"/":
precedence: 3
associativity: "left"
"+":
precedence: 2
associativity: "left"
"-":
precedence: 2
associativity: "left"
)
# TODO: make those meaningful: eg. adjusted parameter lists?!
@new: (operation, expressions...) ->
return new CLASS(operation, expressions)
constructor: (operation, expressions...) ->
# map op string to actual operation object
if typeof operation is "string"
if mathJS.Operations[operation]?
operation = mathJS.Operations[operation]
else
throw new mathJS.Errors.InvalidParametersError("Invalid operation string given: \"#{operation}\".")
# if constructor was called from static .new()
if expressions.first instanceof Array
expressions = expressions.first
# just 1 parameter => constant/value or hash given
if expressions.length is 0
# constant/variable value given => leaf in expression tree
if mathJS.Number.valueIsValid(operation)
@operation = null
@expressions = [new mathJS.Number(operation)]
else
if operation instanceof mathJS.Variable
@operation = null
@expressions = [operation]
# variable string. eg. "x"
else
@operation = null
@expressions = [new mathJS.Variable(operation)]
# else
# throw new mathJS.Errors.InvalidParametersError("...")
else if operation.arity is expressions.length
@operation = operation
@expressions = expressions
else
throw new mathJS.Errors.InvalidArityError("Invalid number of parameters (#{expressions.length}) for Operation \"#{operation.name}\". Expected number of parameters is #{operation.arity}.")
###*
* This method tests for the equality of structure. So 2*3x does not equal 6x!
* For that see mathEquals().
* @method equals
*###
equals: (expression) ->
# immediate return if different number of sub expressions
if @expressions.length isnt expression.expressions.length
return false
# leaf -> anchor
if not @operation?
return not expression.operation? and expression.expressions.first.equals(@expressions.first)
# order of expressions doesnt matter
if @operation.commutative is true
doneExpressions = []
for exp, i in @expressions
res = false
for x, j in expression.expressions when j not in doneExpressions and x.equals(exp)
doneExpressions.push j
res = true
break
# exp does not equals any of the expressions => return false
if not res
return false
return true
# order of expressions matters
else
# res = true
for e1, i in @expressions
e2 = expression.expressions[i]
# res = res and e1.equals(e2)
if not e1.equals(e2)
return false
# return res
return true
###*
* This method tests for the logical/mathematical equality of 2 expressions.
*###
# TODO: change naming here! equals should always be mathematical!!!
mathEquals: (expression) ->
return @simplify().equals expression.simplify()
###*
* @method eval
* @param values {Object}
* An object of the form {varKey: varVal}.
* @returns The value of the expression (specified by the values).
*###
eval: (values) ->
# replace primitives with mathJS objects
for k, v of values
if mathJS.isPrimitive(v) and mathJS.Number.valueIsValid(v)
values[k] = new mathJS.Number(v)
# leaf => first expression is either a mathJS.Variable or a constant (-> Number)
if not @operation?
return @expressions.first.eval(values)
# no leaf => eval substrees
args = []
for expression in @expressions
# evaluated expression is a variable => stop because this and the "above" expression cant be evaluated further
value = expression.eval(values)
if value instanceof mathJS.Variable
return @
# evaluation succeeded => add to list of evaluated values (which will be passed to the operation)
args.push value
return @operation.eval(args)
simplify: () ->
# simplify numeric values aka. non-variable arithmetics
evaluated = @eval()
# actual simplification: less ops!
# TODO: gather simplification patterns
return @
getVariables: () ->
if not @operation?
if (val = @expressions.first) instanceof mathJS.Variable
return [val]
return []
res = []
for expression in @expressions
res = res.concat expression.getVariables()
return res
_getSet: () ->
# leaf
if not @operation?
return @expressions.first._getSet()
# no leaf
res = null
for expression in @expressions
if res?
res = res[@operation.setEquivalent] expression._getSet()
else
res = expression._getSet()
# TODO: the "or new mathJS.Set()" should be unnecessary
return res or new mathJS.Set()
###*
* Get the "range" of the expression (the set of all possible results).
* @method getSet
*###
getSet: () ->
return @eval()._getSet()
# MAKE ALIASES
evaluatesTo: @::getSet
if DEBUG
@test = () ->
e1 = new CLASS(5)
e2 = new CLASS(new mathJS.Variable("x", mathJS.Number))
e4 = new CLASS("+", e1, e2)
console.log e4.getVariables()
# console.log e4.eval({x: new mathJS.Number(5)})
# console.log e4.eval()
# e5 = e4.eval()
# console.log e5.eval({x: new mathJS.Number(5)})
str = "(5x - 3) ^ 2 * 2 / (4y + 3!)"
# (5x-3)^2 * 2 / (4y + 6)
return "test done"
# end js/Formals/Expression.coffee
# from js/Formals/Variable.coffee
###*
* @class Variable
* @constructor
* @param {String} name
* This is name name of the variable (mathematically)
* @param {mathJS.Set} type
*###
# TODO: make interfaces meta: eg. have a Variable@Evaluable.coffee file that contains the interface and inset on build
# class mathJS.Variable extends mathJS.Evaluable
class mathJS.Variable extends mathJS.Expression
# TODO: change this to mathJS.Domains.R when R is implemented
constructor: (name, elementOf=mathJS.Domains.N) ->
@name = name
if elementOf.getSet?
@elementOf = elementOf.getSet()
else
@elementOf = elementOf
_getSet: () ->
return @elementOf
equals: (variable) ->
return @name is variable.name and @elementOf.equals variable.elementOf
plus: (n) ->
return new mathJS.Expression("+", @, n)
minus: (n) ->
return new mathJS.Expression("-", @, n)
times: (n) ->
return new mathJS.Expression("*", @, n)
divide: (n) ->
return new mathJS.Expression("/", @, n)
eval: (values) ->
if values? and (val = values[@name])?
if @elementOf.contains val
return val
console.warn "Given value \"#{val}\" is not in the set \"#{@elementOf.name}\"."
return @
# end js/Formals/Variable.coffee
# from js/Formals/Equation.coffee
class mathJS.Equation
constructor: (left, right) ->
# if left.mathEquals(right)
# @left = left
# @right = right
# else
# # TODO: only if no variables are contained
# throw new mathJS.Errors.InvalidParametersError("The 2 expressions are not (mathematically) equal!")
@left = left
@right = right
solve: (variable) ->
left = @left.simplify()
right = @right.simplify()
solutions = new mathJS.Set()
# convert to actual variable if only the name was given
if variable not instanceof mathJS.Variable
variables = left.getVariables().concat right.getVariables()
variable = (v for v in variables when v.name is variable).first
return solutions
eval: (values) ->
return @left.eval(values).equals @right.eval(values)
simplify: () ->
@left = @left.simplify()
@right = @right.simplify()
return @
# MAKE ALIASES
# ...
# end js/Formals/Equation.coffee
# from js/Sets/AbstractSet.coffee
class _mathJS.AbstractSet extends _mathJS.Object
@implements _mathJS.Orderable, _mathJS.Poolable, _mathJS.Parseable
@fromString: (str) ->
@parse: () ->
return @fromString.apply(@, arguments)
cartesianProduct: (set) ->
clone: () ->
contains: (elem) ->
equals: (set) ->
getElements: () ->
infimum: () ->
intersection: (set) ->
isSubsetOf: (set) ->
min: () ->
max: () ->
# PRE-IMPLEMENTED (may be inherited)
size: () ->
return Infinity
supremum: () ->
union: (set) ->
intersection: (set) ->
without: (set) ->
###########################################################################
# PRE-IMPLEMENTED (to be inherited)
complement: (universe) ->
return universe.minus(@)
disjoint: (set) ->
return @intersection(set).size() is 0
intersects: (set) ->
return not @disjoint(set)
isEmpty: () ->
return @size() is 0
isSupersetOf: (set) ->
return set.isSubsetOf @
pow: (exponent) ->
sets = []
for i in [0...exponent]
sets.push @
return @cartesianProduct.apply(@, sets)
###########################################################################
# ALIASES
@_makeAliases: () ->
aliasesData =
size: ["cardinality"]
without: ["difference", "except", "minus"]
contains: ["has"]
intersection: ["intersect"]
isSubsetOf: ["subsetOf"]
isSupersetOf: ["supersetOf"]
cartesianProduct: ["times"]
for orig, aliases of aliasesData
for alias in aliases
@::[alias] = @::[orig]
return @
@_makeAliases()
# end js/Sets/AbstractSet.coffee
# from js/Sets/Set.coffee
###*
* @class Set
* @constructor
* @param {mixed} specifications
* To create an empty set pass no parameters.
* To create a discrete set list the elements. Those elements must implement the comparable interface and must not be arrays. Non-comparable elements will be ignored unless they are primitives.
* To create a set from set-builder notation pass the parameters must have the following types:
* mathJS.Expression|mathJS.Tuple|mathJS.Number, mathJS.Predicate
# TODO: package all those types (expression-like) into 1 prototype (Variable already is)
*###
class mathJS.Set extends _mathJS.AbstractSet
###########################################################################
# STATIC
###*
* Optionally the left and right configuration can be passed directly (each with an open- and value-property) or the Interval can be parsed from String (like "(2, 6 ]").
* @static
* @method createInterval
* @param leftOpen {Boolean}
* @param leftValue {Number|mathJS.Number}
* @param rightValue {Number|mathJS.Number}
* @param rightOpen {Boolean}
*###
@createInterval: (parameters...) ->
if typeof (str = parameters.first) is "string"
# remove spaces
str = str.replace /\s+/g, ""
.split ","
left =
open: str.first[0] is "("
value: new mathJS.Number(parseInt(str.first.slice(1), 10))
right =
open: str.second.last is ")"
value: new mathJS.Number(parseInt(str.second.slice(0, -1), 10))
# # first parameter has an .open property => assume ctor called from fromString()
# else if parameters.first.open?
# left = parameters.first
# right = parameters.second
else
second = parameters.second
fourth = parameters.fourth
left =
open: parameters.first
value: (if second instanceof mathJS.Number then second else new mathJS.Number(second))
right =
open: parameters.third
value: (if fourth instanceof mathJS.Number then fourth else new mathJS.Number(fourth))
# an interval can be expressed with a conditional set: (a,b) = {x | x in R, a < x < b}
expression = new mathJS.Variable("x", mathJS.Domains.N)
predicate = null
return new mathJS.Set(expression, predicate)
###########################################################################
# CONSTRUCTOR
constructor: (parameters...) ->
# ANALYSE PARAMETERS
# nothing passed => empty set
if parameters.length is 0
@discreteSet = new _mathJS.DiscreteSet()
@conditionalSet = new _mathJS.ConditionalSet()
# discrete and conditional set given (from internal calls like union())
else if parameters.first instanceof _mathJS.DiscreteSet and parameters.second instanceof _mathJS.ConditionalSet
@discreteSet = parameters.first
@conditionalSet = parameters.second
# set-builder notation
else if parameters.first instanceof mathJS.Expression and parameters.second instanceof mathJS.Expression
console.log "set builder"
@discreteSet = new _mathJS.DiscreteSet()
@conditionalSet = new _mathJS.ConditionalSet(parameters.first, parameters.slice(1))
# discrete set
else
# array given -> make its elements the set elements
if parameters.first instanceof Array
parameters = parameters.first
console.log "params:", parameters
@discreteSet = new _mathJS.DiscreteSet(parameters)
@conditionalSet = new _mathJS.ConditionalSet()
###########################################################################
# PRIVATE METHODS
# TODO: inline the following 2 if used nowhere else
newFromDiscrete = (set) ->
return new mathJS.Set(set.getElements())
newFromConditional = (set) ->
return new mathJS.Set(set.expression, set.domains, set.predicate)
###########################################################################
# PROTECTED METHODS
###########################################################################
# PUBLIC METHODS
getElements: (n=mathJS.config.set.defaultNumberOfElements, sorted=false) ->
res = @discreteSet.elems.concat(@conditionalSet.getElements(n, sorted))
if sorted isnt true
return res
return res.sort(mathJS.sortFunction)
size: () ->
return @discreteSet.size() + @conditionalSet.size()
clone: () ->
return newFromDiscrete(@discreteSet).union(newFromConditional(@conditionalSet))
equals: (set) ->
if set.size() isnt @size()
return false
return set.discreteSet.equals(@discreteSet) and set.conditionalSet.equals(@conditionalSet)
getSet: () ->
return @
isSubsetOf: (set) ->
return @conditionalSet.isSubsetOf(set) or @discreteSet.isSubsetOf(set)
isSupersetOf: (set) ->
return @conditionalSet.isSupersetOf(set) or @discreteSet.isSupersetOf(set)
contains: (elem) ->
return @conditionalSet.contains(@conditionalSet) or @discreteSet.contains(@discreteSet)
union: (set) ->
# if domain (N, Z, Q, R, C) let it handle the union because it knows know more about itself than this does
# also domains have neither discrete nor conditional sets
if set.isDomain
return set.union(@)
return new mathJS.Set(@discreteSet.union(set.discreteSet), @conditionalSet.union(set.conditionalSet))
intersection: (set) ->
if set.isDomain
return set.intersection(@)
return new mathJS.Set(@discreteSet.intersection(set.discreteSet), @conditionalSet.intersection(set.conditionalSet))
complement: () ->
if @universe?
return asdf
return new mathJS.EmptySet()
without: (set) ->
cartesianProduct: (set) ->
min: () ->
return mathJS.min(@discreteSet.min().concat @conditionalSet.min())
max: () ->
return mathJS.max(@discreteSet.max().concat @conditionalSet.max())
infimum: () ->
supremum: () ->
# end js/Sets/Set.coffee
# from js/Sets/DiscreteSet.coffee
###*
* This class is a Setof explicitely listed elements (with no needed logic).
* @class DiscreteSet
* @constructor
* @param {Function|Class} type
* @param {Set} universe
* Optional. If given, the created Set will be interpreted as a sub set of the universe.
* @param {mixed} elems...
* Optional. This and the following parameters serve as elements for the new Set. They will be in the new Set immediately.
* @extends Set
*###
class _mathJS.DiscreteSet extends mathJS.Set
###########################################################################
# CONSTRUCTOR
constructor: (elems...) ->
if elems.first instanceof Array
elems = elems.first
@elems = []
for elem in elems when not @contains(elem)
if not mathJS.isNum(elem)
@elems.push elem
else
@elems.push new mathJS.Number(elem)
###########################################################################
# PROTECTED METHODS
###########################################################################
# PUBLIC METHODS
# discrete sets only!
cartesianProduct: (set) ->
elements = []
for e in @elems
for x in set.elems
elements.push new mathJS.Tuple(e, x)
return new _mathJS.DiscreteSet(elements)
clone: () ->
return new _mathJS.DiscreteSet(@elems)
contains: (elem) ->
for e in @elems when elem.equals e
return true
return false
# discrete sets only!
equals: (set) ->
# return @isSubsetOf(set) and set.isSubsetOf(@)
for e in @elems when not set.contains e
return false
for e in set.elems when not @contains e
return false
return true
###*
* Get the elements of the set.
* @method getElements
* @param sorted {Boolean}
* Optional. If set to `true` returns the elements in ascending order.
*###
getElements: (sorted) ->
if sorted isnt true
return @elems.clone()
return @elems.clone().sort(mathJS.sortFunction)
# discrete sets only!
intersection: (set) ->
elems = []
for x in @elems
for y in set.elems when x.equals y
elems.push x
return new _mathJS.DiscreteSet(elems)
isSubsetOf: (set) ->
for e in @elems when not set.contains e
return false
return true
size: () ->
# TODO: cache size
return @elems.length
# discrete sets only!
union: (set) ->
return new _mathJS.DiscreteSet(set.elems.concat(@elems))
without: (set) ->
return (elem for elem in @elems when not set.contains elem)
min: () ->
return mathJS.min @elems
max: () ->
return mathJS.max @elems
infimum: () ->
supremum: () ->
@_makeAliases()
# end js/Sets/DiscreteSet.coffee
# from js/Sets/ConditionalSet.coffee
class _mathJS.ConditionalSet extends mathJS.Set
CLASS = @
###
{2x^2 | x in R and 0 <= x < 20 and x = x^2} ==> {0, 1}
x in R and 0 <= x < 20 and x = x^2 <=> R intersect [0, 20) intersect {0,1} (where 0 and 1 have to be part of the previous set)
do the following:
1. map domains to domains
2. map unequations to intervals
3. map equations to (discrete?!) sets
4. create intersection of all!
simplifications:
1. domains intersect interval = interval (because in this notation the domain is the superset)
so it wouldnt make sense to say: x in N and x in [0, 10] and expect the set to be infinite!!
the order does not matter (otherwise (x in [0, 10] and x in N) would be infinite!!)
2. when trying to get equation solutions numerically (should this ever happen??) look for interval first to get boundaries
###
# predicate is an boolean expression
# TODO: try to find out if the set is actually discrete!
# TODO: maybe a 3rd parameter "baseSet" should be passed to indicate where the generator comes from
# TODO: predicate could also be the base set itself. if not it must be derived from the (boolean) predicate
# TODO: predicate's type is Expression.Boolean
constructor: (expression, predicate) ->
# empty set
if arguments.length is 0
@generator = null
# non-empty set
else if expression instanceof mathJS.Generator
@generator = expression
# no generator passed => standard parameters
else
if predicate instanceof mathJS.Expression
predicate = predicate.getSet()
# f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple
@generator = new mathJS.Generator(
# f: predicate -> ?? (expression.getSet())
# x |-> expression(x)
new mathJS.Function("f", expression, predicate, expression.getSet())
predicate.min()
predicate.max()
)
cartesianProduct: (sets...) ->
generators = [@generator].concat(set.generator for set in sets)
return new _mathJS.ConditionalSet(mathJS.Generator.product(generators...))
clone: () ->
return new CLASS()
contains: (elem) ->
if mathJS.isComparable elem
if @condition?.check(elem) is true
return true
return false
equals: (set) ->
if set instanceof CLASS
return @generator.f.equals set.generator.f
# normal set
return set.discreteSet.isEmpty() and @generator.f.equals set.conditionSet.generator.f
getElements: (n, sorted) ->
res = []
# TODO
return res
# TODO: "and" generators
intersection: (set) ->
isSubsetOf: (set) ->
isSupersetOf: (set) ->
size: () ->
return @generator.f.range.size()
# TODO: "or" generators
union: (set) ->
without: (set) ->
@_makeAliases()
if DEBUG
@test = () ->
e1 = new mathJS.Expression(5)
e2 = new mathJS.Expression(new mathJS.Variable("x", mathJS.Number))
e3 = new mathJS.Expression("+", e1, e2)
p1 = new mathJS.Expression(new mathJS.Variable("x", mathJS.Number))
p2 = new mathJS.Expression(4)
p3 = new mathJS.Expression("=", p1, p2)
console.log p3.eval(x: 4)
console.log p3.getSet()
console.log AAA
# set = new _mathJS.ConditionalSet(e3, p3)
# console.log set
return "done"
# end js/Sets/ConditionalSet.coffee
# from js/Sets/Tuple.coffee
class mathJS.Tuple
###########################################################################
# CONSTRUCTOR
constructor: (elems...) ->
if elems.first instanceof Array
elems = elems.first
temp = []
for elem in elems
if not mathJS.isNum(elem)
temp.push elem
else
temp.push new mathJS.Number(elem)
@elems = temp
@_size = temp.length
###########################################################################
# PUBLIC METHODS
Object.defineProperties @::, {
first:
get: () ->
return @at(0)
set: () ->
return @
length:
get: () ->
return @_size
set: () ->
return @
}
add: (elems...) ->
return new mathJS.Tuple(@elems.concat(elems))
at: (idx) ->
return @elems[idx]
clone: () ->
return new mathJS.Tuple(@elems)
contains: (elem) ->
for e in @elems when e.equals elem
return true
return false
equals: (tuple) ->
if @_size isnt tuple._size
return false
elements = tuple.elems
for elem, idx in @elems when not elem.equals elements[idx]
return false
return true
###*
* Evaluates the tuple.
* @param values {Array}
* # TODO: also enables hash of vars
* A value for each tuple element.
*###
eval: (values) ->
elems = (elem.eval(values[i]) for elem, i in @elems)
return new mathJS.Tuple(elems)
###*
* Get the elements of the Tuple.
* @method getElements
*###
getElements: () ->
return @elems.clone()
insert: (idx, elems...) ->
elements = []
for elem, i in @elems
if i is idx
elements = elements.concat(elems)
elements.push elem
return new mathJS.Tuple(elements)
isEmpty: () ->
return @_size() is 0
###*
* Removes the first occurences of the given elements.
*###
remove: (elems...) ->
elements = @elems.clone()
for e in elems
for elem, i in elements when elem.equals e
elements.splice i, 1
break
return new mathJS.Tuple(elements)
removeAt: (idx, n=1) ->
elems = []
for elem, i in @elems when i < idx or i >= idx + n
elems.push elem
return new mathJS.Tuple(elems)
size: () ->
return @_size
slice: (startIdx, endIdx=@_size) ->
return new mathJS.Tuple(@elems.slice(startIdx, endIdx))
###########################################################################
# ALIASES
cardinality: @::size
extendBy: @::add
get: @::at
has: @::contains
addAt: @::insert
insertAt: @::insert
reduceBy: @::remove
# end js/Sets/Tuple.coffee
# from js/Sets/Function.coffee
class mathJS.Function extends mathJS.Set
# EQUAL!
# function:
# f: X -> Y, f(x) = 3x^2 - 5x + 7
# set:
# {(x, 3x^2 - 5x + 7) | x in X}
# domain is implicit by variables" types contained in the expression
# range is implicit by the expression
# constructor: (name, domain, range, expression) ->
constructor: (name, expression, domain, range) ->
@name = name
@expression = expression
if domain instanceof mathJS.Set
@domain = domain
else
@domain = new mathJS.Set(expression.getVariables())
if range instanceof mathJS.Set
@range = range
else
@range = expression.getSet()
@_cache = {}
@caching = true
super()
###*
* Empty the cache or reset to given cache.
* @method clearCache
* @param cache {Object}
* @return mathJS.Function
* @chainable
*###
clearCache: (cache) ->
if not cache?
@_cache = {}
else
@_cache = cache
return @
###*
* Evaluate the function for given values.
* @method get
* @param values {Array|Object}
* If an array the first value will be associated with the first variable name. Otherwise an object like {x: 42} is expected.
* @return
*###
eval: (values...) ->
tmp = {}
if values instanceof Array
for value, i in values
tmp[@variableNames[i]] = value
values = tmp
# check if values are in domain
for varName, val of values
if not domain.contains(val)
return null
return @expression.eval(values)
# make alias
at: @eval
get: @eval
# end js/Sets/Function.coffee
# from js/Sets/Generators/AbstractGenerator.coffee
class _mathJS.AbstractGenerator extends _mathJS.Object
###########################################################################
# CONSTRUCTOR
constructor: (f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple) ->
@f = f
@inverseF = f.getInverse()
@minX = minX
@maxX = maxX
@stepSize = stepSize
@maxIndex = maxIndex
@tuple = tuple
@x = minX
@overflowed = false
@index = 0
###########################################################################
# DEFINED PROPS
Object.defineProperties @::, {
function:
get: () ->
return @f
set: (f) ->
@f = f
@inverseF = f.getInverse()
return @
}
###########################################################################
# STATIC
@product: (generators...) ->
@or: (gen1, gen2) ->
@and: (gen1, gen2) ->
###########################################################################
# PUBLIC
###*
* Indicates whether the set the generator creates contains the given value or not.
* @method generates
*###
generates: (y) ->
if @f.range.contains(y)
#
if @inverseF?
return @inverseF.eval(y)
return
return false
eval: (n) ->
# eval each tuple element individually (the tuple knows how to do that)
if @tuple?
return @tuple.eval(n)
# eval expression
if @f.eval?
@f.eval(n)
# eval js function
return @f.call(@, n)
hasNext: () ->
if @tuple?
for g, i in @tuple.elems when g.hasNext()
return true
return false
return not @overflowed and @x < @maxX and @index < @maxIndex
_incX: () ->
@index++
# more calculation than just "@x += @stepSize" but more precise!
@x = @minX + @index * @stepSize
if @x > @maxX
@x = @minX
@index = 0
@overflowed = true
return @x
next: () ->
if @tuple?
res = @eval(g.x for g in @tuple.elems)
###
0 0
0 1
1 0
1 1
###
# start binary-like counting (so all possibilities are done)
i = 0
maxI = @tuple.length
generator = @tuple.first
generator._incX()
while i < maxI and generator.overflowed
generator.overflowed = false
generator = @tuple.at(++i)
# # "if" needed for very last value -> i should theoretically overflow
# => i refers to the (n+1)st tuple element (which only has n elements)
if generator?
generator._incX()
return res
# no tuple => simple generator
res = @eval(@x)
@_incX()
return res
reset: () ->
@x = @minX
@index = 0
return @
if DEBUG
@test = () ->
# simple
g = new mathJS.Generator(
(x) ->
return 3*x*x+2*x-5
-10
10
0.2
)
res = []
while g.hasNext()
tmp = g.next()
# console.log tmp
res.push tmp
tmp = g.next()
# console.log tmp
res.push tmp
console.log "simple test:", (if res.length is ((g.maxX - g.minX) / g.stepSize + 1) then "successful" else "failed")
# "nested"
g1 = new mathJS.Generator(
(x) -> x,
0,
5,
0.5
)
g2 = new mathJS.Generator(
(x) -> 2*x,
-2,
10,
2
)
g = mathJS.Generator.product(g1, g2)
res = []
while g.hasNext()
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
console.log "tuple test:", (if res.length is ((g1.maxX - g1.minX) / g1.stepSize + 1) * ((g2.maxX - g2.minX) / g2.stepSize + 1) then "successful" else "failed")
g = new mathJS.Generator((x) -> x)
while g.hasNext()
tmp = g.next()
# console.log tmp
tmp = g.next()
# console.log tmp
return "done"
# end js/Sets/Generators/AbstractGenerator.coffee
# from js/Sets/Generators/DiscreteGenerator.coffee
class mathJS.DiscreteGenerator extends _mathJS.AbstractGenerator
###########################################################################
# CONSTRUCTOR
constructor: (f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple) ->
@f = f
@inverseF = f.getInverse()
@minX = minX
@maxX = maxX
@stepSize = stepSize
@maxIndex = maxIndex
@tuple = tuple
@x = minX
@overflowed = false
@index = 0
###########################################################################
# DEFINED PROPS
Object.defineProperties @::, {
function:
get: () ->
return @f
set: (f) ->
@f = f
@inverseF = f.getInverse()
return @
}
###########################################################################
# STATIC
@product: (generators...) ->
return new mathJS.Generator(null, 0, Infinity, null, null, new mathJS.Tuple(generators))
@or: () ->
@and: () ->
###########################################################################
# PUBLIC
###*
* Indicates whether the set the generator creates contains the given value or not.
* @method generates
*###
generates: (y) ->
if @f.range.contains(y)
#
if @inverseF?
return @inverseF.eval(y)
return
return false
eval: (n) ->
# eval each tuple element individually (the tuple knows how to do that)
if @tuple?
return @tuple.eval(n)
# eval expression
if @f.eval?
@f.eval(n)
# eval js function
return @f.call(@, n)
hasNext: () ->
if @tuple?
for g, i in @tuple.elems when g.hasNext()
return true
return false
return not @overflowed and @x < @maxX and @index < @maxIndex
_incX: () ->
@index++
# more calculation than just "@x += @stepSize" but more precise!
@x = @minX + @index * @stepSize
if @x > @maxX
@x = @minX
@index = 0
@overflowed = true
return @x
next: () ->
if @tuple?
res = @eval(g.x for g in @tuple.elems)
###
0 0
0 1
1 0
1 1
###
# start binary-like counting (so all possibilities are done)
i = 0
maxI = @tuple.length
generator = @tuple.first
generator._incX()
while i < maxI and generator.overflowed
generator.overflowed = false
generator = @tuple.at(++i)
# # "if" needed for very last value -> i should theoretically overflow
# => i refers to the (n+1)st tuple element (which only has n elements)
if generator?
generator._incX()
return res
# no tuple => simple generator
res = @eval(@x)
@_incX()
return res
reset: () ->
@x = @minX
@index = 0
return @
if DEBUG
@test = () ->
# simple
g = new mathJS.Generator(
(x) ->
return 3*x*x+2*x-5
-10
10
0.2
)
res = []
while g.hasNext()
tmp = g.next()
# console.log tmp
res.push tmp
tmp = g.next()
# console.log tmp
res.push tmp
console.log "simple test:", (if res.length is ((g.maxX - g.minX) / g.stepSize + 1) then "successful" else "failed")
# "nested"
g1 = new mathJS.Generator(
(x) -> x,
0,
5,
0.5
)
g2 = new mathJS.Generator(
(x) -> 2*x,
-2,
10,
2
)
g = mathJS.Generator.product(g1, g2)
res = []
while g.hasNext()
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
console.log "tuple test:", (if res.length is ((g1.maxX - g1.minX) / g1.stepSize + 1) * ((g2.maxX - g2.minX) / g2.stepSize + 1) then "successful" else "failed")
g = new mathJS.Generator((x) -> x)
while g.hasNext()
tmp = g.next()
# console.log tmp
tmp = g.next()
# console.log tmp
return "done"
# end js/Sets/Generators/DiscreteGenerator.coffee
# from js/Sets/Generators/ContinuousGenerator.coffee
class mathJS.ContinuousGenerator extends _mathJS.AbstractGenerator
###########################################################################
# CONSTRUCTOR
constructor: (f, minX=0, maxX=Infinity, stepSize=mathJS.config.number.real.distance, maxIndex=mathJS.config.generator.maxIndex, tuple) ->
@f = f
@inverseF = f.getInverse()
@minX = minX
@maxX = maxX
@stepSize = stepSize
@maxIndex = maxIndex
@tuple = tuple
@x = minX
@overflowed = false
@index = 0
###########################################################################
# DEFINED PROPS
Object.defineProperties @::, {
function:
get: () ->
return @f
set: (f) ->
@f = f
@inverseF = f.getInverse()
return @
}
###########################################################################
# STATIC
@product: (generators...) ->
return new mathJS.Generator(null, 0, Infinity, null, null, new mathJS.Tuple(generators))
@or: () ->
@and: () ->
###########################################################################
# PUBLIC
###*
* Indicates whether the set the generator creates contains the given value or not.
* @method generates
*###
generates: (y) ->
if @f.range.contains(y)
#
if @inverseF?
return @inverseF.eval(y)
return
return false
eval: (n) ->
# eval each tuple element individually (the tuple knows how to do that)
if @tuple?
return @tuple.eval(n)
# eval expression
if @f.eval?
@f.eval(n)
# eval js function
return @f.call(@, n)
hasNext: () ->
if @tuple?
for g, i in @tuple.elems when g.hasNext()
return true
return false
return not @overflowed and @x < @maxX and @index < @maxIndex
_incX: () ->
@index++
# more calculation than just "@x += @stepSize" but more precise!
@x = @minX + @index * @stepSize
if @x > @maxX
@x = @minX
@index = 0
@overflowed = true
return @x
next: () ->
if @tuple?
res = @eval(g.x for g in @tuple.elems)
###
0 0
0 1
1 0
1 1
###
# start binary-like counting (so all possibilities are done)
i = 0
maxI = @tuple.length
generator = @tuple.first
generator._incX()
while i < maxI and generator.overflowed
generator.overflowed = false
generator = @tuple.at(++i)
# # "if" needed for very last value -> i should theoretically overflow
# => i refers to the (n+1)st tuple element (which only has n elements)
if generator?
generator._incX()
return res
# no tuple => simple generator
res = @eval(@x)
@_incX()
return res
reset: () ->
@x = @minX
@index = 0
return @
if DEBUG
@test = () ->
# simple
g = new mathJS.Generator(
(x) ->
return 3*x*x+2*x-5
-10
10
0.2
)
res = []
while g.hasNext()
tmp = g.next()
# console.log tmp
res.push tmp
tmp = g.next()
# console.log tmp
res.push tmp
console.log "simple test:", (if res.length is ((g.maxX - g.minX) / g.stepSize + 1) then "successful" else "failed")
# "nested"
g1 = new mathJS.Generator(
(x) -> x,
0,
5,
0.5
)
g2 = new mathJS.Generator(
(x) -> 2*x,
-2,
10,
2
)
g = mathJS.Generator.product(g1, g2)
res = []
while g.hasNext()
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
tmp = g.next()
res.push tmp
# console.log (x.value for x in tmp.elems)
console.log "tuple test:", (if res.length is ((g1.maxX - g1.minX) / g1.stepSize + 1) * ((g2.maxX - g2.minX) / g2.stepSize + 1) then "successful" else "failed")
g = new mathJS.Generator((x) -> x)
while g.hasNext()
tmp = g.next()
# console.log tmp
tmp = g.next()
# console.log tmp
return "done"
# end js/Sets/Generators/ContinuousGenerator.coffee
# from js/Sets/Domains/Domain.coffee
###*
* Domain ranks are like so:
* N -> 0
* Z -> 1
* Q -> 2
* I -> 2
* R -> 3
* C -> 4
* ==> union: take greater rank (if equal (and unequal names) take next greater rank)
* ==> intersection: take smaller rank (if equal (and unequal names) take empty set)
*###
class _mathJS.Sets.Domain extends _mathJS.AbstractSet
CLASS = @
@new: () ->
return new CLASS()
@_byRank: (rank) ->
for name, domain of mathJS.Domains when domain.rank is rank
return domain
return null
constructor: (name, rank, isCountable) ->
@isDomain = true
@name = name
@rank = rank
@isCountable = isCountable
clone: () ->
return @constructor.new()
size: () ->
return Infinity
equals: (set) ->
return set instanceof @constructor
intersection: (set) ->
if set.isDomain
if @name is set.name
return @
if @rank < set.rank
return @
if @rank > set.rank
return set
return new mathJS.Set()
# TODO !!
return false
union: (set) ->
if set.isDomain
if @name is set.name
return @
if @rank > set.rank
return @
if @rank < set.rank
return set
return CLASS._byRank(@rank + 1)
# TODO !!
return false
@_makeAliases()
# end js/Sets/Domains/Domain.coffee
# from js/Sets/Domains/N.coffee
class mathJS.Sets.N extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("N", 0, true)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return mathJS.isInt(x) or new mathJS.Int(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
union: (set, n = mathJS.settings.set.maxIterations, matches = mathJS.settings.set.maxMatches) ->
# AND both checker functions
checker = (elem) ->
return self.checker(elem) or set.checker(elem)
generator = () ->
# TODO: how to avoid doubles? implementations that use boolean arrays => XOR operations on elements
# discrete set
if set instanceof mathJS.DiscreteSet or set.instanceof?(mathJS.DiscreteSet)
# non-discrete set (empty or conditional set, or domain)
else if set instanceof mathJS.Set or set.instanceof?(mathJS.Set)
# check for domains. if set is a domain this or the set can directly be returned because they are immutable
# N
if mathJS.instanceof(set, mathJS.Set.N)
return @
# Q, R # TODO: other domains like I, C
if mathJS.instanceof(set, mathJS.Domains.Q) or mathJS.instanceof(set, mathJS.Domains.R)
return set
self = @
# param was no set
return null
intersect: (set) ->
# AND both checker functions
checker = (elem) ->
return self.checker(elem) and set.checker(elem)
# if the f2-invert of the y-value of f1 lies within f2" domain/universe both ranges include that value
# or vice versa
# we know this generator function has N as domain (and as range of course)
# we even know the set"s generator function also has N as domain as we assume that (because the mapping is always a bijection from N -> X)
# so we can only check a single value at a time so we have to have to boundaries for the number of iterations and the number of matches
# after x matches we try to find a series that produces those matches (otherwise a discrete set will be created)
commonElements = []
x = 0 # current iteration = current x value
m = 0 # current matches
f1 = @generator
f2 = set.generator
f1Elems = [] # in ascending order because generators are increasing
f2Elems = [] # in ascending order because generators are increasing
while x < n and m < matches
y1 = f1(x) # TODO: maybe inline generator function here?? but that would mean every sub class has to overwrite
y2 = f2(x)
# f1 is bigger than f2 at current x => check for y2 in f1Elems
if mathJS.gt(y1, y2)
found = false
for f1Elem, i in f1Elems when mathJS.equals(y2, f1Elem)
# new match!
m++
found = true
# y2 found in f1Elems => add to common elements
commonElements.push y2
# because both functions are increasing dispose of earlier elements
# remove all unneeded elements from f1Elems incl. (current) y1
f1Elems = f1Elems.slice(i + 1)
# y2 was a match (the last in f2Elems) and y1 is bigger than y2 so we can forget everything in f2Elems
f2Elems = []
# exit loop
break
if not found
f1Elems.push y1
f2Elems.push y2
# f2 is bigger than f1 at current x => check for y1 in f2Elems
else if mathJS.lt(y1, y2)
found = false
for f2Elem, i in f2Elems when mathJS.equals(y1, f2Elem)
# new match!
m++
found = true
# y1 found in f2Elems => add to common elements
commonElements.push y1
# because both functions are increasing dispose of earlier elements
# remove all unneeded elements from f2Elems incl. (current) y1
f2Elems = f2Elems.slice(i + 1)
# y1 was a match (the last in f2Elems) and y1 is bigger than y1 so we can forget everything in f1Elems
f1Elems = []
# exit loop
break
if not found
f1Elems.push y1
f2Elems.push y2
# equal
else
m++
commonElements.push y1
# all previous values are unimportant because in the next iteration the new values will BOTH be greater than y1=y2 and the 2 lists contain only smaller elements than y1=y2 so there can"t be a match with the next elements
f1Elems = []
f2Elems = []
# increment
x++
console.log "x=#{x}", "m=#{m}", commonElements
# try to find formular from series (supported is: +,-,*,/)
ops = []
for elem in commonElements
true
# example: c1 = x^2, c2 = 2x+1
# c1: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81...
# c2: 1, 3, 5, 7, 9, 11, 13, 15, 17, ...
# => 1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 441, 529, 625, 729, 841, 961, 1089, 1225, 1369, 1521, 1681, 1849
# this is all odd squares (all odd numbers squared!) ==> f(x) = (2x + 1)^2
# ==> slower increasing function = f, faster increasing function = g -> new-f(x) = g(f(x)) = (g o f)(x)
# actually it is the "bigger function" with a constraint
# inserting smaller in bigger works also for 2x, 3x
# what about 2x, 3x+1 -> 3(2x) + 1 = 6x+1
# but 2x, 2x => 2(2x) = 4x wrong!
# series like *2, +1, *3, -1, *4, +1, *5, -1, *6, +1, ...
# would create 1, 2, 3, 9, 8, 32, 33, 165, 164, 984, 985
# indices: 0 1 2 3 4 5 6 7 8 9 10
# f would be y = x^2 + (-1)^x
return
intersects: (set) ->
return @intersection(set).size > 0
disjoint: (set) ->
return @intersection(set).size is 0
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
times: @::cartesianProduct
# inherited
# isEmpty: () ->
# return @size is 0
# MAKE MATHJS.DOMAINS.N AN INSTANCE
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
N:
value: new mathJS.Sets.N()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/N.coffee
# from js/Sets/Domains/Z.coffee
class mathJS.Sets.Z extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("Z", 1, true)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
Z:
value: new mathJS.Sets.Z()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/Z.coffee
# from js/Sets/Domains/Q.coffee
class mathJS.Sets.Q extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("Q", 2, true)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
Q:
value: new mathJS.Sets.Q()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/Q.coffee
# from js/Sets/Domains/I.coffee
class mathJS.Sets.I extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("I", 2, false)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
I:
value: new mathJS.Sets.I()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/I.coffee
# from js/Sets/Domains/R.coffee
class mathJS.Sets.R extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("R", 3, false)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
R:
value: new mathJS.Sets.R()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/R.coffee
# from js/Sets/Domains/C.coffee
class mathJS.Sets.C extends _mathJS.Sets.Domain
CLASS = @
@new: () ->
return new CLASS()
constructor: () ->
super("C", 4, false)
#################################################################################
# STATIC
#################################################################################
# PUBLIC
contains: (x) ->
return new mathJS.Number(x).equals(x)
###*
* This method checks if `this` is a subset of the given set `set`. Since equality must be checked by checking an arbitrary number of values this method actually does the same as `this.equals()`. For `this.equals()` the number of compared elements is 10x bigger.
*###
isSubsetOf: (set, n = mathJS.settings.set.maxIterations) ->
return @equals(set, n * 10)
isSupersetOf: (set) ->
if @_isSet set
return set.isSubsetOf @
return false
complement: () ->
if @universe?
return @universe.without @
return new mathJS.EmptySet()
###*
* a.without b => returns: removed all common elements from a
*###
without: (set) ->
cartesianProduct: (set) ->
# size becomes the bigger one
@_makeAliases()
do () ->
# mathJS.Domains.N = new mathJS.Sets.N()
Object.defineProperties mathJS.Domains, {
C:
value: new mathJS.Sets.C()
writable: false
enumerable: true
configurable: false
}
# end js/Sets/Domains/C.coffee
# from js/Calculus/Integral.coffee
class mathJS.Integral
CLASS = @
if DEBUG
@test = () ->
i = new mathJS.Integral(
(x) ->
return -2*x*x-3*x+10
-3
1
)
start = Date.now()
console.log i.solve(false, 0.00000000000001), Date.now() - start
start = Date.now()
i.solveAsync(
(res) ->
console.log res, "async took:", Date.now() - start
false
0.0000001
)
start2 = Date.now()
console.log i.solve(), Date.now() - start2
return "test done"
constructor: (integrand, leftBoundary=-Infinity, rightBoundary=Infinity, integrationVariable=new mathJS.Variable("x")) ->
@integrand = integrand
@leftBoundary = leftBoundary
@rightBoundary = rightBoundary
@integrationVariable = integrationVariable
@settings = null
# PRIVATE
_solvePrepareVars = (from, to, abs, stepSize) ->
# absolute integral?
if abs is false
modVal = mathJS.id
else
modVal = (x) ->
return Math.abs(x)
# get primitives
from = from.value or from
to = to.value or to
# swap if in wrong order
if to < from
tmp = to
to = from
from = tmp
if (diff = to - from) < stepSize
# stepSize = diff * stepSize * 0.1
stepSize = diff * 0.001
return {
modVal: modVal
from: from
to: to
stepSize: stepSize
}
# STATIC
@solve = (integrand, from, to, abs=false, stepSize=0.01, settings={}) ->
vars = _solvePrepareVars(from, to, abs, stepSize)
modVal = vars.modVal
from = vars.from
to = vars.to
stepSize = vars.stepSize
if (steps = (to - from) / stepSize) > settings.maxSteps or mathJS.settings.integral.maxSteps
throw new mathJS.Errors.CalculationExceedanceError("Too many calculations (#{steps.toExponential()}) ahead! Either adjust mathJS.Integral.settings.maxSteps, set the Integral\"s instance\"s settings or pass settings to mathJS.Integral.solve() if you really need that many calculations.")
res = 0
# cache 0.5 * stepSize
halfStepSize = 0.5 * stepSize
y1 = integrand(from)
if DEBUG
i = 0
for x2 in [(from + stepSize)..to] by stepSize
if DEBUG
i++
y2 = integrand(x2)
if mathJS.sign(y1) is mathJS.sign(y2)
# trapezoid formula
res += modVal((y1 + y2) * halfStepSize)
# else: round to zero -> no calculation needed
y1 = y2
if DEBUG
console.log "made", i, "calculations"
return res
###*
* For better calculation performance of the integral decrease delay and numBlocks.
* For better overall performance increase them.
* @public
* @static
* @method solveAsync
* @param integrand {Function}
* @param from {Number}
* @param to {Number}
* @param callback {Function}
* @param abs {Boolean}
* Optional. Indicates whether areas below the graph are negative or not.
* Default is false.
* @param stepSize {Number}
* Optional. Defines the width of each trapezoid. Default is 0.01.
* @param delay {Number}
* Optional. Defines the time to pass between blocks of calculations.
* Default is 2ms.
* @param numBlocks {Number}
* Optional. Defines the number of calculation blocks.
* Default is 100.
*###
@solveAsync: (integrand, from, to, callback, abs, stepSize, delay=2, numBlocks=100) ->
if not callback?
return false
# split calculation into numBlocks blocks
blockSize = (to - from) / numBlocks
block = 0
res = 0
f = (from, to) ->
# done with all blocks => return result to callback
if block++ is numBlocks
return callback(res)
res += CLASS.solve(integrand, from, to, abs, stepSize)
setTimeout () ->
f(to, to + blockSize)
, delay
return true
f(from, from + blockSize)
return @
# PUBLIC
solve: (abs, stepSize) ->
return CLASS.solve(@integrand, @leftBoundary, @rightBoundary, abs, stepSize)
solveAsync: (callback, abs, stepSize) ->
return CLASS.solveAsync(@integrand, @leftBoundary, @rightBoundary, callback, abs, stepSize)
# end js/Calculus/Integral.coffee
# from js/LinearAlgebra/Vector.coffee
class mathJS.Vector
_isVectorLike: (v) ->
return v instanceof mathJS.Vector or v.instanceof?(mathJS.Vector)# or v instanceof mathJS.Tuple or v.instanceof?(mathJS.Tuple)
@_isVectorLike: @::_isVectorLike
# CONSTRUCTOR
constructor: (values) ->
# check values for
@values = values
if DEBUG
for val in values when not mathJS.isMathJSNum(val)
console.warn "invalid value:", val
equals: (v) ->
if not @_isVectorLike(v)
return false
for val, i in @values
vValue = v.values[i]
if not val.equals?(vValue) and val isnt vValue
return false
return true
clone: () ->
return new TD.Vector(@values)
move: (v) ->
if not @_isVectorLike v
return @
for val, i in v.values
vValue = v.values[i]
@values[i] = vValue.plus?(val) or val.plus?(vValue) or (vValue + val)
return @
moveBy: @move
moveTo: (p) ->
if not @_isVectorLike v
return @
for val, i in v.values
vValue = v.values[i]
@values[i] = vValue.value or vValue
return @
multiply: (r) ->
if Math.isNum r
return new TD.Point(@x * r, @y * r)
return null
# make alias
times: @multiply
magnitude: () ->
sum = 0
for val, i in @values
sum += val * val
return Math.sqrt(sum)
###*
* This method calculates the distance between 2 points.
* It"s a shortcut for substracting 2 vectors and getting that vector"s magnitude (because no new object is created).
* For that reason this method should be used for pure distance calculations.
*
* @method distanceTo
* @param {Point} p
* @return {Number} Distance between this point and p.
*###
distanceTo: (v) ->
sum = 0
for val, i in @values
sum += (val - v.values[i]) * (val - v.values[i])
return Math.sqrt(sum)
add: (v) ->
if not @_isVectorLike v
return null
values = []
for val, i in v.values
vValue = v.values[i]
values.push(vValue.plus?(val) or val.plus?(vValue) or (vValue + val))
return new mathJS.Vector(values)
# make alias
plus: @add
substract: (p) ->
if isPointLike p
return new TD.Point(@x - p.x, @y - p.y)
return null
# make alias
minus: @substract
xyRatio: () ->
return @x / @y
toArray: () ->
return [@x, @y]
isPositive: () ->
return @x >= 0 and @y >= 0
###*
* Returns the angle of a vector. Beware that the angle is measured in counter clockwise direction beginning at 0˚ which equals the x axis in positive direction.
* So on a computer grid the angle won"t be what you expect! Use anglePC() in that case!
*
* @method angle
* @return {Number} Angle of the vector in degrees. 0 degrees means pointing to the right.
*###
angle: () ->
# 1st quadrant (and zero)
if @x >= 0 and @y >= 0
return Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) ) % 360
# 2nd quadrant
if @x < 0 and @y > 0
return (90 + Math.radToDeg( Math.atan( Math.abs(@x) / Math.abs(@y) ) )) % 360
# 3rd quadrant
if @x < 0 and @y < 0
return (180 + Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) )) % 360
# 4th quadrant
return (270 + Math.radToDeg( Math.atan( Math.abs(@x) / Math.abs(@y) ) )) % 360
###*
* Returns the angle of a vector. 0˚ means pointing to the top. Clockwise.
*
* @method anglePC
* @return {Number} Angle of the vector in degrees. 0 degrees means pointing to the right.
*###
anglePC: () ->
# 1st quadrant: pointing to bottom right
if @x >= 0 and @y >= 0
return (90 + Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) )) % 360
# 2nd quadrant: pointing to bottom left
if @x < 0 and @y > 0
return (180 + Math.radToDeg( Math.atan( Math.abs(@x) / Math.abs(@y) ) )) % 360
# 3rd quadrant: pointing to top left
if @x < 0 and @y < 0
return (270 + Math.radToDeg( Math.atan( Math.abs(@y) / Math.abs(@x) ) )) % 360
# 4th quadrant: pointing to top right
return Math.radToDeg(Math.atan( Math.abs(@x) / Math.abs(@y) ) ) % 360
###*
* Returns a random Point within a given radius.
*
* @method randPointInRadius
* @param {Number} radius
* Default is 10 (pixels). Must not be smaller than 0.
* @param {Boolean} random
* Indicates whether the given radius is the maximum or exact distance between the 2 points.
* @return {Number} Random Point.
*###
randPointInRadius: (radius = 5, random = false) ->
angle = Math.degToRad(Math.randNum(0, 360))
if random is true
radius = Math.randNum(0, radius)
x = radius * Math.cos angle
y = radius * Math.sin angle
return @add( new TD.Point(x, y) )
# end js/LinearAlgebra/Vector.coffee
# from js/Initializer.coffee
class mathJS.Initializer
@start: () ->
mathJS.Algorithms.ShuntingYard.init()
# end js/Initializer.coffee
# from js/start.coffee
mathJS.Initializer.start()
if DEBUG
diff = Date.now() - startTime
console.log "time to load mathJS: ", diff, "ms"
if diff > 100
console.warn "LOADING TIME CRITICAL!"
# end js/start.coffee
|
[
{
"context": " constructor: (@game, @opponent = true, @name = 'SMITH', @level = 30,\n @case = 4, @type =",
"end": 274,
"score": 0.9086205959320068,
"start": 269,
"tag": "NAME",
"value": "SMITH"
}
] | src/js/debater.coffee | Huntrr/Battle-Resolution | 0 | $ = require 'lib/jquery.js'
require 'lib/jquery-ui.js'
Async = require 'lib/async.js'
# constants
dir = './img/char/'
ftype = '.png'
# Basic debater class. Controls an actor in the game
module.exports = class Debater
constructor: (@game, @opponent = true, @name = 'SMITH', @level = 30,
@case = 4, @type = 'DEBATER') ->
@me = if @opponent then @game.opponentElem else @game.playerElem
@img = @name
# set basic statis
# ALREADY SET (constructed)
# @case (HP)
# @level (speaker score) (Lvl)
# @type (type)
@clash = 2 # ATTACK
@presentation = 2 # SP. ATTACK
@organization = 3 # SPEED
@civility = 5 # Totally arbitrary
@cross = 3 # DEFENCE
@moves = []
@statuses = []
@canMove = true
setName: (name) ->
@name = name
getTarget: () ->
@other = if @opponent then @game.player else @game.opponent
return @other # explicit return for readability
load: () ->
@me.setImg(dir + @img + (if @opponent then '' else '_back') + ftype)
@me.setName(@name)
@statuses = [] # reset statuses on load()
@update()
update: () -> #updates states
@me.setLevel(@level)
shownCase = Math.floor(@case * 100)/100
@me.setCase(shownCase)
status = @type + (if @statuses.length > 0 then '|' else '')
status += ' ' + effect.name for effect in @statuses
@me.setStatus(status)
# move loop
go: (callback) ->
@canMove = true
actions = []
i = 0
while i < @statuses.length
status = @statuses[i]
if status.expired() #if it's expired, push its unload function to be executed
actions.push (cb) =>
status.unload(cb)
@update()
@statuses.splice i, 1
else #else execute its invoke function
actions.push (cb) =>
status.invoke(cb)
@update()
i++
actions.push (cb) =>
if @canMove
@getMove (err, move) ->
move.use(callback)
cb(null)
@update()
else
cb(null)
callback(null)
@update()
Async.waterfall actions
say: (what, cb) ->
@game.console.put(@name + ': ' + what, cb)
hasMove: (name) ->
for move in @moves
if move.name is name
return true
return false
addMove: (move) ->
if !@hasMove move.name
move.setUser(@)
move.setGame(@game)
@moves.push(move)
addMoveByClass: (MoveClass) ->
move = new MoveClass()
@addMove move
addStatus: (status) ->
status.setTarget(@)
status.setGame(@game)
@statuses.push(status)
has: (status) ->
for effect in @statuses
if effect.name is status
return true
return false
getStatus: (status) ->
for effect in @statuses
if effect.name is status
return status
return null
removeStatus: (status) ->
for i in [0...@statuses.length]
if @statuses[i].name is status
@statuses.splice i, 1
# re-execute the function, since the indices in the array
# are too messed up to continue. Do this until no instances
# of move are left in statuses (looks heavier than it is
# since there will never be too many things in @statuses)
return @removeStatus status
die: () ->
@me.charElem.hide('explode', {duration: 1000})
setHealth: (amount) ->
@case = amount
@update()
if @case <= 0
@die()
damage: (amount) ->
@setHealth @case - amount
heal: (amount) ->
@damage(-amount)
getMove: (cb) -> # async because player moves
move = @moves[Math.floor(Math.random()*@moves.length)]
cb(null, move)
| 20891 | $ = require 'lib/jquery.js'
require 'lib/jquery-ui.js'
Async = require 'lib/async.js'
# constants
dir = './img/char/'
ftype = '.png'
# Basic debater class. Controls an actor in the game
module.exports = class Debater
constructor: (@game, @opponent = true, @name = '<NAME>', @level = 30,
@case = 4, @type = 'DEBATER') ->
@me = if @opponent then @game.opponentElem else @game.playerElem
@img = @name
# set basic statis
# ALREADY SET (constructed)
# @case (HP)
# @level (speaker score) (Lvl)
# @type (type)
@clash = 2 # ATTACK
@presentation = 2 # SP. ATTACK
@organization = 3 # SPEED
@civility = 5 # Totally arbitrary
@cross = 3 # DEFENCE
@moves = []
@statuses = []
@canMove = true
setName: (name) ->
@name = name
getTarget: () ->
@other = if @opponent then @game.player else @game.opponent
return @other # explicit return for readability
load: () ->
@me.setImg(dir + @img + (if @opponent then '' else '_back') + ftype)
@me.setName(@name)
@statuses = [] # reset statuses on load()
@update()
update: () -> #updates states
@me.setLevel(@level)
shownCase = Math.floor(@case * 100)/100
@me.setCase(shownCase)
status = @type + (if @statuses.length > 0 then '|' else '')
status += ' ' + effect.name for effect in @statuses
@me.setStatus(status)
# move loop
go: (callback) ->
@canMove = true
actions = []
i = 0
while i < @statuses.length
status = @statuses[i]
if status.expired() #if it's expired, push its unload function to be executed
actions.push (cb) =>
status.unload(cb)
@update()
@statuses.splice i, 1
else #else execute its invoke function
actions.push (cb) =>
status.invoke(cb)
@update()
i++
actions.push (cb) =>
if @canMove
@getMove (err, move) ->
move.use(callback)
cb(null)
@update()
else
cb(null)
callback(null)
@update()
Async.waterfall actions
say: (what, cb) ->
@game.console.put(@name + ': ' + what, cb)
hasMove: (name) ->
for move in @moves
if move.name is name
return true
return false
addMove: (move) ->
if !@hasMove move.name
move.setUser(@)
move.setGame(@game)
@moves.push(move)
addMoveByClass: (MoveClass) ->
move = new MoveClass()
@addMove move
addStatus: (status) ->
status.setTarget(@)
status.setGame(@game)
@statuses.push(status)
has: (status) ->
for effect in @statuses
if effect.name is status
return true
return false
getStatus: (status) ->
for effect in @statuses
if effect.name is status
return status
return null
removeStatus: (status) ->
for i in [0...@statuses.length]
if @statuses[i].name is status
@statuses.splice i, 1
# re-execute the function, since the indices in the array
# are too messed up to continue. Do this until no instances
# of move are left in statuses (looks heavier than it is
# since there will never be too many things in @statuses)
return @removeStatus status
die: () ->
@me.charElem.hide('explode', {duration: 1000})
setHealth: (amount) ->
@case = amount
@update()
if @case <= 0
@die()
damage: (amount) ->
@setHealth @case - amount
heal: (amount) ->
@damage(-amount)
getMove: (cb) -> # async because player moves
move = @moves[Math.floor(Math.random()*@moves.length)]
cb(null, move)
| true | $ = require 'lib/jquery.js'
require 'lib/jquery-ui.js'
Async = require 'lib/async.js'
# constants
dir = './img/char/'
ftype = '.png'
# Basic debater class. Controls an actor in the game
module.exports = class Debater
constructor: (@game, @opponent = true, @name = 'PI:NAME:<NAME>END_PI', @level = 30,
@case = 4, @type = 'DEBATER') ->
@me = if @opponent then @game.opponentElem else @game.playerElem
@img = @name
# set basic statis
# ALREADY SET (constructed)
# @case (HP)
# @level (speaker score) (Lvl)
# @type (type)
@clash = 2 # ATTACK
@presentation = 2 # SP. ATTACK
@organization = 3 # SPEED
@civility = 5 # Totally arbitrary
@cross = 3 # DEFENCE
@moves = []
@statuses = []
@canMove = true
setName: (name) ->
@name = name
getTarget: () ->
@other = if @opponent then @game.player else @game.opponent
return @other # explicit return for readability
load: () ->
@me.setImg(dir + @img + (if @opponent then '' else '_back') + ftype)
@me.setName(@name)
@statuses = [] # reset statuses on load()
@update()
update: () -> #updates states
@me.setLevel(@level)
shownCase = Math.floor(@case * 100)/100
@me.setCase(shownCase)
status = @type + (if @statuses.length > 0 then '|' else '')
status += ' ' + effect.name for effect in @statuses
@me.setStatus(status)
# move loop
go: (callback) ->
@canMove = true
actions = []
i = 0
while i < @statuses.length
status = @statuses[i]
if status.expired() #if it's expired, push its unload function to be executed
actions.push (cb) =>
status.unload(cb)
@update()
@statuses.splice i, 1
else #else execute its invoke function
actions.push (cb) =>
status.invoke(cb)
@update()
i++
actions.push (cb) =>
if @canMove
@getMove (err, move) ->
move.use(callback)
cb(null)
@update()
else
cb(null)
callback(null)
@update()
Async.waterfall actions
say: (what, cb) ->
@game.console.put(@name + ': ' + what, cb)
hasMove: (name) ->
for move in @moves
if move.name is name
return true
return false
addMove: (move) ->
if !@hasMove move.name
move.setUser(@)
move.setGame(@game)
@moves.push(move)
addMoveByClass: (MoveClass) ->
move = new MoveClass()
@addMove move
addStatus: (status) ->
status.setTarget(@)
status.setGame(@game)
@statuses.push(status)
has: (status) ->
for effect in @statuses
if effect.name is status
return true
return false
getStatus: (status) ->
for effect in @statuses
if effect.name is status
return status
return null
removeStatus: (status) ->
for i in [0...@statuses.length]
if @statuses[i].name is status
@statuses.splice i, 1
# re-execute the function, since the indices in the array
# are too messed up to continue. Do this until no instances
# of move are left in statuses (looks heavier than it is
# since there will never be too many things in @statuses)
return @removeStatus status
die: () ->
@me.charElem.hide('explode', {duration: 1000})
setHealth: (amount) ->
@case = amount
@update()
if @case <= 0
@die()
damage: (amount) ->
@setHealth @case - amount
heal: (amount) ->
@damage(-amount)
getMove: (cb) -> # async because player moves
move = @moves[Math.floor(Math.random()*@moves.length)]
cb(null, move)
|
[
{
"context": "ersion 1.0.0\n@file Icon.js\n@author Welington Sampaio\n@contact http://jokerjs.zaez.net/contato\n\n@co",
"end": 137,
"score": 0.9998891949653625,
"start": 120,
"tag": "NAME",
"value": "Welington Sampaio"
}
] | vendor/assets/javascripts/joker/Icon.coffee | zaeznet/joker-rails | 0 | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file Icon.js
@author Welington Sampaio
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2014 Zaez Solucoes em Tecnologia, all rights reserved.
This source file is free software, under the license MIT, available at:
http://jokerjs.zaez.net/license
This source file 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 license files for details.
For details please refer to: http://jokerjs.zaez.net
###
###
###
Joker.Icon =
iconBase: '/assets/icons'
mimetypes:
doc: "application/msword"
dot: "application/msword"
pdf: "application/pdf"
pgp: "application/pgp-signature"
ps: "application/postscript"
ai: "application/postscript"
eps: "application/postscript"
rtf: "application/rtf"
xls: "application/vnd.ms-excel"
xlb: "application/vnd.ms-excel"
ppt: "application/vnd.ms-powerpoint"
pps: "application/vnd.ms-powerpoint"
pot: "application/vnd.ms-powerpoint"
zip: "application/zip"
swf: "application/x-shockwave-flash"
swfl: "application/x-shockwave-flash"
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
dotx: "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
potx: "application/vnd.openxmlformats-officedocument.presentationml.template"
ppsx: "application/vnd.openxmlformats-officedocument.presentationml.slideshow"
js: "application/x-javascript"
json: "application/json"
mp3: "audio/mpeg"
mpga: "audio/mpeg"
mpega: "audio/mpeg"
mp2: "audio/mpeg"
wav: "audio/x-wav"
m4a: "audio/x-m4a"
oga: "audio/ogg"
ogg: "audio/ogg"
aiff: "audio/aiff"
aif: "audio/aiff"
flac: "audio/flac"
aac: "audio/aac"
ac3: "audio/ac3"
wma: "audio/x-ms-wma"
bmp: "image/bmp"
gif: "image/gif"
jpg: "image/jpeg"
jpeg: "image/jpeg"
jpe: "image/jpeg"
psd: "image/photoshop"
png: "image/png"
svg: "image/svgxml"
svgz: "image/svgxml"
tiff: "image/tiff"
tif: "image/tiff"
asc: "text/plain"
txt: "text/plain"
text: "text/plain"
diff: "text/plain"
log: "text/plain"
htm: "text/html"
html: "text/html"
xhtml: "text/html"
css: "text/css"
csv: "text/csv"
mpeg: "video/mpeg"
mpg: "video/mpeg"
mpe: "video/mpeg"
rtf: "video/mpeg"
mov: "video/quicktime"
qt: "video/quicktime"
mp4: "video/mp4"
m4v: "video/x-m4v"
flv: "video/x-flv"
wmv: "video/x-ms-wmv"
avi: "video/avi"
webm: "video/webm"
'3gp': "video/3gpp"
'3gpp': "video/3gpp"
'3g2': "video/3gpp2"
rv: "video/vnd.rn-realvideo"
ogv: "video/ogg"
mkv: "video/x-matroska"
otf: "application/vnd.oasis.opendocument.formula-template"
exe: "application/octet-stream"
p12: 'application/x-pkcs12'
existsExtIcon: ($ext)->
$extensions = ['3g2', '3gp', 'ai', 'air', 'asf', 'avi', 'bib', 'cls', 'csv', 'deb', 'djvu', 'dmg', 'doc', 'docx',
'dwf', 'dwg', 'eps', 'epub', 'exe', 'f', 'f77', 'f90', 'flac', 'flv', 'gz', 'indd',
'iso', 'log', 'm4a', 'm4v', 'midi', 'mkv', 'mov', 'mp3', 'mp4', 'mpeg', 'mpg', 'msi',
'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'pdf', 'pps', 'ppsx', 'ppt', 'pptx', 'psd', 'pub',
'py', 'qt', 'ra', 'ram', 'rar', 'rm', 'rpm', 'rtf', 'rv', 'skp', 'sql', 'sty', 'tar', 'tex', 'tgz',
'tiff', 'ttf', 'txt', 'vob', 'wav', 'wmv', 'xls', 'xlsx', 'xml', 'xpi', 'zip']
Joker.Core.libSupport.inArray($ext , $extensions) != -1
generateIconFor: (url)->
return '' if (url == '')
image = /.*\.(jpg|jpeg|png|gif|ico)+/gi
bg = "#{@iconBase}/outhers.png"
ar = url.split('.')
ext = ar[ar.length-1]
bg = url if image.test(url)
bg = "#{@iconBase}/#{ext}.png" if @existsExtIcon(ext)
"""
<div class="joker-icon">
<div class="file" style="background-image: url(#{bg});"></div>
</div>
"""
generateInfoFor: (url)->
return '' if (url == '')
ar = url.split('/')
filename = ar[ar.length-1]
ar = url.split('.')
ext = ar[ar.length-1]
html = "<blockquote>" +
"<p>#{Joker.I18n.translate('icon.filename')}:</p>" +
"<small>"+filename+"</small>"
if @getMimeType(ext)
html += "<p>#{Joker.I18n.translate('icon.mimetype')}:</p>" +
"<small>"+@getMimeType(ext)+"</small>"
html += "</blockquote>"
html
getMimeType: (ext)->
return @mimetypes[ext] if @mimetypes.hasOwnProperty(ext)
false | 178063 | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file Icon.js
@author <NAME>
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2014 Zaez Solucoes em Tecnologia, all rights reserved.
This source file is free software, under the license MIT, available at:
http://jokerjs.zaez.net/license
This source file 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 license files for details.
For details please refer to: http://jokerjs.zaez.net
###
###
###
Joker.Icon =
iconBase: '/assets/icons'
mimetypes:
doc: "application/msword"
dot: "application/msword"
pdf: "application/pdf"
pgp: "application/pgp-signature"
ps: "application/postscript"
ai: "application/postscript"
eps: "application/postscript"
rtf: "application/rtf"
xls: "application/vnd.ms-excel"
xlb: "application/vnd.ms-excel"
ppt: "application/vnd.ms-powerpoint"
pps: "application/vnd.ms-powerpoint"
pot: "application/vnd.ms-powerpoint"
zip: "application/zip"
swf: "application/x-shockwave-flash"
swfl: "application/x-shockwave-flash"
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
dotx: "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
potx: "application/vnd.openxmlformats-officedocument.presentationml.template"
ppsx: "application/vnd.openxmlformats-officedocument.presentationml.slideshow"
js: "application/x-javascript"
json: "application/json"
mp3: "audio/mpeg"
mpga: "audio/mpeg"
mpega: "audio/mpeg"
mp2: "audio/mpeg"
wav: "audio/x-wav"
m4a: "audio/x-m4a"
oga: "audio/ogg"
ogg: "audio/ogg"
aiff: "audio/aiff"
aif: "audio/aiff"
flac: "audio/flac"
aac: "audio/aac"
ac3: "audio/ac3"
wma: "audio/x-ms-wma"
bmp: "image/bmp"
gif: "image/gif"
jpg: "image/jpeg"
jpeg: "image/jpeg"
jpe: "image/jpeg"
psd: "image/photoshop"
png: "image/png"
svg: "image/svgxml"
svgz: "image/svgxml"
tiff: "image/tiff"
tif: "image/tiff"
asc: "text/plain"
txt: "text/plain"
text: "text/plain"
diff: "text/plain"
log: "text/plain"
htm: "text/html"
html: "text/html"
xhtml: "text/html"
css: "text/css"
csv: "text/csv"
mpeg: "video/mpeg"
mpg: "video/mpeg"
mpe: "video/mpeg"
rtf: "video/mpeg"
mov: "video/quicktime"
qt: "video/quicktime"
mp4: "video/mp4"
m4v: "video/x-m4v"
flv: "video/x-flv"
wmv: "video/x-ms-wmv"
avi: "video/avi"
webm: "video/webm"
'3gp': "video/3gpp"
'3gpp': "video/3gpp"
'3g2': "video/3gpp2"
rv: "video/vnd.rn-realvideo"
ogv: "video/ogg"
mkv: "video/x-matroska"
otf: "application/vnd.oasis.opendocument.formula-template"
exe: "application/octet-stream"
p12: 'application/x-pkcs12'
existsExtIcon: ($ext)->
$extensions = ['3g2', '3gp', 'ai', 'air', 'asf', 'avi', 'bib', 'cls', 'csv', 'deb', 'djvu', 'dmg', 'doc', 'docx',
'dwf', 'dwg', 'eps', 'epub', 'exe', 'f', 'f77', 'f90', 'flac', 'flv', 'gz', 'indd',
'iso', 'log', 'm4a', 'm4v', 'midi', 'mkv', 'mov', 'mp3', 'mp4', 'mpeg', 'mpg', 'msi',
'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'pdf', 'pps', 'ppsx', 'ppt', 'pptx', 'psd', 'pub',
'py', 'qt', 'ra', 'ram', 'rar', 'rm', 'rpm', 'rtf', 'rv', 'skp', 'sql', 'sty', 'tar', 'tex', 'tgz',
'tiff', 'ttf', 'txt', 'vob', 'wav', 'wmv', 'xls', 'xlsx', 'xml', 'xpi', 'zip']
Joker.Core.libSupport.inArray($ext , $extensions) != -1
generateIconFor: (url)->
return '' if (url == '')
image = /.*\.(jpg|jpeg|png|gif|ico)+/gi
bg = "#{@iconBase}/outhers.png"
ar = url.split('.')
ext = ar[ar.length-1]
bg = url if image.test(url)
bg = "#{@iconBase}/#{ext}.png" if @existsExtIcon(ext)
"""
<div class="joker-icon">
<div class="file" style="background-image: url(#{bg});"></div>
</div>
"""
generateInfoFor: (url)->
return '' if (url == '')
ar = url.split('/')
filename = ar[ar.length-1]
ar = url.split('.')
ext = ar[ar.length-1]
html = "<blockquote>" +
"<p>#{Joker.I18n.translate('icon.filename')}:</p>" +
"<small>"+filename+"</small>"
if @getMimeType(ext)
html += "<p>#{Joker.I18n.translate('icon.mimetype')}:</p>" +
"<small>"+@getMimeType(ext)+"</small>"
html += "</blockquote>"
html
getMimeType: (ext)->
return @mimetypes[ext] if @mimetypes.hasOwnProperty(ext)
false | true | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file Icon.js
@author PI:NAME:<NAME>END_PI
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2014 Zaez Solucoes em Tecnologia, all rights reserved.
This source file is free software, under the license MIT, available at:
http://jokerjs.zaez.net/license
This source file 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 license files for details.
For details please refer to: http://jokerjs.zaez.net
###
###
###
Joker.Icon =
iconBase: '/assets/icons'
mimetypes:
doc: "application/msword"
dot: "application/msword"
pdf: "application/pdf"
pgp: "application/pgp-signature"
ps: "application/postscript"
ai: "application/postscript"
eps: "application/postscript"
rtf: "application/rtf"
xls: "application/vnd.ms-excel"
xlb: "application/vnd.ms-excel"
ppt: "application/vnd.ms-powerpoint"
pps: "application/vnd.ms-powerpoint"
pot: "application/vnd.ms-powerpoint"
zip: "application/zip"
swf: "application/x-shockwave-flash"
swfl: "application/x-shockwave-flash"
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
dotx: "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation"
potx: "application/vnd.openxmlformats-officedocument.presentationml.template"
ppsx: "application/vnd.openxmlformats-officedocument.presentationml.slideshow"
js: "application/x-javascript"
json: "application/json"
mp3: "audio/mpeg"
mpga: "audio/mpeg"
mpega: "audio/mpeg"
mp2: "audio/mpeg"
wav: "audio/x-wav"
m4a: "audio/x-m4a"
oga: "audio/ogg"
ogg: "audio/ogg"
aiff: "audio/aiff"
aif: "audio/aiff"
flac: "audio/flac"
aac: "audio/aac"
ac3: "audio/ac3"
wma: "audio/x-ms-wma"
bmp: "image/bmp"
gif: "image/gif"
jpg: "image/jpeg"
jpeg: "image/jpeg"
jpe: "image/jpeg"
psd: "image/photoshop"
png: "image/png"
svg: "image/svgxml"
svgz: "image/svgxml"
tiff: "image/tiff"
tif: "image/tiff"
asc: "text/plain"
txt: "text/plain"
text: "text/plain"
diff: "text/plain"
log: "text/plain"
htm: "text/html"
html: "text/html"
xhtml: "text/html"
css: "text/css"
csv: "text/csv"
mpeg: "video/mpeg"
mpg: "video/mpeg"
mpe: "video/mpeg"
rtf: "video/mpeg"
mov: "video/quicktime"
qt: "video/quicktime"
mp4: "video/mp4"
m4v: "video/x-m4v"
flv: "video/x-flv"
wmv: "video/x-ms-wmv"
avi: "video/avi"
webm: "video/webm"
'3gp': "video/3gpp"
'3gpp': "video/3gpp"
'3g2': "video/3gpp2"
rv: "video/vnd.rn-realvideo"
ogv: "video/ogg"
mkv: "video/x-matroska"
otf: "application/vnd.oasis.opendocument.formula-template"
exe: "application/octet-stream"
p12: 'application/x-pkcs12'
existsExtIcon: ($ext)->
$extensions = ['3g2', '3gp', 'ai', 'air', 'asf', 'avi', 'bib', 'cls', 'csv', 'deb', 'djvu', 'dmg', 'doc', 'docx',
'dwf', 'dwg', 'eps', 'epub', 'exe', 'f', 'f77', 'f90', 'flac', 'flv', 'gz', 'indd',
'iso', 'log', 'm4a', 'm4v', 'midi', 'mkv', 'mov', 'mp3', 'mp4', 'mpeg', 'mpg', 'msi',
'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'pdf', 'pps', 'ppsx', 'ppt', 'pptx', 'psd', 'pub',
'py', 'qt', 'ra', 'ram', 'rar', 'rm', 'rpm', 'rtf', 'rv', 'skp', 'sql', 'sty', 'tar', 'tex', 'tgz',
'tiff', 'ttf', 'txt', 'vob', 'wav', 'wmv', 'xls', 'xlsx', 'xml', 'xpi', 'zip']
Joker.Core.libSupport.inArray($ext , $extensions) != -1
generateIconFor: (url)->
return '' if (url == '')
image = /.*\.(jpg|jpeg|png|gif|ico)+/gi
bg = "#{@iconBase}/outhers.png"
ar = url.split('.')
ext = ar[ar.length-1]
bg = url if image.test(url)
bg = "#{@iconBase}/#{ext}.png" if @existsExtIcon(ext)
"""
<div class="joker-icon">
<div class="file" style="background-image: url(#{bg});"></div>
</div>
"""
generateInfoFor: (url)->
return '' if (url == '')
ar = url.split('/')
filename = ar[ar.length-1]
ar = url.split('.')
ext = ar[ar.length-1]
html = "<blockquote>" +
"<p>#{Joker.I18n.translate('icon.filename')}:</p>" +
"<small>"+filename+"</small>"
if @getMimeType(ext)
html += "<p>#{Joker.I18n.translate('icon.mimetype')}:</p>" +
"<small>"+@getMimeType(ext)+"</small>"
html += "</blockquote>"
html
getMimeType: (ext)->
return @mimetypes[ext] if @mimetypes.hasOwnProperty(ext)
false |
[
{
"context": "it\n lines.shift() # tag v0.0.2\n\n # bob <bob@example.com>\n author_line = lines.shift()\n [m",
"end": 1222,
"score": 0.9999297857284546,
"start": 1207,
"tag": "EMAIL",
"value": "bob@example.com"
}
] | src/tag.coffee | roelofjan-elsinga/gift | 85 | _ = require 'underscore'
Commit = require './commit'
Actor = require './actor'
{Ref} = require './ref'
module.exports = class Tag extends Ref
@find_all: (repo, callback) ->
Ref.find_all repo, "tag", Tag, callback
# Public: Get the tag message.
#
# Returns String.
message: (callback) ->
@lazy (err, data) ->
return callback err if err
return callback null, data.message
# Public: Get the tag author.
#
# Returns Actor.
tagger: (callback) ->
@lazy (err, data) ->
return callback err if err
return callback null, data.tagger
# Public: Get the date that the tag was created.
#
# Returns Date.
tag_date: (callback) ->
@lazy (err, data) ->
return callback err if err
return callback null, data.tag_date
# Internal: Load the tag data.
lazy: (callback) ->
return callback null, @_lazy_data if @_lazy_data
@repo.git "cat-file", {}, ["tag", @name]
, (err, stdout, stderr) =>
return callback err if err
lines = stdout.split "\n"
data = {}
lines.shift() # object 4ae1cc5e6c7bb85b14ecdf221030c71d0654a42e
lines.shift() # type commit
lines.shift() # tag v0.0.2
# bob <bob@example.com>
author_line = lines.shift()
[m, author, epoch] = /^.+? (.*) (\d+) .*$/.exec author_line
data.tagger = Actor.from_string author
data.tag_date = new Date epoch
lines.shift()
message = []
while line = lines.shift()
message.push line
data.message = message.join("\n")
return callback null, (@_lazy_data = data)
| 224436 | _ = require 'underscore'
Commit = require './commit'
Actor = require './actor'
{Ref} = require './ref'
module.exports = class Tag extends Ref
@find_all: (repo, callback) ->
Ref.find_all repo, "tag", Tag, callback
# Public: Get the tag message.
#
# Returns String.
message: (callback) ->
@lazy (err, data) ->
return callback err if err
return callback null, data.message
# Public: Get the tag author.
#
# Returns Actor.
tagger: (callback) ->
@lazy (err, data) ->
return callback err if err
return callback null, data.tagger
# Public: Get the date that the tag was created.
#
# Returns Date.
tag_date: (callback) ->
@lazy (err, data) ->
return callback err if err
return callback null, data.tag_date
# Internal: Load the tag data.
lazy: (callback) ->
return callback null, @_lazy_data if @_lazy_data
@repo.git "cat-file", {}, ["tag", @name]
, (err, stdout, stderr) =>
return callback err if err
lines = stdout.split "\n"
data = {}
lines.shift() # object 4ae1cc5e6c7bb85b14ecdf221030c71d0654a42e
lines.shift() # type commit
lines.shift() # tag v0.0.2
# bob <<EMAIL>>
author_line = lines.shift()
[m, author, epoch] = /^.+? (.*) (\d+) .*$/.exec author_line
data.tagger = Actor.from_string author
data.tag_date = new Date epoch
lines.shift()
message = []
while line = lines.shift()
message.push line
data.message = message.join("\n")
return callback null, (@_lazy_data = data)
| true | _ = require 'underscore'
Commit = require './commit'
Actor = require './actor'
{Ref} = require './ref'
module.exports = class Tag extends Ref
@find_all: (repo, callback) ->
Ref.find_all repo, "tag", Tag, callback
# Public: Get the tag message.
#
# Returns String.
message: (callback) ->
@lazy (err, data) ->
return callback err if err
return callback null, data.message
# Public: Get the tag author.
#
# Returns Actor.
tagger: (callback) ->
@lazy (err, data) ->
return callback err if err
return callback null, data.tagger
# Public: Get the date that the tag was created.
#
# Returns Date.
tag_date: (callback) ->
@lazy (err, data) ->
return callback err if err
return callback null, data.tag_date
# Internal: Load the tag data.
lazy: (callback) ->
return callback null, @_lazy_data if @_lazy_data
@repo.git "cat-file", {}, ["tag", @name]
, (err, stdout, stderr) =>
return callback err if err
lines = stdout.split "\n"
data = {}
lines.shift() # object 4ae1cc5e6c7bb85b14ecdf221030c71d0654a42e
lines.shift() # type commit
lines.shift() # tag v0.0.2
# bob <PI:EMAIL:<EMAIL>END_PI>
author_line = lines.shift()
[m, author, epoch] = /^.+? (.*) (\d+) .*$/.exec author_line
data.tagger = Actor.from_string author
data.tag_date = new Date epoch
lines.shift()
message = []
while line = lines.shift()
message.push line
data.message = message.join("\n")
return callback null, (@_lazy_data = data)
|
[
{
"context": "twUrl = @getSocialSharingUrl()\n twhashtag = '#rizzoma'\n tweetLength = 140 - twUrl.length - twhas",
"end": 8578,
"score": 0.7245956659317017,
"start": 8569,
"tag": "PASSWORD",
"value": "'#rizzoma"
},
{
"context": "E_LINK_PUBLIC, @_byLinkRoleId)\n setPopup(@_sharedRoleSelect, getRole, setRole)\n getRole = =>",
"end": 13367,
"score": 0.5605186820030212,
"start": 13361,
"tag": "USERNAME",
"value": "shared"
},
{
"context": "LIC, @_byLinkRoleId)\n setPopup(@_sharedRoleSelect, getRole, setRole)\n getRole = => @_publicR",
"end": 13377,
"score": 0.5149103403091431,
"start": 13371,
"tag": "USERNAME",
"value": "Select"
},
{
"context": "Id is @_publicRoleId\n setPopup(@_publicRoleSelect, getRole, setRole)\n @_initSocialShareButto",
"end": 13833,
"score": 0.5227828025817871,
"start": 13827,
"tag": "USERNAME",
"value": "Select"
},
{
"context": "reply', handler: checkPermission(@_eventHandler(@_insertBlipButtonClick))}\n {className: '.js-ins",
"end": 20297,
"score": 0.5537826418876648,
"start": 20290,
"tag": "USERNAME",
"value": "insertB"
},
{
"context": "me: '.js-insert-mention', handler: checkPermission(@_eventHandler(@_insertMention))}\n {className: '.js-i",
"end": 20400,
"score": 0.7409319281578064,
"start": 20386,
"tag": "USERNAME",
"value": "@_eventHandler"
},
{
"context": "-mention', handler: checkPermission(@_eventHandler(@_insertMention))}\n {className: '.js-insert-tag', hand",
"end": 20416,
"score": 0.8607765436172485,
"start": 20401,
"tag": "USERNAME",
"value": "@_insertMention"
},
{
"context": "ssName: '.js-insert-tag', handler: checkPermission(@_eventHandler(@_insertTag))}\n {className: '.js-inser",
"end": 20501,
"score": 0.7586149573326111,
"start": 20487,
"tag": "USERNAME",
"value": "@_eventHandler"
},
{
"context": "rt-tag', handler: checkPermission(@_eventHandler(@_insertTag))}\n {className: '.js-insert-gadget', h",
"end": 20513,
"score": 0.9196109771728516,
"start": 20504,
"tag": "USERNAME",
"value": "insertTag"
},
{
"context": "t-task', handler: checkPermission(@_eventHandler(@_insertTask))}]\n if accountProcessor.isBusinessUser()\n",
"end": 20877,
"score": 0.7064154744148254,
"start": 20867,
"tag": "USERNAME",
"value": "insertTask"
},
{
"context": " participants = @_waveViewModel.getUsers(@_participants.all())\n for p in participants\n ",
"end": 29490,
"score": 0.5455335974693298,
"start": 29478,
"tag": "USERNAME",
"value": "participants"
}
] | src/client/wave/view.coffee | robintibor/rizzoma | 2 | WaveViewBase = require('./view_base')
{Participants} = require('./participants')
{trackParticipantAddition} = require('./participants/utils')
{ROLES, ROLE_OWNER, ROLE_EDITOR, ROLE_COMMENTATOR, ROLE_READER, ROLE_NO_ROLE} = require('./participants/constants')
{renderWave, renderSelectAccountTypeBanner} = require('./template')
DOM = require('../utils/dom')
popup = require('../popup').popup
randomString = require('../utils/random_string').randomString
{TextLevelParams, LineLevelParams} = require('../editor/model')
BrowserSupport = require('../utils/browser_support')
{SettingsMenu} = require('./settings_menu')
{AccountMenu} = require('./account_menu')
{isEmail, strip} = require('../utils/string')
{WAVE_SHARED_STATE_PUBLIC, WAVE_SHARED_STATE_LINK_PUBLIC, WAVE_SHARED_STATE_PRIVATE} = require('./model')
BlipThread = require('../blip/blip_thread').BlipThread
AddParticipantForm = require('./participants/add_form').AddParticipantForm
{EDIT_PERMISSION, COMMENT_PERMISSION} = require('../blip/model')
{RoleSelectPopup} = require('./role_select_popup')
{LocalStorage} = require('../utils/localStorage')
{MindMap} = require('../mindmap')
RangeMenu = require('../blip/menu/range_menu')
History = require('../utils/history_navigation')
BrowserEvents = require('../utils/browser_events')
SCROLL_INTO_VIEW_OFFSET = -90
ADD_BUTTONS = []
for role in ROLES when role.id isnt ROLE_OWNER
ADD_BUTTONS.push {
id: role.id
name: role.name.toLowerCase()
}
DEFAULT_ROLES = [
[ROLE_EDITOR, 'edit']
[ROLE_COMMENTATOR, 'comment']
[ROLE_READER, 'read']
]
class WaveView extends WaveViewBase
constructor: (@_waveViewModel, @_waveProcessor, participants, @_container) ->
###
@param waveViewModel: WaveViewModel
@param _waveProcessor: WaveProcessor
@param participants: array, часть ShareJS-документа, отвечающего за участников
@param container: HTMLNode, нода, в которой отображаться сообщению
###
super()
@container = @_container # TODO: deprecated. backward compatibility
@_init(@_waveViewModel, participants)
_init: (waveViewModel, participants) ->
###
@param waveViewModel: WaveViewModel
@param participants: array, часть ShareJS-документа, отвечающего за участников
###
@_inEditMode = no
@_isAnonymous = !window.userInfo?.id?
@_model = waveViewModel.getModel()
@_editable = BrowserSupport.isSupported() and not @_isAnonymous
@_createDOM()
@_initWaveHeader(waveViewModel, participants)
@_initEditingMenu()
@_updateParticipantsManagement()
@_initRootBlip(waveViewModel)
@_updateReplyButtonState()
@_initTips()
@_initDragScroll()
waveViewModel.on('waveLoaded', =>
$(@_waveBlips).on 'scroll', @_setOnScrollMenuPosition
$(window).on('scroll', @_setOnScrollMenuPosition)
$(window).on 'resize resizeTopicByResizer', @_resizerRepositionMenu
)
@_initBuffer()
@_$wavePanel.addClass('visible') if not BrowserSupport.isSupported() and not @_isAnonymous
_contactSelectHandler: (item) =>
@_$participantIdInput.val(item.email) if item? and item
@_processAddParticipantClick()
_contactButtonHandler: (e) =>
source = $(e.currentTarget).attr('source')
_gaq.push(['_trackEvent', 'Contacts synchronization', 'Synchronize contacts click', "add users #{source}"])
@_waveProcessor.initContactsUpdate source, e.screenX-630, e.screenY, =>
return if @_closed
@activateContacts(source)
_gaq.push(['_trackEvent', 'Contacts synchronization', 'Successfull synchronization', "add users #{source}"])
activateContacts: (source) ->
@_addParticipantForm?.refreshContacts(source)
_getRole: ->
role = @_waveViewModel.getRole()
for r in ROLES
if r.id == role
return r
_initWaveHeader: (waveViewModel, participants)->
###
Инициализирует заголовок волны
###
@_reservedHeaderSpace = 0
$c = $(@container)
@_waveHeader = $c.find('.js-wave-header')[0]
@_$wavePanel = $c.find('.js-wave-panel')
@_initParticipantAddition()
@_initParticipants(waveViewModel, participants)
if @_isAnonymous
$c.find('.js-enter-rizzoma-btn').click (e) ->
window.AuthDialog.initAndShow(true, History.getLoginRedirectUrl())
e.stopPropagation()
e.preventDefault()
@_initWaveShareMenu()
@_curView = 'text'
role = @_getRole()
$(@_waveHeader).find('.js-account-section-role').text(role.name) if role
@_initSavingMessage()
@_initSettingsMenu()
@_initAccountMenu()
@_initSelectAccountTypeBanner()
_initSelectAccountTypeBanner: ->
return if !window.showAccountSelectionBanner
$(@container).prepend(renderSelectAccountTypeBanner())
$(@container).find(".js-open-account-select").on "click", =>
_gaq.push(['_trackEvent', 'Monetization', 'Upgrade account link click'])
$('.js-account-wizard-banner').remove()
delete window.showAccountSelectionWizard
delete window.showAccountSelectionBanner
@_waveProcessor.openAccountWizard()
$(@container).find('.js-account-wizard-banner').on "click", ->
$('.js-account-wizard-banner').remove()
_initParticipantAddition: ->
return if @_isAnonymous
@_$addParticipantsBlock = $(@_waveHeader).find('.js-add-form')
@_addParticipantsBlockButton = DOM.findAndBind($(@_waveHeader), '.js-add-block-button', 'click', @_processAddParticipantBlockClick)
_processAddButtonChange: =>
@_addButtonRole = parseInt(@_$addButtonSelect.val())
_createAddParticipantForm: ->
maxResults = if History.isEmbedded() then 5 else 7
@_addParticipantForm = new AddParticipantForm(@_$addParticipantsBlock, maxResults, ADD_BUTTONS, @_waveProcessor, @_contactSelectHandler, @_contactButtonHandler)
@_$participantIdInput = @_$addParticipantsBlock.find('.js-input-email')
setTimeout =>
@_$addButtonSelect = @_$addParticipantsBlock.find('.js-add-select')
@_$addButtonSelect.selectBox().change(@_processAddButtonChange)
@_$addButtonSelect.on 'close', =>
window.setTimeout =>
$(@_participantIdInput).focus()
0
@_$addButton = @_$addParticipantsBlock.find('.js-add-button')
@_updateParticipantAddition()
,0
_processAddParticipantBlockClick: (event) =>
if @_addParticipantForm?.isVisible()
@_addParticipantForm.hide()
else
if not @_addParticipantForm?
@_createAddParticipantForm()
@_addParticipantForm.show()
@_$participantIdInput.focus()
_initSocialShareButtons: ->
socialSection = $(@_waveHeader).find('.js-social-section')
@_facebookButton = socialSection.find('.js-social-facebook')
@_twitterButton = socialSection.find('.js-social-twitter')
@_googleButton = socialSection.find('.js-social-google')
@_socialOverlay = socialSection.find('.js-social-overlay')
loadWnd = (title, url, e) =>
wnd = window.open("/share_topic_wait/", title, "width=640,height=440,left=#{e.screenX-630},top=#{e.screenY},scrollbars=no")
if @_waveProcessor.rootRouterIsConnected()
@_waveProcessor.markWaveAsSocialSharing(@_model.serverId, () =>
wnd.document.location.href = url if wnd
)
else
wnd.document.location.href = url
@_facebookButton.on 'click', (e) =>
_gaq.push(['_trackEvent', 'Topic sharing', 'Share topic on Facebook'])
mixpanel.track('Topic sharing', {'channel': 'Facebook'})
loadWnd('Facebook', "http://www.facebook.com/sharer/sharer.php?u=#{encodeURIComponent(@getSocialSharingUrl())}", e)
return false
@_googleButton.on 'click', (e) =>
_gaq.push(['_trackEvent', 'Topic sharing', 'Share topic on Google+'])
mixpanel.track('Topic sharing', {'channel': 'Google+'})
loadWnd('Google', "https://plus.google.com/share?url=#{encodeURIComponent(@getSocialSharingUrl())}", e)
return false
twUrl = @getSocialSharingUrl()
twhashtag = '#rizzoma'
tweetLength = 140 - twUrl.length - twhashtag.length
@_twitterButton.on 'click', (e) =>
_gaq.push(['_trackEvent', 'Topic sharing', 'Share topic on Twitter'])
mixpanel.track('Topic sharing', {'channel': 'Twitter'})
snippet = ''
for t in @rootBlip.getModel().getSnapshotContent()
break if snippet.length >= tweetLength
if t.params.__TYPE != 'TEXT'
snippet += " "
else
snippet += t.t
if snippet.length >= tweetLength
snippet = snippet.substr(0, tweetLength-3)
snippet += "...#{twhashtag}"
else
snippet += " #{twhashtag}"
window.open("https://twitter.com/intent/tweet?source=tw&text=#{encodeURIComponent(snippet)}&url=#{encodeURIComponent(twUrl)}", 'Twitter', "width=640,height=290,left=#{e.screenX-630},top=#{e.screenY},scrollbars=no")
return false
_shareButtonHandler: (e) =>
waveUrl = @_sharePopup.find('.js-wave-url')
if @_sharePopup.is(':visible')
return @_sharePopup.hide()
@_sharePopup.show()
_gaq.push(['_trackEvent', 'Topic sharing', 'Topic sharing manage'])
waveUrl.select()
waveUrl.on 'mousedown', =>
waveUrl.select()
# Обработчик на закрывание устанавливается с задержкой, чтобы не обработать
# текущий клик
window.setTimeout =>
$(document).on 'click.shareWaveBlock', (e) =>
if $(e.target).closest('.js-share-window, .js-role-selector-popup').length == 0
@_sharePopup.hide()
$(document).off('click.shareWaveBlock')
true
, 0
#эта проверка нужна в ff, без нее не прячутся панели
@_checkRange()
_handleGDriveViewShareButton: (e) =>
menu = @_shareContainer.find('.js-gdrive-share-menu')
if menu.is(':visible')
return menu.hide()
menu.show()
window.setTimeout =>
$(document).on 'click.gDriveShareMenu', (e) =>
if $(e.target).closest('.js-gdrive-share-menu').length == 0
menu.hide()
$(document).off('click.gDriveShareMenu')
true
, 0
#эта проверка нужна в ff, без нее не прячутся панели
@_checkRange()
_initWaveShareMenu: ->
###
Инициализирует меню расшаривания волны
###
return if @_isAnonymous
@_shareContainer = $(@_waveHeader).find('.js-share-container')
@_shareButton = @_shareContainer.find('.js-show-share-button')
@_sharePopup = @_shareContainer.find('.js-share-window')
if History.isGDrive()
menu = @_shareContainer.find('.js-gdrive-share-menu')
menu.on 'click', 'a.js-btn', (e) ->
e.preventDefault()
menu.hide()
$(document).off('click.gDriveShareMenu')
@_shareButton.on('click', @_handleGDriveViewShareButton)
@_shareContainer.find('.js-share-window-button').on('click', @_shareButtonHandler)
else
@_shareButton.on('click', @_shareButtonHandler)
if not BrowserSupport.isSupported() or !window.loggedIn
###
Не авторизованные пользователи или пользователи
не под Chrome не могут расшарить волну
###
@_shareButton.attr('disabled', 'disabled')
$c = $(@container)
@_byLinkRoleId = ROLE_EDITOR
@_publicRoleId = ROLE_COMMENTATOR
@_isPrivateButton = DOM.findAndBind $c, '.js-is-private-button', 'change', =>
@setSharedState(WAVE_SHARED_STATE_PRIVATE) if @_isPrivateButton.checked
@_isByLinkButton = DOM.findAndBind $c, '.js-by-link-button', 'change', =>
@setSharedState(WAVE_SHARED_STATE_LINK_PUBLIC, @_byLinkRoleId) if @_isByLinkButton.checked
@_isPublicButton = DOM.findAndBind $c, '.js-is-public-button', 'change', =>
@setSharedState(WAVE_SHARED_STATE_PUBLIC, @_publicRoleId) if @_isPublicButton.checked
@_sharedRoleSelect = $(@_sharePopup).find('.js-shared-role-select')[0]
setPopup = (node, getRole, setRole) =>
$(node).click (event) =>
return if not @_canChangeTopicShare
popup.hide()
popup.render(new RoleSelectPopup(DEFAULT_ROLES, getRole, setRole), event.target)
popup.show()
return false
getRole = => @_byLinkRoleId
setRole = (roleId) =>
@_byLinkRoleId = roleId
popup.hide()
@setSharedState(WAVE_SHARED_STATE_LINK_PUBLIC, @_byLinkRoleId)
setPopup(@_sharedRoleSelect, getRole, setRole)
getRole = => @_publicRoleId
setRole = (roleId) =>
@_publicRoleId = roleId
popup.hide()
@setSharedState(WAVE_SHARED_STATE_PUBLIC, @_publicRoleId)
@_publicRoleSelect = $(@_sharePopup).find('.js-public-role-select')[0]
for [roleId, roleName] in DEFAULT_ROLES
$(@_publicRoleSelect).text(roleName) if roleId is @_publicRoleId
setPopup(@_publicRoleSelect, getRole, setRole)
@_initSocialShareButtons()
@updatePublicState()
_disableSocialButtons: ->
@_socialOverlay.addClass('social-overlay')
@_facebookButton.attr('disabled', 'disabled')
@_twitterButton.attr('disabled', 'disabled')
@_googleButton.attr('disabled', 'disabled')
_enableSocialButtons: ->
@_socialOverlay.removeClass('social-overlay')
@_facebookButton.removeAttr('disabled')
@_twitterButton.removeAttr('disabled')
@_googleButton.removeAttr('disabled')
_setShareContainerClass: (className) ->
$(@_shareContainer).removeClass('private')
$(@_shareContainer).removeClass('public')
$(@_shareContainer).removeClass('shared')
$(@_shareContainer).addClass(className)
_setDefaultRoleId: (element, roleId) ->
for [id, name] in DEFAULT_ROLES
continue if roleId isnt id
$(element).text(name)
__scrollToBlipContainer: (blipContainer) ->
DOM.scrollTargetIntoViewWithAnimation(blipContainer, @_waveBlips, yes, SCROLL_INTO_VIEW_OFFSET)
updatePublicState: (sharedState = @_model.getSharedState(), defaultRoleId = @_model.getDefaultRole()) ->
###
Устанавливает состояние переключателя публичности волны
@param isPublic: boolean
@param defaultRoleId: int
###
return if not window.loggedIn
if sharedState == WAVE_SHARED_STATE_LINK_PUBLIC
@_isByLinkButton.checked = true
@_setDefaultRoleId(@_sharedRoleSelect, defaultRoleId)
@_byLinkRoleId = defaultRoleId
@_setShareContainerClass('shared')
@_enableSocialButtons()
@_shareButton.attr('title', "Topic is shared by link, click to change")
@_participants.showCreateTopicForSelectedButton()
else if sharedState == WAVE_SHARED_STATE_PRIVATE
@_isPrivateButton.checked = true
@_setShareContainerClass('private')
@_disableSocialButtons()
@_shareButton.attr('title', "Topic is private, click to change")
@_participants.showCreateTopicForSelectedButton()
else
@_isPublicButton.checked = true
@_setDefaultRoleId(@_publicRoleSelect, defaultRoleId)
@_publicRoleId = defaultRoleId
@_setShareContainerClass('public')
@_enableSocialButtons()
@_shareButton.attr('title', "Topic is public, click to change")
@_participants.hideCreateTopicForSelectedButton()
@_shareContainerWidth = $(@_shareContainer).width() +
parseInt($(@_shareContainer).css('margin-left')) +
parseInt($(@_shareContainer).css('margin-right'))
return if @_waveViewModel.getRole() in [ROLE_OWNER, ROLE_EDITOR]
@_updateParticipantsManagement()
setSharedState: (sharedState, defaultRole=1) ->
###
Устанавливает публичность волны
Обновляет кнопку в интерфейсе и отправляет команду серверу при необходимости
@param isPublic: boolean
@param defaultRole: int
###
@updatePublicState(sharedState, defaultRole)
@_waveProcessor.setWaveShareState @_model.serverId, sharedState, defaultRole, (err) =>
if @_isPublicButton.checked
_gaq.push(['_trackEvent', 'Topic sharing', 'Set topic public'])
else if @_isPrivateButton.checked
_gaq.push(['_trackEvent', 'Topic sharing', 'Set topic private'])
else
_gaq.push(['_trackEvent', 'Topic sharing', 'Set topic shared'])
return if not err
@_waveViewModel.showWarning(err.message)
@updatePublicState()
_initParticipants: (waveViewModel, participants) ->
###
Инициализирует панель с участниками волны
@param participants: array, часть ShareJS-документа, отвечающего за участников
###
@_participants = new Participants(waveViewModel, @_waveProcessor, @_model.serverId,
participants, yes, @_model.getGDriveShareUrl())
$(@container).find('.js-wave-participants').append(@_participants.getContainer())
@_excludeParticipantsWidth = 0
headerChildren = $(@_waveHeader).children()
for child in headerChildren
if $(child).hasClass('js-wave-participants') or $(child).hasClass('clearer') or not $(child).is(':visible')
continue
@_excludeParticipantsWidth += $(child).outerWidth(true)
@_setParticipantsWidth()
$(window).on 'resize resizeTopicByResizer', @_setParticipantsWidth #resizeTopicByResizer срабатывает при изменении ширины ресайзером
getParticipantIds: ->
@_participants.all()
_setParticipantsWidth: () =>
if @_isAnonymous
participantsWidth = $(@container).find('.js-wave-participants').outerWidth()
else
headerInnerWidth = $(@_waveHeader).width() -
parseInt($(@_waveHeader).css('padding-left')) -
parseInt($(@_waveHeader).css('padding-right'))
participantsWidth = headerInnerWidth - @_excludeParticipantsWidth -
parseInt($($(@_waveHeader).find('.js-participant-container')[0]).css('margin-left')) -
parseInt($($(@_waveHeader).find('.js-participant-container')[0]).css('margin-right'))
participantsWidth -= @_reservedHeaderSpace
@_participants.setParticipantsWidth(participantsWidth)
_initEditingMenu: ->
###
Инициализирует меню редактирования волны
###
return if not @_editable
@_initEditingMenuKeyHandlers()
@_disableEditingButtons()
@_disableActiveBlipControls()
@_initActiveBlipControls()
_initActiveBlipControls: ->
###
Инициализирует кнопки вставки реплая или меншена в активный блиб
###
checkPermission = (callback) => (args...) =>
return false if @_activeBlipControlsEnabled is no
callback(args...)
activateButtons = (buttons) =>
for controlInfo in buttons
{className, handler} = controlInfo
controlInfo.$button = @_$activeBlipControls.find(className)
controlInfo.$button.mousedown(handler)
@_activeBlipControlButtons = [
{className: '.js-insert-reply', handler: checkPermission(@_eventHandler(@_insertBlipButtonClick))}
{className: '.js-insert-mention', handler: checkPermission(@_eventHandler(@_insertMention))}
{className: '.js-insert-tag', handler: checkPermission(@_eventHandler(@_insertTag))}
{className: '.js-insert-gadget', handler: checkPermission(@_eventHandler(@_showGadgetPopup))}
]
activateButtons(@_activeBlipControlButtons)
accountProcessor = require('../account_setup_wizard/processor').instance
businessButtons = [{className: '.js-insert-task', handler: checkPermission(@_eventHandler(@_insertTask))}]
if accountProcessor.isBusinessUser()
activateButtons(businessButtons)
@_activeBlipControlButtons.push(businessButtons[0])
else
$insertTaskBtn = @_$activeBlipControls.find('.js-insert-task').hide()
businessChangeCallback = (isBusiness) =>
return unless isBusiness
return unless @_activeBlipControlButtons
$insertTaskBtn.show()
accountProcessor.removeListener('is-business-change', businessChangeCallback)
activateButtons(businessButtons)
@_activeBlipControlButtons.push(businessButtons[0])
accountProcessor.on('is-business-change', businessChangeCallback)
_deinitActiveBlipControls: ->
for {$button, handler} in @_activeBlipControlButtons
$button?.off('mousedown', handler)
delete @_activeBlipControlButtons
_initEditingMenuKeyHandlers: ->
###
Инициализирует обработчики нажатий на клавиши в топике
###
@_ctrlHandlers =
65: @_selectAll # A
69: @_changeBlipEditMode # e
@_globalCtrlHandlers =
32: @_goToUnread # Space
@_ctrlShiftHandlers =
38: @_foldChildBlips # Up arrow
40: @_unfoldChildBlips # Down arrow
@_shiftHandlers =
13: @_setBlipReadMode # Enter
@_ctrlRepeats = {}
@blipNode.addEventListener('keydown', @_preProcessKeyDownEvent, true)
@blipNode.addEventListener('keypress', @_processFFEnterKeypress, true) if BrowserSupport.isMozilla()
@_globalKeyHandler = (e) =>
return if not (e.ctrlKey or e.metaKey)
@_processKeyDownEvent(@_globalCtrlHandlers, e)
window.addEventListener('keydown', @_globalKeyHandler, true)
@blipNode.addEventListener('keyup', @_processBlipKeyUpEvent, true)
@blipNode.addEventListener('click', @_processClickEvent, false) if BrowserSupport.isSupported()
_changeBlipEditMode: =>
blip = @_getBlipAndRange()[0]
return if not blip
blip.setEditable(!@_inEditMode)
_processFFEnterKeypress: (e) =>
# превентим keypress у Enter для ff, чтобы при завершении
# режима редактирования по Shift+Enter не создавался новый блип
return if e.keyCode != 13 or !e.shiftKey
e.stopPropagation()
_setBlipReadMode: (e) =>
blip = @_getBlipAndRange()[0]
return if not blip
blip.setEditable(no)
_initRootBlip: (waveViewModel) ->
###
Инициализирует корневой блип
###
processor = require('../blip/processor').instance
processor.openBlip waveViewModel, @_model.getContainerBlipId(), @blipNode, null, (err, @rootBlip) =>
return @_waveProcessor.showPageError(err) if err
@_initRangeChangeEvent()
@on 'range-change', (range, blip) =>
if blip
@markActiveBlip(blip)
_disableEditingButtons: -> @_editingButtonsEnabled = no
_enableEditingButtons: -> @_editingButtonsEnabled = yes
_disableActiveBlipControls: ->
return if not @_editable
return if @_activeBlipControlsEnabled is no
@_activeBlipControlsEnabled = no
@_hideGadgetPopup()
@_$activeBlipControls.addClass('unvisible')
enableActiveBlipControls: ->
# Показ меню делаем на следующей итерации, чтобы меню сначала спряталось
# остальными топиками, а затем показалось этим
window.setTimeout =>
return if @_activeBlipControlsEnabled is yes
@_activeBlipControlsEnabled = yes
@_$activeBlipControls.removeClass('unvisible')
, 0
cursorIsInText: -> @_editingButtonsEnabled
_checkChangedRange: (range, blipView) ->
if range
DOM.addClass(@container, 'has-cursor')
else
DOM.removeClass(@container, 'has-cursor')
if range and blipView.getPermission() in [EDIT_PERMISSION, COMMENT_PERMISSION]
if @_inEditMode
@enableActiveBlipControls()
else
@_disableActiveBlipControls()
if blipView.getPermission() is EDIT_PERMISSION
@_enableEditingButtons()
else
@_disableEditingButtons()
else
@_disableEditingButtons()
@_disableActiveBlipControls()
if blipView is @_lastBlip
return if range is @_lastRange
return if range and @_lastRange and
range.compareBoundaryPoints(Range.START_TO_START, @_lastRange) is 0 and
range.compareBoundaryPoints(Range.END_TO_END, @_lastRange) is 0
@_lastRange = range
@_lastRange = @_lastRange.cloneRange() if @_lastRange
@_lastBlip = blipView
@emit('range-change', @_lastRange, blipView)
_checkRange: =>
###
Проверяет положение курсора и генерирует событие изменения положения
курсора при необходимости
###
params = @_getBlipAndRange()
if params
@_checkChangedRange(params[1], params[0])
else
@_checkChangedRange(null, null)
runCheckRange: =>
window.setTimeout =>
@_checkRange()
, 0
_windowCheckCusor: (e) =>
window.setTimeout =>
return unless @rootBlip
params = @_getBlipAndRange()
if params
@_checkChangedRange(params[1], params[0])
else
blip = @rootBlip.getView().getBlipContainingElement(e.target)
@_checkChangedRange(null, blip)
, 0
_initRangeChangeEvent: ->
###
Инициализирует событие "изменение курсора"
###
@_lastRange = null
@_lastBlip = null
window.addEventListener('keydown', @runCheckRange, false)
window.addEventListener('mousedown', @_windowCheckCusor, no)
window.addEventListener('mouseup', @_windowCheckCusor, no)
_eventHandler: (func) ->
###
Возвращает функцию, которая остановит событие и вызовет переданную
@param func: function
@return: function
function(event)
###
(event) ->
event.preventDefault()
event.stopPropagation()
func(event)
_createDOM: () ->
###
Создает DOM для отображения документа
###
c = $(@container)
BrowserEvents.addPropagationBlocker(@container, BrowserEvents.DOM_NODE_INSERTED) # TODO: find better place
c.empty()
waveParams =
url: @getUrl()
editable: @_editable
isAnonymous: @_isAnonymous
gDriveShareUrl: @_model.getGDriveShareUrl()
isGDriveView: History.isGDrive()
c.append renderWave(waveParams)
@_waveContent = $(@container).find('.js-wave-content')[0]
@_waveBlips = $(@container).find('.js-wave-blips')[0]
@_$activeBlipControls = $('.js-right-tools-panel .js-active-blip-controls')
@blipNode = $(@container).find('.js-container-blip')[0]
_initSettingsMenu: ->
menu = new SettingsMenu()
$settingsContainer = $(@container).find('.js-settings-container')
$settingsContainer.on BrowserEvents.C_READ_ALL_EVENT, =>
@emit(@constructor.Events.READ_ALL)
menu.render($settingsContainer[0],
topicId: @_waveViewModel.getServerId()
exportUrl: @getExportUrl()
embeddedUrl: @_getEmbeddedUrl()
)
_initAccountMenu: ->
menu = new AccountMenu()
menu.render($('.js-account-container')[0],
role: @_getRole()
)
markActiveBlip: (blip) =>
###
@param blip: BlipView
###
# TODO: work with BlipViewModel only
return blip.updateCursor() if @_activeBlip is blip
if @_activeBlip
@_activeBlip.clearCursor()
@_activeBlip.unmarkActive()
@_activeBlip = blip
@_activeBlip.setCursor()
@_activeBlip.markActive()
@_activeBlip.setReadState(true)
@_model.setActiveBlip(blip.getViewModel())
@_setOnScrollMenuPosition()
_resizerRepositionMenu: =>
RangeMenu.get().hide()
@_activeBlip?.updateMenuLeftPosition()
_setOnScrollMenuPosition: (e = false) =>
RangeMenu.get().hide()
@_activeBlip?.updateMenuPosition(e)
_isExistParticipant: (email) =>
participants = @_waveViewModel.getUsers(@_participants.all())
for p in participants
if p.getEmail() == email
return true
false
_processAddParticipantClick: =>
###
Обрабатывает нажатие на кнопку добавления участника
###
email = strip(@_$participantIdInput.val())
return if not email
if not isEmail(email)
return @_waveViewModel.showWarning("Enter valid e-mail")
if @_isExistParticipant(email)
@_waveViewModel.showWarning("Participant already added to topic")
@_$participantIdInput.select()
return
@_waveProcessor.addParticipant(@_model.serverId, email, @_addButtonRole, @_processAddParticipantResponse)
@_$participantIdInput.val('').focus()
_processAddParticipantResponse: (err, user) =>
###
Обрабатывает ответ сервера на добавление пользователя
@param err: object|null
###
return @_waveViewModel.showWarning(err.message) if err
$(@container).parent('.js-inner-wave-container').find('.js-wave-notifications .js-wave-warning').remove()
trackParticipantAddition('By email field', user)
@_waveViewModel.updateUserInfo(user)
@_waveProcessor.addOrUpdateContact(user)
@_addParticipantForm?.restartAutocompleter()
_expandCrossedBlipRange: (range, blipViewStart, blipViewEnd, directionForward) ->
if blipViewEnd
start = []
end = []
startView = blipViewStart
while startView
start.push(startView)
startView = startView.getParent()
endView = blipViewEnd
while endView
end.push(endView)
endView = endView.getParent()
while (startView = start.pop()) is (endView = end.pop())
commonView = startView
if startView
startThread = BlipThread.getBlipThread(startView.getContainer())
startViewContainer = startThread.getContainer()
range.setStartBefore(startViewContainer)
if @_lastRange
if range.compareBoundaryPoints(Range.START_TO_START, @_lastRange) > -1
range.setStartAfter(startViewContainer)
if endView
endThread = BlipThread.getBlipThread(endView.getContainer())
endViewContainer = endThread.getContainer()
range.setEndAfter(endViewContainer)
if @_lastRange
if range.compareBoundaryPoints(Range.END_TO_END, @_lastRange) < 1
range.setEndBefore(endViewContainer)
else
el = blipViewStart.getEditor()?.getContainer()
commonView = blipViewStart
range.setEnd(el, el.childNodes.length) if el
DOM.setRange(range, directionForward)
commonView?.getEditor().focus()
return [commonView, range]
_getBlipAndRange: ->
###
Возвращает текущее выделение и блип, в котором оно сделано
@return: [BlipView, DOM range]|null
###
return null if not @rootBlip
selection = window.getSelection()
return if not selection or not selection.rangeCount
range = selection.getRangeAt(0)
return null if not range
cursor = [range.startContainer, range.startOffset]
blipViewStart = @rootBlip.getView().getBlipContainingCursor(cursor)
directionForward = if selection.anchorNode is range.startContainer and selection.anchorOffset is range.startOffset then yes else no
unless blipViewStart
# selection.removeAllRanges()
return null
cursor = [range.endContainer, range.endOffset]
blipViewEnd = if range.collapsed then blipViewStart else @rootBlip.getView().getBlipContainingCursor(cursor)
if blipViewStart isnt blipViewEnd
return @_expandCrossedBlipRange(range, blipViewStart, blipViewEnd, directionForward)
else if blipViewStart isnt @_lastBlip
editor = blipViewStart.getEditor()
editor.focus()
return [blipViewStart, range]
# TODO: remove it
_createBlip: (forceCreate=false) ->
###
@param: forceCreate boolean
@return: BlipViewModel | undefined
###
opParams = @_getBlipAndRange()
return if not opParams
[blip] = opParams
if not @_inEditMode or forceCreate
blipViewModel = blip.initInsertInlineBlip()
return if not blipViewModel
return blipViewModel
_insertBlipButtonClick: =>
blipViewModel = @_createBlip(true)
return if not blipViewModel
_gaq.push(['_trackEvent', 'Blip usage', 'Insert reply', 'Re in editing menu'])
_insertMention: =>
blipViewModel = @_createBlip()
blipView = if not blipViewModel then @_activeBlip else blipViewModel.getView()
return if not blipView
setTimeout ->
recipientInput = blipView.getEditor().insertRecipient()
recipientInput?.insertionEventLabel = 'Menu button'
, 0
_insertTag: =>
blipViewModel = @_createBlip()
blipView = if not blipViewModel then @_activeBlip else blipViewModel.getView()
return if not blipView
setTimeout ->
tagInput = blipView.getEditor().insertTag()
tagInput?.insertionEventLabel = 'Menu button'
, 0
_insertTask: =>
blipViewModel = @_createBlip()
blipView = if not blipViewModel then @_activeBlip else blipViewModel.getView()
return if not blipView
setTimeout ->
taskInput = blipView.getEditor().insertTaskRecipient()
taskInput?.insertionEventLabel = 'Menu button'
, 0
_showGadgetPopup: (event) =>
if event.ctrlKey and event.shiftKey
@_insertGadget()
else
gadgetPopup = @getInsertGadgetPopup()
if gadgetPopup.isVisible()
@_hideGadgetPopup()
else
gadgetPopup.show(@getActiveBlip())
gadgetPopup.shownAt = Date.now()
_hideGadgetPopup: ->
gadgetPopup = @getInsertGadgetPopup()
return if not gadgetPopup?
shouldHide = true
if gadgetPopup.shownAt?
timeDiff = Date.now() - gadgetPopup.shownAt
shouldHide = timeDiff > 100
# Не скрываем popup, если после открытия прошло меньше 100 мс. Нужно, чтобы несколько топиков не
# мешали друг другу
gadgetPopup.hide() if shouldHide
getInsertGadgetPopup: ->
if not @_insertGadgetPopup and @_activeBlipControlButtons
for control in @_activeBlipControlButtons when control.className is '.js-insert-gadget'
@_insertGadgetPopup = control.$button[0].insertGadgetPopup
return @_insertGadgetPopup
_insertGadget: =>
opParams = @_getBlipAndRange()
return if not opParams
[blip, range] = opParams
blip.initInsertGadget()
_foldChildBlips: =>
###
Сворачивает все блипы, вложенные в текщуий
###
@_ctrlRepeats.foldChildBlips ?= 0
if @_ctrlRepeats.foldChildBlips
blip = @rootBlip.getView()
blip.foldAllChildBlips()
blip.setCursorToStart()
@_checkRange()
else
r = @_getBlipAndRange()
return if not r
[blip] = r
blip.foldAllChildBlips()
if blip is @rootBlip.getView()
_gaq.push(['_trackEvent', 'Blip usage', 'Hide replies', 'Root shortcut'])
else
_gaq.push(['_trackEvent', 'Blip usage', 'Hide replies', 'Reply shortcut'])
@_ctrlRepeats.foldChildBlips++
_unfoldChildBlips: =>
###
Разворачивает все блипы, вложенные в текщуий
###
@_ctrlRepeats.foldChildBlips = 0
r = @_getBlipAndRange()
return if not r
[blip] = r
if blip is @rootBlip.getView()
_gaq.push(['_trackEvent', 'Blip usage', 'Show replies', 'Root shortcut'])
else
_gaq.push(['_trackEvent', 'Blip usage', 'Show replies', 'Reply shortcut'])
blip.unfoldAllChildBlips()
_selectAll: =>
###
Выделяет все содержимое блипа, при двукратном нажатии - все содержимое корневого тредового блипа
###
@_ctrlRepeats.selectAll ?= 0
if @_ctrlRepeats.selectAll
blips = @rootBlip.getView().getChildBlips()
blip = null
r = DOM.getRange()
return if not r
node = r.startContainer
for own _, b of blips
bView = b.getView()
bContainer = bView.getContainer()
if DOM.contains(bContainer, node) or bContainer is node
blip = bView
break
return if not blip
else
r = @_getBlipAndRange()
return if not r
[blip] = r
@_ctrlRepeats.selectAll++
range = blip.selectAll()
@_checkChangedRange(range, blip)
_goToUnread: =>
###
Переводит фокус на первый непрочитаный блип,
расположенный после блипа под фокусом
###
return if @_curView isnt 'text'
@emit('goToNextUnread')
getActiveBlip: ->
#TODO: hack activeBlip
@_activeBlip.getViewModel()
getRootBlip: ->
@rootBlip
updateRangePos: ->
@_setOrUpdateRangeMenuPos(yes)
_setOrUpdateRangeMenuPos: (update) ->
menu = RangeMenu.get()
return menu.hide() if not @_lastBlip or not @_lastRange
return menu.hide() unless BrowserSupport.isSupported()
if update
@_lastBlip.updateRangeMenuPosByRange(@_lastRange, @container)
else
@_lastBlip.setRangeMenuPosByRange(@_lastRange, @container)
_preProcessKeyDownEvent: (e) =>
if e.ctrlKey or e.metaKey
handlers = @_ctrlHandlers
if e.shiftKey
handlers = @_ctrlShiftHandlers
else if e.shiftKey
handlers = @_shiftHandlers
@_processKeyDownEvent(handlers, e)
_processKeyDownEvent: (handlers, e) =>
###
Обрабатывает нажатия клавиш внутри блипов
@param e: DOM event
###
return if ((not (e.ctrlKey or e.metaKey)) and (not e.shiftKey)) or e.altKey
return if not (e.keyCode of handlers)
handlers[e.keyCode]()
e.preventDefault()
e.stopPropagation()
_processBlipKeyUpEvent: (e) =>
###
Обрабатывает отпускание клавиш внутри блипов
@param e: DOM event
###
return if e.which != 17 or e.keyCode != 17
# Обрабатываем только отпускание ctrl
@_ctrlRepeats = {}
_removeAutocompleter: ->
@_autoCompleter?.deactivate()
@_autoCompleter?.dom.$results.remove()
delete @_autoCompleter
_processClickEvent: =>
@_setOrUpdateRangeMenuPos(no)
destroy: ->
super()
# TODO: move it to another function
delete @_ctrlHandlers
delete @_ctrlShiftHandlers
delete @_shiftHandlers
delete @_globalCtrlHandlers
window.removeEventListener 'keydown', @_globalKeyHandler, true
delete @_globalKeyHandler
LocalStorage.removeListener('buffer', @_handleBufferUpdate)
@_closed = true
@_$addButtonSelect?.selectBox('destroy')
@_addParticipantForm?.destroy()
delete @_insertGadgetPopup
@_participants.destroy()
delete @_participants
@_destroySavingMessage()
require('../editor/file/upload_form').removeInstance()
@removeListeners('range-change')
@removeAllListeners()
$(@_waveBlips).off 'scroll'
$(window).off('scroll', @_setOnScrollMenuPosition)
@blipNode.removeEventListener 'keydown', @_preProcessKeyDownEvent, true
@blipNode.removeEventListener('keypress', @_processFFEnterKeypress, true) if BrowserSupport.isMozilla()
@blipNode.removeEventListener 'keyup', @_processBlipKeyUpEvent, true
@blipNode.removeEventListener('click', @_processClickEvent, false)
delete @blipNode
window.removeEventListener 'keydown', @runCheckRange, false
window.removeEventListener('mousedown', @_windowCheckCusor, no)
window.removeEventListener('mouseup', @_windowCheckCusor, no)
$wnd = $(window)
$wnd.off('resize resizeTopicByResizer', @_setParticipantsWidth)
$wnd.off('resize resizeTopicByResizer', @_resizerRepositionMenu)
@_destroyMindmap()
@_removeAutocompleter()
$(@container).empty().unbind()
@_disableActiveBlipControls()
@_deinitActiveBlipControls()
delete @rootBlip
delete @_activeBlip if @_activeBlip
delete @_editingBlip if @_editingBlip
delete @_lastBlip if @_lastBlip
delete @_lastEditableBlip if @_lastEditableBlip
@_destroyDragScroll()
@container = undefined
delete @_model
delete @_waveViewModel
# hack - clean jQuery's cached fragments
jQuery.fragments = {}
applyParticipantOp: (op) ->
@_participants.applyOp(op)
return if not window.loggedIn
isMyOp = op.ld?.id is window.userInfo.id or op.li?.id is window.userInfo.id
return if not isMyOp
@updateInterfaceAccordingToRole()
updateInterfaceAccordingToRole: ->
@_waveViewModel.updateParticipants()
@_updateParticipantsManagement()
@rootBlip.getView().recursivelyUpdatePermission()
@_updateReplyButtonState()
_updateReplyButtonState: ->
###
Ставится или снимается класс, прячущий кнопки реплаев
###
if @_waveViewModel.getRole() in [ROLE_OWNER, ROLE_EDITOR, ROLE_COMMENTATOR]
$(@container).removeClass('read-only')
@_canReply = true
else
$(@container).addClass('read-only')
@_canReply = false
_updateParticipantsManagement: ->
###
Приводит окна управления пользователей в состояние, соответствующее текущим правам
###
@_updateParticipantAddition()
@_updateWaveSharing()
_updateParticipantAddition: ->
myRole = @_waveViewModel.getRole()
if myRole is ROLE_NO_ROLE
@_$addButton?.attr('disabled', 'disabled')
else
@_$addButton?.removeAttr('disabled')
if @_model.getSharedState() is WAVE_SHARED_STATE_PRIVATE
defaultRole = myRole
defaultRole = ROLE_EDITOR if defaultRole is ROLE_OWNER
@_addButtonRole = defaultRole
@_$addButtonSelect?.selectBox('value', defaultRole)
else
@_addButtonRole = @_model.getDefaultRole()
@_$addButtonSelect?.selectBox('value', @_model.getDefaultRole())
if (myRole in [ROLE_OWNER, ROLE_EDITOR])
@_$addButtonSelect?.selectBox('enable')
else
@_$addButtonSelect?.selectBox('disable')
_updateWaveSharing: ->
if (@_waveViewModel.getRole() in [ROLE_OWNER, ROLE_EDITOR])
$([@_isPrivateButton, @_isByLinkButton, @_isPublicButton]).removeAttr('disabled')
$([@_publicRoleSelect, @_sharedRoleSelect]).removeClass('disabled')
@_canChangeTopicShare = true
else
$([@_isPrivateButton, @_isByLinkButton, @_isPublicButton]).attr('disabled', 'disabled') if @_isPrivateButton or @_isByLinkButton or @_isPublicButton
$([@_publicRoleSelect, @_sharedRoleSelect]).addClass('disabled') if @_publicRoleSelect or @_sharedRoleSelect
@_canChangeTopicShare = false
isExistParticipant: (email) ->
@_isExistParticipant(email)
processAddParticipantResponse: (err, user) =>
@_processAddParticipantResponse(err, user)
getUrl: ->
###
Возвращает ссылку, соответствующую волне
@return: string
###
return "#{document.location.protocol}//#{window.HOST + History.getWavePrefix()}#{@_model.serverId}/"
getExportUrl: ->
return "/api/export/1/#{@_model.serverId}/html/"
_getEmbeddedUrl: ->
"#{document.location.protocol}//#{window.HOST + History.getEmbeddedPrefix()}#{@_model.serverId}/"
getSocialSharingUrl: ->
###
Возвращает ссылку для шаринга волны в соцсетях
@return: string
###
return document.location.protocol + '//' +
window.HOST +
window.socialSharingConf.url +
@_model.serverId +
@_model.socialSharingUrl.substr(0, window.socialSharingConf.signLength) +
"/#{randomString(2)}"
_initTips: ->
@_$topicTipsContainer = $(@container).find('.js-topic-tip')
@_$topicTipsContainer.find('.js-hide-topic-tip').click(@_hideTip)
@_$topicTipsContainer.find('.js-next-tip').click(@_showNextTip)
_tipIsHidden: ->
return true if not LocalStorage.loginCountIsMoreThanTwo()
lastHiddenDate = LocalStorage.getLastHiddenTipDate() - 0
return @_lastTipDate <= lastHiddenDate
showTip: (text, @_lastTipDate, force=false) ->
return if not force and @_tipIsHidden()
LocalStorage.removeLastHiddenTipDate() if force
$textContainer = @_$topicTipsContainer.find('.js-topic-tip-text')
$textContainer.html(text).find('a').attr('target', '_blank')
$textContainer.attr('title', $textContainer.text())
$(@container).addClass('tip-shown')
_hideTip: =>
_gaq.push(['_trackEvent', 'Tips', 'Close tip'])
LocalStorage.setLastHiddenTipDate(@_lastTipDate)
$(@container).removeClass('tip-shown')
_showNextTip: =>
_gaq.push(['_trackEvent', 'Tips', 'Show next tip'])
@_waveProcessor.showNextTip()
setTextView: =>
return if @_curView is 'text'
@_curView = 'text'
$(@_waveContent).removeClass('mindmap-view')
@emit('wave-view-change')
setMindmapView: =>
return if @_curView is 'mindmap'
@_curView = 'mindmap'
$(@_waveContent).addClass('mindmap-view')
_gaq.push(['_trackEvent', 'Topic content', 'Switch to mindmap'])
if not @_mindmap?
@_initMindmap()
else
@_mindmap.update()
@emit('wave-view-change')
setShortMindmapView: =>
@_mindmap?.setShortMode()
setLongMindmapView: =>
@_mindmap?.setLongMode()
getCurView: -> @_curView
getScrollableElement: -> @_waveBlips
_initMindmap: ->
@_mindmap = new MindMap(@_waveViewModel)
mindMapContainer = $(@container).find('.js-topic-mindmap-container')[0]
@_mindmap.render(mindMapContainer)
_destroyMindmap: ->
@_mindmap?.destroy()
delete @_mindmap
_initDragScroll: ->
@_resetDragScrollVars()
@container.addEventListener('dragenter', @_handleContainerDragEnterEvent, no)
@container.addEventListener('dragleave', @_handleContainerDragLeaveEvent, no)
@container.addEventListener('drop', @_handleContainerDropEvent, no)
for el in @container.getElementsByClassName('js-scroll')
el.addEventListener('dragenter', @_handleScrollDragEnterEvent, no)
el.addEventListener('dragleave', @_handleScrollDragLeaveEvent, no)
@_scrollUpEl = @container.getElementsByClassName('js-scroll-up')[0]
@_scrollDownEl = @container.getElementsByClassName('js-scroll-down')[0]
_destroyDragScroll: ->
@_resetDragScrollVars()
@container.removeEventListener('dragenter', @_handleContainerDragEnterEvent, no)
@container.removeEventListener('dragleave', @_handleContainerDragLeaveEvent, no)
@container.removeEventListener('drop', @_handleContainerDropEvent, no)
for el in @container.getElementsByClassName('js-scroll')
el.removeEventListener('dragenter', @_handleScrollDragEnterEvent, no)
el.removeEventListener('dragleave', @_handleScrollDragLeaveEvent, no)
@_handleContainerDragEnterEvent = undefined
@_handleContainerDragLeaveEvent = undefined
@_handleContainerDropEvent = undefined
@_handleScrollDragEnterEvent = undefined
@_handleScrollDragLeaveEvent = undefined
@_doScrollOnDrag = undefined
@_scrollUpEl = undefined
@_scrollDownEl = undefined
_handleContainerDragEnterEvent: =>
@_dragCount++
@_updateDragState()
_handleContainerDragLeaveEvent: =>
@_dragCount--
@_updateDragState()
_handleContainerDropEvent: =>
@_resetDragScrollVars()
@_updateDragState()
_handleScrollDragEnterEvent: (e) =>
@_lastDraggedOverClass = e.target.className
@_dragScrollAmount = parseInt(e.target.getAttribute('offset')) || 0
@_setDragScrollInterval() if @_dragScrollAmount
_handleScrollDragLeaveEvent: (e) =>
if e.target.className is @_lastDraggedOverClass
@_lastDraggedOverClass = ''
@_clearDragScrollInterval()
_resetDragScrollVars: ->
@_clearDragScrollInterval()
@_dragScrollAmount = 0
@_dragCount = 0
@_lastDraggedOverClass = ''
_setDragScrollInterval: ->
@_clearDragScrollInterval()
@_dragScrollIntervalId = setInterval(@_doScrollOnDrag, 100)
_doScrollOnDrag: =>
scrollTop = @_waveBlips.scrollTop
scrollHeight = @_waveBlips.scrollHeight
height = @_waveBlips.offsetHeight
if scrollTop + @_dragScrollAmount <= 0
@_waveBlips.scrollTop = 0
@_clearDragScrollInterval()
return @_updateDragState()
if scrollTop + height + @_dragScrollAmount >= scrollHeight
@_waveBlips.scrollTop = scrollHeight - height
@_clearDragScrollInterval()
return @_updateDragState()
@_waveBlips.scrollTop += @_dragScrollAmount
_clearDragScrollInterval: ->
return unless @_dragScrollIntervalId
@_dragScrollIntervalId = clearInterval(@_dragScrollIntervalId)
_updateTopScrollArea: (show) ->
if show
@_scrollUpEl.style.display = 'block'
else
@_scrollUpEl.style.display = 'none'
_updateBottomScrollArea: (show) ->
if show
@_scrollDownEl.style.display = 'block'
else
@_scrollDownEl.style.display = 'none'
_showScrollableAreas: ->
height = @_waveBlips.offsetHeight
scrollHeight = @_waveBlips.scrollHeight
return @_hideScrollableAreas() if height is scrollHeight
scrollTop = @_waveBlips.scrollTop
unless scrollTop
@_updateTopScrollArea(no)
else
@_updateTopScrollArea(yes)
if scrollTop + height >= scrollHeight
@_updateBottomScrollArea(no)
else
@_updateBottomScrollArea(yes)
_hideScrollableAreas: ->
@_updateTopScrollArea(no)
@_updateBottomScrollArea(no)
_updateDragState: ->
if @_dragCount
@_showScrollableAreas()
else
@_hideScrollableAreas()
_initSavingMessage: ->
@_savingMessage = new SavingMessageView()
@_savingMessage.init(@_waveViewModel.getId(), @_waveHeader)
_destroySavingMessage: ->
@_savingMessage?.destroy()
delete @_savingMessage
_setEditMode: (@_inEditMode) ->
cl = 'wave-edit-mode'
if @_inEditMode then DOM.addClass(@_container, cl) else DOM.removeClass(@_container, cl)
@_checkChangedRange(@_lastRange, @_lastBlip) # show/hide controls # TODO: is it good?
hasCursor: ->
DOM.hasClass(@container, 'has-cursor')
setEditModeEnabled: (enabled) -> @_setEditMode(enabled)
isEditMode: -> @_inEditMode
getContainer: -> @container
foldAll: ->
if @_curView is 'text'
@rootBlip.getView().foldAllChildBlips()
else
@_mindmap.fold()
unfoldAll: ->
if @_curView is 'text'
@rootBlip.getView().unfoldAllChildBlips()
else
@_mindmap.unfold()
_initBuffer: ->
LocalStorage.on('buffer', @_handleBufferUpdate)
@_updateBufferPresenceMark(LocalStorage.hasBuffer())
_updateBufferPresenceMark: (hasBuffer) ->
if hasBuffer
$(@container).addClass('has-buffer')
else
$(@container).removeClass('has-buffer')
_handleBufferUpdate: (param) =>
@_updateBufferPresenceMark(param.newValue?)
setReservedHeaderSpace: (@_reservedHeaderSpace) ->
@_setParticipantsWidth()
class SavingMessageView
SAVE_TIME: 0.5
FADE_TIME: 120
constructor: ->
@_saveTimeout = null
@_fadeTimeout = null
_getMessages: ->
container = $(@_container)
return [container.find('.js-saving-message-saving'), container.find('.js-saving-message-saved')]
_onStartSend: (groupId) =>
return if groupId isnt @_waveId
[saving, saved] = @_getMessages()
saved.removeClass('visible')
saving.addClass('visible')
_onFinishSend: (groupId) =>
clearTimeout(@_saveTimeout) if @_saveTimeout
@_saveTimeout = setTimeout =>
return if groupId isnt @_waveId
[saving, saved] = @_getMessages()
saving.removeClass('visible')
saved.addClass('visible')
clearTimeout(@_fadeTimeout) if @_fadeTimeout
@_fadeTimeout = setTimeout ->
saved.removeClass('visible')
, @FADE_TIME * 1000
, @SAVE_TIME * 1000
init: (@_waveId, @_container) ->
processor = require('../ot/processor').instance
processor.on('start-send', @_onStartSend)
processor.on('finish-send', @_onFinishSend)
destroy: ->
processor = require('../ot/processor').instance
processor.removeListener('start-send', @_onStartSend)
processor.removeListener('finish-send', @_onFinishSend)
clearTimeout(@_saveTimeout)
clearTimeout(@_fadeTimeout)
module.exports = WaveView: WaveView
| 214182 | WaveViewBase = require('./view_base')
{Participants} = require('./participants')
{trackParticipantAddition} = require('./participants/utils')
{ROLES, ROLE_OWNER, ROLE_EDITOR, ROLE_COMMENTATOR, ROLE_READER, ROLE_NO_ROLE} = require('./participants/constants')
{renderWave, renderSelectAccountTypeBanner} = require('./template')
DOM = require('../utils/dom')
popup = require('../popup').popup
randomString = require('../utils/random_string').randomString
{TextLevelParams, LineLevelParams} = require('../editor/model')
BrowserSupport = require('../utils/browser_support')
{SettingsMenu} = require('./settings_menu')
{AccountMenu} = require('./account_menu')
{isEmail, strip} = require('../utils/string')
{WAVE_SHARED_STATE_PUBLIC, WAVE_SHARED_STATE_LINK_PUBLIC, WAVE_SHARED_STATE_PRIVATE} = require('./model')
BlipThread = require('../blip/blip_thread').BlipThread
AddParticipantForm = require('./participants/add_form').AddParticipantForm
{EDIT_PERMISSION, COMMENT_PERMISSION} = require('../blip/model')
{RoleSelectPopup} = require('./role_select_popup')
{LocalStorage} = require('../utils/localStorage')
{MindMap} = require('../mindmap')
RangeMenu = require('../blip/menu/range_menu')
History = require('../utils/history_navigation')
BrowserEvents = require('../utils/browser_events')
SCROLL_INTO_VIEW_OFFSET = -90
ADD_BUTTONS = []
for role in ROLES when role.id isnt ROLE_OWNER
ADD_BUTTONS.push {
id: role.id
name: role.name.toLowerCase()
}
DEFAULT_ROLES = [
[ROLE_EDITOR, 'edit']
[ROLE_COMMENTATOR, 'comment']
[ROLE_READER, 'read']
]
class WaveView extends WaveViewBase
constructor: (@_waveViewModel, @_waveProcessor, participants, @_container) ->
###
@param waveViewModel: WaveViewModel
@param _waveProcessor: WaveProcessor
@param participants: array, часть ShareJS-документа, отвечающего за участников
@param container: HTMLNode, нода, в которой отображаться сообщению
###
super()
@container = @_container # TODO: deprecated. backward compatibility
@_init(@_waveViewModel, participants)
_init: (waveViewModel, participants) ->
###
@param waveViewModel: WaveViewModel
@param participants: array, часть ShareJS-документа, отвечающего за участников
###
@_inEditMode = no
@_isAnonymous = !window.userInfo?.id?
@_model = waveViewModel.getModel()
@_editable = BrowserSupport.isSupported() and not @_isAnonymous
@_createDOM()
@_initWaveHeader(waveViewModel, participants)
@_initEditingMenu()
@_updateParticipantsManagement()
@_initRootBlip(waveViewModel)
@_updateReplyButtonState()
@_initTips()
@_initDragScroll()
waveViewModel.on('waveLoaded', =>
$(@_waveBlips).on 'scroll', @_setOnScrollMenuPosition
$(window).on('scroll', @_setOnScrollMenuPosition)
$(window).on 'resize resizeTopicByResizer', @_resizerRepositionMenu
)
@_initBuffer()
@_$wavePanel.addClass('visible') if not BrowserSupport.isSupported() and not @_isAnonymous
_contactSelectHandler: (item) =>
@_$participantIdInput.val(item.email) if item? and item
@_processAddParticipantClick()
_contactButtonHandler: (e) =>
source = $(e.currentTarget).attr('source')
_gaq.push(['_trackEvent', 'Contacts synchronization', 'Synchronize contacts click', "add users #{source}"])
@_waveProcessor.initContactsUpdate source, e.screenX-630, e.screenY, =>
return if @_closed
@activateContacts(source)
_gaq.push(['_trackEvent', 'Contacts synchronization', 'Successfull synchronization', "add users #{source}"])
activateContacts: (source) ->
@_addParticipantForm?.refreshContacts(source)
_getRole: ->
role = @_waveViewModel.getRole()
for r in ROLES
if r.id == role
return r
_initWaveHeader: (waveViewModel, participants)->
###
Инициализирует заголовок волны
###
@_reservedHeaderSpace = 0
$c = $(@container)
@_waveHeader = $c.find('.js-wave-header')[0]
@_$wavePanel = $c.find('.js-wave-panel')
@_initParticipantAddition()
@_initParticipants(waveViewModel, participants)
if @_isAnonymous
$c.find('.js-enter-rizzoma-btn').click (e) ->
window.AuthDialog.initAndShow(true, History.getLoginRedirectUrl())
e.stopPropagation()
e.preventDefault()
@_initWaveShareMenu()
@_curView = 'text'
role = @_getRole()
$(@_waveHeader).find('.js-account-section-role').text(role.name) if role
@_initSavingMessage()
@_initSettingsMenu()
@_initAccountMenu()
@_initSelectAccountTypeBanner()
_initSelectAccountTypeBanner: ->
return if !window.showAccountSelectionBanner
$(@container).prepend(renderSelectAccountTypeBanner())
$(@container).find(".js-open-account-select").on "click", =>
_gaq.push(['_trackEvent', 'Monetization', 'Upgrade account link click'])
$('.js-account-wizard-banner').remove()
delete window.showAccountSelectionWizard
delete window.showAccountSelectionBanner
@_waveProcessor.openAccountWizard()
$(@container).find('.js-account-wizard-banner').on "click", ->
$('.js-account-wizard-banner').remove()
_initParticipantAddition: ->
return if @_isAnonymous
@_$addParticipantsBlock = $(@_waveHeader).find('.js-add-form')
@_addParticipantsBlockButton = DOM.findAndBind($(@_waveHeader), '.js-add-block-button', 'click', @_processAddParticipantBlockClick)
_processAddButtonChange: =>
@_addButtonRole = parseInt(@_$addButtonSelect.val())
_createAddParticipantForm: ->
maxResults = if History.isEmbedded() then 5 else 7
@_addParticipantForm = new AddParticipantForm(@_$addParticipantsBlock, maxResults, ADD_BUTTONS, @_waveProcessor, @_contactSelectHandler, @_contactButtonHandler)
@_$participantIdInput = @_$addParticipantsBlock.find('.js-input-email')
setTimeout =>
@_$addButtonSelect = @_$addParticipantsBlock.find('.js-add-select')
@_$addButtonSelect.selectBox().change(@_processAddButtonChange)
@_$addButtonSelect.on 'close', =>
window.setTimeout =>
$(@_participantIdInput).focus()
0
@_$addButton = @_$addParticipantsBlock.find('.js-add-button')
@_updateParticipantAddition()
,0
_processAddParticipantBlockClick: (event) =>
if @_addParticipantForm?.isVisible()
@_addParticipantForm.hide()
else
if not @_addParticipantForm?
@_createAddParticipantForm()
@_addParticipantForm.show()
@_$participantIdInput.focus()
_initSocialShareButtons: ->
socialSection = $(@_waveHeader).find('.js-social-section')
@_facebookButton = socialSection.find('.js-social-facebook')
@_twitterButton = socialSection.find('.js-social-twitter')
@_googleButton = socialSection.find('.js-social-google')
@_socialOverlay = socialSection.find('.js-social-overlay')
loadWnd = (title, url, e) =>
wnd = window.open("/share_topic_wait/", title, "width=640,height=440,left=#{e.screenX-630},top=#{e.screenY},scrollbars=no")
if @_waveProcessor.rootRouterIsConnected()
@_waveProcessor.markWaveAsSocialSharing(@_model.serverId, () =>
wnd.document.location.href = url if wnd
)
else
wnd.document.location.href = url
@_facebookButton.on 'click', (e) =>
_gaq.push(['_trackEvent', 'Topic sharing', 'Share topic on Facebook'])
mixpanel.track('Topic sharing', {'channel': 'Facebook'})
loadWnd('Facebook', "http://www.facebook.com/sharer/sharer.php?u=#{encodeURIComponent(@getSocialSharingUrl())}", e)
return false
@_googleButton.on 'click', (e) =>
_gaq.push(['_trackEvent', 'Topic sharing', 'Share topic on Google+'])
mixpanel.track('Topic sharing', {'channel': 'Google+'})
loadWnd('Google', "https://plus.google.com/share?url=#{encodeURIComponent(@getSocialSharingUrl())}", e)
return false
twUrl = @getSocialSharingUrl()
twhashtag = <PASSWORD>'
tweetLength = 140 - twUrl.length - twhashtag.length
@_twitterButton.on 'click', (e) =>
_gaq.push(['_trackEvent', 'Topic sharing', 'Share topic on Twitter'])
mixpanel.track('Topic sharing', {'channel': 'Twitter'})
snippet = ''
for t in @rootBlip.getModel().getSnapshotContent()
break if snippet.length >= tweetLength
if t.params.__TYPE != 'TEXT'
snippet += " "
else
snippet += t.t
if snippet.length >= tweetLength
snippet = snippet.substr(0, tweetLength-3)
snippet += "...#{twhashtag}"
else
snippet += " #{twhashtag}"
window.open("https://twitter.com/intent/tweet?source=tw&text=#{encodeURIComponent(snippet)}&url=#{encodeURIComponent(twUrl)}", 'Twitter', "width=640,height=290,left=#{e.screenX-630},top=#{e.screenY},scrollbars=no")
return false
_shareButtonHandler: (e) =>
waveUrl = @_sharePopup.find('.js-wave-url')
if @_sharePopup.is(':visible')
return @_sharePopup.hide()
@_sharePopup.show()
_gaq.push(['_trackEvent', 'Topic sharing', 'Topic sharing manage'])
waveUrl.select()
waveUrl.on 'mousedown', =>
waveUrl.select()
# Обработчик на закрывание устанавливается с задержкой, чтобы не обработать
# текущий клик
window.setTimeout =>
$(document).on 'click.shareWaveBlock', (e) =>
if $(e.target).closest('.js-share-window, .js-role-selector-popup').length == 0
@_sharePopup.hide()
$(document).off('click.shareWaveBlock')
true
, 0
#эта проверка нужна в ff, без нее не прячутся панели
@_checkRange()
_handleGDriveViewShareButton: (e) =>
menu = @_shareContainer.find('.js-gdrive-share-menu')
if menu.is(':visible')
return menu.hide()
menu.show()
window.setTimeout =>
$(document).on 'click.gDriveShareMenu', (e) =>
if $(e.target).closest('.js-gdrive-share-menu').length == 0
menu.hide()
$(document).off('click.gDriveShareMenu')
true
, 0
#эта проверка нужна в ff, без нее не прячутся панели
@_checkRange()
_initWaveShareMenu: ->
###
Инициализирует меню расшаривания волны
###
return if @_isAnonymous
@_shareContainer = $(@_waveHeader).find('.js-share-container')
@_shareButton = @_shareContainer.find('.js-show-share-button')
@_sharePopup = @_shareContainer.find('.js-share-window')
if History.isGDrive()
menu = @_shareContainer.find('.js-gdrive-share-menu')
menu.on 'click', 'a.js-btn', (e) ->
e.preventDefault()
menu.hide()
$(document).off('click.gDriveShareMenu')
@_shareButton.on('click', @_handleGDriveViewShareButton)
@_shareContainer.find('.js-share-window-button').on('click', @_shareButtonHandler)
else
@_shareButton.on('click', @_shareButtonHandler)
if not BrowserSupport.isSupported() or !window.loggedIn
###
Не авторизованные пользователи или пользователи
не под Chrome не могут расшарить волну
###
@_shareButton.attr('disabled', 'disabled')
$c = $(@container)
@_byLinkRoleId = ROLE_EDITOR
@_publicRoleId = ROLE_COMMENTATOR
@_isPrivateButton = DOM.findAndBind $c, '.js-is-private-button', 'change', =>
@setSharedState(WAVE_SHARED_STATE_PRIVATE) if @_isPrivateButton.checked
@_isByLinkButton = DOM.findAndBind $c, '.js-by-link-button', 'change', =>
@setSharedState(WAVE_SHARED_STATE_LINK_PUBLIC, @_byLinkRoleId) if @_isByLinkButton.checked
@_isPublicButton = DOM.findAndBind $c, '.js-is-public-button', 'change', =>
@setSharedState(WAVE_SHARED_STATE_PUBLIC, @_publicRoleId) if @_isPublicButton.checked
@_sharedRoleSelect = $(@_sharePopup).find('.js-shared-role-select')[0]
setPopup = (node, getRole, setRole) =>
$(node).click (event) =>
return if not @_canChangeTopicShare
popup.hide()
popup.render(new RoleSelectPopup(DEFAULT_ROLES, getRole, setRole), event.target)
popup.show()
return false
getRole = => @_byLinkRoleId
setRole = (roleId) =>
@_byLinkRoleId = roleId
popup.hide()
@setSharedState(WAVE_SHARED_STATE_LINK_PUBLIC, @_byLinkRoleId)
setPopup(@_sharedRoleSelect, getRole, setRole)
getRole = => @_publicRoleId
setRole = (roleId) =>
@_publicRoleId = roleId
popup.hide()
@setSharedState(WAVE_SHARED_STATE_PUBLIC, @_publicRoleId)
@_publicRoleSelect = $(@_sharePopup).find('.js-public-role-select')[0]
for [roleId, roleName] in DEFAULT_ROLES
$(@_publicRoleSelect).text(roleName) if roleId is @_publicRoleId
setPopup(@_publicRoleSelect, getRole, setRole)
@_initSocialShareButtons()
@updatePublicState()
_disableSocialButtons: ->
@_socialOverlay.addClass('social-overlay')
@_facebookButton.attr('disabled', 'disabled')
@_twitterButton.attr('disabled', 'disabled')
@_googleButton.attr('disabled', 'disabled')
_enableSocialButtons: ->
@_socialOverlay.removeClass('social-overlay')
@_facebookButton.removeAttr('disabled')
@_twitterButton.removeAttr('disabled')
@_googleButton.removeAttr('disabled')
_setShareContainerClass: (className) ->
$(@_shareContainer).removeClass('private')
$(@_shareContainer).removeClass('public')
$(@_shareContainer).removeClass('shared')
$(@_shareContainer).addClass(className)
_setDefaultRoleId: (element, roleId) ->
for [id, name] in DEFAULT_ROLES
continue if roleId isnt id
$(element).text(name)
__scrollToBlipContainer: (blipContainer) ->
DOM.scrollTargetIntoViewWithAnimation(blipContainer, @_waveBlips, yes, SCROLL_INTO_VIEW_OFFSET)
updatePublicState: (sharedState = @_model.getSharedState(), defaultRoleId = @_model.getDefaultRole()) ->
###
Устанавливает состояние переключателя публичности волны
@param isPublic: boolean
@param defaultRoleId: int
###
return if not window.loggedIn
if sharedState == WAVE_SHARED_STATE_LINK_PUBLIC
@_isByLinkButton.checked = true
@_setDefaultRoleId(@_sharedRoleSelect, defaultRoleId)
@_byLinkRoleId = defaultRoleId
@_setShareContainerClass('shared')
@_enableSocialButtons()
@_shareButton.attr('title', "Topic is shared by link, click to change")
@_participants.showCreateTopicForSelectedButton()
else if sharedState == WAVE_SHARED_STATE_PRIVATE
@_isPrivateButton.checked = true
@_setShareContainerClass('private')
@_disableSocialButtons()
@_shareButton.attr('title', "Topic is private, click to change")
@_participants.showCreateTopicForSelectedButton()
else
@_isPublicButton.checked = true
@_setDefaultRoleId(@_publicRoleSelect, defaultRoleId)
@_publicRoleId = defaultRoleId
@_setShareContainerClass('public')
@_enableSocialButtons()
@_shareButton.attr('title', "Topic is public, click to change")
@_participants.hideCreateTopicForSelectedButton()
@_shareContainerWidth = $(@_shareContainer).width() +
parseInt($(@_shareContainer).css('margin-left')) +
parseInt($(@_shareContainer).css('margin-right'))
return if @_waveViewModel.getRole() in [ROLE_OWNER, ROLE_EDITOR]
@_updateParticipantsManagement()
setSharedState: (sharedState, defaultRole=1) ->
###
Устанавливает публичность волны
Обновляет кнопку в интерфейсе и отправляет команду серверу при необходимости
@param isPublic: boolean
@param defaultRole: int
###
@updatePublicState(sharedState, defaultRole)
@_waveProcessor.setWaveShareState @_model.serverId, sharedState, defaultRole, (err) =>
if @_isPublicButton.checked
_gaq.push(['_trackEvent', 'Topic sharing', 'Set topic public'])
else if @_isPrivateButton.checked
_gaq.push(['_trackEvent', 'Topic sharing', 'Set topic private'])
else
_gaq.push(['_trackEvent', 'Topic sharing', 'Set topic shared'])
return if not err
@_waveViewModel.showWarning(err.message)
@updatePublicState()
_initParticipants: (waveViewModel, participants) ->
###
Инициализирует панель с участниками волны
@param participants: array, часть ShareJS-документа, отвечающего за участников
###
@_participants = new Participants(waveViewModel, @_waveProcessor, @_model.serverId,
participants, yes, @_model.getGDriveShareUrl())
$(@container).find('.js-wave-participants').append(@_participants.getContainer())
@_excludeParticipantsWidth = 0
headerChildren = $(@_waveHeader).children()
for child in headerChildren
if $(child).hasClass('js-wave-participants') or $(child).hasClass('clearer') or not $(child).is(':visible')
continue
@_excludeParticipantsWidth += $(child).outerWidth(true)
@_setParticipantsWidth()
$(window).on 'resize resizeTopicByResizer', @_setParticipantsWidth #resizeTopicByResizer срабатывает при изменении ширины ресайзером
getParticipantIds: ->
@_participants.all()
_setParticipantsWidth: () =>
if @_isAnonymous
participantsWidth = $(@container).find('.js-wave-participants').outerWidth()
else
headerInnerWidth = $(@_waveHeader).width() -
parseInt($(@_waveHeader).css('padding-left')) -
parseInt($(@_waveHeader).css('padding-right'))
participantsWidth = headerInnerWidth - @_excludeParticipantsWidth -
parseInt($($(@_waveHeader).find('.js-participant-container')[0]).css('margin-left')) -
parseInt($($(@_waveHeader).find('.js-participant-container')[0]).css('margin-right'))
participantsWidth -= @_reservedHeaderSpace
@_participants.setParticipantsWidth(participantsWidth)
_initEditingMenu: ->
###
Инициализирует меню редактирования волны
###
return if not @_editable
@_initEditingMenuKeyHandlers()
@_disableEditingButtons()
@_disableActiveBlipControls()
@_initActiveBlipControls()
_initActiveBlipControls: ->
###
Инициализирует кнопки вставки реплая или меншена в активный блиб
###
checkPermission = (callback) => (args...) =>
return false if @_activeBlipControlsEnabled is no
callback(args...)
activateButtons = (buttons) =>
for controlInfo in buttons
{className, handler} = controlInfo
controlInfo.$button = @_$activeBlipControls.find(className)
controlInfo.$button.mousedown(handler)
@_activeBlipControlButtons = [
{className: '.js-insert-reply', handler: checkPermission(@_eventHandler(@_insertBlipButtonClick))}
{className: '.js-insert-mention', handler: checkPermission(@_eventHandler(@_insertMention))}
{className: '.js-insert-tag', handler: checkPermission(@_eventHandler(@_insertTag))}
{className: '.js-insert-gadget', handler: checkPermission(@_eventHandler(@_showGadgetPopup))}
]
activateButtons(@_activeBlipControlButtons)
accountProcessor = require('../account_setup_wizard/processor').instance
businessButtons = [{className: '.js-insert-task', handler: checkPermission(@_eventHandler(@_insertTask))}]
if accountProcessor.isBusinessUser()
activateButtons(businessButtons)
@_activeBlipControlButtons.push(businessButtons[0])
else
$insertTaskBtn = @_$activeBlipControls.find('.js-insert-task').hide()
businessChangeCallback = (isBusiness) =>
return unless isBusiness
return unless @_activeBlipControlButtons
$insertTaskBtn.show()
accountProcessor.removeListener('is-business-change', businessChangeCallback)
activateButtons(businessButtons)
@_activeBlipControlButtons.push(businessButtons[0])
accountProcessor.on('is-business-change', businessChangeCallback)
_deinitActiveBlipControls: ->
for {$button, handler} in @_activeBlipControlButtons
$button?.off('mousedown', handler)
delete @_activeBlipControlButtons
_initEditingMenuKeyHandlers: ->
###
Инициализирует обработчики нажатий на клавиши в топике
###
@_ctrlHandlers =
65: @_selectAll # A
69: @_changeBlipEditMode # e
@_globalCtrlHandlers =
32: @_goToUnread # Space
@_ctrlShiftHandlers =
38: @_foldChildBlips # Up arrow
40: @_unfoldChildBlips # Down arrow
@_shiftHandlers =
13: @_setBlipReadMode # Enter
@_ctrlRepeats = {}
@blipNode.addEventListener('keydown', @_preProcessKeyDownEvent, true)
@blipNode.addEventListener('keypress', @_processFFEnterKeypress, true) if BrowserSupport.isMozilla()
@_globalKeyHandler = (e) =>
return if not (e.ctrlKey or e.metaKey)
@_processKeyDownEvent(@_globalCtrlHandlers, e)
window.addEventListener('keydown', @_globalKeyHandler, true)
@blipNode.addEventListener('keyup', @_processBlipKeyUpEvent, true)
@blipNode.addEventListener('click', @_processClickEvent, false) if BrowserSupport.isSupported()
_changeBlipEditMode: =>
blip = @_getBlipAndRange()[0]
return if not blip
blip.setEditable(!@_inEditMode)
_processFFEnterKeypress: (e) =>
# превентим keypress у Enter для ff, чтобы при завершении
# режима редактирования по Shift+Enter не создавался новый блип
return if e.keyCode != 13 or !e.shiftKey
e.stopPropagation()
_setBlipReadMode: (e) =>
blip = @_getBlipAndRange()[0]
return if not blip
blip.setEditable(no)
_initRootBlip: (waveViewModel) ->
###
Инициализирует корневой блип
###
processor = require('../blip/processor').instance
processor.openBlip waveViewModel, @_model.getContainerBlipId(), @blipNode, null, (err, @rootBlip) =>
return @_waveProcessor.showPageError(err) if err
@_initRangeChangeEvent()
@on 'range-change', (range, blip) =>
if blip
@markActiveBlip(blip)
_disableEditingButtons: -> @_editingButtonsEnabled = no
_enableEditingButtons: -> @_editingButtonsEnabled = yes
_disableActiveBlipControls: ->
return if not @_editable
return if @_activeBlipControlsEnabled is no
@_activeBlipControlsEnabled = no
@_hideGadgetPopup()
@_$activeBlipControls.addClass('unvisible')
enableActiveBlipControls: ->
# Показ меню делаем на следующей итерации, чтобы меню сначала спряталось
# остальными топиками, а затем показалось этим
window.setTimeout =>
return if @_activeBlipControlsEnabled is yes
@_activeBlipControlsEnabled = yes
@_$activeBlipControls.removeClass('unvisible')
, 0
cursorIsInText: -> @_editingButtonsEnabled
_checkChangedRange: (range, blipView) ->
if range
DOM.addClass(@container, 'has-cursor')
else
DOM.removeClass(@container, 'has-cursor')
if range and blipView.getPermission() in [EDIT_PERMISSION, COMMENT_PERMISSION]
if @_inEditMode
@enableActiveBlipControls()
else
@_disableActiveBlipControls()
if blipView.getPermission() is EDIT_PERMISSION
@_enableEditingButtons()
else
@_disableEditingButtons()
else
@_disableEditingButtons()
@_disableActiveBlipControls()
if blipView is @_lastBlip
return if range is @_lastRange
return if range and @_lastRange and
range.compareBoundaryPoints(Range.START_TO_START, @_lastRange) is 0 and
range.compareBoundaryPoints(Range.END_TO_END, @_lastRange) is 0
@_lastRange = range
@_lastRange = @_lastRange.cloneRange() if @_lastRange
@_lastBlip = blipView
@emit('range-change', @_lastRange, blipView)
_checkRange: =>
###
Проверяет положение курсора и генерирует событие изменения положения
курсора при необходимости
###
params = @_getBlipAndRange()
if params
@_checkChangedRange(params[1], params[0])
else
@_checkChangedRange(null, null)
runCheckRange: =>
window.setTimeout =>
@_checkRange()
, 0
_windowCheckCusor: (e) =>
window.setTimeout =>
return unless @rootBlip
params = @_getBlipAndRange()
if params
@_checkChangedRange(params[1], params[0])
else
blip = @rootBlip.getView().getBlipContainingElement(e.target)
@_checkChangedRange(null, blip)
, 0
_initRangeChangeEvent: ->
###
Инициализирует событие "изменение курсора"
###
@_lastRange = null
@_lastBlip = null
window.addEventListener('keydown', @runCheckRange, false)
window.addEventListener('mousedown', @_windowCheckCusor, no)
window.addEventListener('mouseup', @_windowCheckCusor, no)
_eventHandler: (func) ->
###
Возвращает функцию, которая остановит событие и вызовет переданную
@param func: function
@return: function
function(event)
###
(event) ->
event.preventDefault()
event.stopPropagation()
func(event)
_createDOM: () ->
###
Создает DOM для отображения документа
###
c = $(@container)
BrowserEvents.addPropagationBlocker(@container, BrowserEvents.DOM_NODE_INSERTED) # TODO: find better place
c.empty()
waveParams =
url: @getUrl()
editable: @_editable
isAnonymous: @_isAnonymous
gDriveShareUrl: @_model.getGDriveShareUrl()
isGDriveView: History.isGDrive()
c.append renderWave(waveParams)
@_waveContent = $(@container).find('.js-wave-content')[0]
@_waveBlips = $(@container).find('.js-wave-blips')[0]
@_$activeBlipControls = $('.js-right-tools-panel .js-active-blip-controls')
@blipNode = $(@container).find('.js-container-blip')[0]
_initSettingsMenu: ->
menu = new SettingsMenu()
$settingsContainer = $(@container).find('.js-settings-container')
$settingsContainer.on BrowserEvents.C_READ_ALL_EVENT, =>
@emit(@constructor.Events.READ_ALL)
menu.render($settingsContainer[0],
topicId: @_waveViewModel.getServerId()
exportUrl: @getExportUrl()
embeddedUrl: @_getEmbeddedUrl()
)
_initAccountMenu: ->
menu = new AccountMenu()
menu.render($('.js-account-container')[0],
role: @_getRole()
)
markActiveBlip: (blip) =>
###
@param blip: BlipView
###
# TODO: work with BlipViewModel only
return blip.updateCursor() if @_activeBlip is blip
if @_activeBlip
@_activeBlip.clearCursor()
@_activeBlip.unmarkActive()
@_activeBlip = blip
@_activeBlip.setCursor()
@_activeBlip.markActive()
@_activeBlip.setReadState(true)
@_model.setActiveBlip(blip.getViewModel())
@_setOnScrollMenuPosition()
_resizerRepositionMenu: =>
RangeMenu.get().hide()
@_activeBlip?.updateMenuLeftPosition()
_setOnScrollMenuPosition: (e = false) =>
RangeMenu.get().hide()
@_activeBlip?.updateMenuPosition(e)
_isExistParticipant: (email) =>
participants = @_waveViewModel.getUsers(@_participants.all())
for p in participants
if p.getEmail() == email
return true
false
_processAddParticipantClick: =>
###
Обрабатывает нажатие на кнопку добавления участника
###
email = strip(@_$participantIdInput.val())
return if not email
if not isEmail(email)
return @_waveViewModel.showWarning("Enter valid e-mail")
if @_isExistParticipant(email)
@_waveViewModel.showWarning("Participant already added to topic")
@_$participantIdInput.select()
return
@_waveProcessor.addParticipant(@_model.serverId, email, @_addButtonRole, @_processAddParticipantResponse)
@_$participantIdInput.val('').focus()
_processAddParticipantResponse: (err, user) =>
###
Обрабатывает ответ сервера на добавление пользователя
@param err: object|null
###
return @_waveViewModel.showWarning(err.message) if err
$(@container).parent('.js-inner-wave-container').find('.js-wave-notifications .js-wave-warning').remove()
trackParticipantAddition('By email field', user)
@_waveViewModel.updateUserInfo(user)
@_waveProcessor.addOrUpdateContact(user)
@_addParticipantForm?.restartAutocompleter()
_expandCrossedBlipRange: (range, blipViewStart, blipViewEnd, directionForward) ->
if blipViewEnd
start = []
end = []
startView = blipViewStart
while startView
start.push(startView)
startView = startView.getParent()
endView = blipViewEnd
while endView
end.push(endView)
endView = endView.getParent()
while (startView = start.pop()) is (endView = end.pop())
commonView = startView
if startView
startThread = BlipThread.getBlipThread(startView.getContainer())
startViewContainer = startThread.getContainer()
range.setStartBefore(startViewContainer)
if @_lastRange
if range.compareBoundaryPoints(Range.START_TO_START, @_lastRange) > -1
range.setStartAfter(startViewContainer)
if endView
endThread = BlipThread.getBlipThread(endView.getContainer())
endViewContainer = endThread.getContainer()
range.setEndAfter(endViewContainer)
if @_lastRange
if range.compareBoundaryPoints(Range.END_TO_END, @_lastRange) < 1
range.setEndBefore(endViewContainer)
else
el = blipViewStart.getEditor()?.getContainer()
commonView = blipViewStart
range.setEnd(el, el.childNodes.length) if el
DOM.setRange(range, directionForward)
commonView?.getEditor().focus()
return [commonView, range]
_getBlipAndRange: ->
###
Возвращает текущее выделение и блип, в котором оно сделано
@return: [BlipView, DOM range]|null
###
return null if not @rootBlip
selection = window.getSelection()
return if not selection or not selection.rangeCount
range = selection.getRangeAt(0)
return null if not range
cursor = [range.startContainer, range.startOffset]
blipViewStart = @rootBlip.getView().getBlipContainingCursor(cursor)
directionForward = if selection.anchorNode is range.startContainer and selection.anchorOffset is range.startOffset then yes else no
unless blipViewStart
# selection.removeAllRanges()
return null
cursor = [range.endContainer, range.endOffset]
blipViewEnd = if range.collapsed then blipViewStart else @rootBlip.getView().getBlipContainingCursor(cursor)
if blipViewStart isnt blipViewEnd
return @_expandCrossedBlipRange(range, blipViewStart, blipViewEnd, directionForward)
else if blipViewStart isnt @_lastBlip
editor = blipViewStart.getEditor()
editor.focus()
return [blipViewStart, range]
# TODO: remove it
_createBlip: (forceCreate=false) ->
###
@param: forceCreate boolean
@return: BlipViewModel | undefined
###
opParams = @_getBlipAndRange()
return if not opParams
[blip] = opParams
if not @_inEditMode or forceCreate
blipViewModel = blip.initInsertInlineBlip()
return if not blipViewModel
return blipViewModel
_insertBlipButtonClick: =>
blipViewModel = @_createBlip(true)
return if not blipViewModel
_gaq.push(['_trackEvent', 'Blip usage', 'Insert reply', 'Re in editing menu'])
_insertMention: =>
blipViewModel = @_createBlip()
blipView = if not blipViewModel then @_activeBlip else blipViewModel.getView()
return if not blipView
setTimeout ->
recipientInput = blipView.getEditor().insertRecipient()
recipientInput?.insertionEventLabel = 'Menu button'
, 0
_insertTag: =>
blipViewModel = @_createBlip()
blipView = if not blipViewModel then @_activeBlip else blipViewModel.getView()
return if not blipView
setTimeout ->
tagInput = blipView.getEditor().insertTag()
tagInput?.insertionEventLabel = 'Menu button'
, 0
_insertTask: =>
blipViewModel = @_createBlip()
blipView = if not blipViewModel then @_activeBlip else blipViewModel.getView()
return if not blipView
setTimeout ->
taskInput = blipView.getEditor().insertTaskRecipient()
taskInput?.insertionEventLabel = 'Menu button'
, 0
_showGadgetPopup: (event) =>
if event.ctrlKey and event.shiftKey
@_insertGadget()
else
gadgetPopup = @getInsertGadgetPopup()
if gadgetPopup.isVisible()
@_hideGadgetPopup()
else
gadgetPopup.show(@getActiveBlip())
gadgetPopup.shownAt = Date.now()
_hideGadgetPopup: ->
gadgetPopup = @getInsertGadgetPopup()
return if not gadgetPopup?
shouldHide = true
if gadgetPopup.shownAt?
timeDiff = Date.now() - gadgetPopup.shownAt
shouldHide = timeDiff > 100
# Не скрываем popup, если после открытия прошло меньше 100 мс. Нужно, чтобы несколько топиков не
# мешали друг другу
gadgetPopup.hide() if shouldHide
getInsertGadgetPopup: ->
if not @_insertGadgetPopup and @_activeBlipControlButtons
for control in @_activeBlipControlButtons when control.className is '.js-insert-gadget'
@_insertGadgetPopup = control.$button[0].insertGadgetPopup
return @_insertGadgetPopup
_insertGadget: =>
opParams = @_getBlipAndRange()
return if not opParams
[blip, range] = opParams
blip.initInsertGadget()
_foldChildBlips: =>
###
Сворачивает все блипы, вложенные в текщуий
###
@_ctrlRepeats.foldChildBlips ?= 0
if @_ctrlRepeats.foldChildBlips
blip = @rootBlip.getView()
blip.foldAllChildBlips()
blip.setCursorToStart()
@_checkRange()
else
r = @_getBlipAndRange()
return if not r
[blip] = r
blip.foldAllChildBlips()
if blip is @rootBlip.getView()
_gaq.push(['_trackEvent', 'Blip usage', 'Hide replies', 'Root shortcut'])
else
_gaq.push(['_trackEvent', 'Blip usage', 'Hide replies', 'Reply shortcut'])
@_ctrlRepeats.foldChildBlips++
_unfoldChildBlips: =>
###
Разворачивает все блипы, вложенные в текщуий
###
@_ctrlRepeats.foldChildBlips = 0
r = @_getBlipAndRange()
return if not r
[blip] = r
if blip is @rootBlip.getView()
_gaq.push(['_trackEvent', 'Blip usage', 'Show replies', 'Root shortcut'])
else
_gaq.push(['_trackEvent', 'Blip usage', 'Show replies', 'Reply shortcut'])
blip.unfoldAllChildBlips()
_selectAll: =>
###
Выделяет все содержимое блипа, при двукратном нажатии - все содержимое корневого тредового блипа
###
@_ctrlRepeats.selectAll ?= 0
if @_ctrlRepeats.selectAll
blips = @rootBlip.getView().getChildBlips()
blip = null
r = DOM.getRange()
return if not r
node = r.startContainer
for own _, b of blips
bView = b.getView()
bContainer = bView.getContainer()
if DOM.contains(bContainer, node) or bContainer is node
blip = bView
break
return if not blip
else
r = @_getBlipAndRange()
return if not r
[blip] = r
@_ctrlRepeats.selectAll++
range = blip.selectAll()
@_checkChangedRange(range, blip)
_goToUnread: =>
###
Переводит фокус на первый непрочитаный блип,
расположенный после блипа под фокусом
###
return if @_curView isnt 'text'
@emit('goToNextUnread')
getActiveBlip: ->
#TODO: hack activeBlip
@_activeBlip.getViewModel()
getRootBlip: ->
@rootBlip
updateRangePos: ->
@_setOrUpdateRangeMenuPos(yes)
_setOrUpdateRangeMenuPos: (update) ->
menu = RangeMenu.get()
return menu.hide() if not @_lastBlip or not @_lastRange
return menu.hide() unless BrowserSupport.isSupported()
if update
@_lastBlip.updateRangeMenuPosByRange(@_lastRange, @container)
else
@_lastBlip.setRangeMenuPosByRange(@_lastRange, @container)
_preProcessKeyDownEvent: (e) =>
if e.ctrlKey or e.metaKey
handlers = @_ctrlHandlers
if e.shiftKey
handlers = @_ctrlShiftHandlers
else if e.shiftKey
handlers = @_shiftHandlers
@_processKeyDownEvent(handlers, e)
_processKeyDownEvent: (handlers, e) =>
###
Обрабатывает нажатия клавиш внутри блипов
@param e: DOM event
###
return if ((not (e.ctrlKey or e.metaKey)) and (not e.shiftKey)) or e.altKey
return if not (e.keyCode of handlers)
handlers[e.keyCode]()
e.preventDefault()
e.stopPropagation()
_processBlipKeyUpEvent: (e) =>
###
Обрабатывает отпускание клавиш внутри блипов
@param e: DOM event
###
return if e.which != 17 or e.keyCode != 17
# Обрабатываем только отпускание ctrl
@_ctrlRepeats = {}
_removeAutocompleter: ->
@_autoCompleter?.deactivate()
@_autoCompleter?.dom.$results.remove()
delete @_autoCompleter
_processClickEvent: =>
@_setOrUpdateRangeMenuPos(no)
destroy: ->
super()
# TODO: move it to another function
delete @_ctrlHandlers
delete @_ctrlShiftHandlers
delete @_shiftHandlers
delete @_globalCtrlHandlers
window.removeEventListener 'keydown', @_globalKeyHandler, true
delete @_globalKeyHandler
LocalStorage.removeListener('buffer', @_handleBufferUpdate)
@_closed = true
@_$addButtonSelect?.selectBox('destroy')
@_addParticipantForm?.destroy()
delete @_insertGadgetPopup
@_participants.destroy()
delete @_participants
@_destroySavingMessage()
require('../editor/file/upload_form').removeInstance()
@removeListeners('range-change')
@removeAllListeners()
$(@_waveBlips).off 'scroll'
$(window).off('scroll', @_setOnScrollMenuPosition)
@blipNode.removeEventListener 'keydown', @_preProcessKeyDownEvent, true
@blipNode.removeEventListener('keypress', @_processFFEnterKeypress, true) if BrowserSupport.isMozilla()
@blipNode.removeEventListener 'keyup', @_processBlipKeyUpEvent, true
@blipNode.removeEventListener('click', @_processClickEvent, false)
delete @blipNode
window.removeEventListener 'keydown', @runCheckRange, false
window.removeEventListener('mousedown', @_windowCheckCusor, no)
window.removeEventListener('mouseup', @_windowCheckCusor, no)
$wnd = $(window)
$wnd.off('resize resizeTopicByResizer', @_setParticipantsWidth)
$wnd.off('resize resizeTopicByResizer', @_resizerRepositionMenu)
@_destroyMindmap()
@_removeAutocompleter()
$(@container).empty().unbind()
@_disableActiveBlipControls()
@_deinitActiveBlipControls()
delete @rootBlip
delete @_activeBlip if @_activeBlip
delete @_editingBlip if @_editingBlip
delete @_lastBlip if @_lastBlip
delete @_lastEditableBlip if @_lastEditableBlip
@_destroyDragScroll()
@container = undefined
delete @_model
delete @_waveViewModel
# hack - clean jQuery's cached fragments
jQuery.fragments = {}
applyParticipantOp: (op) ->
@_participants.applyOp(op)
return if not window.loggedIn
isMyOp = op.ld?.id is window.userInfo.id or op.li?.id is window.userInfo.id
return if not isMyOp
@updateInterfaceAccordingToRole()
updateInterfaceAccordingToRole: ->
@_waveViewModel.updateParticipants()
@_updateParticipantsManagement()
@rootBlip.getView().recursivelyUpdatePermission()
@_updateReplyButtonState()
_updateReplyButtonState: ->
###
Ставится или снимается класс, прячущий кнопки реплаев
###
if @_waveViewModel.getRole() in [ROLE_OWNER, ROLE_EDITOR, ROLE_COMMENTATOR]
$(@container).removeClass('read-only')
@_canReply = true
else
$(@container).addClass('read-only')
@_canReply = false
_updateParticipantsManagement: ->
###
Приводит окна управления пользователей в состояние, соответствующее текущим правам
###
@_updateParticipantAddition()
@_updateWaveSharing()
_updateParticipantAddition: ->
myRole = @_waveViewModel.getRole()
if myRole is ROLE_NO_ROLE
@_$addButton?.attr('disabled', 'disabled')
else
@_$addButton?.removeAttr('disabled')
if @_model.getSharedState() is WAVE_SHARED_STATE_PRIVATE
defaultRole = myRole
defaultRole = ROLE_EDITOR if defaultRole is ROLE_OWNER
@_addButtonRole = defaultRole
@_$addButtonSelect?.selectBox('value', defaultRole)
else
@_addButtonRole = @_model.getDefaultRole()
@_$addButtonSelect?.selectBox('value', @_model.getDefaultRole())
if (myRole in [ROLE_OWNER, ROLE_EDITOR])
@_$addButtonSelect?.selectBox('enable')
else
@_$addButtonSelect?.selectBox('disable')
_updateWaveSharing: ->
if (@_waveViewModel.getRole() in [ROLE_OWNER, ROLE_EDITOR])
$([@_isPrivateButton, @_isByLinkButton, @_isPublicButton]).removeAttr('disabled')
$([@_publicRoleSelect, @_sharedRoleSelect]).removeClass('disabled')
@_canChangeTopicShare = true
else
$([@_isPrivateButton, @_isByLinkButton, @_isPublicButton]).attr('disabled', 'disabled') if @_isPrivateButton or @_isByLinkButton or @_isPublicButton
$([@_publicRoleSelect, @_sharedRoleSelect]).addClass('disabled') if @_publicRoleSelect or @_sharedRoleSelect
@_canChangeTopicShare = false
isExistParticipant: (email) ->
@_isExistParticipant(email)
processAddParticipantResponse: (err, user) =>
@_processAddParticipantResponse(err, user)
getUrl: ->
###
Возвращает ссылку, соответствующую волне
@return: string
###
return "#{document.location.protocol}//#{window.HOST + History.getWavePrefix()}#{@_model.serverId}/"
getExportUrl: ->
return "/api/export/1/#{@_model.serverId}/html/"
_getEmbeddedUrl: ->
"#{document.location.protocol}//#{window.HOST + History.getEmbeddedPrefix()}#{@_model.serverId}/"
getSocialSharingUrl: ->
###
Возвращает ссылку для шаринга волны в соцсетях
@return: string
###
return document.location.protocol + '//' +
window.HOST +
window.socialSharingConf.url +
@_model.serverId +
@_model.socialSharingUrl.substr(0, window.socialSharingConf.signLength) +
"/#{randomString(2)}"
_initTips: ->
@_$topicTipsContainer = $(@container).find('.js-topic-tip')
@_$topicTipsContainer.find('.js-hide-topic-tip').click(@_hideTip)
@_$topicTipsContainer.find('.js-next-tip').click(@_showNextTip)
_tipIsHidden: ->
return true if not LocalStorage.loginCountIsMoreThanTwo()
lastHiddenDate = LocalStorage.getLastHiddenTipDate() - 0
return @_lastTipDate <= lastHiddenDate
showTip: (text, @_lastTipDate, force=false) ->
return if not force and @_tipIsHidden()
LocalStorage.removeLastHiddenTipDate() if force
$textContainer = @_$topicTipsContainer.find('.js-topic-tip-text')
$textContainer.html(text).find('a').attr('target', '_blank')
$textContainer.attr('title', $textContainer.text())
$(@container).addClass('tip-shown')
_hideTip: =>
_gaq.push(['_trackEvent', 'Tips', 'Close tip'])
LocalStorage.setLastHiddenTipDate(@_lastTipDate)
$(@container).removeClass('tip-shown')
_showNextTip: =>
_gaq.push(['_trackEvent', 'Tips', 'Show next tip'])
@_waveProcessor.showNextTip()
setTextView: =>
return if @_curView is 'text'
@_curView = 'text'
$(@_waveContent).removeClass('mindmap-view')
@emit('wave-view-change')
setMindmapView: =>
return if @_curView is 'mindmap'
@_curView = 'mindmap'
$(@_waveContent).addClass('mindmap-view')
_gaq.push(['_trackEvent', 'Topic content', 'Switch to mindmap'])
if not @_mindmap?
@_initMindmap()
else
@_mindmap.update()
@emit('wave-view-change')
setShortMindmapView: =>
@_mindmap?.setShortMode()
setLongMindmapView: =>
@_mindmap?.setLongMode()
getCurView: -> @_curView
getScrollableElement: -> @_waveBlips
_initMindmap: ->
@_mindmap = new MindMap(@_waveViewModel)
mindMapContainer = $(@container).find('.js-topic-mindmap-container')[0]
@_mindmap.render(mindMapContainer)
_destroyMindmap: ->
@_mindmap?.destroy()
delete @_mindmap
_initDragScroll: ->
@_resetDragScrollVars()
@container.addEventListener('dragenter', @_handleContainerDragEnterEvent, no)
@container.addEventListener('dragleave', @_handleContainerDragLeaveEvent, no)
@container.addEventListener('drop', @_handleContainerDropEvent, no)
for el in @container.getElementsByClassName('js-scroll')
el.addEventListener('dragenter', @_handleScrollDragEnterEvent, no)
el.addEventListener('dragleave', @_handleScrollDragLeaveEvent, no)
@_scrollUpEl = @container.getElementsByClassName('js-scroll-up')[0]
@_scrollDownEl = @container.getElementsByClassName('js-scroll-down')[0]
_destroyDragScroll: ->
@_resetDragScrollVars()
@container.removeEventListener('dragenter', @_handleContainerDragEnterEvent, no)
@container.removeEventListener('dragleave', @_handleContainerDragLeaveEvent, no)
@container.removeEventListener('drop', @_handleContainerDropEvent, no)
for el in @container.getElementsByClassName('js-scroll')
el.removeEventListener('dragenter', @_handleScrollDragEnterEvent, no)
el.removeEventListener('dragleave', @_handleScrollDragLeaveEvent, no)
@_handleContainerDragEnterEvent = undefined
@_handleContainerDragLeaveEvent = undefined
@_handleContainerDropEvent = undefined
@_handleScrollDragEnterEvent = undefined
@_handleScrollDragLeaveEvent = undefined
@_doScrollOnDrag = undefined
@_scrollUpEl = undefined
@_scrollDownEl = undefined
_handleContainerDragEnterEvent: =>
@_dragCount++
@_updateDragState()
_handleContainerDragLeaveEvent: =>
@_dragCount--
@_updateDragState()
_handleContainerDropEvent: =>
@_resetDragScrollVars()
@_updateDragState()
_handleScrollDragEnterEvent: (e) =>
@_lastDraggedOverClass = e.target.className
@_dragScrollAmount = parseInt(e.target.getAttribute('offset')) || 0
@_setDragScrollInterval() if @_dragScrollAmount
_handleScrollDragLeaveEvent: (e) =>
if e.target.className is @_lastDraggedOverClass
@_lastDraggedOverClass = ''
@_clearDragScrollInterval()
_resetDragScrollVars: ->
@_clearDragScrollInterval()
@_dragScrollAmount = 0
@_dragCount = 0
@_lastDraggedOverClass = ''
_setDragScrollInterval: ->
@_clearDragScrollInterval()
@_dragScrollIntervalId = setInterval(@_doScrollOnDrag, 100)
_doScrollOnDrag: =>
scrollTop = @_waveBlips.scrollTop
scrollHeight = @_waveBlips.scrollHeight
height = @_waveBlips.offsetHeight
if scrollTop + @_dragScrollAmount <= 0
@_waveBlips.scrollTop = 0
@_clearDragScrollInterval()
return @_updateDragState()
if scrollTop + height + @_dragScrollAmount >= scrollHeight
@_waveBlips.scrollTop = scrollHeight - height
@_clearDragScrollInterval()
return @_updateDragState()
@_waveBlips.scrollTop += @_dragScrollAmount
_clearDragScrollInterval: ->
return unless @_dragScrollIntervalId
@_dragScrollIntervalId = clearInterval(@_dragScrollIntervalId)
_updateTopScrollArea: (show) ->
if show
@_scrollUpEl.style.display = 'block'
else
@_scrollUpEl.style.display = 'none'
_updateBottomScrollArea: (show) ->
if show
@_scrollDownEl.style.display = 'block'
else
@_scrollDownEl.style.display = 'none'
_showScrollableAreas: ->
height = @_waveBlips.offsetHeight
scrollHeight = @_waveBlips.scrollHeight
return @_hideScrollableAreas() if height is scrollHeight
scrollTop = @_waveBlips.scrollTop
unless scrollTop
@_updateTopScrollArea(no)
else
@_updateTopScrollArea(yes)
if scrollTop + height >= scrollHeight
@_updateBottomScrollArea(no)
else
@_updateBottomScrollArea(yes)
_hideScrollableAreas: ->
@_updateTopScrollArea(no)
@_updateBottomScrollArea(no)
_updateDragState: ->
if @_dragCount
@_showScrollableAreas()
else
@_hideScrollableAreas()
_initSavingMessage: ->
@_savingMessage = new SavingMessageView()
@_savingMessage.init(@_waveViewModel.getId(), @_waveHeader)
_destroySavingMessage: ->
@_savingMessage?.destroy()
delete @_savingMessage
_setEditMode: (@_inEditMode) ->
cl = 'wave-edit-mode'
if @_inEditMode then DOM.addClass(@_container, cl) else DOM.removeClass(@_container, cl)
@_checkChangedRange(@_lastRange, @_lastBlip) # show/hide controls # TODO: is it good?
hasCursor: ->
DOM.hasClass(@container, 'has-cursor')
setEditModeEnabled: (enabled) -> @_setEditMode(enabled)
isEditMode: -> @_inEditMode
getContainer: -> @container
foldAll: ->
if @_curView is 'text'
@rootBlip.getView().foldAllChildBlips()
else
@_mindmap.fold()
unfoldAll: ->
if @_curView is 'text'
@rootBlip.getView().unfoldAllChildBlips()
else
@_mindmap.unfold()
_initBuffer: ->
LocalStorage.on('buffer', @_handleBufferUpdate)
@_updateBufferPresenceMark(LocalStorage.hasBuffer())
_updateBufferPresenceMark: (hasBuffer) ->
if hasBuffer
$(@container).addClass('has-buffer')
else
$(@container).removeClass('has-buffer')
_handleBufferUpdate: (param) =>
@_updateBufferPresenceMark(param.newValue?)
setReservedHeaderSpace: (@_reservedHeaderSpace) ->
@_setParticipantsWidth()
class SavingMessageView
SAVE_TIME: 0.5
FADE_TIME: 120
constructor: ->
@_saveTimeout = null
@_fadeTimeout = null
_getMessages: ->
container = $(@_container)
return [container.find('.js-saving-message-saving'), container.find('.js-saving-message-saved')]
_onStartSend: (groupId) =>
return if groupId isnt @_waveId
[saving, saved] = @_getMessages()
saved.removeClass('visible')
saving.addClass('visible')
_onFinishSend: (groupId) =>
clearTimeout(@_saveTimeout) if @_saveTimeout
@_saveTimeout = setTimeout =>
return if groupId isnt @_waveId
[saving, saved] = @_getMessages()
saving.removeClass('visible')
saved.addClass('visible')
clearTimeout(@_fadeTimeout) if @_fadeTimeout
@_fadeTimeout = setTimeout ->
saved.removeClass('visible')
, @FADE_TIME * 1000
, @SAVE_TIME * 1000
init: (@_waveId, @_container) ->
processor = require('../ot/processor').instance
processor.on('start-send', @_onStartSend)
processor.on('finish-send', @_onFinishSend)
destroy: ->
processor = require('../ot/processor').instance
processor.removeListener('start-send', @_onStartSend)
processor.removeListener('finish-send', @_onFinishSend)
clearTimeout(@_saveTimeout)
clearTimeout(@_fadeTimeout)
module.exports = WaveView: WaveView
| true | WaveViewBase = require('./view_base')
{Participants} = require('./participants')
{trackParticipantAddition} = require('./participants/utils')
{ROLES, ROLE_OWNER, ROLE_EDITOR, ROLE_COMMENTATOR, ROLE_READER, ROLE_NO_ROLE} = require('./participants/constants')
{renderWave, renderSelectAccountTypeBanner} = require('./template')
DOM = require('../utils/dom')
popup = require('../popup').popup
randomString = require('../utils/random_string').randomString
{TextLevelParams, LineLevelParams} = require('../editor/model')
BrowserSupport = require('../utils/browser_support')
{SettingsMenu} = require('./settings_menu')
{AccountMenu} = require('./account_menu')
{isEmail, strip} = require('../utils/string')
{WAVE_SHARED_STATE_PUBLIC, WAVE_SHARED_STATE_LINK_PUBLIC, WAVE_SHARED_STATE_PRIVATE} = require('./model')
BlipThread = require('../blip/blip_thread').BlipThread
AddParticipantForm = require('./participants/add_form').AddParticipantForm
{EDIT_PERMISSION, COMMENT_PERMISSION} = require('../blip/model')
{RoleSelectPopup} = require('./role_select_popup')
{LocalStorage} = require('../utils/localStorage')
{MindMap} = require('../mindmap')
RangeMenu = require('../blip/menu/range_menu')
History = require('../utils/history_navigation')
BrowserEvents = require('../utils/browser_events')
SCROLL_INTO_VIEW_OFFSET = -90
ADD_BUTTONS = []
for role in ROLES when role.id isnt ROLE_OWNER
ADD_BUTTONS.push {
id: role.id
name: role.name.toLowerCase()
}
DEFAULT_ROLES = [
[ROLE_EDITOR, 'edit']
[ROLE_COMMENTATOR, 'comment']
[ROLE_READER, 'read']
]
class WaveView extends WaveViewBase
constructor: (@_waveViewModel, @_waveProcessor, participants, @_container) ->
###
@param waveViewModel: WaveViewModel
@param _waveProcessor: WaveProcessor
@param participants: array, часть ShareJS-документа, отвечающего за участников
@param container: HTMLNode, нода, в которой отображаться сообщению
###
super()
@container = @_container # TODO: deprecated. backward compatibility
@_init(@_waveViewModel, participants)
_init: (waveViewModel, participants) ->
###
@param waveViewModel: WaveViewModel
@param participants: array, часть ShareJS-документа, отвечающего за участников
###
@_inEditMode = no
@_isAnonymous = !window.userInfo?.id?
@_model = waveViewModel.getModel()
@_editable = BrowserSupport.isSupported() and not @_isAnonymous
@_createDOM()
@_initWaveHeader(waveViewModel, participants)
@_initEditingMenu()
@_updateParticipantsManagement()
@_initRootBlip(waveViewModel)
@_updateReplyButtonState()
@_initTips()
@_initDragScroll()
waveViewModel.on('waveLoaded', =>
$(@_waveBlips).on 'scroll', @_setOnScrollMenuPosition
$(window).on('scroll', @_setOnScrollMenuPosition)
$(window).on 'resize resizeTopicByResizer', @_resizerRepositionMenu
)
@_initBuffer()
@_$wavePanel.addClass('visible') if not BrowserSupport.isSupported() and not @_isAnonymous
_contactSelectHandler: (item) =>
@_$participantIdInput.val(item.email) if item? and item
@_processAddParticipantClick()
_contactButtonHandler: (e) =>
source = $(e.currentTarget).attr('source')
_gaq.push(['_trackEvent', 'Contacts synchronization', 'Synchronize contacts click', "add users #{source}"])
@_waveProcessor.initContactsUpdate source, e.screenX-630, e.screenY, =>
return if @_closed
@activateContacts(source)
_gaq.push(['_trackEvent', 'Contacts synchronization', 'Successfull synchronization', "add users #{source}"])
activateContacts: (source) ->
@_addParticipantForm?.refreshContacts(source)
_getRole: ->
role = @_waveViewModel.getRole()
for r in ROLES
if r.id == role
return r
_initWaveHeader: (waveViewModel, participants)->
###
Инициализирует заголовок волны
###
@_reservedHeaderSpace = 0
$c = $(@container)
@_waveHeader = $c.find('.js-wave-header')[0]
@_$wavePanel = $c.find('.js-wave-panel')
@_initParticipantAddition()
@_initParticipants(waveViewModel, participants)
if @_isAnonymous
$c.find('.js-enter-rizzoma-btn').click (e) ->
window.AuthDialog.initAndShow(true, History.getLoginRedirectUrl())
e.stopPropagation()
e.preventDefault()
@_initWaveShareMenu()
@_curView = 'text'
role = @_getRole()
$(@_waveHeader).find('.js-account-section-role').text(role.name) if role
@_initSavingMessage()
@_initSettingsMenu()
@_initAccountMenu()
@_initSelectAccountTypeBanner()
_initSelectAccountTypeBanner: ->
return if !window.showAccountSelectionBanner
$(@container).prepend(renderSelectAccountTypeBanner())
$(@container).find(".js-open-account-select").on "click", =>
_gaq.push(['_trackEvent', 'Monetization', 'Upgrade account link click'])
$('.js-account-wizard-banner').remove()
delete window.showAccountSelectionWizard
delete window.showAccountSelectionBanner
@_waveProcessor.openAccountWizard()
$(@container).find('.js-account-wizard-banner').on "click", ->
$('.js-account-wizard-banner').remove()
_initParticipantAddition: ->
return if @_isAnonymous
@_$addParticipantsBlock = $(@_waveHeader).find('.js-add-form')
@_addParticipantsBlockButton = DOM.findAndBind($(@_waveHeader), '.js-add-block-button', 'click', @_processAddParticipantBlockClick)
_processAddButtonChange: =>
@_addButtonRole = parseInt(@_$addButtonSelect.val())
_createAddParticipantForm: ->
maxResults = if History.isEmbedded() then 5 else 7
@_addParticipantForm = new AddParticipantForm(@_$addParticipantsBlock, maxResults, ADD_BUTTONS, @_waveProcessor, @_contactSelectHandler, @_contactButtonHandler)
@_$participantIdInput = @_$addParticipantsBlock.find('.js-input-email')
setTimeout =>
@_$addButtonSelect = @_$addParticipantsBlock.find('.js-add-select')
@_$addButtonSelect.selectBox().change(@_processAddButtonChange)
@_$addButtonSelect.on 'close', =>
window.setTimeout =>
$(@_participantIdInput).focus()
0
@_$addButton = @_$addParticipantsBlock.find('.js-add-button')
@_updateParticipantAddition()
,0
_processAddParticipantBlockClick: (event) =>
if @_addParticipantForm?.isVisible()
@_addParticipantForm.hide()
else
if not @_addParticipantForm?
@_createAddParticipantForm()
@_addParticipantForm.show()
@_$participantIdInput.focus()
_initSocialShareButtons: ->
socialSection = $(@_waveHeader).find('.js-social-section')
@_facebookButton = socialSection.find('.js-social-facebook')
@_twitterButton = socialSection.find('.js-social-twitter')
@_googleButton = socialSection.find('.js-social-google')
@_socialOverlay = socialSection.find('.js-social-overlay')
loadWnd = (title, url, e) =>
wnd = window.open("/share_topic_wait/", title, "width=640,height=440,left=#{e.screenX-630},top=#{e.screenY},scrollbars=no")
if @_waveProcessor.rootRouterIsConnected()
@_waveProcessor.markWaveAsSocialSharing(@_model.serverId, () =>
wnd.document.location.href = url if wnd
)
else
wnd.document.location.href = url
@_facebookButton.on 'click', (e) =>
_gaq.push(['_trackEvent', 'Topic sharing', 'Share topic on Facebook'])
mixpanel.track('Topic sharing', {'channel': 'Facebook'})
loadWnd('Facebook', "http://www.facebook.com/sharer/sharer.php?u=#{encodeURIComponent(@getSocialSharingUrl())}", e)
return false
@_googleButton.on 'click', (e) =>
_gaq.push(['_trackEvent', 'Topic sharing', 'Share topic on Google+'])
mixpanel.track('Topic sharing', {'channel': 'Google+'})
loadWnd('Google', "https://plus.google.com/share?url=#{encodeURIComponent(@getSocialSharingUrl())}", e)
return false
twUrl = @getSocialSharingUrl()
twhashtag = PI:PASSWORD:<PASSWORD>END_PI'
tweetLength = 140 - twUrl.length - twhashtag.length
@_twitterButton.on 'click', (e) =>
_gaq.push(['_trackEvent', 'Topic sharing', 'Share topic on Twitter'])
mixpanel.track('Topic sharing', {'channel': 'Twitter'})
snippet = ''
for t in @rootBlip.getModel().getSnapshotContent()
break if snippet.length >= tweetLength
if t.params.__TYPE != 'TEXT'
snippet += " "
else
snippet += t.t
if snippet.length >= tweetLength
snippet = snippet.substr(0, tweetLength-3)
snippet += "...#{twhashtag}"
else
snippet += " #{twhashtag}"
window.open("https://twitter.com/intent/tweet?source=tw&text=#{encodeURIComponent(snippet)}&url=#{encodeURIComponent(twUrl)}", 'Twitter', "width=640,height=290,left=#{e.screenX-630},top=#{e.screenY},scrollbars=no")
return false
_shareButtonHandler: (e) =>
waveUrl = @_sharePopup.find('.js-wave-url')
if @_sharePopup.is(':visible')
return @_sharePopup.hide()
@_sharePopup.show()
_gaq.push(['_trackEvent', 'Topic sharing', 'Topic sharing manage'])
waveUrl.select()
waveUrl.on 'mousedown', =>
waveUrl.select()
# Обработчик на закрывание устанавливается с задержкой, чтобы не обработать
# текущий клик
window.setTimeout =>
$(document).on 'click.shareWaveBlock', (e) =>
if $(e.target).closest('.js-share-window, .js-role-selector-popup').length == 0
@_sharePopup.hide()
$(document).off('click.shareWaveBlock')
true
, 0
#эта проверка нужна в ff, без нее не прячутся панели
@_checkRange()
_handleGDriveViewShareButton: (e) =>
menu = @_shareContainer.find('.js-gdrive-share-menu')
if menu.is(':visible')
return menu.hide()
menu.show()
window.setTimeout =>
$(document).on 'click.gDriveShareMenu', (e) =>
if $(e.target).closest('.js-gdrive-share-menu').length == 0
menu.hide()
$(document).off('click.gDriveShareMenu')
true
, 0
#эта проверка нужна в ff, без нее не прячутся панели
@_checkRange()
_initWaveShareMenu: ->
###
Инициализирует меню расшаривания волны
###
return if @_isAnonymous
@_shareContainer = $(@_waveHeader).find('.js-share-container')
@_shareButton = @_shareContainer.find('.js-show-share-button')
@_sharePopup = @_shareContainer.find('.js-share-window')
if History.isGDrive()
menu = @_shareContainer.find('.js-gdrive-share-menu')
menu.on 'click', 'a.js-btn', (e) ->
e.preventDefault()
menu.hide()
$(document).off('click.gDriveShareMenu')
@_shareButton.on('click', @_handleGDriveViewShareButton)
@_shareContainer.find('.js-share-window-button').on('click', @_shareButtonHandler)
else
@_shareButton.on('click', @_shareButtonHandler)
if not BrowserSupport.isSupported() or !window.loggedIn
###
Не авторизованные пользователи или пользователи
не под Chrome не могут расшарить волну
###
@_shareButton.attr('disabled', 'disabled')
$c = $(@container)
@_byLinkRoleId = ROLE_EDITOR
@_publicRoleId = ROLE_COMMENTATOR
@_isPrivateButton = DOM.findAndBind $c, '.js-is-private-button', 'change', =>
@setSharedState(WAVE_SHARED_STATE_PRIVATE) if @_isPrivateButton.checked
@_isByLinkButton = DOM.findAndBind $c, '.js-by-link-button', 'change', =>
@setSharedState(WAVE_SHARED_STATE_LINK_PUBLIC, @_byLinkRoleId) if @_isByLinkButton.checked
@_isPublicButton = DOM.findAndBind $c, '.js-is-public-button', 'change', =>
@setSharedState(WAVE_SHARED_STATE_PUBLIC, @_publicRoleId) if @_isPublicButton.checked
@_sharedRoleSelect = $(@_sharePopup).find('.js-shared-role-select')[0]
setPopup = (node, getRole, setRole) =>
$(node).click (event) =>
return if not @_canChangeTopicShare
popup.hide()
popup.render(new RoleSelectPopup(DEFAULT_ROLES, getRole, setRole), event.target)
popup.show()
return false
getRole = => @_byLinkRoleId
setRole = (roleId) =>
@_byLinkRoleId = roleId
popup.hide()
@setSharedState(WAVE_SHARED_STATE_LINK_PUBLIC, @_byLinkRoleId)
setPopup(@_sharedRoleSelect, getRole, setRole)
getRole = => @_publicRoleId
setRole = (roleId) =>
@_publicRoleId = roleId
popup.hide()
@setSharedState(WAVE_SHARED_STATE_PUBLIC, @_publicRoleId)
@_publicRoleSelect = $(@_sharePopup).find('.js-public-role-select')[0]
for [roleId, roleName] in DEFAULT_ROLES
$(@_publicRoleSelect).text(roleName) if roleId is @_publicRoleId
setPopup(@_publicRoleSelect, getRole, setRole)
@_initSocialShareButtons()
@updatePublicState()
_disableSocialButtons: ->
@_socialOverlay.addClass('social-overlay')
@_facebookButton.attr('disabled', 'disabled')
@_twitterButton.attr('disabled', 'disabled')
@_googleButton.attr('disabled', 'disabled')
_enableSocialButtons: ->
@_socialOverlay.removeClass('social-overlay')
@_facebookButton.removeAttr('disabled')
@_twitterButton.removeAttr('disabled')
@_googleButton.removeAttr('disabled')
_setShareContainerClass: (className) ->
$(@_shareContainer).removeClass('private')
$(@_shareContainer).removeClass('public')
$(@_shareContainer).removeClass('shared')
$(@_shareContainer).addClass(className)
_setDefaultRoleId: (element, roleId) ->
for [id, name] in DEFAULT_ROLES
continue if roleId isnt id
$(element).text(name)
__scrollToBlipContainer: (blipContainer) ->
DOM.scrollTargetIntoViewWithAnimation(blipContainer, @_waveBlips, yes, SCROLL_INTO_VIEW_OFFSET)
updatePublicState: (sharedState = @_model.getSharedState(), defaultRoleId = @_model.getDefaultRole()) ->
###
Устанавливает состояние переключателя публичности волны
@param isPublic: boolean
@param defaultRoleId: int
###
return if not window.loggedIn
if sharedState == WAVE_SHARED_STATE_LINK_PUBLIC
@_isByLinkButton.checked = true
@_setDefaultRoleId(@_sharedRoleSelect, defaultRoleId)
@_byLinkRoleId = defaultRoleId
@_setShareContainerClass('shared')
@_enableSocialButtons()
@_shareButton.attr('title', "Topic is shared by link, click to change")
@_participants.showCreateTopicForSelectedButton()
else if sharedState == WAVE_SHARED_STATE_PRIVATE
@_isPrivateButton.checked = true
@_setShareContainerClass('private')
@_disableSocialButtons()
@_shareButton.attr('title', "Topic is private, click to change")
@_participants.showCreateTopicForSelectedButton()
else
@_isPublicButton.checked = true
@_setDefaultRoleId(@_publicRoleSelect, defaultRoleId)
@_publicRoleId = defaultRoleId
@_setShareContainerClass('public')
@_enableSocialButtons()
@_shareButton.attr('title', "Topic is public, click to change")
@_participants.hideCreateTopicForSelectedButton()
@_shareContainerWidth = $(@_shareContainer).width() +
parseInt($(@_shareContainer).css('margin-left')) +
parseInt($(@_shareContainer).css('margin-right'))
return if @_waveViewModel.getRole() in [ROLE_OWNER, ROLE_EDITOR]
@_updateParticipantsManagement()
setSharedState: (sharedState, defaultRole=1) ->
###
Устанавливает публичность волны
Обновляет кнопку в интерфейсе и отправляет команду серверу при необходимости
@param isPublic: boolean
@param defaultRole: int
###
@updatePublicState(sharedState, defaultRole)
@_waveProcessor.setWaveShareState @_model.serverId, sharedState, defaultRole, (err) =>
if @_isPublicButton.checked
_gaq.push(['_trackEvent', 'Topic sharing', 'Set topic public'])
else if @_isPrivateButton.checked
_gaq.push(['_trackEvent', 'Topic sharing', 'Set topic private'])
else
_gaq.push(['_trackEvent', 'Topic sharing', 'Set topic shared'])
return if not err
@_waveViewModel.showWarning(err.message)
@updatePublicState()
_initParticipants: (waveViewModel, participants) ->
###
Инициализирует панель с участниками волны
@param participants: array, часть ShareJS-документа, отвечающего за участников
###
@_participants = new Participants(waveViewModel, @_waveProcessor, @_model.serverId,
participants, yes, @_model.getGDriveShareUrl())
$(@container).find('.js-wave-participants').append(@_participants.getContainer())
@_excludeParticipantsWidth = 0
headerChildren = $(@_waveHeader).children()
for child in headerChildren
if $(child).hasClass('js-wave-participants') or $(child).hasClass('clearer') or not $(child).is(':visible')
continue
@_excludeParticipantsWidth += $(child).outerWidth(true)
@_setParticipantsWidth()
$(window).on 'resize resizeTopicByResizer', @_setParticipantsWidth #resizeTopicByResizer срабатывает при изменении ширины ресайзером
getParticipantIds: ->
@_participants.all()
_setParticipantsWidth: () =>
if @_isAnonymous
participantsWidth = $(@container).find('.js-wave-participants').outerWidth()
else
headerInnerWidth = $(@_waveHeader).width() -
parseInt($(@_waveHeader).css('padding-left')) -
parseInt($(@_waveHeader).css('padding-right'))
participantsWidth = headerInnerWidth - @_excludeParticipantsWidth -
parseInt($($(@_waveHeader).find('.js-participant-container')[0]).css('margin-left')) -
parseInt($($(@_waveHeader).find('.js-participant-container')[0]).css('margin-right'))
participantsWidth -= @_reservedHeaderSpace
@_participants.setParticipantsWidth(participantsWidth)
_initEditingMenu: ->
###
Инициализирует меню редактирования волны
###
return if not @_editable
@_initEditingMenuKeyHandlers()
@_disableEditingButtons()
@_disableActiveBlipControls()
@_initActiveBlipControls()
_initActiveBlipControls: ->
###
Инициализирует кнопки вставки реплая или меншена в активный блиб
###
checkPermission = (callback) => (args...) =>
return false if @_activeBlipControlsEnabled is no
callback(args...)
activateButtons = (buttons) =>
for controlInfo in buttons
{className, handler} = controlInfo
controlInfo.$button = @_$activeBlipControls.find(className)
controlInfo.$button.mousedown(handler)
@_activeBlipControlButtons = [
{className: '.js-insert-reply', handler: checkPermission(@_eventHandler(@_insertBlipButtonClick))}
{className: '.js-insert-mention', handler: checkPermission(@_eventHandler(@_insertMention))}
{className: '.js-insert-tag', handler: checkPermission(@_eventHandler(@_insertTag))}
{className: '.js-insert-gadget', handler: checkPermission(@_eventHandler(@_showGadgetPopup))}
]
activateButtons(@_activeBlipControlButtons)
accountProcessor = require('../account_setup_wizard/processor').instance
businessButtons = [{className: '.js-insert-task', handler: checkPermission(@_eventHandler(@_insertTask))}]
if accountProcessor.isBusinessUser()
activateButtons(businessButtons)
@_activeBlipControlButtons.push(businessButtons[0])
else
$insertTaskBtn = @_$activeBlipControls.find('.js-insert-task').hide()
businessChangeCallback = (isBusiness) =>
return unless isBusiness
return unless @_activeBlipControlButtons
$insertTaskBtn.show()
accountProcessor.removeListener('is-business-change', businessChangeCallback)
activateButtons(businessButtons)
@_activeBlipControlButtons.push(businessButtons[0])
accountProcessor.on('is-business-change', businessChangeCallback)
_deinitActiveBlipControls: ->
for {$button, handler} in @_activeBlipControlButtons
$button?.off('mousedown', handler)
delete @_activeBlipControlButtons
_initEditingMenuKeyHandlers: ->
###
Инициализирует обработчики нажатий на клавиши в топике
###
@_ctrlHandlers =
65: @_selectAll # A
69: @_changeBlipEditMode # e
@_globalCtrlHandlers =
32: @_goToUnread # Space
@_ctrlShiftHandlers =
38: @_foldChildBlips # Up arrow
40: @_unfoldChildBlips # Down arrow
@_shiftHandlers =
13: @_setBlipReadMode # Enter
@_ctrlRepeats = {}
@blipNode.addEventListener('keydown', @_preProcessKeyDownEvent, true)
@blipNode.addEventListener('keypress', @_processFFEnterKeypress, true) if BrowserSupport.isMozilla()
@_globalKeyHandler = (e) =>
return if not (e.ctrlKey or e.metaKey)
@_processKeyDownEvent(@_globalCtrlHandlers, e)
window.addEventListener('keydown', @_globalKeyHandler, true)
@blipNode.addEventListener('keyup', @_processBlipKeyUpEvent, true)
@blipNode.addEventListener('click', @_processClickEvent, false) if BrowserSupport.isSupported()
_changeBlipEditMode: =>
blip = @_getBlipAndRange()[0]
return if not blip
blip.setEditable(!@_inEditMode)
_processFFEnterKeypress: (e) =>
# превентим keypress у Enter для ff, чтобы при завершении
# режима редактирования по Shift+Enter не создавался новый блип
return if e.keyCode != 13 or !e.shiftKey
e.stopPropagation()
_setBlipReadMode: (e) =>
blip = @_getBlipAndRange()[0]
return if not blip
blip.setEditable(no)
_initRootBlip: (waveViewModel) ->
###
Инициализирует корневой блип
###
processor = require('../blip/processor').instance
processor.openBlip waveViewModel, @_model.getContainerBlipId(), @blipNode, null, (err, @rootBlip) =>
return @_waveProcessor.showPageError(err) if err
@_initRangeChangeEvent()
@on 'range-change', (range, blip) =>
if blip
@markActiveBlip(blip)
_disableEditingButtons: -> @_editingButtonsEnabled = no
_enableEditingButtons: -> @_editingButtonsEnabled = yes
_disableActiveBlipControls: ->
return if not @_editable
return if @_activeBlipControlsEnabled is no
@_activeBlipControlsEnabled = no
@_hideGadgetPopup()
@_$activeBlipControls.addClass('unvisible')
enableActiveBlipControls: ->
# Показ меню делаем на следующей итерации, чтобы меню сначала спряталось
# остальными топиками, а затем показалось этим
window.setTimeout =>
return if @_activeBlipControlsEnabled is yes
@_activeBlipControlsEnabled = yes
@_$activeBlipControls.removeClass('unvisible')
, 0
cursorIsInText: -> @_editingButtonsEnabled
_checkChangedRange: (range, blipView) ->
if range
DOM.addClass(@container, 'has-cursor')
else
DOM.removeClass(@container, 'has-cursor')
if range and blipView.getPermission() in [EDIT_PERMISSION, COMMENT_PERMISSION]
if @_inEditMode
@enableActiveBlipControls()
else
@_disableActiveBlipControls()
if blipView.getPermission() is EDIT_PERMISSION
@_enableEditingButtons()
else
@_disableEditingButtons()
else
@_disableEditingButtons()
@_disableActiveBlipControls()
if blipView is @_lastBlip
return if range is @_lastRange
return if range and @_lastRange and
range.compareBoundaryPoints(Range.START_TO_START, @_lastRange) is 0 and
range.compareBoundaryPoints(Range.END_TO_END, @_lastRange) is 0
@_lastRange = range
@_lastRange = @_lastRange.cloneRange() if @_lastRange
@_lastBlip = blipView
@emit('range-change', @_lastRange, blipView)
_checkRange: =>
###
Проверяет положение курсора и генерирует событие изменения положения
курсора при необходимости
###
params = @_getBlipAndRange()
if params
@_checkChangedRange(params[1], params[0])
else
@_checkChangedRange(null, null)
runCheckRange: =>
window.setTimeout =>
@_checkRange()
, 0
_windowCheckCusor: (e) =>
window.setTimeout =>
return unless @rootBlip
params = @_getBlipAndRange()
if params
@_checkChangedRange(params[1], params[0])
else
blip = @rootBlip.getView().getBlipContainingElement(e.target)
@_checkChangedRange(null, blip)
, 0
_initRangeChangeEvent: ->
###
Инициализирует событие "изменение курсора"
###
@_lastRange = null
@_lastBlip = null
window.addEventListener('keydown', @runCheckRange, false)
window.addEventListener('mousedown', @_windowCheckCusor, no)
window.addEventListener('mouseup', @_windowCheckCusor, no)
_eventHandler: (func) ->
###
Возвращает функцию, которая остановит событие и вызовет переданную
@param func: function
@return: function
function(event)
###
(event) ->
event.preventDefault()
event.stopPropagation()
func(event)
_createDOM: () ->
###
Создает DOM для отображения документа
###
c = $(@container)
BrowserEvents.addPropagationBlocker(@container, BrowserEvents.DOM_NODE_INSERTED) # TODO: find better place
c.empty()
waveParams =
url: @getUrl()
editable: @_editable
isAnonymous: @_isAnonymous
gDriveShareUrl: @_model.getGDriveShareUrl()
isGDriveView: History.isGDrive()
c.append renderWave(waveParams)
@_waveContent = $(@container).find('.js-wave-content')[0]
@_waveBlips = $(@container).find('.js-wave-blips')[0]
@_$activeBlipControls = $('.js-right-tools-panel .js-active-blip-controls')
@blipNode = $(@container).find('.js-container-blip')[0]
_initSettingsMenu: ->
menu = new SettingsMenu()
$settingsContainer = $(@container).find('.js-settings-container')
$settingsContainer.on BrowserEvents.C_READ_ALL_EVENT, =>
@emit(@constructor.Events.READ_ALL)
menu.render($settingsContainer[0],
topicId: @_waveViewModel.getServerId()
exportUrl: @getExportUrl()
embeddedUrl: @_getEmbeddedUrl()
)
_initAccountMenu: ->
menu = new AccountMenu()
menu.render($('.js-account-container')[0],
role: @_getRole()
)
markActiveBlip: (blip) =>
###
@param blip: BlipView
###
# TODO: work with BlipViewModel only
return blip.updateCursor() if @_activeBlip is blip
if @_activeBlip
@_activeBlip.clearCursor()
@_activeBlip.unmarkActive()
@_activeBlip = blip
@_activeBlip.setCursor()
@_activeBlip.markActive()
@_activeBlip.setReadState(true)
@_model.setActiveBlip(blip.getViewModel())
@_setOnScrollMenuPosition()
_resizerRepositionMenu: =>
RangeMenu.get().hide()
@_activeBlip?.updateMenuLeftPosition()
_setOnScrollMenuPosition: (e = false) =>
RangeMenu.get().hide()
@_activeBlip?.updateMenuPosition(e)
_isExistParticipant: (email) =>
participants = @_waveViewModel.getUsers(@_participants.all())
for p in participants
if p.getEmail() == email
return true
false
_processAddParticipantClick: =>
###
Обрабатывает нажатие на кнопку добавления участника
###
email = strip(@_$participantIdInput.val())
return if not email
if not isEmail(email)
return @_waveViewModel.showWarning("Enter valid e-mail")
if @_isExistParticipant(email)
@_waveViewModel.showWarning("Participant already added to topic")
@_$participantIdInput.select()
return
@_waveProcessor.addParticipant(@_model.serverId, email, @_addButtonRole, @_processAddParticipantResponse)
@_$participantIdInput.val('').focus()
_processAddParticipantResponse: (err, user) =>
###
Обрабатывает ответ сервера на добавление пользователя
@param err: object|null
###
return @_waveViewModel.showWarning(err.message) if err
$(@container).parent('.js-inner-wave-container').find('.js-wave-notifications .js-wave-warning').remove()
trackParticipantAddition('By email field', user)
@_waveViewModel.updateUserInfo(user)
@_waveProcessor.addOrUpdateContact(user)
@_addParticipantForm?.restartAutocompleter()
_expandCrossedBlipRange: (range, blipViewStart, blipViewEnd, directionForward) ->
if blipViewEnd
start = []
end = []
startView = blipViewStart
while startView
start.push(startView)
startView = startView.getParent()
endView = blipViewEnd
while endView
end.push(endView)
endView = endView.getParent()
while (startView = start.pop()) is (endView = end.pop())
commonView = startView
if startView
startThread = BlipThread.getBlipThread(startView.getContainer())
startViewContainer = startThread.getContainer()
range.setStartBefore(startViewContainer)
if @_lastRange
if range.compareBoundaryPoints(Range.START_TO_START, @_lastRange) > -1
range.setStartAfter(startViewContainer)
if endView
endThread = BlipThread.getBlipThread(endView.getContainer())
endViewContainer = endThread.getContainer()
range.setEndAfter(endViewContainer)
if @_lastRange
if range.compareBoundaryPoints(Range.END_TO_END, @_lastRange) < 1
range.setEndBefore(endViewContainer)
else
el = blipViewStart.getEditor()?.getContainer()
commonView = blipViewStart
range.setEnd(el, el.childNodes.length) if el
DOM.setRange(range, directionForward)
commonView?.getEditor().focus()
return [commonView, range]
_getBlipAndRange: ->
###
Возвращает текущее выделение и блип, в котором оно сделано
@return: [BlipView, DOM range]|null
###
return null if not @rootBlip
selection = window.getSelection()
return if not selection or not selection.rangeCount
range = selection.getRangeAt(0)
return null if not range
cursor = [range.startContainer, range.startOffset]
blipViewStart = @rootBlip.getView().getBlipContainingCursor(cursor)
directionForward = if selection.anchorNode is range.startContainer and selection.anchorOffset is range.startOffset then yes else no
unless blipViewStart
# selection.removeAllRanges()
return null
cursor = [range.endContainer, range.endOffset]
blipViewEnd = if range.collapsed then blipViewStart else @rootBlip.getView().getBlipContainingCursor(cursor)
if blipViewStart isnt blipViewEnd
return @_expandCrossedBlipRange(range, blipViewStart, blipViewEnd, directionForward)
else if blipViewStart isnt @_lastBlip
editor = blipViewStart.getEditor()
editor.focus()
return [blipViewStart, range]
# TODO: remove it
_createBlip: (forceCreate=false) ->
###
@param: forceCreate boolean
@return: BlipViewModel | undefined
###
opParams = @_getBlipAndRange()
return if not opParams
[blip] = opParams
if not @_inEditMode or forceCreate
blipViewModel = blip.initInsertInlineBlip()
return if not blipViewModel
return blipViewModel
_insertBlipButtonClick: =>
blipViewModel = @_createBlip(true)
return if not blipViewModel
_gaq.push(['_trackEvent', 'Blip usage', 'Insert reply', 'Re in editing menu'])
_insertMention: =>
blipViewModel = @_createBlip()
blipView = if not blipViewModel then @_activeBlip else blipViewModel.getView()
return if not blipView
setTimeout ->
recipientInput = blipView.getEditor().insertRecipient()
recipientInput?.insertionEventLabel = 'Menu button'
, 0
_insertTag: =>
blipViewModel = @_createBlip()
blipView = if not blipViewModel then @_activeBlip else blipViewModel.getView()
return if not blipView
setTimeout ->
tagInput = blipView.getEditor().insertTag()
tagInput?.insertionEventLabel = 'Menu button'
, 0
_insertTask: =>
blipViewModel = @_createBlip()
blipView = if not blipViewModel then @_activeBlip else blipViewModel.getView()
return if not blipView
setTimeout ->
taskInput = blipView.getEditor().insertTaskRecipient()
taskInput?.insertionEventLabel = 'Menu button'
, 0
_showGadgetPopup: (event) =>
if event.ctrlKey and event.shiftKey
@_insertGadget()
else
gadgetPopup = @getInsertGadgetPopup()
if gadgetPopup.isVisible()
@_hideGadgetPopup()
else
gadgetPopup.show(@getActiveBlip())
gadgetPopup.shownAt = Date.now()
_hideGadgetPopup: ->
gadgetPopup = @getInsertGadgetPopup()
return if not gadgetPopup?
shouldHide = true
if gadgetPopup.shownAt?
timeDiff = Date.now() - gadgetPopup.shownAt
shouldHide = timeDiff > 100
# Не скрываем popup, если после открытия прошло меньше 100 мс. Нужно, чтобы несколько топиков не
# мешали друг другу
gadgetPopup.hide() if shouldHide
getInsertGadgetPopup: ->
if not @_insertGadgetPopup and @_activeBlipControlButtons
for control in @_activeBlipControlButtons when control.className is '.js-insert-gadget'
@_insertGadgetPopup = control.$button[0].insertGadgetPopup
return @_insertGadgetPopup
_insertGadget: =>
opParams = @_getBlipAndRange()
return if not opParams
[blip, range] = opParams
blip.initInsertGadget()
_foldChildBlips: =>
###
Сворачивает все блипы, вложенные в текщуий
###
@_ctrlRepeats.foldChildBlips ?= 0
if @_ctrlRepeats.foldChildBlips
blip = @rootBlip.getView()
blip.foldAllChildBlips()
blip.setCursorToStart()
@_checkRange()
else
r = @_getBlipAndRange()
return if not r
[blip] = r
blip.foldAllChildBlips()
if blip is @rootBlip.getView()
_gaq.push(['_trackEvent', 'Blip usage', 'Hide replies', 'Root shortcut'])
else
_gaq.push(['_trackEvent', 'Blip usage', 'Hide replies', 'Reply shortcut'])
@_ctrlRepeats.foldChildBlips++
_unfoldChildBlips: =>
###
Разворачивает все блипы, вложенные в текщуий
###
@_ctrlRepeats.foldChildBlips = 0
r = @_getBlipAndRange()
return if not r
[blip] = r
if blip is @rootBlip.getView()
_gaq.push(['_trackEvent', 'Blip usage', 'Show replies', 'Root shortcut'])
else
_gaq.push(['_trackEvent', 'Blip usage', 'Show replies', 'Reply shortcut'])
blip.unfoldAllChildBlips()
_selectAll: =>
###
Выделяет все содержимое блипа, при двукратном нажатии - все содержимое корневого тредового блипа
###
@_ctrlRepeats.selectAll ?= 0
if @_ctrlRepeats.selectAll
blips = @rootBlip.getView().getChildBlips()
blip = null
r = DOM.getRange()
return if not r
node = r.startContainer
for own _, b of blips
bView = b.getView()
bContainer = bView.getContainer()
if DOM.contains(bContainer, node) or bContainer is node
blip = bView
break
return if not blip
else
r = @_getBlipAndRange()
return if not r
[blip] = r
@_ctrlRepeats.selectAll++
range = blip.selectAll()
@_checkChangedRange(range, blip)
_goToUnread: =>
###
Переводит фокус на первый непрочитаный блип,
расположенный после блипа под фокусом
###
return if @_curView isnt 'text'
@emit('goToNextUnread')
getActiveBlip: ->
#TODO: hack activeBlip
@_activeBlip.getViewModel()
getRootBlip: ->
@rootBlip
updateRangePos: ->
@_setOrUpdateRangeMenuPos(yes)
_setOrUpdateRangeMenuPos: (update) ->
menu = RangeMenu.get()
return menu.hide() if not @_lastBlip or not @_lastRange
return menu.hide() unless BrowserSupport.isSupported()
if update
@_lastBlip.updateRangeMenuPosByRange(@_lastRange, @container)
else
@_lastBlip.setRangeMenuPosByRange(@_lastRange, @container)
_preProcessKeyDownEvent: (e) =>
if e.ctrlKey or e.metaKey
handlers = @_ctrlHandlers
if e.shiftKey
handlers = @_ctrlShiftHandlers
else if e.shiftKey
handlers = @_shiftHandlers
@_processKeyDownEvent(handlers, e)
_processKeyDownEvent: (handlers, e) =>
###
Обрабатывает нажатия клавиш внутри блипов
@param e: DOM event
###
return if ((not (e.ctrlKey or e.metaKey)) and (not e.shiftKey)) or e.altKey
return if not (e.keyCode of handlers)
handlers[e.keyCode]()
e.preventDefault()
e.stopPropagation()
_processBlipKeyUpEvent: (e) =>
###
Обрабатывает отпускание клавиш внутри блипов
@param e: DOM event
###
return if e.which != 17 or e.keyCode != 17
# Обрабатываем только отпускание ctrl
@_ctrlRepeats = {}
_removeAutocompleter: ->
@_autoCompleter?.deactivate()
@_autoCompleter?.dom.$results.remove()
delete @_autoCompleter
_processClickEvent: =>
@_setOrUpdateRangeMenuPos(no)
destroy: ->
super()
# TODO: move it to another function
delete @_ctrlHandlers
delete @_ctrlShiftHandlers
delete @_shiftHandlers
delete @_globalCtrlHandlers
window.removeEventListener 'keydown', @_globalKeyHandler, true
delete @_globalKeyHandler
LocalStorage.removeListener('buffer', @_handleBufferUpdate)
@_closed = true
@_$addButtonSelect?.selectBox('destroy')
@_addParticipantForm?.destroy()
delete @_insertGadgetPopup
@_participants.destroy()
delete @_participants
@_destroySavingMessage()
require('../editor/file/upload_form').removeInstance()
@removeListeners('range-change')
@removeAllListeners()
$(@_waveBlips).off 'scroll'
$(window).off('scroll', @_setOnScrollMenuPosition)
@blipNode.removeEventListener 'keydown', @_preProcessKeyDownEvent, true
@blipNode.removeEventListener('keypress', @_processFFEnterKeypress, true) if BrowserSupport.isMozilla()
@blipNode.removeEventListener 'keyup', @_processBlipKeyUpEvent, true
@blipNode.removeEventListener('click', @_processClickEvent, false)
delete @blipNode
window.removeEventListener 'keydown', @runCheckRange, false
window.removeEventListener('mousedown', @_windowCheckCusor, no)
window.removeEventListener('mouseup', @_windowCheckCusor, no)
$wnd = $(window)
$wnd.off('resize resizeTopicByResizer', @_setParticipantsWidth)
$wnd.off('resize resizeTopicByResizer', @_resizerRepositionMenu)
@_destroyMindmap()
@_removeAutocompleter()
$(@container).empty().unbind()
@_disableActiveBlipControls()
@_deinitActiveBlipControls()
delete @rootBlip
delete @_activeBlip if @_activeBlip
delete @_editingBlip if @_editingBlip
delete @_lastBlip if @_lastBlip
delete @_lastEditableBlip if @_lastEditableBlip
@_destroyDragScroll()
@container = undefined
delete @_model
delete @_waveViewModel
# hack - clean jQuery's cached fragments
jQuery.fragments = {}
applyParticipantOp: (op) ->
@_participants.applyOp(op)
return if not window.loggedIn
isMyOp = op.ld?.id is window.userInfo.id or op.li?.id is window.userInfo.id
return if not isMyOp
@updateInterfaceAccordingToRole()
updateInterfaceAccordingToRole: ->
@_waveViewModel.updateParticipants()
@_updateParticipantsManagement()
@rootBlip.getView().recursivelyUpdatePermission()
@_updateReplyButtonState()
_updateReplyButtonState: ->
###
Ставится или снимается класс, прячущий кнопки реплаев
###
if @_waveViewModel.getRole() in [ROLE_OWNER, ROLE_EDITOR, ROLE_COMMENTATOR]
$(@container).removeClass('read-only')
@_canReply = true
else
$(@container).addClass('read-only')
@_canReply = false
_updateParticipantsManagement: ->
###
Приводит окна управления пользователей в состояние, соответствующее текущим правам
###
@_updateParticipantAddition()
@_updateWaveSharing()
_updateParticipantAddition: ->
myRole = @_waveViewModel.getRole()
if myRole is ROLE_NO_ROLE
@_$addButton?.attr('disabled', 'disabled')
else
@_$addButton?.removeAttr('disabled')
if @_model.getSharedState() is WAVE_SHARED_STATE_PRIVATE
defaultRole = myRole
defaultRole = ROLE_EDITOR if defaultRole is ROLE_OWNER
@_addButtonRole = defaultRole
@_$addButtonSelect?.selectBox('value', defaultRole)
else
@_addButtonRole = @_model.getDefaultRole()
@_$addButtonSelect?.selectBox('value', @_model.getDefaultRole())
if (myRole in [ROLE_OWNER, ROLE_EDITOR])
@_$addButtonSelect?.selectBox('enable')
else
@_$addButtonSelect?.selectBox('disable')
_updateWaveSharing: ->
if (@_waveViewModel.getRole() in [ROLE_OWNER, ROLE_EDITOR])
$([@_isPrivateButton, @_isByLinkButton, @_isPublicButton]).removeAttr('disabled')
$([@_publicRoleSelect, @_sharedRoleSelect]).removeClass('disabled')
@_canChangeTopicShare = true
else
$([@_isPrivateButton, @_isByLinkButton, @_isPublicButton]).attr('disabled', 'disabled') if @_isPrivateButton or @_isByLinkButton or @_isPublicButton
$([@_publicRoleSelect, @_sharedRoleSelect]).addClass('disabled') if @_publicRoleSelect or @_sharedRoleSelect
@_canChangeTopicShare = false
isExistParticipant: (email) ->
@_isExistParticipant(email)
processAddParticipantResponse: (err, user) =>
@_processAddParticipantResponse(err, user)
getUrl: ->
###
Возвращает ссылку, соответствующую волне
@return: string
###
return "#{document.location.protocol}//#{window.HOST + History.getWavePrefix()}#{@_model.serverId}/"
getExportUrl: ->
return "/api/export/1/#{@_model.serverId}/html/"
_getEmbeddedUrl: ->
"#{document.location.protocol}//#{window.HOST + History.getEmbeddedPrefix()}#{@_model.serverId}/"
getSocialSharingUrl: ->
###
Возвращает ссылку для шаринга волны в соцсетях
@return: string
###
return document.location.protocol + '//' +
window.HOST +
window.socialSharingConf.url +
@_model.serverId +
@_model.socialSharingUrl.substr(0, window.socialSharingConf.signLength) +
"/#{randomString(2)}"
_initTips: ->
@_$topicTipsContainer = $(@container).find('.js-topic-tip')
@_$topicTipsContainer.find('.js-hide-topic-tip').click(@_hideTip)
@_$topicTipsContainer.find('.js-next-tip').click(@_showNextTip)
_tipIsHidden: ->
return true if not LocalStorage.loginCountIsMoreThanTwo()
lastHiddenDate = LocalStorage.getLastHiddenTipDate() - 0
return @_lastTipDate <= lastHiddenDate
showTip: (text, @_lastTipDate, force=false) ->
return if not force and @_tipIsHidden()
LocalStorage.removeLastHiddenTipDate() if force
$textContainer = @_$topicTipsContainer.find('.js-topic-tip-text')
$textContainer.html(text).find('a').attr('target', '_blank')
$textContainer.attr('title', $textContainer.text())
$(@container).addClass('tip-shown')
_hideTip: =>
_gaq.push(['_trackEvent', 'Tips', 'Close tip'])
LocalStorage.setLastHiddenTipDate(@_lastTipDate)
$(@container).removeClass('tip-shown')
_showNextTip: =>
_gaq.push(['_trackEvent', 'Tips', 'Show next tip'])
@_waveProcessor.showNextTip()
setTextView: =>
return if @_curView is 'text'
@_curView = 'text'
$(@_waveContent).removeClass('mindmap-view')
@emit('wave-view-change')
setMindmapView: =>
return if @_curView is 'mindmap'
@_curView = 'mindmap'
$(@_waveContent).addClass('mindmap-view')
_gaq.push(['_trackEvent', 'Topic content', 'Switch to mindmap'])
if not @_mindmap?
@_initMindmap()
else
@_mindmap.update()
@emit('wave-view-change')
setShortMindmapView: =>
@_mindmap?.setShortMode()
setLongMindmapView: =>
@_mindmap?.setLongMode()
getCurView: -> @_curView
getScrollableElement: -> @_waveBlips
_initMindmap: ->
@_mindmap = new MindMap(@_waveViewModel)
mindMapContainer = $(@container).find('.js-topic-mindmap-container')[0]
@_mindmap.render(mindMapContainer)
_destroyMindmap: ->
@_mindmap?.destroy()
delete @_mindmap
_initDragScroll: ->
@_resetDragScrollVars()
@container.addEventListener('dragenter', @_handleContainerDragEnterEvent, no)
@container.addEventListener('dragleave', @_handleContainerDragLeaveEvent, no)
@container.addEventListener('drop', @_handleContainerDropEvent, no)
for el in @container.getElementsByClassName('js-scroll')
el.addEventListener('dragenter', @_handleScrollDragEnterEvent, no)
el.addEventListener('dragleave', @_handleScrollDragLeaveEvent, no)
@_scrollUpEl = @container.getElementsByClassName('js-scroll-up')[0]
@_scrollDownEl = @container.getElementsByClassName('js-scroll-down')[0]
_destroyDragScroll: ->
@_resetDragScrollVars()
@container.removeEventListener('dragenter', @_handleContainerDragEnterEvent, no)
@container.removeEventListener('dragleave', @_handleContainerDragLeaveEvent, no)
@container.removeEventListener('drop', @_handleContainerDropEvent, no)
for el in @container.getElementsByClassName('js-scroll')
el.removeEventListener('dragenter', @_handleScrollDragEnterEvent, no)
el.removeEventListener('dragleave', @_handleScrollDragLeaveEvent, no)
@_handleContainerDragEnterEvent = undefined
@_handleContainerDragLeaveEvent = undefined
@_handleContainerDropEvent = undefined
@_handleScrollDragEnterEvent = undefined
@_handleScrollDragLeaveEvent = undefined
@_doScrollOnDrag = undefined
@_scrollUpEl = undefined
@_scrollDownEl = undefined
_handleContainerDragEnterEvent: =>
@_dragCount++
@_updateDragState()
_handleContainerDragLeaveEvent: =>
@_dragCount--
@_updateDragState()
_handleContainerDropEvent: =>
@_resetDragScrollVars()
@_updateDragState()
_handleScrollDragEnterEvent: (e) =>
@_lastDraggedOverClass = e.target.className
@_dragScrollAmount = parseInt(e.target.getAttribute('offset')) || 0
@_setDragScrollInterval() if @_dragScrollAmount
_handleScrollDragLeaveEvent: (e) =>
if e.target.className is @_lastDraggedOverClass
@_lastDraggedOverClass = ''
@_clearDragScrollInterval()
_resetDragScrollVars: ->
@_clearDragScrollInterval()
@_dragScrollAmount = 0
@_dragCount = 0
@_lastDraggedOverClass = ''
_setDragScrollInterval: ->
@_clearDragScrollInterval()
@_dragScrollIntervalId = setInterval(@_doScrollOnDrag, 100)
_doScrollOnDrag: =>
scrollTop = @_waveBlips.scrollTop
scrollHeight = @_waveBlips.scrollHeight
height = @_waveBlips.offsetHeight
if scrollTop + @_dragScrollAmount <= 0
@_waveBlips.scrollTop = 0
@_clearDragScrollInterval()
return @_updateDragState()
if scrollTop + height + @_dragScrollAmount >= scrollHeight
@_waveBlips.scrollTop = scrollHeight - height
@_clearDragScrollInterval()
return @_updateDragState()
@_waveBlips.scrollTop += @_dragScrollAmount
_clearDragScrollInterval: ->
return unless @_dragScrollIntervalId
@_dragScrollIntervalId = clearInterval(@_dragScrollIntervalId)
_updateTopScrollArea: (show) ->
if show
@_scrollUpEl.style.display = 'block'
else
@_scrollUpEl.style.display = 'none'
_updateBottomScrollArea: (show) ->
if show
@_scrollDownEl.style.display = 'block'
else
@_scrollDownEl.style.display = 'none'
_showScrollableAreas: ->
height = @_waveBlips.offsetHeight
scrollHeight = @_waveBlips.scrollHeight
return @_hideScrollableAreas() if height is scrollHeight
scrollTop = @_waveBlips.scrollTop
unless scrollTop
@_updateTopScrollArea(no)
else
@_updateTopScrollArea(yes)
if scrollTop + height >= scrollHeight
@_updateBottomScrollArea(no)
else
@_updateBottomScrollArea(yes)
_hideScrollableAreas: ->
@_updateTopScrollArea(no)
@_updateBottomScrollArea(no)
_updateDragState: ->
if @_dragCount
@_showScrollableAreas()
else
@_hideScrollableAreas()
_initSavingMessage: ->
@_savingMessage = new SavingMessageView()
@_savingMessage.init(@_waveViewModel.getId(), @_waveHeader)
_destroySavingMessage: ->
@_savingMessage?.destroy()
delete @_savingMessage
_setEditMode: (@_inEditMode) ->
cl = 'wave-edit-mode'
if @_inEditMode then DOM.addClass(@_container, cl) else DOM.removeClass(@_container, cl)
@_checkChangedRange(@_lastRange, @_lastBlip) # show/hide controls # TODO: is it good?
hasCursor: ->
DOM.hasClass(@container, 'has-cursor')
setEditModeEnabled: (enabled) -> @_setEditMode(enabled)
isEditMode: -> @_inEditMode
getContainer: -> @container
foldAll: ->
if @_curView is 'text'
@rootBlip.getView().foldAllChildBlips()
else
@_mindmap.fold()
unfoldAll: ->
if @_curView is 'text'
@rootBlip.getView().unfoldAllChildBlips()
else
@_mindmap.unfold()
_initBuffer: ->
LocalStorage.on('buffer', @_handleBufferUpdate)
@_updateBufferPresenceMark(LocalStorage.hasBuffer())
_updateBufferPresenceMark: (hasBuffer) ->
if hasBuffer
$(@container).addClass('has-buffer')
else
$(@container).removeClass('has-buffer')
_handleBufferUpdate: (param) =>
@_updateBufferPresenceMark(param.newValue?)
setReservedHeaderSpace: (@_reservedHeaderSpace) ->
@_setParticipantsWidth()
class SavingMessageView
SAVE_TIME: 0.5
FADE_TIME: 120
constructor: ->
@_saveTimeout = null
@_fadeTimeout = null
_getMessages: ->
container = $(@_container)
return [container.find('.js-saving-message-saving'), container.find('.js-saving-message-saved')]
_onStartSend: (groupId) =>
return if groupId isnt @_waveId
[saving, saved] = @_getMessages()
saved.removeClass('visible')
saving.addClass('visible')
_onFinishSend: (groupId) =>
clearTimeout(@_saveTimeout) if @_saveTimeout
@_saveTimeout = setTimeout =>
return if groupId isnt @_waveId
[saving, saved] = @_getMessages()
saving.removeClass('visible')
saved.addClass('visible')
clearTimeout(@_fadeTimeout) if @_fadeTimeout
@_fadeTimeout = setTimeout ->
saved.removeClass('visible')
, @FADE_TIME * 1000
, @SAVE_TIME * 1000
init: (@_waveId, @_container) ->
processor = require('../ot/processor').instance
processor.on('start-send', @_onStartSend)
processor.on('finish-send', @_onFinishSend)
destroy: ->
processor = require('../ot/processor').instance
processor.removeListener('start-send', @_onStartSend)
processor.removeListener('finish-send', @_onFinishSend)
clearTimeout(@_saveTimeout)
clearTimeout(@_fadeTimeout)
module.exports = WaveView: WaveView
|
[
{
"context": "68d37'\n process.env.HUBOT_STATUS_PAGE_TOKEN = '89a229ce1a8dbcf9ff30430fbe35eb4c0426574bca932061892cefd2138aa4b1'\n room = helper.createRoom()\n nock.disableN",
"end": 429,
"score": 0.938030481338501,
"start": 365,
"tag": "KEY",
"value": "89a229ce1a8dbcf9ff30430fbe35eb4c0426574bca932061892cefd2138aa4b1"
},
{
"context": "'/fixtures/components.json')\n room.user.say 'alice', 'hubot statuspage?'\n setTimeout done, 100\n",
"end": 2217,
"score": 0.6918142437934875,
"start": 2212,
"tag": "USERNAME",
"value": "alice"
},
{
"context": ">\n expect(room.messages).to.eql [\n [ 'alice', 'hubot statuspage?' ]\n [ 'hubot', 'There",
"end": 2371,
"score": 0.4778847098350525,
"start": 2366,
"tag": "NAME",
"value": "alice"
},
{
"context": " '/fixtures/incidents.json')\n room.user.say 'alice', 'hubot statuspage incidents'\n setTimeout d",
"end": 2836,
"score": 0.6951594352722168,
"start": 2831,
"tag": "USERNAME",
"value": "alice"
},
{
"context": ">\n expect(room.messages).to.eql [\n [ 'alice', 'hubot statuspage incidents' ]\n [ 'hubot",
"end": 2998,
"score": 0.5633332133293152,
"start": 2993,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "/unresolved-incidents.json')\n room.user.say 'alice', 'hubot statuspage update monitoring We have dis",
"end": 3653,
"score": 0.9884238839149475,
"start": 3648,
"tag": "USERNAME",
"value": "alice"
},
{
"context": ">\n expect(room.messages).to.eql [\n [ 'alice', 'hubot statuspage update monitoring We have dis",
"end": 3857,
"score": 0.954371988773346,
"start": 3852,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "+ '/fixtures/incident.json')\n room.user.say 'alice', 'hubot statuspage update bd0b7yh8rkfz monitorin",
"end": 4466,
"score": 0.9784518480300903,
"start": 4461,
"tag": "USERNAME",
"value": "alice"
},
{
"context": ">\n expect(room.messages).to.eql [\n [ 'alice', 'hubot statuspage update bd0b7yh8rkfz monitorin",
"end": 4683,
"score": 0.9774227142333984,
"start": 4678,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "/unresolved-incidents.json')\n room.user.say 'alice', 'hubot statuspage open investigating System has",
"end": 5123,
"score": 0.8106561303138733,
"start": 5118,
"tag": "USERNAME",
"value": "alice"
},
{
"context": ">\n expect(room.messages).to.eql [\n [ 'alice', 'hubot statuspage open investigating System has",
"end": 5319,
"score": 0.7221158146858215,
"start": 5314,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "/unresolved-incidents.json')\n room.user.say 'alice', 'hubot statuspage open investigating System has",
"end": 5760,
"score": 0.8374826908111572,
"start": 5755,
"tag": "USERNAME",
"value": "alice"
},
{
"context": ">\n expect(room.messages).to.eql [\n [ 'alice', 'hubot statuspage open investigating System has",
"end": 5985,
"score": 0.6471127867698669,
"start": 5980,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "'/fixtures/components.json')\n room.user.say 'alice', 'hubot statuspage Backend major outage'\n s",
"end": 6435,
"score": 0.8570229411125183,
"start": 6430,
"tag": "USERNAME",
"value": "alice"
},
{
"context": ">\n expect(room.messages).to.eql [\n [ 'alice', 'hubot statuspage Backend major outage' ]\n ",
"end": 6605,
"score": 0.7616516351699829,
"start": 6600,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "'/fixtures/components.json')\n room.user.say 'alice', 'hubot statuspage Backend Database major outage",
"end": 7150,
"score": 0.9983077049255371,
"start": 7145,
"tag": "USERNAME",
"value": "alice"
},
{
"context": ">\n expect(room.messages).to.eql [\n [ 'alice', 'hubot statuspage Backend Database major outage",
"end": 7337,
"score": 0.9962097406387329,
"start": 7332,
"tag": "USERNAME",
"value": "alice"
}
] | test/statuspage_test.coffee | stephenyeargin/hubot-statuspage | 0 | Helper = require('hubot-test-helper')
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
nock = require('nock')
helper = new Helper('./../src/statuspage.coffee')
expect = chai.expect
describe 'statuspage', ->
room = null
beforeEach ->
process.env.HUBOT_STATUS_PAGE_ID = '63kbmt268d37'
process.env.HUBOT_STATUS_PAGE_TOKEN = '89a229ce1a8dbcf9ff30430fbe35eb4c0426574bca932061892cefd2138aa4b1'
room = helper.createRoom()
nock.disableNetConnect()
@robot =
respond: sinon.spy()
hear: sinon.spy()
require('../src/statuspage')(@robot)
afterEach ->
room.destroy()
nock.cleanAll()
delete process.env.HUBOT_STATUS_PAGE_ID
delete process.env.HUBOT_STATUS_PAGE_TOKEN
context 'ensure all listeners are registered', ->
it 'registers a respond listener for all incidents', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) incidents\??/i)
it 'registers a respond listener for update incident', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) update (investigating|identified|monitoring|resolved) (.+)/i)
it 'registers a respond listener for create new incident', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) open (investigating|identified|monitoring|resolved) ([^:]+)(: ?(.+))?/i)
it 'registers a respond listener for getting all component statuses', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage)\?$/i)
it 'registers a respond listener for getting single component status', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) ((?!(incidents|open|update|resolve|create))(\S ?)+)\?$/i)
it 'registers a respond listener for update component', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) ((\S ?)+) (major( outage)?|degraded( performance)?|partial( outage)?|operational)/i)
context 'show all component status', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/components.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
room.user.say 'alice', 'hubot statuspage?'
setTimeout done, 100
it 'responds with all component status', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage?' ]
[ 'hubot', 'There are currently 1 components in a degraded state' ]
[ 'hubot', "\nBroken Components:\n-------------\n"]
[ 'hubot', "Backend Database: degraded\n"]
]
context 'list incidents', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/incidents.json')
room.user.say 'alice', 'hubot statuspage incidents'
setTimeout done, 100
it 'responds with a list of incidents', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage incidents' ]
[ 'hubot', 'Unresolved incidents:']
[ 'hubot', 'Data Layer Migration (Status: scheduled, Created: 2020-08-14T16:11:34Z, ID: bd0b7yh8rkfz)']
]
context 'update most recent incident', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
nock('https://api.statuspage.io')
.patch('/v1/pages/63kbmt268d37/incidents/bd0b7yh8rkfz.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
room.user.say 'alice', 'hubot statuspage update monitoring We have dispatched an army to fix it.'
setTimeout done, 100
it 'updates the most recent issue', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage update monitoring We have dispatched an army to fix it.' ]
[ 'hubot', 'Updated incident "System has been invaded by Barbarians"']
]
context 'update specific incident', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
nock('https://api.statuspage.io')
.patch('/v1/pages/63kbmt268d37/incidents/bd0b7yh8rkfz.json')
.replyWithFile(200, __dirname + '/fixtures/incident.json')
room.user.say 'alice', 'hubot statuspage update bd0b7yh8rkfz monitoring We have dispatched an army to fix it.'
setTimeout done, 100
it 'updates the most recent issue', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage update bd0b7yh8rkfz monitoring We have dispatched an army to fix it.' ]
[ 'hubot', 'Updated incident "System has been invaded by Barbarians"']
]
context 'open new incident', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.post('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
room.user.say 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians'
setTimeout done, 100
it 'opens a new incident', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians' ]
[ 'hubot', 'Created incident "System has been invaded by Barbarians"']
]
context 'open new incident with message', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.post('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
room.user.say 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians:Send help fast!'
setTimeout done, 100
it 'opens a new incident with message', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians:Send help fast!' ]
[ 'hubot', 'Created incident "System has been invaded by Barbarians"']
]
context 'update component not found status', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/components.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
room.user.say 'alice', 'hubot statuspage Backend major outage'
setTimeout done, 100
it 'responds with an error message', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage Backend major outage' ]
[ 'hubot', 'Couldn\'t find a component named Backend']
]
context 'update component status', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/components.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
nock('https://api.statuspage.io')
.patch('/v1/pages/63kbmt268d37/components/string.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
room.user.say 'alice', 'hubot statuspage Backend Database major outage'
setTimeout done, 100
it 'responds with updated component status', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage Backend Database major outage' ]
[ 'hubot', 'Status for Backend Database is now major outage (was: degraded)']
]
| 4378 | Helper = require('hubot-test-helper')
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
nock = require('nock')
helper = new Helper('./../src/statuspage.coffee')
expect = chai.expect
describe 'statuspage', ->
room = null
beforeEach ->
process.env.HUBOT_STATUS_PAGE_ID = '63kbmt268d37'
process.env.HUBOT_STATUS_PAGE_TOKEN = '<KEY>'
room = helper.createRoom()
nock.disableNetConnect()
@robot =
respond: sinon.spy()
hear: sinon.spy()
require('../src/statuspage')(@robot)
afterEach ->
room.destroy()
nock.cleanAll()
delete process.env.HUBOT_STATUS_PAGE_ID
delete process.env.HUBOT_STATUS_PAGE_TOKEN
context 'ensure all listeners are registered', ->
it 'registers a respond listener for all incidents', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) incidents\??/i)
it 'registers a respond listener for update incident', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) update (investigating|identified|monitoring|resolved) (.+)/i)
it 'registers a respond listener for create new incident', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) open (investigating|identified|monitoring|resolved) ([^:]+)(: ?(.+))?/i)
it 'registers a respond listener for getting all component statuses', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage)\?$/i)
it 'registers a respond listener for getting single component status', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) ((?!(incidents|open|update|resolve|create))(\S ?)+)\?$/i)
it 'registers a respond listener for update component', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) ((\S ?)+) (major( outage)?|degraded( performance)?|partial( outage)?|operational)/i)
context 'show all component status', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/components.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
room.user.say 'alice', 'hubot statuspage?'
setTimeout done, 100
it 'responds with all component status', ->
expect(room.messages).to.eql [
[ '<NAME>', 'hubot statuspage?' ]
[ 'hubot', 'There are currently 1 components in a degraded state' ]
[ 'hubot', "\nBroken Components:\n-------------\n"]
[ 'hubot', "Backend Database: degraded\n"]
]
context 'list incidents', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/incidents.json')
room.user.say 'alice', 'hubot statuspage incidents'
setTimeout done, 100
it 'responds with a list of incidents', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage incidents' ]
[ 'hubot', 'Unresolved incidents:']
[ 'hubot', 'Data Layer Migration (Status: scheduled, Created: 2020-08-14T16:11:34Z, ID: bd0b7yh8rkfz)']
]
context 'update most recent incident', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
nock('https://api.statuspage.io')
.patch('/v1/pages/63kbmt268d37/incidents/bd0b7yh8rkfz.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
room.user.say 'alice', 'hubot statuspage update monitoring We have dispatched an army to fix it.'
setTimeout done, 100
it 'updates the most recent issue', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage update monitoring We have dispatched an army to fix it.' ]
[ 'hubot', 'Updated incident "System has been invaded by Barbarians"']
]
context 'update specific incident', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
nock('https://api.statuspage.io')
.patch('/v1/pages/63kbmt268d37/incidents/bd0b7yh8rkfz.json')
.replyWithFile(200, __dirname + '/fixtures/incident.json')
room.user.say 'alice', 'hubot statuspage update bd0b7yh8rkfz monitoring We have dispatched an army to fix it.'
setTimeout done, 100
it 'updates the most recent issue', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage update bd0b7yh8rkfz monitoring We have dispatched an army to fix it.' ]
[ 'hubot', 'Updated incident "System has been invaded by Barbarians"']
]
context 'open new incident', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.post('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
room.user.say 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians'
setTimeout done, 100
it 'opens a new incident', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians' ]
[ 'hubot', 'Created incident "System has been invaded by Barbarians"']
]
context 'open new incident with message', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.post('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
room.user.say 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians:Send help fast!'
setTimeout done, 100
it 'opens a new incident with message', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians:Send help fast!' ]
[ 'hubot', 'Created incident "System has been invaded by Barbarians"']
]
context 'update component not found status', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/components.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
room.user.say 'alice', 'hubot statuspage Backend major outage'
setTimeout done, 100
it 'responds with an error message', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage Backend major outage' ]
[ 'hubot', 'Couldn\'t find a component named Backend']
]
context 'update component status', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/components.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
nock('https://api.statuspage.io')
.patch('/v1/pages/63kbmt268d37/components/string.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
room.user.say 'alice', 'hubot statuspage Backend Database major outage'
setTimeout done, 100
it 'responds with updated component status', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage Backend Database major outage' ]
[ 'hubot', 'Status for Backend Database is now major outage (was: degraded)']
]
| true | Helper = require('hubot-test-helper')
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
nock = require('nock')
helper = new Helper('./../src/statuspage.coffee')
expect = chai.expect
describe 'statuspage', ->
room = null
beforeEach ->
process.env.HUBOT_STATUS_PAGE_ID = '63kbmt268d37'
process.env.HUBOT_STATUS_PAGE_TOKEN = 'PI:KEY:<KEY>END_PI'
room = helper.createRoom()
nock.disableNetConnect()
@robot =
respond: sinon.spy()
hear: sinon.spy()
require('../src/statuspage')(@robot)
afterEach ->
room.destroy()
nock.cleanAll()
delete process.env.HUBOT_STATUS_PAGE_ID
delete process.env.HUBOT_STATUS_PAGE_TOKEN
context 'ensure all listeners are registered', ->
it 'registers a respond listener for all incidents', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) incidents\??/i)
it 'registers a respond listener for update incident', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) update (investigating|identified|monitoring|resolved) (.+)/i)
it 'registers a respond listener for create new incident', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) open (investigating|identified|monitoring|resolved) ([^:]+)(: ?(.+))?/i)
it 'registers a respond listener for getting all component statuses', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage)\?$/i)
it 'registers a respond listener for getting single component status', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) ((?!(incidents|open|update|resolve|create))(\S ?)+)\?$/i)
it 'registers a respond listener for update component', ->
expect(@robot.respond).to.have.been.calledWith(/(?:status|statuspage) ((\S ?)+) (major( outage)?|degraded( performance)?|partial( outage)?|operational)/i)
context 'show all component status', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/components.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
room.user.say 'alice', 'hubot statuspage?'
setTimeout done, 100
it 'responds with all component status', ->
expect(room.messages).to.eql [
[ 'PI:NAME:<NAME>END_PI', 'hubot statuspage?' ]
[ 'hubot', 'There are currently 1 components in a degraded state' ]
[ 'hubot', "\nBroken Components:\n-------------\n"]
[ 'hubot', "Backend Database: degraded\n"]
]
context 'list incidents', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/incidents.json')
room.user.say 'alice', 'hubot statuspage incidents'
setTimeout done, 100
it 'responds with a list of incidents', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage incidents' ]
[ 'hubot', 'Unresolved incidents:']
[ 'hubot', 'Data Layer Migration (Status: scheduled, Created: 2020-08-14T16:11:34Z, ID: bd0b7yh8rkfz)']
]
context 'update most recent incident', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
nock('https://api.statuspage.io')
.patch('/v1/pages/63kbmt268d37/incidents/bd0b7yh8rkfz.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
room.user.say 'alice', 'hubot statuspage update monitoring We have dispatched an army to fix it.'
setTimeout done, 100
it 'updates the most recent issue', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage update monitoring We have dispatched an army to fix it.' ]
[ 'hubot', 'Updated incident "System has been invaded by Barbarians"']
]
context 'update specific incident', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
nock('https://api.statuspage.io')
.patch('/v1/pages/63kbmt268d37/incidents/bd0b7yh8rkfz.json')
.replyWithFile(200, __dirname + '/fixtures/incident.json')
room.user.say 'alice', 'hubot statuspage update bd0b7yh8rkfz monitoring We have dispatched an army to fix it.'
setTimeout done, 100
it 'updates the most recent issue', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage update bd0b7yh8rkfz monitoring We have dispatched an army to fix it.' ]
[ 'hubot', 'Updated incident "System has been invaded by Barbarians"']
]
context 'open new incident', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.post('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
room.user.say 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians'
setTimeout done, 100
it 'opens a new incident', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians' ]
[ 'hubot', 'Created incident "System has been invaded by Barbarians"']
]
context 'open new incident with message', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.post('/v1/pages/63kbmt268d37/incidents.json')
.replyWithFile(200, __dirname + '/fixtures/unresolved-incidents.json')
room.user.say 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians:Send help fast!'
setTimeout done, 100
it 'opens a new incident with message', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage open investigating System has been invaded by Barbarians:Send help fast!' ]
[ 'hubot', 'Created incident "System has been invaded by Barbarians"']
]
context 'update component not found status', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/components.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
room.user.say 'alice', 'hubot statuspage Backend major outage'
setTimeout done, 100
it 'responds with an error message', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage Backend major outage' ]
[ 'hubot', 'Couldn\'t find a component named Backend']
]
context 'update component status', ->
beforeEach (done) ->
nock('https://api.statuspage.io')
.get('/v1/pages/63kbmt268d37/components.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
nock('https://api.statuspage.io')
.patch('/v1/pages/63kbmt268d37/components/string.json')
.replyWithFile(200, __dirname + '/fixtures/components.json')
room.user.say 'alice', 'hubot statuspage Backend Database major outage'
setTimeout done, 100
it 'responds with updated component status', ->
expect(room.messages).to.eql [
[ 'alice', 'hubot statuspage Backend Database major outage' ]
[ 'hubot', 'Status for Backend Database is now major outage (was: degraded)']
]
|
[
{
"context": "ration = {}\nconfiguration[nerfed + \"username\"] = \"username\"\nconfiguration[nerfed + \"_password\"] = new Buffer",
"end": 249,
"score": 0.9986844658851624,
"start": 241,
"tag": "USERNAME",
"value": "username"
},
{
"context": "nfiguration[nerfed + \"_password\"] = new Buffer(\"%1234@asdf%\").toString(\"base64\")\nconfiguration[nerfed +",
"end": 306,
"score": 0.6435298323631287,
"start": 303,
"tag": "PASSWORD",
"value": "234"
},
{
"context": "ring(\"base64\")\nconfiguration[nerfed + \"email\"] = \"ogd@aoaioxxysz.net\"\nclient = common.freshClient(configuration)\n_auth",
"end": 387,
"score": 0.9999288320541382,
"start": 369,
"tag": "EMAIL",
"value": "ogd@aoaioxxysz.net"
},
{
"context": "on.freshClient(configuration)\n_auth = new Buffer(\"username:%1234@asdf%\").toString(\"base64\")\ntap.test \"publis",
"end": 460,
"score": 0.6636985540390015,
"start": 452,
"tag": "USERNAME",
"value": "username"
},
{
"context": " pkg\n t.same o.maintainers, [\n name: \"username\"\n email: \"ogd@aoaioxxysz.net\"\n ]\n ",
"end": 1207,
"score": 0.9993801116943359,
"start": 1199,
"tag": "USERNAME",
"value": "username"
},
{
"context": "iners, [\n name: \"username\"\n email: \"ogd@aoaioxxysz.net\"\n ]\n t.same o.maintainers, o.versions[p",
"end": 1243,
"score": 0.9999319911003113,
"start": 1225,
"tag": "EMAIL",
"value": "ogd@aoaioxxysz.net"
}
] | deps/npm/node_modules/npm-registry-client/test/publish-scoped.coffee | lxe/io.coffee | 0 | tap = require("tap")
crypto = require("crypto")
fs = require("fs")
server = require("./lib/server.js")
common = require("./lib/common.js")
nerfed = "//localhost:" + server.port + "/:"
configuration = {}
configuration[nerfed + "username"] = "username"
configuration[nerfed + "_password"] = new Buffer("%1234@asdf%").toString("base64")
configuration[nerfed + "email"] = "ogd@aoaioxxysz.net"
client = common.freshClient(configuration)
_auth = new Buffer("username:%1234@asdf%").toString("base64")
tap.test "publish", (t) ->
# not really a tarball, but doesn't matter
tarball = require.resolve("../package.json")
pd = fs.readFileSync(tarball, "base64")
pkg = require("../package.json")
pkg.name = "@npm/npm-registry-client"
server.expect "/@npm%2fnpm-registry-client", (req, res) ->
t.equal req.method, "PUT"
t.equal req.headers.authorization, "Basic " + _auth
b = ""
req.setEncoding "utf8"
req.on "data", (d) ->
b += d
return
req.on "end", ->
o = JSON.parse(b)
t.equal o._id, "@npm/npm-registry-client"
t.equal o["dist-tags"].latest, pkg.version
t.has o.versions[pkg.version], pkg
t.same o.maintainers, [
name: "username"
email: "ogd@aoaioxxysz.net"
]
t.same o.maintainers, o.versions[pkg.version].maintainers
att = o._attachments[pkg.name + "-" + pkg.version + ".tgz"]
t.same att.data, pd
hash = crypto.createHash("sha1").update(pd, "base64").digest("hex")
t.equal o.versions[pkg.version].dist.shasum, hash
res.statusCode = 201
res.json created: true
return
return
client.publish common.registry, pkg, tarball, (er, data) ->
throw er if er
t.deepEqual data,
created: true
t.end()
return
return
| 109517 | tap = require("tap")
crypto = require("crypto")
fs = require("fs")
server = require("./lib/server.js")
common = require("./lib/common.js")
nerfed = "//localhost:" + server.port + "/:"
configuration = {}
configuration[nerfed + "username"] = "username"
configuration[nerfed + "_password"] = new Buffer("%1<PASSWORD>@asdf%").toString("base64")
configuration[nerfed + "email"] = "<EMAIL>"
client = common.freshClient(configuration)
_auth = new Buffer("username:%1234@asdf%").toString("base64")
tap.test "publish", (t) ->
# not really a tarball, but doesn't matter
tarball = require.resolve("../package.json")
pd = fs.readFileSync(tarball, "base64")
pkg = require("../package.json")
pkg.name = "@npm/npm-registry-client"
server.expect "/@npm%2fnpm-registry-client", (req, res) ->
t.equal req.method, "PUT"
t.equal req.headers.authorization, "Basic " + _auth
b = ""
req.setEncoding "utf8"
req.on "data", (d) ->
b += d
return
req.on "end", ->
o = JSON.parse(b)
t.equal o._id, "@npm/npm-registry-client"
t.equal o["dist-tags"].latest, pkg.version
t.has o.versions[pkg.version], pkg
t.same o.maintainers, [
name: "username"
email: "<EMAIL>"
]
t.same o.maintainers, o.versions[pkg.version].maintainers
att = o._attachments[pkg.name + "-" + pkg.version + ".tgz"]
t.same att.data, pd
hash = crypto.createHash("sha1").update(pd, "base64").digest("hex")
t.equal o.versions[pkg.version].dist.shasum, hash
res.statusCode = 201
res.json created: true
return
return
client.publish common.registry, pkg, tarball, (er, data) ->
throw er if er
t.deepEqual data,
created: true
t.end()
return
return
| true | tap = require("tap")
crypto = require("crypto")
fs = require("fs")
server = require("./lib/server.js")
common = require("./lib/common.js")
nerfed = "//localhost:" + server.port + "/:"
configuration = {}
configuration[nerfed + "username"] = "username"
configuration[nerfed + "_password"] = new Buffer("%1PI:PASSWORD:<PASSWORD>END_PI@asdf%").toString("base64")
configuration[nerfed + "email"] = "PI:EMAIL:<EMAIL>END_PI"
client = common.freshClient(configuration)
_auth = new Buffer("username:%1234@asdf%").toString("base64")
tap.test "publish", (t) ->
# not really a tarball, but doesn't matter
tarball = require.resolve("../package.json")
pd = fs.readFileSync(tarball, "base64")
pkg = require("../package.json")
pkg.name = "@npm/npm-registry-client"
server.expect "/@npm%2fnpm-registry-client", (req, res) ->
t.equal req.method, "PUT"
t.equal req.headers.authorization, "Basic " + _auth
b = ""
req.setEncoding "utf8"
req.on "data", (d) ->
b += d
return
req.on "end", ->
o = JSON.parse(b)
t.equal o._id, "@npm/npm-registry-client"
t.equal o["dist-tags"].latest, pkg.version
t.has o.versions[pkg.version], pkg
t.same o.maintainers, [
name: "username"
email: "PI:EMAIL:<EMAIL>END_PI"
]
t.same o.maintainers, o.versions[pkg.version].maintainers
att = o._attachments[pkg.name + "-" + pkg.version + ".tgz"]
t.same att.data, pd
hash = crypto.createHash("sha1").update(pd, "base64").digest("hex")
t.equal o.versions[pkg.version].dist.shasum, hash
res.statusCode = 201
res.json created: true
return
return
client.publish common.registry, pkg, tarball, (er, data) ->
throw er if er
t.deepEqual data,
created: true
t.end()
return
return
|
[
{
"context": ".env.HUBOT_ZENDESK_USER}\"\n zendesk_password = \"#{process.env.HUBOT_ZENDESK_PASSWORD}\"\n auth = new Buffer(\"#{zendesk_user}:#{zendesk_",
"end": 1645,
"score": 0.9174197912216187,
"start": 1611,
"tag": "PASSWORD",
"value": "process.env.HUBOT_ZENDESK_PASSWORD"
}
] | src/scripts/zendesk.coffee | TaxiOS/hubot-scripts | 1 | # Description:
# Queries Zendesk for information about support tickets
#
# Configuration:
# HUBOT_ZENDESK_USER
# HUBOT_ZENDESK_PASSWORD
# HUBOT_ZENDESK_SUBDOMAIN
#
# Commands:
# (all) tickets - returns the total count of all unsolved tickets. The 'all'
# keyword is optional.
# new tickets - returns the count of all new (unassigned) tickets
# open tickets - returns the count of all open tickets
# escalated tickets - returns a count of tickets with escalated tag that are open or pending
# pending tickets - returns a count of tickets that are pending
# list (all) tickets - returns a list of all unsolved tickets. The 'all'
# keyword is optional.
# list new tickets - returns a list of all new tickets
# list open tickets - returns a list of all open tickets
# list pending tickets - returns a list of pending tickets
# list escalated tickets - returns a list of escalated tickets
# ticket <ID> - returns information about the specified ticket
sys = require 'sys' # Used for debugging
tickets_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/tickets"
queries =
unsolved: "search.json?query=status<solved+type:ticket"
open: "search.json?query=status:open+type:ticket"
new: "search.json?query=status:new+type:ticket"
escalated: "search.json?query=tags:escalated+status:open+status:pending+type:ticket"
pending: "search.json?query=status:pending+type:ticket"
tickets: "tickets"
users: "users"
zendesk_request = (msg, url, handler) ->
zendesk_user = "#{process.env.HUBOT_ZENDESK_USER}"
zendesk_password = "#{process.env.HUBOT_ZENDESK_PASSWORD}"
auth = new Buffer("#{zendesk_user}:#{zendesk_password}").toString('base64')
zendesk_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/api/v2"
msg.http("#{zendesk_url}/#{url}")
.headers(Authorization: "Basic #{auth}", Accept: "application/json")
.get() (err, res, body) ->
if err
msg.send "Zendesk says: #{err}"
return
content = JSON.parse(body)
if content.error?
if content.error?.title
msg.send "Zendesk says: #{content.error.title}"
else
msg.send "Zendesk says: #{content.error}"
return
handler content
# FIXME this works about as well as a brick floats
zendesk_user = (msg, user_id) ->
zendesk_request msg, "#{queries.users}/#{user_id}.json", (result) ->
if result.error
msg.send result.description
return
result.user
module.exports = (robot) ->
robot.respond /(all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} unsolved tickets"
robot.respond /pending tickets$/i, (msg) ->
zendesk_request msg, queries.pending, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} unsolved tickets"
robot.respond /new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} new tickets"
robot.respond /escalated tickets$/i, (msg) ->
zendesk_request msg, queries.escalated, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} escalated tickets"
robot.respond /open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} open tickets"
robot.respond /list (all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list pending tickets$/i, (msg) ->
zendesk_request msg, queries.pending, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list escalated tickets$/i, (msg) ->
zendesk_request msg, queries.escalated, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is escalated and #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /ticket ([\d]+)$/i, (msg) ->
ticket_id = msg.match[1]
zendesk_request msg, "#{queries.tickets}/#{ticket_id}.json", (result) ->
if result.error
msg.send result.description
return
message = "#{tickets_url}/#{result.ticket.id} ##{result.ticket.id} (#{result.ticket.status.toUpperCase()})"
message += "\nUpdated: #{result.ticket.updated_at}"
message += "\nAdded: #{result.ticket.created_at}"
message += "\nDescription:\n-------\n#{result.ticket.description}\n--------"
msg.send message
| 186615 | # Description:
# Queries Zendesk for information about support tickets
#
# Configuration:
# HUBOT_ZENDESK_USER
# HUBOT_ZENDESK_PASSWORD
# HUBOT_ZENDESK_SUBDOMAIN
#
# Commands:
# (all) tickets - returns the total count of all unsolved tickets. The 'all'
# keyword is optional.
# new tickets - returns the count of all new (unassigned) tickets
# open tickets - returns the count of all open tickets
# escalated tickets - returns a count of tickets with escalated tag that are open or pending
# pending tickets - returns a count of tickets that are pending
# list (all) tickets - returns a list of all unsolved tickets. The 'all'
# keyword is optional.
# list new tickets - returns a list of all new tickets
# list open tickets - returns a list of all open tickets
# list pending tickets - returns a list of pending tickets
# list escalated tickets - returns a list of escalated tickets
# ticket <ID> - returns information about the specified ticket
sys = require 'sys' # Used for debugging
tickets_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/tickets"
queries =
unsolved: "search.json?query=status<solved+type:ticket"
open: "search.json?query=status:open+type:ticket"
new: "search.json?query=status:new+type:ticket"
escalated: "search.json?query=tags:escalated+status:open+status:pending+type:ticket"
pending: "search.json?query=status:pending+type:ticket"
tickets: "tickets"
users: "users"
zendesk_request = (msg, url, handler) ->
zendesk_user = "#{process.env.HUBOT_ZENDESK_USER}"
zendesk_password = "#{<PASSWORD>}"
auth = new Buffer("#{zendesk_user}:#{zendesk_password}").toString('base64')
zendesk_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/api/v2"
msg.http("#{zendesk_url}/#{url}")
.headers(Authorization: "Basic #{auth}", Accept: "application/json")
.get() (err, res, body) ->
if err
msg.send "Zendesk says: #{err}"
return
content = JSON.parse(body)
if content.error?
if content.error?.title
msg.send "Zendesk says: #{content.error.title}"
else
msg.send "Zendesk says: #{content.error}"
return
handler content
# FIXME this works about as well as a brick floats
zendesk_user = (msg, user_id) ->
zendesk_request msg, "#{queries.users}/#{user_id}.json", (result) ->
if result.error
msg.send result.description
return
result.user
module.exports = (robot) ->
robot.respond /(all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} unsolved tickets"
robot.respond /pending tickets$/i, (msg) ->
zendesk_request msg, queries.pending, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} unsolved tickets"
robot.respond /new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} new tickets"
robot.respond /escalated tickets$/i, (msg) ->
zendesk_request msg, queries.escalated, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} escalated tickets"
robot.respond /open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} open tickets"
robot.respond /list (all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list pending tickets$/i, (msg) ->
zendesk_request msg, queries.pending, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list escalated tickets$/i, (msg) ->
zendesk_request msg, queries.escalated, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is escalated and #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /ticket ([\d]+)$/i, (msg) ->
ticket_id = msg.match[1]
zendesk_request msg, "#{queries.tickets}/#{ticket_id}.json", (result) ->
if result.error
msg.send result.description
return
message = "#{tickets_url}/#{result.ticket.id} ##{result.ticket.id} (#{result.ticket.status.toUpperCase()})"
message += "\nUpdated: #{result.ticket.updated_at}"
message += "\nAdded: #{result.ticket.created_at}"
message += "\nDescription:\n-------\n#{result.ticket.description}\n--------"
msg.send message
| true | # Description:
# Queries Zendesk for information about support tickets
#
# Configuration:
# HUBOT_ZENDESK_USER
# HUBOT_ZENDESK_PASSWORD
# HUBOT_ZENDESK_SUBDOMAIN
#
# Commands:
# (all) tickets - returns the total count of all unsolved tickets. The 'all'
# keyword is optional.
# new tickets - returns the count of all new (unassigned) tickets
# open tickets - returns the count of all open tickets
# escalated tickets - returns a count of tickets with escalated tag that are open or pending
# pending tickets - returns a count of tickets that are pending
# list (all) tickets - returns a list of all unsolved tickets. The 'all'
# keyword is optional.
# list new tickets - returns a list of all new tickets
# list open tickets - returns a list of all open tickets
# list pending tickets - returns a list of pending tickets
# list escalated tickets - returns a list of escalated tickets
# ticket <ID> - returns information about the specified ticket
sys = require 'sys' # Used for debugging
tickets_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/tickets"
queries =
unsolved: "search.json?query=status<solved+type:ticket"
open: "search.json?query=status:open+type:ticket"
new: "search.json?query=status:new+type:ticket"
escalated: "search.json?query=tags:escalated+status:open+status:pending+type:ticket"
pending: "search.json?query=status:pending+type:ticket"
tickets: "tickets"
users: "users"
zendesk_request = (msg, url, handler) ->
zendesk_user = "#{process.env.HUBOT_ZENDESK_USER}"
zendesk_password = "#{PI:PASSWORD:<PASSWORD>END_PI}"
auth = new Buffer("#{zendesk_user}:#{zendesk_password}").toString('base64')
zendesk_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/api/v2"
msg.http("#{zendesk_url}/#{url}")
.headers(Authorization: "Basic #{auth}", Accept: "application/json")
.get() (err, res, body) ->
if err
msg.send "Zendesk says: #{err}"
return
content = JSON.parse(body)
if content.error?
if content.error?.title
msg.send "Zendesk says: #{content.error.title}"
else
msg.send "Zendesk says: #{content.error}"
return
handler content
# FIXME this works about as well as a brick floats
zendesk_user = (msg, user_id) ->
zendesk_request msg, "#{queries.users}/#{user_id}.json", (result) ->
if result.error
msg.send result.description
return
result.user
module.exports = (robot) ->
robot.respond /(all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} unsolved tickets"
robot.respond /pending tickets$/i, (msg) ->
zendesk_request msg, queries.pending, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} unsolved tickets"
robot.respond /new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} new tickets"
robot.respond /escalated tickets$/i, (msg) ->
zendesk_request msg, queries.escalated, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} escalated tickets"
robot.respond /open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} open tickets"
robot.respond /list (all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list pending tickets$/i, (msg) ->
zendesk_request msg, queries.pending, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list escalated tickets$/i, (msg) ->
zendesk_request msg, queries.escalated, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is escalated and #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /list open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /ticket ([\d]+)$/i, (msg) ->
ticket_id = msg.match[1]
zendesk_request msg, "#{queries.tickets}/#{ticket_id}.json", (result) ->
if result.error
msg.send result.description
return
message = "#{tickets_url}/#{result.ticket.id} ##{result.ticket.id} (#{result.ticket.status.toUpperCase()})"
message += "\nUpdated: #{result.ticket.updated_at}"
message += "\nAdded: #{result.ticket.created_at}"
message += "\nDescription:\n-------\n#{result.ticket.description}\n--------"
msg.send message
|
[
{
"context": " 201\n# headers: {\n# \"x-token\": \"123-abc\"\n# \"contentType\": \"foo/bar\"\n# ",
"end": 13977,
"score": 0.9918259382247925,
"start": 13970,
"tag": "KEY",
"value": "123-abc"
},
{
"context": " headers = JSON.stringify({\n# \"x-token\": \"123-abc\"\n# \"content-type\": \"foo/bar\"\n# \"x",
"end": 14859,
"score": 0.9910236597061157,
"start": 14852,
"tag": "KEY",
"value": "123-abc"
},
{
"context": "\"content-type\": \"foo/bar\"\n# \"x-foo-bar\": \"sekret\"\n# })\n# @expectRequestHeader(\"Headers",
"end": 14927,
"score": 0.6025979518890381,
"start": 14921,
"tag": "NAME",
"value": "sekret"
}
] | packages/driver/test/unit_old/cypress/server_spec.coffee | Everworks/cypress | 3 | { $, _ } = window.testUtils
describe "$Cypress.Cy Server API", ->
beforeEach ->
@iframe = $("<iframe />").appendTo $("body")
@window = @iframe.prop("contentWindow")
afterEach ->
@iframe.remove()
it ".create", ->
server = $Cypress.Server.create({})
expect(server).to.be.instanceof $Cypress.Server
it ".defaults", ->
defaults = _.clone $Cypress.Server.defaults()
expect(defaults.status).to.eq(200)
defaults2 = $Cypress.Server.defaults({status: 500})
expect(defaults2.status).to.eq(500)
server = $Cypress.Server.create({})
route = server.route()
expect(route.status).to.eq(500)
$Cypress.Server.defaults(defaults)
context "#isWhitelisted", ->
beforeEach ->
@server = $Cypress.Server.create()
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
it "whitelists GET *.js", ->
@xhr.method = "GET"
@xhr.url = "/foo.js"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.jsx", ->
@xhr.method = "GET"
@xhr.url = "/foo.jsx"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.html", ->
@xhr.method = "GET"
@xhr.url = "/foo.html"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.css", ->
@xhr.method = "GET"
@xhr.url = "/foo.css"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.scss", ->
@xhr.method = "GET"
@xhr.url = "/foo.scss"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.less", ->
@xhr.method = "GET"
@xhr.url = "/foo.less"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.coffee", ->
@xhr.method = "GET"
@xhr.url = "/foo.coffee"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.js.coffee", ->
@xhr.method = "GET"
@xhr.url = "/foo.js.coffee"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.js?_=123123", ->
@xhr.method = "GET"
@xhr.url = "/foo.js?_=123123"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.html?_=123123&foo=bar", ->
@xhr.method = "GET"
@xhr.url = "/foo.html?_=123123&foo=bar"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.svg", ->
@xhr.method = "GET"
@xhr.url = "/foo.svg"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "does not whitelist GET *.json?_=123123", ->
@xhr.method = "GET"
@xhr.url = "/foo.json?_=123123"
expect(@server.isWhitelisted(@xhr)).not.to.be.true
it "does not whitelist OPTIONS *.js?_=123123", ->
@xhr.method = "OPTIONS"
@xhr.url = "/foo.js?_=123123"
expect(@server.isWhitelisted(@xhr)).not.to.be.true
context "#setRequestHeader", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@srh = @sandbox.spy(@window.XMLHttpRequest.prototype, "setRequestHeader")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "sets request.headers", ->
@proxy.setRequestHeader("foo", "bar")
expect(@proxy.request.headers).to.deep.eq({foo: "bar"})
it "appends to request.headers", ->
@proxy.setRequestHeader("foo", "bar")
@proxy.setRequestHeader("foo", "baz")
expect(@proxy.request.headers).to.deep.eq({foo: "bar, baz"})
it "ignores cypress headers", ->
@proxy.setRequestHeader("X-Cypress-Delay", 1000)
expect(@proxy.request.headers).not.to.be.ok
it "sets proxy request headers from xhr", ->
@xhr.setRequestHeader("foo", "bar")
## the original setRequestHeaders method should be called here
expect(@srh).to.be.calledWith("foo", "bar")
expect(@proxy.request.headers).to.deep.eq({foo: "bar"})
## since we yield the xhrProxy object in tests
## we need to call the original xhr's implementation
## on setRequestHeaders
it "calls the original xhr's implementation", ->
@proxy.setRequestHeader("foo", "bar")
expect(@srh).to.be.calledWith("foo", "bar")
expect(@srh).to.be.calledOn(@xhr)
context "#applyStubProperties", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@srh = @sandbox.spy(@window.XMLHttpRequest.prototype, "setRequestHeader")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "encodes the http header value", ->
route = {
response: {"test": "We’ll"}
}
@sandbox.spy(@xhr, "setRequestHeader")
## this function would previous throw unless
## we decoded the value
@server.applyStubProperties(@xhr, route)
expect(@xhr.setRequestHeader).to.be.calledWith("X-Cypress-Response", "%7B%22test%22:%22We%E2%80%99ll%22%7D")
context "#getResponseHeader", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@grh = @sandbox.spy(@window.XMLHttpRequest.prototype, "getResponseHeader")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "calls the original xhr implementation", ->
@proxy.getResponseHeader("foo")
expect(@grh).to.be.calledWith("foo")
expect(@grh).to.be.calledOn(@xhr)
context "#getAllResponseHeaders", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@garh = @sandbox.spy(@window.XMLHttpRequest.prototype, "getAllResponseHeaders")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "calls the original xhr implementation", ->
@proxy.getAllResponseHeaders()
expect(@garh).to.be.calledOnce
expect(@garh).to.be.calledOn(@xhr)
context "#setResponseHeaders", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
it "sets response.headers and responseHeaders", (done) ->
headers = """
X-Powered-By: Express
Vary: Accept-Encoding
Content-Type: application/json
Cache-Control: public, max-age=0
Connection: keep-alive
Content-Length: 53
""".split("\n").join('\u000d\u000a')
@sandbox.stub(@xhr, "getAllResponseHeaders").returns(headers)
@xhr.open("GET", "/fixtures/app.json")
proxy = @server.getProxyFor(@xhr)
@xhr.onload = ->
expect(proxy.responseHeaders).to.eq(proxy.response.headers)
expect(proxy.responseHeaders).to.deep.eq({
"X-Powered-By": "Express"
"Vary": "Accept-Encoding"
"Content-Type": "application/json"
"Cache-Control": "public, max-age=0"
"Connection": "keep-alive"
"Content-Length": "53"
})
done()
@xhr.send()
context "#getFullyQualifiedUrl", ->
beforeEach ->
@server = $Cypress.Server.create()
@expectUrlToEq = (url, url2) =>
expect(@server.getFullyQualifiedUrl(window, url)).to.eq(url2)
it "resolves absolute relative links", ->
@expectUrlToEq("/foo/bar.html", "#{window.location.origin}/foo/bar.html")
it "resolves relative links", ->
## slice off the last path segment since this is a relative link
## http://localhost:3500/specs/api/cypress/server_spec -> http://localhost:3500/specs/api/cypress
path = window.location.origin + window.location.pathname.split("/").slice(0, -1).join("/")
@expectUrlToEq("foo/bar.html", "#{path}/foo/bar.html")
context "#urlsMatch", ->
beforeEach ->
@server = $Cypress.Server.create({
stripOrigin: (url) ->
location = $Cypress.Location.create(url)
url.replace(location.origin, "")
})
@matches = (url1, url2) ->
expect(@server.urlsMatch(url1, url2)).to.be.true
@notMatches = (url1, url2) ->
expect(@server.urlsMatch(url1, url2)).to.be.false
it "matches fully qualified route", ->
@matches("http://localhost:2020/foo", "http://localhost:2020/foo")
it "matches absolute relative route", ->
@matches("/foo", "http://localhost:2020/foo")
it "prepends with forward slash on glob", ->
@matches("foo/bar", "http://localhost:2020/foo/bar")
it "uses default urlMatchingOptions", ->
## test that matchBase is true by default
expect(@server.options.urlMatchingOptions).to.deep.eq({matchBase: true})
@matches("foo", "http://localhost:2020/a/b/c/foo")
it "prepends with forward slash", ->
@matches("foo/*", "http://localhost:2020/foo/123")
it "use glob stars", ->
@matches("/users/**", "https://localhost:2020/users/foo/bar?a=1")
it "use glob stars between url segments", ->
@matches("/users/*/comments/*", "http://localhost:2020/users/1/comments/2")
it "matches with regex", ->
@matches(/foo/, "http://localhost:2020/foo/bar/baz/123")
context "XHR#abort", ->
beforeEach ->
@send = @sandbox.stub(@window.XMLHttpRequest.prototype, "send")
@open = @sandbox.spy(@window.XMLHttpRequest.prototype, "open")
@abort = @sandbox.spy(@window.XMLHttpRequest.prototype, "abort")
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
onXhrAbort: ->
onAnyAbort: ->
})
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
it "sets aborted=true", ->
@xhr.open("GET", "/foo")
@xhr.abort()
expect(@xhr.aborted).to.eq(true)
it "calls the original abort", ->
@xhr.open("GET", "/foo")
@xhr.abort()
expect(@abort).to.be.calledOn(@xhr)
it "calls onXhrAbort callback with xhr + stack trace", ->
@sandbox.stub(@server, "getStack").returns("foobarbaz")
onXhrAbort = @sandbox.spy @server.options, "onXhrAbort"
@xhr.open("GET", "/foo")
@xhr.abort()
expect(onXhrAbort).to.be.calledWith(@server.getProxyFor(@xhr), "foobarbaz")
it "calls onAnyAbort callback with route + xhr", ->
onAnyAbort = @sandbox.spy @server.options, "onAnyAbort"
@xhr.open("GET", "/foo")
@xhr.abort()
expect(onAnyAbort).to.be.called
# context "XHR#open", ->
# beforeEach ->
# @send = @sandbox.stub(@window.XMLHttpRequest.prototype, "send")
# @open = @sandbox.spy(@window.XMLHttpRequest.prototype, "open")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @xhr = new @window.XMLHttpRequest
# it "adds to server#xhrs", ->
# expect(@server.xhrs).to.deep.eq({})
# @xhr.open("GET", "/foo")
# expect(@server.xhrs[@xhr.id]).to.eq(@xhr)
# it "normalizes async", ->
# @xhr.open("GET", "/foo")
# expect(@open).to.be.calledWith("GET", "/foo", true)
# it "changes url to stub url", ->
# @sandbox.stub(@server, "shouldApplyStub").returns(true)
# @xhr.open("GET", "/foo")
# expect(@open).to.be.calledWith("GET", "/__cypress/xhrs/foo")
# it "calls the original open", ->
# @xhr.open("GET", "/foo", true, "us", "pw")
# expect(@open).to.be.calledOn(@xhr)
# expect(@open).to.be.calledWith("GET", "/foo", true, "us", "pw")
# context "XHR#send", ->
# beforeEach ->
# @send = @sandbox.spy(@window.XMLHttpRequest.prototype, "send")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @xhr = new @window.XMLHttpRequest
# it "bails if server isnt active"
# it "sets requestBody on all requests", ->
# @xhr.open("GET", "/foo")
# @xhr.send("a=b")
# proxy = @server.getProxyFor(@xhr)
# expect(proxy.requestBody).to.eq("a=b")
# expect(proxy.request.body).to.eq("a=b")
# it "parses requestBody into JSON", ->
# @xhr.open("POST", "/users")
# @xhr.send(JSON.stringify({foo: "bar"}))
# proxy = @server.getProxyFor(@xhr)
# expect(proxy.requestBody).to.deep.eq({foo: "bar"})
# expect(proxy.request.body).to.deep.eq({foo: "bar"})
# it "sets requestBody on formData", ->
# formData = new FormData
# formData.append("foo", "bar")
# formData.append("baz", "quux")
# @xhr.open("POST", "/form")
# @xhr.send(formData)
# proxy = @server.getProxyFor(@xhr)
# expect(proxy.requestBody).to.eq(formData)
# it "sets x-cypress-id"
# it "sets x-cypress-testId"
# it "calls applyStubProperties", ->
# @server.enableStubs()
# applyStubProperties = @sandbox.spy @server, "applyStubProperties"
# stub1 = @server.stub({
# method: "POST"
# url: /.+/
# response: {}
# onRequest: ->
# })
# stub2 = @server.stub({
# method: "POST"
# url: /users/
# response: {}
# onRequest: ->
# })
# @xhr.open("POST", "/users/123")
# @xhr.send()
# expect(applyStubProperties).to.be.calledWith(@xhr, stub2)
# it "captures send (initiator) stack"
# it "calls stub.onRequest"
# it "calls send"
# context "#applyStubProperties", ->
# beforeEach ->
# @setRequestHeader = @sandbox.spy(@window.XMLHttpRequest.prototype, "setRequestHeader")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @stub = @server.stub({
# method: "POST"
# url: /foo/
# delay: 25
# status: 201
# headers: {
# "x-token": "123-abc"
# "contentType": "foo/bar"
# "X-Foo-Bar": "sekret"
# }
# response: [{name: "b"}, {name: "j"}]
# })
# @xhr = new @window.XMLHttpRequest
# @xhr.open("POST", "foobar")
# @server.applyStubProperties(@xhr, @stub)
# @expectRequestHeader = (key, val) =>
# expect(@setRequestHeader).to.be.calledOn(@xhr)
# expect(@setRequestHeader).to.be.calledWith("X-Cypress-#{key}", val)
# it "sets status", ->
# @expectRequestHeader("Status", 201)
# it "sets response", ->
# @expectRequestHeader("Response", JSON.stringify([{name: "b"}, {name: "j"}]))
# it "sets matched url", ->
# @expectRequestHeader("Matched", "/foo/")
# it "sets delay", ->
# @expectRequestHeader("Delay", 25)
# it "sets headers", ->
# headers = JSON.stringify({
# "x-token": "123-abc"
# "content-type": "foo/bar"
# "x-foo-bar": "sekret"
# })
# @expectRequestHeader("Headers", headers)
# it "does not set null/undefined headers", ->
# @setRequestHeader.reset()
# stub = @server.stub({
# method: "POST"
# url: /foo/
# })
# xhr = new @window.XMLHttpRequest
# xhr.open("POST", "foobar")
# @server.applyStubProperties(xhr, stub)
# expect(@setRequestHeader).not.to.be.calledWith("X-Cypress-Headers")
# context "#stub", ->
# beforeEach ->
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# delay: 100
# waitOnResponses: false
# foo: "bar"
# })
# @server.bindTo(@window)
# @server.enableStubs()
# it "merges defaults into stubs", ->
# expect(@server.stubs).to.be.empty
# @server.stub({
# url: /foo/
# response: {}
# delay: 50
# })
# expect(@server.stubs.length).to.eq(1)
# expect(@server.stubs[0]).to.deep.eq {
# url: /foo/
# response: {}
# delay: 50
# method: "GET"
# status: 200
# stub: true
# autoRespond: true
# waitOnResponses: false
# onRequest: undefined
# onResponse: undefined
# }
# context "#add", ->
# beforeEach ->
# @send = @sandbox.stub(@window.XMLHttpRequest.prototype, "send")
# @open = @sandbox.spy(@window.XMLHttpRequest.prototype, "open")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @xhr = new @window.XMLHttpRequest
# it "sets a unique xhrId", ->
# @xhr.open("GET", "/")
# expect(@xhr.id).to.be.a("string")
# it "merges in attrs", ->
# @xhr.open("POST", "/bar")
# expect(@xhr.method).to.eq("POST")
# expect(@xhr.url).to.include("/bar")
# context "#deactivate", ->
# beforeEach ->
# @abort = @sandbox.spy(@window.XMLHttpRequest.prototype, "abort")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# it "sets isActive=false", ->
# @server.deactivate()
# expect(@server.isActive).to.be.false
# it "aborts outstanding requests", (done) ->
# xhr1 = new @window.XMLHttpRequest
# xhr2 = new @window.XMLHttpRequest
# xhr3 = new @window.XMLHttpRequest
# xhr1.open("GET", "/fixtures/dom.html")
# xhr2.open("GET", "/timeout?ms=500")
# xhr3.open("GET", "/timeout?ms=500")
# xhr1.onload = =>
# @server.deactivate()
# ## abort should not have been called
# ## on xhr1, only xhr2 + xhr3
# expect(@abort).to.be.calledTwice
# expect(@abort).to.be.calledOn(xhr2)
# expect(@abort).to.be.calledOn(xhr3)
# done()
# _.invokeMap [xhr1, xhr2, xhr3], "send"
# context ".whitelist", ->
# it "ignores whitelisted routes even when matching stub"
context "#abort", ->
it "only aborts xhrs which have not already been aborted", ->
xhrAbort = 0
anyAbort = 0
@abort = @sandbox.spy(@window.XMLHttpRequest.prototype, "abort")
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
onXhrAbort: -> xhrAbort += 1
onAnyAbort: -> anyAbort += 1
})
@server.bindTo(@window)
@xhr1 = new @window.XMLHttpRequest
@xhr1.open("GET", "/foo")
@xhr2 = new @window.XMLHttpRequest
@xhr2.open("GET", "/foo")
@xhr3 = new @window.XMLHttpRequest
@xhr3.open("GET", "/foo")
@xhr1.abort()
@server.abort()
expect(xhrAbort).to.eq(3)
expect(anyAbort).to.eq(3)
| 76633 | { $, _ } = window.testUtils
describe "$Cypress.Cy Server API", ->
beforeEach ->
@iframe = $("<iframe />").appendTo $("body")
@window = @iframe.prop("contentWindow")
afterEach ->
@iframe.remove()
it ".create", ->
server = $Cypress.Server.create({})
expect(server).to.be.instanceof $Cypress.Server
it ".defaults", ->
defaults = _.clone $Cypress.Server.defaults()
expect(defaults.status).to.eq(200)
defaults2 = $Cypress.Server.defaults({status: 500})
expect(defaults2.status).to.eq(500)
server = $Cypress.Server.create({})
route = server.route()
expect(route.status).to.eq(500)
$Cypress.Server.defaults(defaults)
context "#isWhitelisted", ->
beforeEach ->
@server = $Cypress.Server.create()
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
it "whitelists GET *.js", ->
@xhr.method = "GET"
@xhr.url = "/foo.js"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.jsx", ->
@xhr.method = "GET"
@xhr.url = "/foo.jsx"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.html", ->
@xhr.method = "GET"
@xhr.url = "/foo.html"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.css", ->
@xhr.method = "GET"
@xhr.url = "/foo.css"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.scss", ->
@xhr.method = "GET"
@xhr.url = "/foo.scss"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.less", ->
@xhr.method = "GET"
@xhr.url = "/foo.less"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.coffee", ->
@xhr.method = "GET"
@xhr.url = "/foo.coffee"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.js.coffee", ->
@xhr.method = "GET"
@xhr.url = "/foo.js.coffee"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.js?_=123123", ->
@xhr.method = "GET"
@xhr.url = "/foo.js?_=123123"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.html?_=123123&foo=bar", ->
@xhr.method = "GET"
@xhr.url = "/foo.html?_=123123&foo=bar"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.svg", ->
@xhr.method = "GET"
@xhr.url = "/foo.svg"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "does not whitelist GET *.json?_=123123", ->
@xhr.method = "GET"
@xhr.url = "/foo.json?_=123123"
expect(@server.isWhitelisted(@xhr)).not.to.be.true
it "does not whitelist OPTIONS *.js?_=123123", ->
@xhr.method = "OPTIONS"
@xhr.url = "/foo.js?_=123123"
expect(@server.isWhitelisted(@xhr)).not.to.be.true
context "#setRequestHeader", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@srh = @sandbox.spy(@window.XMLHttpRequest.prototype, "setRequestHeader")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "sets request.headers", ->
@proxy.setRequestHeader("foo", "bar")
expect(@proxy.request.headers).to.deep.eq({foo: "bar"})
it "appends to request.headers", ->
@proxy.setRequestHeader("foo", "bar")
@proxy.setRequestHeader("foo", "baz")
expect(@proxy.request.headers).to.deep.eq({foo: "bar, baz"})
it "ignores cypress headers", ->
@proxy.setRequestHeader("X-Cypress-Delay", 1000)
expect(@proxy.request.headers).not.to.be.ok
it "sets proxy request headers from xhr", ->
@xhr.setRequestHeader("foo", "bar")
## the original setRequestHeaders method should be called here
expect(@srh).to.be.calledWith("foo", "bar")
expect(@proxy.request.headers).to.deep.eq({foo: "bar"})
## since we yield the xhrProxy object in tests
## we need to call the original xhr's implementation
## on setRequestHeaders
it "calls the original xhr's implementation", ->
@proxy.setRequestHeader("foo", "bar")
expect(@srh).to.be.calledWith("foo", "bar")
expect(@srh).to.be.calledOn(@xhr)
context "#applyStubProperties", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@srh = @sandbox.spy(@window.XMLHttpRequest.prototype, "setRequestHeader")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "encodes the http header value", ->
route = {
response: {"test": "We’ll"}
}
@sandbox.spy(@xhr, "setRequestHeader")
## this function would previous throw unless
## we decoded the value
@server.applyStubProperties(@xhr, route)
expect(@xhr.setRequestHeader).to.be.calledWith("X-Cypress-Response", "%7B%22test%22:%22We%E2%80%99ll%22%7D")
context "#getResponseHeader", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@grh = @sandbox.spy(@window.XMLHttpRequest.prototype, "getResponseHeader")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "calls the original xhr implementation", ->
@proxy.getResponseHeader("foo")
expect(@grh).to.be.calledWith("foo")
expect(@grh).to.be.calledOn(@xhr)
context "#getAllResponseHeaders", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@garh = @sandbox.spy(@window.XMLHttpRequest.prototype, "getAllResponseHeaders")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "calls the original xhr implementation", ->
@proxy.getAllResponseHeaders()
expect(@garh).to.be.calledOnce
expect(@garh).to.be.calledOn(@xhr)
context "#setResponseHeaders", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
it "sets response.headers and responseHeaders", (done) ->
headers = """
X-Powered-By: Express
Vary: Accept-Encoding
Content-Type: application/json
Cache-Control: public, max-age=0
Connection: keep-alive
Content-Length: 53
""".split("\n").join('\u000d\u000a')
@sandbox.stub(@xhr, "getAllResponseHeaders").returns(headers)
@xhr.open("GET", "/fixtures/app.json")
proxy = @server.getProxyFor(@xhr)
@xhr.onload = ->
expect(proxy.responseHeaders).to.eq(proxy.response.headers)
expect(proxy.responseHeaders).to.deep.eq({
"X-Powered-By": "Express"
"Vary": "Accept-Encoding"
"Content-Type": "application/json"
"Cache-Control": "public, max-age=0"
"Connection": "keep-alive"
"Content-Length": "53"
})
done()
@xhr.send()
context "#getFullyQualifiedUrl", ->
beforeEach ->
@server = $Cypress.Server.create()
@expectUrlToEq = (url, url2) =>
expect(@server.getFullyQualifiedUrl(window, url)).to.eq(url2)
it "resolves absolute relative links", ->
@expectUrlToEq("/foo/bar.html", "#{window.location.origin}/foo/bar.html")
it "resolves relative links", ->
## slice off the last path segment since this is a relative link
## http://localhost:3500/specs/api/cypress/server_spec -> http://localhost:3500/specs/api/cypress
path = window.location.origin + window.location.pathname.split("/").slice(0, -1).join("/")
@expectUrlToEq("foo/bar.html", "#{path}/foo/bar.html")
context "#urlsMatch", ->
beforeEach ->
@server = $Cypress.Server.create({
stripOrigin: (url) ->
location = $Cypress.Location.create(url)
url.replace(location.origin, "")
})
@matches = (url1, url2) ->
expect(@server.urlsMatch(url1, url2)).to.be.true
@notMatches = (url1, url2) ->
expect(@server.urlsMatch(url1, url2)).to.be.false
it "matches fully qualified route", ->
@matches("http://localhost:2020/foo", "http://localhost:2020/foo")
it "matches absolute relative route", ->
@matches("/foo", "http://localhost:2020/foo")
it "prepends with forward slash on glob", ->
@matches("foo/bar", "http://localhost:2020/foo/bar")
it "uses default urlMatchingOptions", ->
## test that matchBase is true by default
expect(@server.options.urlMatchingOptions).to.deep.eq({matchBase: true})
@matches("foo", "http://localhost:2020/a/b/c/foo")
it "prepends with forward slash", ->
@matches("foo/*", "http://localhost:2020/foo/123")
it "use glob stars", ->
@matches("/users/**", "https://localhost:2020/users/foo/bar?a=1")
it "use glob stars between url segments", ->
@matches("/users/*/comments/*", "http://localhost:2020/users/1/comments/2")
it "matches with regex", ->
@matches(/foo/, "http://localhost:2020/foo/bar/baz/123")
context "XHR#abort", ->
beforeEach ->
@send = @sandbox.stub(@window.XMLHttpRequest.prototype, "send")
@open = @sandbox.spy(@window.XMLHttpRequest.prototype, "open")
@abort = @sandbox.spy(@window.XMLHttpRequest.prototype, "abort")
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
onXhrAbort: ->
onAnyAbort: ->
})
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
it "sets aborted=true", ->
@xhr.open("GET", "/foo")
@xhr.abort()
expect(@xhr.aborted).to.eq(true)
it "calls the original abort", ->
@xhr.open("GET", "/foo")
@xhr.abort()
expect(@abort).to.be.calledOn(@xhr)
it "calls onXhrAbort callback with xhr + stack trace", ->
@sandbox.stub(@server, "getStack").returns("foobarbaz")
onXhrAbort = @sandbox.spy @server.options, "onXhrAbort"
@xhr.open("GET", "/foo")
@xhr.abort()
expect(onXhrAbort).to.be.calledWith(@server.getProxyFor(@xhr), "foobarbaz")
it "calls onAnyAbort callback with route + xhr", ->
onAnyAbort = @sandbox.spy @server.options, "onAnyAbort"
@xhr.open("GET", "/foo")
@xhr.abort()
expect(onAnyAbort).to.be.called
# context "XHR#open", ->
# beforeEach ->
# @send = @sandbox.stub(@window.XMLHttpRequest.prototype, "send")
# @open = @sandbox.spy(@window.XMLHttpRequest.prototype, "open")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @xhr = new @window.XMLHttpRequest
# it "adds to server#xhrs", ->
# expect(@server.xhrs).to.deep.eq({})
# @xhr.open("GET", "/foo")
# expect(@server.xhrs[@xhr.id]).to.eq(@xhr)
# it "normalizes async", ->
# @xhr.open("GET", "/foo")
# expect(@open).to.be.calledWith("GET", "/foo", true)
# it "changes url to stub url", ->
# @sandbox.stub(@server, "shouldApplyStub").returns(true)
# @xhr.open("GET", "/foo")
# expect(@open).to.be.calledWith("GET", "/__cypress/xhrs/foo")
# it "calls the original open", ->
# @xhr.open("GET", "/foo", true, "us", "pw")
# expect(@open).to.be.calledOn(@xhr)
# expect(@open).to.be.calledWith("GET", "/foo", true, "us", "pw")
# context "XHR#send", ->
# beforeEach ->
# @send = @sandbox.spy(@window.XMLHttpRequest.prototype, "send")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @xhr = new @window.XMLHttpRequest
# it "bails if server isnt active"
# it "sets requestBody on all requests", ->
# @xhr.open("GET", "/foo")
# @xhr.send("a=b")
# proxy = @server.getProxyFor(@xhr)
# expect(proxy.requestBody).to.eq("a=b")
# expect(proxy.request.body).to.eq("a=b")
# it "parses requestBody into JSON", ->
# @xhr.open("POST", "/users")
# @xhr.send(JSON.stringify({foo: "bar"}))
# proxy = @server.getProxyFor(@xhr)
# expect(proxy.requestBody).to.deep.eq({foo: "bar"})
# expect(proxy.request.body).to.deep.eq({foo: "bar"})
# it "sets requestBody on formData", ->
# formData = new FormData
# formData.append("foo", "bar")
# formData.append("baz", "quux")
# @xhr.open("POST", "/form")
# @xhr.send(formData)
# proxy = @server.getProxyFor(@xhr)
# expect(proxy.requestBody).to.eq(formData)
# it "sets x-cypress-id"
# it "sets x-cypress-testId"
# it "calls applyStubProperties", ->
# @server.enableStubs()
# applyStubProperties = @sandbox.spy @server, "applyStubProperties"
# stub1 = @server.stub({
# method: "POST"
# url: /.+/
# response: {}
# onRequest: ->
# })
# stub2 = @server.stub({
# method: "POST"
# url: /users/
# response: {}
# onRequest: ->
# })
# @xhr.open("POST", "/users/123")
# @xhr.send()
# expect(applyStubProperties).to.be.calledWith(@xhr, stub2)
# it "captures send (initiator) stack"
# it "calls stub.onRequest"
# it "calls send"
# context "#applyStubProperties", ->
# beforeEach ->
# @setRequestHeader = @sandbox.spy(@window.XMLHttpRequest.prototype, "setRequestHeader")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @stub = @server.stub({
# method: "POST"
# url: /foo/
# delay: 25
# status: 201
# headers: {
# "x-token": "<KEY>"
# "contentType": "foo/bar"
# "X-Foo-Bar": "sekret"
# }
# response: [{name: "b"}, {name: "j"}]
# })
# @xhr = new @window.XMLHttpRequest
# @xhr.open("POST", "foobar")
# @server.applyStubProperties(@xhr, @stub)
# @expectRequestHeader = (key, val) =>
# expect(@setRequestHeader).to.be.calledOn(@xhr)
# expect(@setRequestHeader).to.be.calledWith("X-Cypress-#{key}", val)
# it "sets status", ->
# @expectRequestHeader("Status", 201)
# it "sets response", ->
# @expectRequestHeader("Response", JSON.stringify([{name: "b"}, {name: "j"}]))
# it "sets matched url", ->
# @expectRequestHeader("Matched", "/foo/")
# it "sets delay", ->
# @expectRequestHeader("Delay", 25)
# it "sets headers", ->
# headers = JSON.stringify({
# "x-token": "<KEY>"
# "content-type": "foo/bar"
# "x-foo-bar": "<NAME>"
# })
# @expectRequestHeader("Headers", headers)
# it "does not set null/undefined headers", ->
# @setRequestHeader.reset()
# stub = @server.stub({
# method: "POST"
# url: /foo/
# })
# xhr = new @window.XMLHttpRequest
# xhr.open("POST", "foobar")
# @server.applyStubProperties(xhr, stub)
# expect(@setRequestHeader).not.to.be.calledWith("X-Cypress-Headers")
# context "#stub", ->
# beforeEach ->
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# delay: 100
# waitOnResponses: false
# foo: "bar"
# })
# @server.bindTo(@window)
# @server.enableStubs()
# it "merges defaults into stubs", ->
# expect(@server.stubs).to.be.empty
# @server.stub({
# url: /foo/
# response: {}
# delay: 50
# })
# expect(@server.stubs.length).to.eq(1)
# expect(@server.stubs[0]).to.deep.eq {
# url: /foo/
# response: {}
# delay: 50
# method: "GET"
# status: 200
# stub: true
# autoRespond: true
# waitOnResponses: false
# onRequest: undefined
# onResponse: undefined
# }
# context "#add", ->
# beforeEach ->
# @send = @sandbox.stub(@window.XMLHttpRequest.prototype, "send")
# @open = @sandbox.spy(@window.XMLHttpRequest.prototype, "open")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @xhr = new @window.XMLHttpRequest
# it "sets a unique xhrId", ->
# @xhr.open("GET", "/")
# expect(@xhr.id).to.be.a("string")
# it "merges in attrs", ->
# @xhr.open("POST", "/bar")
# expect(@xhr.method).to.eq("POST")
# expect(@xhr.url).to.include("/bar")
# context "#deactivate", ->
# beforeEach ->
# @abort = @sandbox.spy(@window.XMLHttpRequest.prototype, "abort")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# it "sets isActive=false", ->
# @server.deactivate()
# expect(@server.isActive).to.be.false
# it "aborts outstanding requests", (done) ->
# xhr1 = new @window.XMLHttpRequest
# xhr2 = new @window.XMLHttpRequest
# xhr3 = new @window.XMLHttpRequest
# xhr1.open("GET", "/fixtures/dom.html")
# xhr2.open("GET", "/timeout?ms=500")
# xhr3.open("GET", "/timeout?ms=500")
# xhr1.onload = =>
# @server.deactivate()
# ## abort should not have been called
# ## on xhr1, only xhr2 + xhr3
# expect(@abort).to.be.calledTwice
# expect(@abort).to.be.calledOn(xhr2)
# expect(@abort).to.be.calledOn(xhr3)
# done()
# _.invokeMap [xhr1, xhr2, xhr3], "send"
# context ".whitelist", ->
# it "ignores whitelisted routes even when matching stub"
context "#abort", ->
it "only aborts xhrs which have not already been aborted", ->
xhrAbort = 0
anyAbort = 0
@abort = @sandbox.spy(@window.XMLHttpRequest.prototype, "abort")
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
onXhrAbort: -> xhrAbort += 1
onAnyAbort: -> anyAbort += 1
})
@server.bindTo(@window)
@xhr1 = new @window.XMLHttpRequest
@xhr1.open("GET", "/foo")
@xhr2 = new @window.XMLHttpRequest
@xhr2.open("GET", "/foo")
@xhr3 = new @window.XMLHttpRequest
@xhr3.open("GET", "/foo")
@xhr1.abort()
@server.abort()
expect(xhrAbort).to.eq(3)
expect(anyAbort).to.eq(3)
| true | { $, _ } = window.testUtils
describe "$Cypress.Cy Server API", ->
beforeEach ->
@iframe = $("<iframe />").appendTo $("body")
@window = @iframe.prop("contentWindow")
afterEach ->
@iframe.remove()
it ".create", ->
server = $Cypress.Server.create({})
expect(server).to.be.instanceof $Cypress.Server
it ".defaults", ->
defaults = _.clone $Cypress.Server.defaults()
expect(defaults.status).to.eq(200)
defaults2 = $Cypress.Server.defaults({status: 500})
expect(defaults2.status).to.eq(500)
server = $Cypress.Server.create({})
route = server.route()
expect(route.status).to.eq(500)
$Cypress.Server.defaults(defaults)
context "#isWhitelisted", ->
beforeEach ->
@server = $Cypress.Server.create()
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
it "whitelists GET *.js", ->
@xhr.method = "GET"
@xhr.url = "/foo.js"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.jsx", ->
@xhr.method = "GET"
@xhr.url = "/foo.jsx"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.html", ->
@xhr.method = "GET"
@xhr.url = "/foo.html"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.css", ->
@xhr.method = "GET"
@xhr.url = "/foo.css"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.scss", ->
@xhr.method = "GET"
@xhr.url = "/foo.scss"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.less", ->
@xhr.method = "GET"
@xhr.url = "/foo.less"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.coffee", ->
@xhr.method = "GET"
@xhr.url = "/foo.coffee"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.js.coffee", ->
@xhr.method = "GET"
@xhr.url = "/foo.js.coffee"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.js?_=123123", ->
@xhr.method = "GET"
@xhr.url = "/foo.js?_=123123"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.html?_=123123&foo=bar", ->
@xhr.method = "GET"
@xhr.url = "/foo.html?_=123123&foo=bar"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "whitelists GET *.svg", ->
@xhr.method = "GET"
@xhr.url = "/foo.svg"
expect(@server.isWhitelisted(@xhr)).to.be.true
it "does not whitelist GET *.json?_=123123", ->
@xhr.method = "GET"
@xhr.url = "/foo.json?_=123123"
expect(@server.isWhitelisted(@xhr)).not.to.be.true
it "does not whitelist OPTIONS *.js?_=123123", ->
@xhr.method = "OPTIONS"
@xhr.url = "/foo.js?_=123123"
expect(@server.isWhitelisted(@xhr)).not.to.be.true
context "#setRequestHeader", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@srh = @sandbox.spy(@window.XMLHttpRequest.prototype, "setRequestHeader")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "sets request.headers", ->
@proxy.setRequestHeader("foo", "bar")
expect(@proxy.request.headers).to.deep.eq({foo: "bar"})
it "appends to request.headers", ->
@proxy.setRequestHeader("foo", "bar")
@proxy.setRequestHeader("foo", "baz")
expect(@proxy.request.headers).to.deep.eq({foo: "bar, baz"})
it "ignores cypress headers", ->
@proxy.setRequestHeader("X-Cypress-Delay", 1000)
expect(@proxy.request.headers).not.to.be.ok
it "sets proxy request headers from xhr", ->
@xhr.setRequestHeader("foo", "bar")
## the original setRequestHeaders method should be called here
expect(@srh).to.be.calledWith("foo", "bar")
expect(@proxy.request.headers).to.deep.eq({foo: "bar"})
## since we yield the xhrProxy object in tests
## we need to call the original xhr's implementation
## on setRequestHeaders
it "calls the original xhr's implementation", ->
@proxy.setRequestHeader("foo", "bar")
expect(@srh).to.be.calledWith("foo", "bar")
expect(@srh).to.be.calledOn(@xhr)
context "#applyStubProperties", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@srh = @sandbox.spy(@window.XMLHttpRequest.prototype, "setRequestHeader")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "encodes the http header value", ->
route = {
response: {"test": "We’ll"}
}
@sandbox.spy(@xhr, "setRequestHeader")
## this function would previous throw unless
## we decoded the value
@server.applyStubProperties(@xhr, route)
expect(@xhr.setRequestHeader).to.be.calledWith("X-Cypress-Response", "%7B%22test%22:%22We%E2%80%99ll%22%7D")
context "#getResponseHeader", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@grh = @sandbox.spy(@window.XMLHttpRequest.prototype, "getResponseHeader")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "calls the original xhr implementation", ->
@proxy.getResponseHeader("foo")
expect(@grh).to.be.calledWith("foo")
expect(@grh).to.be.calledOn(@xhr)
context "#getAllResponseHeaders", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@garh = @sandbox.spy(@window.XMLHttpRequest.prototype, "getAllResponseHeaders")
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
@xhr.open("GET", "/fixtures/app.json")
@proxy = @server.getProxyFor(@xhr)
it "calls the original xhr implementation", ->
@proxy.getAllResponseHeaders()
expect(@garh).to.be.calledOnce
expect(@garh).to.be.calledOn(@xhr)
context "#setResponseHeaders", ->
beforeEach ->
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
})
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
it "sets response.headers and responseHeaders", (done) ->
headers = """
X-Powered-By: Express
Vary: Accept-Encoding
Content-Type: application/json
Cache-Control: public, max-age=0
Connection: keep-alive
Content-Length: 53
""".split("\n").join('\u000d\u000a')
@sandbox.stub(@xhr, "getAllResponseHeaders").returns(headers)
@xhr.open("GET", "/fixtures/app.json")
proxy = @server.getProxyFor(@xhr)
@xhr.onload = ->
expect(proxy.responseHeaders).to.eq(proxy.response.headers)
expect(proxy.responseHeaders).to.deep.eq({
"X-Powered-By": "Express"
"Vary": "Accept-Encoding"
"Content-Type": "application/json"
"Cache-Control": "public, max-age=0"
"Connection": "keep-alive"
"Content-Length": "53"
})
done()
@xhr.send()
context "#getFullyQualifiedUrl", ->
beforeEach ->
@server = $Cypress.Server.create()
@expectUrlToEq = (url, url2) =>
expect(@server.getFullyQualifiedUrl(window, url)).to.eq(url2)
it "resolves absolute relative links", ->
@expectUrlToEq("/foo/bar.html", "#{window.location.origin}/foo/bar.html")
it "resolves relative links", ->
## slice off the last path segment since this is a relative link
## http://localhost:3500/specs/api/cypress/server_spec -> http://localhost:3500/specs/api/cypress
path = window.location.origin + window.location.pathname.split("/").slice(0, -1).join("/")
@expectUrlToEq("foo/bar.html", "#{path}/foo/bar.html")
context "#urlsMatch", ->
beforeEach ->
@server = $Cypress.Server.create({
stripOrigin: (url) ->
location = $Cypress.Location.create(url)
url.replace(location.origin, "")
})
@matches = (url1, url2) ->
expect(@server.urlsMatch(url1, url2)).to.be.true
@notMatches = (url1, url2) ->
expect(@server.urlsMatch(url1, url2)).to.be.false
it "matches fully qualified route", ->
@matches("http://localhost:2020/foo", "http://localhost:2020/foo")
it "matches absolute relative route", ->
@matches("/foo", "http://localhost:2020/foo")
it "prepends with forward slash on glob", ->
@matches("foo/bar", "http://localhost:2020/foo/bar")
it "uses default urlMatchingOptions", ->
## test that matchBase is true by default
expect(@server.options.urlMatchingOptions).to.deep.eq({matchBase: true})
@matches("foo", "http://localhost:2020/a/b/c/foo")
it "prepends with forward slash", ->
@matches("foo/*", "http://localhost:2020/foo/123")
it "use glob stars", ->
@matches("/users/**", "https://localhost:2020/users/foo/bar?a=1")
it "use glob stars between url segments", ->
@matches("/users/*/comments/*", "http://localhost:2020/users/1/comments/2")
it "matches with regex", ->
@matches(/foo/, "http://localhost:2020/foo/bar/baz/123")
context "XHR#abort", ->
beforeEach ->
@send = @sandbox.stub(@window.XMLHttpRequest.prototype, "send")
@open = @sandbox.spy(@window.XMLHttpRequest.prototype, "open")
@abort = @sandbox.spy(@window.XMLHttpRequest.prototype, "abort")
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
onXhrAbort: ->
onAnyAbort: ->
})
@server.bindTo(@window)
@xhr = new @window.XMLHttpRequest
it "sets aborted=true", ->
@xhr.open("GET", "/foo")
@xhr.abort()
expect(@xhr.aborted).to.eq(true)
it "calls the original abort", ->
@xhr.open("GET", "/foo")
@xhr.abort()
expect(@abort).to.be.calledOn(@xhr)
it "calls onXhrAbort callback with xhr + stack trace", ->
@sandbox.stub(@server, "getStack").returns("foobarbaz")
onXhrAbort = @sandbox.spy @server.options, "onXhrAbort"
@xhr.open("GET", "/foo")
@xhr.abort()
expect(onXhrAbort).to.be.calledWith(@server.getProxyFor(@xhr), "foobarbaz")
it "calls onAnyAbort callback with route + xhr", ->
onAnyAbort = @sandbox.spy @server.options, "onAnyAbort"
@xhr.open("GET", "/foo")
@xhr.abort()
expect(onAnyAbort).to.be.called
# context "XHR#open", ->
# beforeEach ->
# @send = @sandbox.stub(@window.XMLHttpRequest.prototype, "send")
# @open = @sandbox.spy(@window.XMLHttpRequest.prototype, "open")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @xhr = new @window.XMLHttpRequest
# it "adds to server#xhrs", ->
# expect(@server.xhrs).to.deep.eq({})
# @xhr.open("GET", "/foo")
# expect(@server.xhrs[@xhr.id]).to.eq(@xhr)
# it "normalizes async", ->
# @xhr.open("GET", "/foo")
# expect(@open).to.be.calledWith("GET", "/foo", true)
# it "changes url to stub url", ->
# @sandbox.stub(@server, "shouldApplyStub").returns(true)
# @xhr.open("GET", "/foo")
# expect(@open).to.be.calledWith("GET", "/__cypress/xhrs/foo")
# it "calls the original open", ->
# @xhr.open("GET", "/foo", true, "us", "pw")
# expect(@open).to.be.calledOn(@xhr)
# expect(@open).to.be.calledWith("GET", "/foo", true, "us", "pw")
# context "XHR#send", ->
# beforeEach ->
# @send = @sandbox.spy(@window.XMLHttpRequest.prototype, "send")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @xhr = new @window.XMLHttpRequest
# it "bails if server isnt active"
# it "sets requestBody on all requests", ->
# @xhr.open("GET", "/foo")
# @xhr.send("a=b")
# proxy = @server.getProxyFor(@xhr)
# expect(proxy.requestBody).to.eq("a=b")
# expect(proxy.request.body).to.eq("a=b")
# it "parses requestBody into JSON", ->
# @xhr.open("POST", "/users")
# @xhr.send(JSON.stringify({foo: "bar"}))
# proxy = @server.getProxyFor(@xhr)
# expect(proxy.requestBody).to.deep.eq({foo: "bar"})
# expect(proxy.request.body).to.deep.eq({foo: "bar"})
# it "sets requestBody on formData", ->
# formData = new FormData
# formData.append("foo", "bar")
# formData.append("baz", "quux")
# @xhr.open("POST", "/form")
# @xhr.send(formData)
# proxy = @server.getProxyFor(@xhr)
# expect(proxy.requestBody).to.eq(formData)
# it "sets x-cypress-id"
# it "sets x-cypress-testId"
# it "calls applyStubProperties", ->
# @server.enableStubs()
# applyStubProperties = @sandbox.spy @server, "applyStubProperties"
# stub1 = @server.stub({
# method: "POST"
# url: /.+/
# response: {}
# onRequest: ->
# })
# stub2 = @server.stub({
# method: "POST"
# url: /users/
# response: {}
# onRequest: ->
# })
# @xhr.open("POST", "/users/123")
# @xhr.send()
# expect(applyStubProperties).to.be.calledWith(@xhr, stub2)
# it "captures send (initiator) stack"
# it "calls stub.onRequest"
# it "calls send"
# context "#applyStubProperties", ->
# beforeEach ->
# @setRequestHeader = @sandbox.spy(@window.XMLHttpRequest.prototype, "setRequestHeader")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @stub = @server.stub({
# method: "POST"
# url: /foo/
# delay: 25
# status: 201
# headers: {
# "x-token": "PI:KEY:<KEY>END_PI"
# "contentType": "foo/bar"
# "X-Foo-Bar": "sekret"
# }
# response: [{name: "b"}, {name: "j"}]
# })
# @xhr = new @window.XMLHttpRequest
# @xhr.open("POST", "foobar")
# @server.applyStubProperties(@xhr, @stub)
# @expectRequestHeader = (key, val) =>
# expect(@setRequestHeader).to.be.calledOn(@xhr)
# expect(@setRequestHeader).to.be.calledWith("X-Cypress-#{key}", val)
# it "sets status", ->
# @expectRequestHeader("Status", 201)
# it "sets response", ->
# @expectRequestHeader("Response", JSON.stringify([{name: "b"}, {name: "j"}]))
# it "sets matched url", ->
# @expectRequestHeader("Matched", "/foo/")
# it "sets delay", ->
# @expectRequestHeader("Delay", 25)
# it "sets headers", ->
# headers = JSON.stringify({
# "x-token": "PI:KEY:<KEY>END_PI"
# "content-type": "foo/bar"
# "x-foo-bar": "PI:NAME:<NAME>END_PI"
# })
# @expectRequestHeader("Headers", headers)
# it "does not set null/undefined headers", ->
# @setRequestHeader.reset()
# stub = @server.stub({
# method: "POST"
# url: /foo/
# })
# xhr = new @window.XMLHttpRequest
# xhr.open("POST", "foobar")
# @server.applyStubProperties(xhr, stub)
# expect(@setRequestHeader).not.to.be.calledWith("X-Cypress-Headers")
# context "#stub", ->
# beforeEach ->
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# delay: 100
# waitOnResponses: false
# foo: "bar"
# })
# @server.bindTo(@window)
# @server.enableStubs()
# it "merges defaults into stubs", ->
# expect(@server.stubs).to.be.empty
# @server.stub({
# url: /foo/
# response: {}
# delay: 50
# })
# expect(@server.stubs.length).to.eq(1)
# expect(@server.stubs[0]).to.deep.eq {
# url: /foo/
# response: {}
# delay: 50
# method: "GET"
# status: 200
# stub: true
# autoRespond: true
# waitOnResponses: false
# onRequest: undefined
# onResponse: undefined
# }
# context "#add", ->
# beforeEach ->
# @send = @sandbox.stub(@window.XMLHttpRequest.prototype, "send")
# @open = @sandbox.spy(@window.XMLHttpRequest.prototype, "open")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# @xhr = new @window.XMLHttpRequest
# it "sets a unique xhrId", ->
# @xhr.open("GET", "/")
# expect(@xhr.id).to.be.a("string")
# it "merges in attrs", ->
# @xhr.open("POST", "/bar")
# expect(@xhr.method).to.eq("POST")
# expect(@xhr.url).to.include("/bar")
# context "#deactivate", ->
# beforeEach ->
# @abort = @sandbox.spy(@window.XMLHttpRequest.prototype, "abort")
# @server = $Cypress.Server.create({
# xhrUrl: "__cypress/xhrs/"
# })
# @server.bindTo(@window)
# it "sets isActive=false", ->
# @server.deactivate()
# expect(@server.isActive).to.be.false
# it "aborts outstanding requests", (done) ->
# xhr1 = new @window.XMLHttpRequest
# xhr2 = new @window.XMLHttpRequest
# xhr3 = new @window.XMLHttpRequest
# xhr1.open("GET", "/fixtures/dom.html")
# xhr2.open("GET", "/timeout?ms=500")
# xhr3.open("GET", "/timeout?ms=500")
# xhr1.onload = =>
# @server.deactivate()
# ## abort should not have been called
# ## on xhr1, only xhr2 + xhr3
# expect(@abort).to.be.calledTwice
# expect(@abort).to.be.calledOn(xhr2)
# expect(@abort).to.be.calledOn(xhr3)
# done()
# _.invokeMap [xhr1, xhr2, xhr3], "send"
# context ".whitelist", ->
# it "ignores whitelisted routes even when matching stub"
context "#abort", ->
it "only aborts xhrs which have not already been aborted", ->
xhrAbort = 0
anyAbort = 0
@abort = @sandbox.spy(@window.XMLHttpRequest.prototype, "abort")
@server = $Cypress.Server.create({
xhrUrl: "__cypress/xhrs/"
onXhrAbort: -> xhrAbort += 1
onAnyAbort: -> anyAbort += 1
})
@server.bindTo(@window)
@xhr1 = new @window.XMLHttpRequest
@xhr1.open("GET", "/foo")
@xhr2 = new @window.XMLHttpRequest
@xhr2.open("GET", "/foo")
@xhr3 = new @window.XMLHttpRequest
@xhr3.open("GET", "/foo")
@xhr1.abort()
@server.abort()
expect(xhrAbort).to.eq(3)
expect(anyAbort).to.eq(3)
|
[
{
"context": "ssert.deepEqual(data.fr, {\n \"Hello!\": \"Bonjour!\"\n \"This is a test\": \"Ceci est un test",
"end": 2016,
"score": 0.7803230285644531,
"start": 2009,
"tag": "NAME",
"value": "Bonjour"
},
{
"context": "rt.deepEqual(data.nl, {\n \"Hello!\": \"Hallo!\"\n \"This is a test\": \"Dit is een test\"",
"end": 2186,
"score": 0.7348093390464783,
"start": 2184,
"tag": "NAME",
"value": "lo"
},
{
"context": "ssert.deepEqual(data.fr, {\n \"Hello!\": \"Bonjour!\"\n \"This is a test\": \"Ceci est un test",
"end": 2571,
"score": 0.9638954997062683,
"start": 2564,
"tag": "NAME",
"value": "Bonjour"
}
] | test/compile.coffee | gruntjs-updater/grunt-angular-gettext-message | 0 | assert = require 'assert'
fs = require 'fs'
vm = require 'vm'
# Fake Angular environment
makeEnv = (mod, catalog) -> {
angular:
module: (modDefined) ->
assert.equal(modDefined, mod)
return {
run: (block) ->
assert.equal(block[0], 'gettextCatalog')
block[1](catalog)
}
}
describe 'Compile', ->
it 'Compiles a .po file into a .js catalog', ->
assert(fs.existsSync('tmp/test1.js'))
catalog = {
setStrings: (language, strings) ->
assert.equal(language, 'nl')
assert.equal(strings['Hello!'], 'Hallo!')
assert.equal(strings['This is a test'], 'Dit is een test')
assert.deepEqual(strings['Bird'], [ 'Vogel', 'Vogels' ])
assert.deepEqual(strings['Hello \"world\"'], 'Hallo \"wereld\"')
}
context = vm.createContext(makeEnv('gettext', catalog))
vm.runInContext(fs.readFileSync('tmp/test1.js', 'utf8'), context)
it 'Accepts a module parameter', ->
assert(fs.existsSync('tmp/test2.js'))
catalog = {
setStrings: (language, strings) ->
}
context = vm.createContext(makeEnv('myApp', catalog))
vm.runInContext(fs.readFileSync('tmp/test2.js', 'utf8'), context)
it 'Allows merging multiple languages', ->
assert(fs.existsSync('tmp/test3.js'))
languages = 0
catalog = {
setStrings: (language, strings) ->
assert(language == 'nl' || language == 'fr')
languages++
}
context = vm.createContext(makeEnv('gettext', catalog))
vm.runInContext(fs.readFileSync('tmp/test3.js', 'utf8'), context)
assert.equal(languages, 2)
it 'Can output to JSON', ->
assert(fs.existsSync('tmp/test4.json'))
data = JSON.parse(fs.readFileSync('tmp/test4.json'))
assert.deepEqual(data.fr, {
"Hello!": "Bonjour!"
"This is a test": "Ceci est un test",
"Bird": ["Oiseau", "Oiseaux"]
})
assert.deepEqual(data.nl, {
"Hello!": "Hallo!"
"This is a test": "Dit is een test",
"Bird": ["Vogel", "Vogels"],
"Hello \"world\"": "Hallo \"wereld\""
})
it 'Can output multiple files to single JSON', ->
assert(fs.existsSync('tmp/test5.json'))
data = JSON.parse(fs.readFileSync('tmp/test5.json'))
assert.deepEqual(data.fr, {
"Hello!": "Bonjour!"
"This is a test": "Ceci est un test",
"Bird": ["Oiseau", "Oiseaux"],
"Goodbye!": "Au revoir!"
})
| 100248 | assert = require 'assert'
fs = require 'fs'
vm = require 'vm'
# Fake Angular environment
makeEnv = (mod, catalog) -> {
angular:
module: (modDefined) ->
assert.equal(modDefined, mod)
return {
run: (block) ->
assert.equal(block[0], 'gettextCatalog')
block[1](catalog)
}
}
describe 'Compile', ->
it 'Compiles a .po file into a .js catalog', ->
assert(fs.existsSync('tmp/test1.js'))
catalog = {
setStrings: (language, strings) ->
assert.equal(language, 'nl')
assert.equal(strings['Hello!'], 'Hallo!')
assert.equal(strings['This is a test'], 'Dit is een test')
assert.deepEqual(strings['Bird'], [ 'Vogel', 'Vogels' ])
assert.deepEqual(strings['Hello \"world\"'], 'Hallo \"wereld\"')
}
context = vm.createContext(makeEnv('gettext', catalog))
vm.runInContext(fs.readFileSync('tmp/test1.js', 'utf8'), context)
it 'Accepts a module parameter', ->
assert(fs.existsSync('tmp/test2.js'))
catalog = {
setStrings: (language, strings) ->
}
context = vm.createContext(makeEnv('myApp', catalog))
vm.runInContext(fs.readFileSync('tmp/test2.js', 'utf8'), context)
it 'Allows merging multiple languages', ->
assert(fs.existsSync('tmp/test3.js'))
languages = 0
catalog = {
setStrings: (language, strings) ->
assert(language == 'nl' || language == 'fr')
languages++
}
context = vm.createContext(makeEnv('gettext', catalog))
vm.runInContext(fs.readFileSync('tmp/test3.js', 'utf8'), context)
assert.equal(languages, 2)
it 'Can output to JSON', ->
assert(fs.existsSync('tmp/test4.json'))
data = JSON.parse(fs.readFileSync('tmp/test4.json'))
assert.deepEqual(data.fr, {
"Hello!": "<NAME>!"
"This is a test": "Ceci est un test",
"Bird": ["Oiseau", "Oiseaux"]
})
assert.deepEqual(data.nl, {
"Hello!": "Hal<NAME>!"
"This is a test": "Dit is een test",
"Bird": ["Vogel", "Vogels"],
"Hello \"world\"": "Hallo \"wereld\""
})
it 'Can output multiple files to single JSON', ->
assert(fs.existsSync('tmp/test5.json'))
data = JSON.parse(fs.readFileSync('tmp/test5.json'))
assert.deepEqual(data.fr, {
"Hello!": "<NAME>!"
"This is a test": "Ceci est un test",
"Bird": ["Oiseau", "Oiseaux"],
"Goodbye!": "Au revoir!"
})
| true | assert = require 'assert'
fs = require 'fs'
vm = require 'vm'
# Fake Angular environment
makeEnv = (mod, catalog) -> {
angular:
module: (modDefined) ->
assert.equal(modDefined, mod)
return {
run: (block) ->
assert.equal(block[0], 'gettextCatalog')
block[1](catalog)
}
}
describe 'Compile', ->
it 'Compiles a .po file into a .js catalog', ->
assert(fs.existsSync('tmp/test1.js'))
catalog = {
setStrings: (language, strings) ->
assert.equal(language, 'nl')
assert.equal(strings['Hello!'], 'Hallo!')
assert.equal(strings['This is a test'], 'Dit is een test')
assert.deepEqual(strings['Bird'], [ 'Vogel', 'Vogels' ])
assert.deepEqual(strings['Hello \"world\"'], 'Hallo \"wereld\"')
}
context = vm.createContext(makeEnv('gettext', catalog))
vm.runInContext(fs.readFileSync('tmp/test1.js', 'utf8'), context)
it 'Accepts a module parameter', ->
assert(fs.existsSync('tmp/test2.js'))
catalog = {
setStrings: (language, strings) ->
}
context = vm.createContext(makeEnv('myApp', catalog))
vm.runInContext(fs.readFileSync('tmp/test2.js', 'utf8'), context)
it 'Allows merging multiple languages', ->
assert(fs.existsSync('tmp/test3.js'))
languages = 0
catalog = {
setStrings: (language, strings) ->
assert(language == 'nl' || language == 'fr')
languages++
}
context = vm.createContext(makeEnv('gettext', catalog))
vm.runInContext(fs.readFileSync('tmp/test3.js', 'utf8'), context)
assert.equal(languages, 2)
it 'Can output to JSON', ->
assert(fs.existsSync('tmp/test4.json'))
data = JSON.parse(fs.readFileSync('tmp/test4.json'))
assert.deepEqual(data.fr, {
"Hello!": "PI:NAME:<NAME>END_PI!"
"This is a test": "Ceci est un test",
"Bird": ["Oiseau", "Oiseaux"]
})
assert.deepEqual(data.nl, {
"Hello!": "HalPI:NAME:<NAME>END_PI!"
"This is a test": "Dit is een test",
"Bird": ["Vogel", "Vogels"],
"Hello \"world\"": "Hallo \"wereld\""
})
it 'Can output multiple files to single JSON', ->
assert(fs.existsSync('tmp/test5.json'))
data = JSON.parse(fs.readFileSync('tmp/test5.json'))
assert.deepEqual(data.fr, {
"Hello!": "PI:NAME:<NAME>END_PI!"
"This is a test": "Ceci est un test",
"Bird": ["Oiseau", "Oiseaux"],
"Goodbye!": "Au revoir!"
})
|
[
{
"context": "# Made with Framer\n# By Jay Stakelon\n# www.framerjs.com\n\n# Set default cursor\ndocument",
"end": 36,
"score": 0.9998897910118103,
"start": 24,
"tag": "NAME",
"value": "Jay Stakelon"
}
] | examples/video-player.framer/app.coffee | benjamindenboer/Framer-VideoPlayer | 1 | # Made with Framer
# By Jay Stakelon
# www.framerjs.com
# Set default cursor
document.body.style.cursor = "auto"
bg = new BackgroundLayer
backgroundColor: "#fff"
{VideoPlayer} = require "videoplayer"
video = new VideoPlayer
video: "video.mp4"
width: 700
height: 394
video.centerX()
video.centerY(-50)
video.showProgress = true
video.progressBar.centerX()
video.progressBar.centerY video.height/2
video.showTimeElapsed = true
video.timeElapsed.x = video.x + 50
video.timeElapsed.centerY video.height/2 + 35
video.showTimeLeft = true
video.timeLeft.maxX = video.maxX
video.timeLeft.centerY video.height/2 + 35
video.shyPlayButton = true
video.player.loop = true | 146460 | # Made with Framer
# By <NAME>
# www.framerjs.com
# Set default cursor
document.body.style.cursor = "auto"
bg = new BackgroundLayer
backgroundColor: "#fff"
{VideoPlayer} = require "videoplayer"
video = new VideoPlayer
video: "video.mp4"
width: 700
height: 394
video.centerX()
video.centerY(-50)
video.showProgress = true
video.progressBar.centerX()
video.progressBar.centerY video.height/2
video.showTimeElapsed = true
video.timeElapsed.x = video.x + 50
video.timeElapsed.centerY video.height/2 + 35
video.showTimeLeft = true
video.timeLeft.maxX = video.maxX
video.timeLeft.centerY video.height/2 + 35
video.shyPlayButton = true
video.player.loop = true | true | # Made with Framer
# By PI:NAME:<NAME>END_PI
# www.framerjs.com
# Set default cursor
document.body.style.cursor = "auto"
bg = new BackgroundLayer
backgroundColor: "#fff"
{VideoPlayer} = require "videoplayer"
video = new VideoPlayer
video: "video.mp4"
width: 700
height: 394
video.centerX()
video.centerY(-50)
video.showProgress = true
video.progressBar.centerX()
video.progressBar.centerY video.height/2
video.showTimeElapsed = true
video.timeElapsed.x = video.x + 50
video.timeElapsed.centerY video.height/2 + 35
video.showTimeLeft = true
video.timeLeft.maxX = video.maxX
video.timeLeft.centerY video.height/2 + 35
video.shyPlayButton = true
video.player.loop = true |
[
{
"context": "ake-key/tokens'\n .reply 201, { token: 'qwerty' }\n\n it 'callbacks with accessToken', (don",
"end": 1430,
"score": 0.6359672546386719,
"start": 1424,
"tag": "KEY",
"value": "qwerty"
},
{
"context": "ts/fake-key/tokens'\n .reply 201, { token: 'qwerty' }\n before ->\n opts =\n clientK",
"end": 2312,
"score": 0.8537389039993286,
"start": 2310,
"tag": "PASSWORD",
"value": "qw"
},
{
"context": "/fake-key/tokens'\n .reply 201, { token: 'qwerty' }\n before ->\n opts =\n clientKey: ",
"end": 2316,
"score": 0.5596376061439514,
"start": 2312,
"tag": "KEY",
"value": "erty"
},
{
"context": " clientKey: 'fake-key'\n clientSecret: 'fake-secret'\n context 'when request succeeded', ->\n b",
"end": 2411,
"score": 0.9601739048957825,
"start": 2400,
"tag": "KEY",
"value": "fake-secret"
}
] | test/client_test.coffee | oneteam-dev/node-oneteam-client | 1 | {expect} = require 'chai'
nock = require 'nock'
sinon = require 'sinon'
describe 'client', ->
client = null
opts = null
clock = null
nockScope = null
currentTime = 1455008759942
Client = null
beforeEach ->
process.env.ONETEAM_BASE_API_URL = 'https://api.one-team.test'
Client = require '../src/client'
client = new Client opts
clock = sinon.useFakeTimers currentTime
nockScope = nock 'https://api.one-team.test'
nock.disableNetConnect()
afterEach ->
nock.cleanAll()
describe 'fetchAccessToken(callback)', ->
subject = null
beforeEach ->
subject = client.fetchAccessToken.bind client
context 'when required options are not set', ->
before ->
opts = {}
it 'throw an error', ->
expect(subject).to.throw 'accessToken or pair of clientKey + clientSecret is must be set.'
context 'when accessToken is set', ->
before ->
opts = accessToken: 'asdf'
it 'callbacks with accessToken', (done) ->
subject (err, data) ->
expect(data).to.equal 'asdf'
do done
context 'when clientKey and clientSecret is set', (done) ->
before ->
opts =
clientKey: 'fake-key'
clientSecret: 'fake-secret'
context 'when request succeeded', ->
beforeEach ->
nockScope
.post '/clients/fake-key/tokens'
.reply 201, { token: 'qwerty' }
it 'callbacks with accessToken', (done) ->
subject (err, data) ->
expect(err).to.be.null
expect(client.accessToken).to.equal 'qwerty'
expect(data).to.equal 'qwerty'
do done
context 'when request failed', ->
beforeEach ->
nockScope
.post '/clients/fake-key/tokens'
.reply 400, { errors: [{message: 'bad req'}] }
it 'callbacks with accessToken', (done) ->
subject (err, data) ->
expect(err.message).to.equal 'bad req'
expect(client.accessToken).to.be.null
expect(data).to.be.null
do done
describe 'team(teamName, callback)', ->
subject = null
beforeEach ->
subject = client.team.bind client
nockScope
.post '/clients/fake-key/tokens'
.reply 201, { token: 'qwerty' }
before ->
opts =
clientKey: 'fake-key'
clientSecret: 'fake-secret'
context 'when request succeeded', ->
beforeEach ->
nockScope
.get '/teams/oneteam'
.replyWithFile 200, "#{__dirname}/fixtures/team.json"
it 'callbacks with team instance', (done) ->
subject 'oneteam', (err, team) ->
expect(err).to.be.null
expect(team).not.to.be.null
expect(team.client).to.equal client
expect(team.name).to.equal 'Oneteam Inc.'
do done
| 74526 | {expect} = require 'chai'
nock = require 'nock'
sinon = require 'sinon'
describe 'client', ->
client = null
opts = null
clock = null
nockScope = null
currentTime = 1455008759942
Client = null
beforeEach ->
process.env.ONETEAM_BASE_API_URL = 'https://api.one-team.test'
Client = require '../src/client'
client = new Client opts
clock = sinon.useFakeTimers currentTime
nockScope = nock 'https://api.one-team.test'
nock.disableNetConnect()
afterEach ->
nock.cleanAll()
describe 'fetchAccessToken(callback)', ->
subject = null
beforeEach ->
subject = client.fetchAccessToken.bind client
context 'when required options are not set', ->
before ->
opts = {}
it 'throw an error', ->
expect(subject).to.throw 'accessToken or pair of clientKey + clientSecret is must be set.'
context 'when accessToken is set', ->
before ->
opts = accessToken: 'asdf'
it 'callbacks with accessToken', (done) ->
subject (err, data) ->
expect(data).to.equal 'asdf'
do done
context 'when clientKey and clientSecret is set', (done) ->
before ->
opts =
clientKey: 'fake-key'
clientSecret: 'fake-secret'
context 'when request succeeded', ->
beforeEach ->
nockScope
.post '/clients/fake-key/tokens'
.reply 201, { token: '<KEY>' }
it 'callbacks with accessToken', (done) ->
subject (err, data) ->
expect(err).to.be.null
expect(client.accessToken).to.equal 'qwerty'
expect(data).to.equal 'qwerty'
do done
context 'when request failed', ->
beforeEach ->
nockScope
.post '/clients/fake-key/tokens'
.reply 400, { errors: [{message: 'bad req'}] }
it 'callbacks with accessToken', (done) ->
subject (err, data) ->
expect(err.message).to.equal 'bad req'
expect(client.accessToken).to.be.null
expect(data).to.be.null
do done
describe 'team(teamName, callback)', ->
subject = null
beforeEach ->
subject = client.team.bind client
nockScope
.post '/clients/fake-key/tokens'
.reply 201, { token: '<PASSWORD> <KEY>' }
before ->
opts =
clientKey: 'fake-key'
clientSecret: '<KEY>'
context 'when request succeeded', ->
beforeEach ->
nockScope
.get '/teams/oneteam'
.replyWithFile 200, "#{__dirname}/fixtures/team.json"
it 'callbacks with team instance', (done) ->
subject 'oneteam', (err, team) ->
expect(err).to.be.null
expect(team).not.to.be.null
expect(team.client).to.equal client
expect(team.name).to.equal 'Oneteam Inc.'
do done
| true | {expect} = require 'chai'
nock = require 'nock'
sinon = require 'sinon'
describe 'client', ->
client = null
opts = null
clock = null
nockScope = null
currentTime = 1455008759942
Client = null
beforeEach ->
process.env.ONETEAM_BASE_API_URL = 'https://api.one-team.test'
Client = require '../src/client'
client = new Client opts
clock = sinon.useFakeTimers currentTime
nockScope = nock 'https://api.one-team.test'
nock.disableNetConnect()
afterEach ->
nock.cleanAll()
describe 'fetchAccessToken(callback)', ->
subject = null
beforeEach ->
subject = client.fetchAccessToken.bind client
context 'when required options are not set', ->
before ->
opts = {}
it 'throw an error', ->
expect(subject).to.throw 'accessToken or pair of clientKey + clientSecret is must be set.'
context 'when accessToken is set', ->
before ->
opts = accessToken: 'asdf'
it 'callbacks with accessToken', (done) ->
subject (err, data) ->
expect(data).to.equal 'asdf'
do done
context 'when clientKey and clientSecret is set', (done) ->
before ->
opts =
clientKey: 'fake-key'
clientSecret: 'fake-secret'
context 'when request succeeded', ->
beforeEach ->
nockScope
.post '/clients/fake-key/tokens'
.reply 201, { token: 'PI:KEY:<KEY>END_PI' }
it 'callbacks with accessToken', (done) ->
subject (err, data) ->
expect(err).to.be.null
expect(client.accessToken).to.equal 'qwerty'
expect(data).to.equal 'qwerty'
do done
context 'when request failed', ->
beforeEach ->
nockScope
.post '/clients/fake-key/tokens'
.reply 400, { errors: [{message: 'bad req'}] }
it 'callbacks with accessToken', (done) ->
subject (err, data) ->
expect(err.message).to.equal 'bad req'
expect(client.accessToken).to.be.null
expect(data).to.be.null
do done
describe 'team(teamName, callback)', ->
subject = null
beforeEach ->
subject = client.team.bind client
nockScope
.post '/clients/fake-key/tokens'
.reply 201, { token: 'PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI' }
before ->
opts =
clientKey: 'fake-key'
clientSecret: 'PI:KEY:<KEY>END_PI'
context 'when request succeeded', ->
beforeEach ->
nockScope
.get '/teams/oneteam'
.replyWithFile 200, "#{__dirname}/fixtures/team.json"
it 'callbacks with team instance', (done) ->
subject 'oneteam', (err, team) ->
expect(err).to.be.null
expect(team).not.to.be.null
expect(team.client).to.equal client
expect(team.name).to.equal 'Oneteam Inc.'
do done
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9976190328598022,
"start": 16,
"tag": "NAME",
"value": "Konode"
},
{
"context": "\t\t\t\t# TODO: Include user's full name + username (\"Andrew Appleby (aappleby)\")\n\t\t\t\t\t\t\t\tR.span({className: 'author'}",
"end": 8531,
"score": 0.9998258352279663,
"start": 8517,
"tag": "NAME",
"value": "Andrew Appleby"
},
{
"context": "ude user's full name + username (\"Andrew Appleby (aappleby)\")\n\t\t\t\t\t\t\t\tR.span({className: 'author'}, @props.d",
"end": 8541,
"score": 0.9000375866889954,
"start": 8533,
"tag": "USERNAME",
"value": "aappleby"
},
{
"context": "\t\t\t\t# TODO: Include user's full name + username (\"Andrew Appleby (aappleby)\")\n\t\t\t\t\t\t\tR.span({className: 'author'},",
"end": 8819,
"score": 0.9998447895050049,
"start": 8805,
"tag": "NAME",
"value": "Andrew Appleby"
},
{
"context": "ude user's full name + username (\"Andrew Appleby (aappleby)\")\n\t\t\t\t\t\t\tR.span({className: 'author'}, global.Ac",
"end": 8829,
"score": 0.8975227475166321,
"start": 8821,
"tag": "USERNAME",
"value": "aappleby"
},
{
"context": "\t\t\t\t\t\t\t\t\tisEditable: false\n\t\t\t\t\t\t\t\t\t\t\t\tkey: metric.get('id')\n\t\t\t\t\t\t\t\t\t\t\t\tname: metric.get('name')\n\t\t\t\t\t\t",
"end": 10344,
"score": 0.6486390829086304,
"start": 10341,
"tag": "KEY",
"value": "get"
},
{
"context": "\t\t\tisEditable: false\n\t\t\t\t\t\t\t\t\t\t\t\tkey: metric.get('id')\n\t\t\t\t\t\t\t\t\t\t\t\tname: metric.get('name')\n\t\t\t\t\t\t\t\t\t\t",
"end": 10348,
"score": 0.6673466563224792,
"start": 10346,
"tag": "KEY",
"value": "id"
}
] | src/printPreviewPage.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Print preview page receives data from the printButton's data,
# and matches printing components with the type(s) of data received
Imm = require 'immutable'
Moment = require 'moment'
Fs = require 'fs'
Officegen = require 'officegen'
Config = require './config'
Term = require './term'
load = (win, {dataSet}) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
R = React.DOM
Window = nw.Window.get(win)
MetricWidget = require('./metricWidget').load(win)
ProgEventWidget = require('./progEventWidget').load(win)
ExpandedMetricWidget = require('./expandedMetricWidget').load(win)
{FaIcon,renderLineBreaks, renderName,
renderRecordId, showWhen, formatTimestamp} = require('./utils').load(win)
PrintPreviewPage = React.createFactory React.createClass
displayName: 'PrintPreviewPage'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
printDataSet: Imm.fromJS JSON.parse(dataSet)
}
init: -> # Do nothing
deinit: (cb=(->)) ->
# Do nothing
cb()
suggestClose: ->
@props.closeWindow()
getPageListeners: -> {}
render: ->
new PrintPreviewPageUi {
printDataSet: @state.printDataSet
}
PrintPreviewPageUi = React.createFactory React.createClass
displayName: 'PrintPreviewPageUi'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: ->
return {
previewType: 'default'
}
_printPage: ->
Window.print
autoprint: false
headerFooterEnabled: Config.printHeaderFooterEnabled
headerString: Config.printHeader
footerString: Config.printFooter
_exportPage: ->
# feature enabled/disabled via config
data = @props.printDataSet.first().get('data')
clientFile = @props.printDataSet.first().get('clientFile')
clientFirstName = clientFile.get('clientName').get('first')
clientLastName = clientFile.get('clientName').get('last')
fileName = "KN Plan " + clientFirstName + " " + clientLastName
$(@refs.nwsaveas)
.off()
.val('')
.attr('nwsaveas', fileName)
.attr('accept', ".doc")
.on('change', (event) =>
tableData = [
[
{val: 'Goals for Youth', opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Indicators', opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Intervention Method',opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Person Responsible',opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Expected Date of Completion',opts: {b: true, shd: {fill: "99ddff"}}}
]
]
data.get('sections')
.filter (section) =>
section.get('status') is 'default'
.map (section) =>
tableData.push [
{val: section.get('name'), opts: {b: true, shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}}
]
section.get('targetIds')
.filter (targetId) =>
targets = data.get('targets')
thisTarget = targets.get(targetId)
return thisTarget.get('status') is 'default'
.map (targetId) =>
targets = data.get('targets')
thisTarget = targets.get(targetId)
targetName = thisTarget.get('name')
targetDescription = thisTarget.get('description')
metrics = ''
thisTarget.get('metricIds').map (metricId) =>
metric = data.get('metrics').get(metricId)
metrics += metric.get('name') + metric.get('definition')
tableData.push [
{val: targetName, opts: {shd: {fill: 'ffffff'}}},
{val: metrics, opts: {shd: {fill: 'ffffff'}}},
{val: targetDescription, opts: {shd: {fill: 'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
]
tableStyle = {
tableColWidth: 4261,
tableSize: 24,
color: '000000'
tableAlign: "left",
tableFontFamily: "Segoe UI",
borders: true
}
docx = Officegen {
'type': 'docx'
'orientation': 'landscape'
}
docx.createTable(tableData, tableStyle)
header = docx.getHeader().createP()
header.addText ("PLAN FOR " + clientFirstName + " " + clientLastName).toUpperCase() + " - " + Moment().format("MMM DD YYYY")
out = Fs.createWriteStream event.target.value
out.on 'error', (err) ->
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
out.on 'close', () ->
Window.close()
docx.generate out,
'error': (err) ->
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
)
.click()
render: ->
R.div({className: 'printPreview'},
(@props.printDataSet.map (printObj) =>
clientFile = printObj.get('clientFile')
data = printObj.get('data')
progEvents = printObj.get('progEvents')
title = null
R.div({className: 'printObj'},
R.div({className: 'noPrint'},
R.button({
ref: 'print'
className: 'print btn btn-primary'
onClick: @_printPage
},
FaIcon('print')
" "
"Print"
)
(if printObj.get('format') is 'plan' and Config.features.planExportToWord.isEnabled
R.button({
ref: 'export'
className: 'print btn btn-primary'
onClick: @_exportPage
},
FaIcon('download')
" "
"Export"
)
)
(if printObj.get('format') is 'plan'
R.div({className: 'toggle btn-group btn-group-sm'},
R.button({
ref: 'print'
className: 'default btn btn-primary'
onClick: @_togglePreviewType.bind null, 'default'
disabled: @state.previewType is 'default'
},
"Default"
)
R.button({
ref: 'print'
className: 'cheatSheet btn btn-primary'
onClick: @_togglePreviewType.bind null, 'cheatSheet'
disabled: @state.previewType is 'cheatSheet'
},
"Cheat Sheet"
)
R.input({
ref: 'nwsaveas'
className: 'hidden'
type: 'file'
})
)
)
)
PrintHeader({
data
format: printObj.get('format')
clientFile: clientFile
})
switch printObj.get('format')
when 'progNote'
switch data.get('type')
when 'basic'
BasicProgNoteView({
progNote: data
clientFile
progEvents
})
when 'full'
FullProgNoteView({
progNote: data
clientFile
progEvents
})
else
throw new Error "Unknown progNote type: #{progNote.get('type')}"
when 'plan'
if @state.previewType is 'default'
SinglePlanView({
title: "Care Plan"
data
clientFile
progEvents
})
else if @state.previewType is 'cheatSheet'
CheatSheetPlanView({
title: "Care Plan"
data
clientFile
progEvents
})
else
throw new Error "Unknown print-data type: #{setType}"
)
).toJS()...
)
_togglePreviewType: (t) ->
@setState {previewType: t}
PrintHeader = React.createFactory React.createClass
displayName: 'PrintHeader'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
# Calculate timestamp for backdate if exists
timestamp = formatTimestamp(@props.data.get('backdate') or @props.data.get('timestamp'))
if @props.data.get('backdate') then timestamp = "(late entry) #{timestamp}"
return R.header({className: 'header'},
R.div({className: 'basicInfo'},
R.h1({className: 'title'},
switch @props.format
when 'progNote' then "Progress Note"
when 'plan' then "Care Plan"
)
R.h3({className: 'clientName'},
renderName @props.clientFile.get('clientName')
)
R.span({className: 'clientRecordId'},
renderRecordId @props.clientFile.get('recordId')
)
)
R.div({className: 'authorInfo'},
(if @props.format isnt 'plan'
R.ul({},
R.li({},
FaIcon('user')
"Authored by: "
# TODO: Include user's full name + username ("Andrew Appleby (aappleby)")
R.span({className: 'author'}, @props.data.get('author'))
)
R.li({className: 'date'}, timestamp)
)
)
R.ul({},
R.li({},
FaIcon('print')
"Printed by: "
# TODO: Include user's full name + username ("Andrew Appleby (aappleby)")
R.span({className: 'author'}, global.ActiveSession.userName)
)
R.li({className: 'date'},
Moment().format 'Do MMM, YYYY [at] h:mma'
)
)
)
R.div({className: 'brandLogo'},
R.div({},
R.img({
className: 'logo'
src: Config.logoCustomerLg
})
)
)
)
BasicProgNoteView = React.createFactory React.createClass
displayName: 'BasicProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'basic progNote'},
R.div({className: 'notes'},
renderLineBreaks @props.progNote.get('notes')
)
)
FullProgNoteView = React.createFactory React.createClass
displayName: 'FullProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'full progNote'},
R.div({className: 'units'},
(@props.progNote.get('units').map (unit) =>
switch unit.get('type')
when 'basic'
R.div({
className: 'basic unit'
key: unit.get('id')
},
R.h3({}, unit.get 'name')
R.div({className: "empty #{showWhen unit.get('notes').length is 0}"},
'(blank)'
)
R.div({className: 'notes'},
renderLineBreaks unit.get('notes')
)
R.div({className: 'metrics'},
(unit.get('metrics').map (metric) =>
MetricWidget({
isEditable: false
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
).toJS()...
)
)
when 'plan'
R.div({className: 'plan unit', key: unit.get('id')},
(unit.get('sections').map (section) =>
R.section({},
R.h2({}, section.get 'name')
(section.get('targets').map (target) =>
R.div({
className: 'target'
key: target.get('id')
},
R.h3({}, target.get('name'))
R.div({className: "empty #{showWhen not target.get('notes')}"},
'(blank)'
)
R.div({className: 'description'},
renderLineBreaks target.get('notes')
)
R.div({className: 'metrics'},
(target.get('metrics').map (metric) =>
MetricWidget({
isEditable: false
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
).toJS()...
)
)
).toJS()...
)
).toJS()...
)
).toJS()...
)
(unless @props.progEvents.isEmpty()
R.div({className: 'progEvents'},
R.h3({}, Term 'Events')
(@props.progEvents.map (progEvent) =>
R.div({}
ProgEventWidget({
format: 'print'
progEvent
})
)
).toJS()...
)
)
)
SinglePlanView = React.createFactory React.createClass
displayName: 'SinglePlanView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'plan unit'},
R.div({className: 'sections'},
(@props.data.get('sections').filter (section) =>
section.get('status') is 'default'
.map (section) =>
R.section({className: 'section planTargets', key: section.get('id')},
R.h2({className: 'name'}, section.get('name'))
(if section.get('targetIds').size is 0
R.div({className: 'noTargets'},
"This #{Term 'section'} is empty."
)
)
R.div({className: 'targets'},
(section.get('targetIds')
.filter (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
return thisTarget.get('status') is 'default'
.map (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
R.div({className: 'target'},
R.h3({className: 'name'}, thisTarget.get('name'))
R.div({className: 'description'},
renderLineBreaks thisTarget.get('description')
)
R.div({className: 'metrics'},
(thisTarget.get('metricIds').map (metricId) =>
metric = @props.data.get('metrics').get(metricId)
MetricWidget({
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
key: metricId
})
).toJS()...
)
)
).toJS()...
)
)
).toJS()...
)
)
CheatSheetPlanView = React.createFactory React.createClass
displayName: 'SinglePlanView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'plan unit'},
R.div({className: 'sections'},
(@props.data.get('sections')
.filter (section) =>
section.get('status') is 'default'
.map (section) =>
R.section({className: 'section planTargets', key: section.get('id')},
R.h2({className: 'name'}, section.get('name'))
(if section.get('targetIds').size is 0
R.div({className: 'noTargets'},
"This #{Term 'section'} is empty."
)
)
R.div({className: 'targets'},
(section.get('targetIds')
.filter (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
return thisTarget.get('status') is 'default'
.map (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
R.div({className: 'target'},
R.h3({className: 'name'}, thisTarget.get('name'))
R.div({className: 'description'},
renderLineBreaks thisTarget.get('description')
)
R.div({className: 'cheatMetrics'},
(thisTarget.get('metricIds').map (metricId) =>
metric = @props.data.get('metrics').get(metricId)
ExpandedMetricWidget({
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
key: metricId
})
).toJS()...
)
)
).toJS()...
)
)
).toJS()...
)
)
return PrintPreviewPage
module.exports = {load}
| 167086 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Print preview page receives data from the printButton's data,
# and matches printing components with the type(s) of data received
Imm = require 'immutable'
Moment = require 'moment'
Fs = require 'fs'
Officegen = require 'officegen'
Config = require './config'
Term = require './term'
load = (win, {dataSet}) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
R = React.DOM
Window = nw.Window.get(win)
MetricWidget = require('./metricWidget').load(win)
ProgEventWidget = require('./progEventWidget').load(win)
ExpandedMetricWidget = require('./expandedMetricWidget').load(win)
{FaIcon,renderLineBreaks, renderName,
renderRecordId, showWhen, formatTimestamp} = require('./utils').load(win)
PrintPreviewPage = React.createFactory React.createClass
displayName: 'PrintPreviewPage'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
printDataSet: Imm.fromJS JSON.parse(dataSet)
}
init: -> # Do nothing
deinit: (cb=(->)) ->
# Do nothing
cb()
suggestClose: ->
@props.closeWindow()
getPageListeners: -> {}
render: ->
new PrintPreviewPageUi {
printDataSet: @state.printDataSet
}
PrintPreviewPageUi = React.createFactory React.createClass
displayName: 'PrintPreviewPageUi'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: ->
return {
previewType: 'default'
}
_printPage: ->
Window.print
autoprint: false
headerFooterEnabled: Config.printHeaderFooterEnabled
headerString: Config.printHeader
footerString: Config.printFooter
_exportPage: ->
# feature enabled/disabled via config
data = @props.printDataSet.first().get('data')
clientFile = @props.printDataSet.first().get('clientFile')
clientFirstName = clientFile.get('clientName').get('first')
clientLastName = clientFile.get('clientName').get('last')
fileName = "KN Plan " + clientFirstName + " " + clientLastName
$(@refs.nwsaveas)
.off()
.val('')
.attr('nwsaveas', fileName)
.attr('accept', ".doc")
.on('change', (event) =>
tableData = [
[
{val: 'Goals for Youth', opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Indicators', opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Intervention Method',opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Person Responsible',opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Expected Date of Completion',opts: {b: true, shd: {fill: "99ddff"}}}
]
]
data.get('sections')
.filter (section) =>
section.get('status') is 'default'
.map (section) =>
tableData.push [
{val: section.get('name'), opts: {b: true, shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}}
]
section.get('targetIds')
.filter (targetId) =>
targets = data.get('targets')
thisTarget = targets.get(targetId)
return thisTarget.get('status') is 'default'
.map (targetId) =>
targets = data.get('targets')
thisTarget = targets.get(targetId)
targetName = thisTarget.get('name')
targetDescription = thisTarget.get('description')
metrics = ''
thisTarget.get('metricIds').map (metricId) =>
metric = data.get('metrics').get(metricId)
metrics += metric.get('name') + metric.get('definition')
tableData.push [
{val: targetName, opts: {shd: {fill: 'ffffff'}}},
{val: metrics, opts: {shd: {fill: 'ffffff'}}},
{val: targetDescription, opts: {shd: {fill: 'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
]
tableStyle = {
tableColWidth: 4261,
tableSize: 24,
color: '000000'
tableAlign: "left",
tableFontFamily: "Segoe UI",
borders: true
}
docx = Officegen {
'type': 'docx'
'orientation': 'landscape'
}
docx.createTable(tableData, tableStyle)
header = docx.getHeader().createP()
header.addText ("PLAN FOR " + clientFirstName + " " + clientLastName).toUpperCase() + " - " + Moment().format("MMM DD YYYY")
out = Fs.createWriteStream event.target.value
out.on 'error', (err) ->
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
out.on 'close', () ->
Window.close()
docx.generate out,
'error': (err) ->
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
)
.click()
render: ->
R.div({className: 'printPreview'},
(@props.printDataSet.map (printObj) =>
clientFile = printObj.get('clientFile')
data = printObj.get('data')
progEvents = printObj.get('progEvents')
title = null
R.div({className: 'printObj'},
R.div({className: 'noPrint'},
R.button({
ref: 'print'
className: 'print btn btn-primary'
onClick: @_printPage
},
FaIcon('print')
" "
"Print"
)
(if printObj.get('format') is 'plan' and Config.features.planExportToWord.isEnabled
R.button({
ref: 'export'
className: 'print btn btn-primary'
onClick: @_exportPage
},
FaIcon('download')
" "
"Export"
)
)
(if printObj.get('format') is 'plan'
R.div({className: 'toggle btn-group btn-group-sm'},
R.button({
ref: 'print'
className: 'default btn btn-primary'
onClick: @_togglePreviewType.bind null, 'default'
disabled: @state.previewType is 'default'
},
"Default"
)
R.button({
ref: 'print'
className: 'cheatSheet btn btn-primary'
onClick: @_togglePreviewType.bind null, 'cheatSheet'
disabled: @state.previewType is 'cheatSheet'
},
"Cheat Sheet"
)
R.input({
ref: 'nwsaveas'
className: 'hidden'
type: 'file'
})
)
)
)
PrintHeader({
data
format: printObj.get('format')
clientFile: clientFile
})
switch printObj.get('format')
when 'progNote'
switch data.get('type')
when 'basic'
BasicProgNoteView({
progNote: data
clientFile
progEvents
})
when 'full'
FullProgNoteView({
progNote: data
clientFile
progEvents
})
else
throw new Error "Unknown progNote type: #{progNote.get('type')}"
when 'plan'
if @state.previewType is 'default'
SinglePlanView({
title: "Care Plan"
data
clientFile
progEvents
})
else if @state.previewType is 'cheatSheet'
CheatSheetPlanView({
title: "Care Plan"
data
clientFile
progEvents
})
else
throw new Error "Unknown print-data type: #{setType}"
)
).toJS()...
)
_togglePreviewType: (t) ->
@setState {previewType: t}
PrintHeader = React.createFactory React.createClass
displayName: 'PrintHeader'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
# Calculate timestamp for backdate if exists
timestamp = formatTimestamp(@props.data.get('backdate') or @props.data.get('timestamp'))
if @props.data.get('backdate') then timestamp = "(late entry) #{timestamp}"
return R.header({className: 'header'},
R.div({className: 'basicInfo'},
R.h1({className: 'title'},
switch @props.format
when 'progNote' then "Progress Note"
when 'plan' then "Care Plan"
)
R.h3({className: 'clientName'},
renderName @props.clientFile.get('clientName')
)
R.span({className: 'clientRecordId'},
renderRecordId @props.clientFile.get('recordId')
)
)
R.div({className: 'authorInfo'},
(if @props.format isnt 'plan'
R.ul({},
R.li({},
FaIcon('user')
"Authored by: "
# TODO: Include user's full name + username ("<NAME> (aappleby)")
R.span({className: 'author'}, @props.data.get('author'))
)
R.li({className: 'date'}, timestamp)
)
)
R.ul({},
R.li({},
FaIcon('print')
"Printed by: "
# TODO: Include user's full name + username ("<NAME> (aappleby)")
R.span({className: 'author'}, global.ActiveSession.userName)
)
R.li({className: 'date'},
Moment().format 'Do MMM, YYYY [at] h:mma'
)
)
)
R.div({className: 'brandLogo'},
R.div({},
R.img({
className: 'logo'
src: Config.logoCustomerLg
})
)
)
)
BasicProgNoteView = React.createFactory React.createClass
displayName: 'BasicProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'basic progNote'},
R.div({className: 'notes'},
renderLineBreaks @props.progNote.get('notes')
)
)
FullProgNoteView = React.createFactory React.createClass
displayName: 'FullProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'full progNote'},
R.div({className: 'units'},
(@props.progNote.get('units').map (unit) =>
switch unit.get('type')
when 'basic'
R.div({
className: 'basic unit'
key: unit.get('id')
},
R.h3({}, unit.get 'name')
R.div({className: "empty #{showWhen unit.get('notes').length is 0}"},
'(blank)'
)
R.div({className: 'notes'},
renderLineBreaks unit.get('notes')
)
R.div({className: 'metrics'},
(unit.get('metrics').map (metric) =>
MetricWidget({
isEditable: false
key: metric.<KEY>('<KEY>')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
).toJS()...
)
)
when 'plan'
R.div({className: 'plan unit', key: unit.get('id')},
(unit.get('sections').map (section) =>
R.section({},
R.h2({}, section.get 'name')
(section.get('targets').map (target) =>
R.div({
className: 'target'
key: target.get('id')
},
R.h3({}, target.get('name'))
R.div({className: "empty #{showWhen not target.get('notes')}"},
'(blank)'
)
R.div({className: 'description'},
renderLineBreaks target.get('notes')
)
R.div({className: 'metrics'},
(target.get('metrics').map (metric) =>
MetricWidget({
isEditable: false
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
).toJS()...
)
)
).toJS()...
)
).toJS()...
)
).toJS()...
)
(unless @props.progEvents.isEmpty()
R.div({className: 'progEvents'},
R.h3({}, Term 'Events')
(@props.progEvents.map (progEvent) =>
R.div({}
ProgEventWidget({
format: 'print'
progEvent
})
)
).toJS()...
)
)
)
SinglePlanView = React.createFactory React.createClass
displayName: 'SinglePlanView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'plan unit'},
R.div({className: 'sections'},
(@props.data.get('sections').filter (section) =>
section.get('status') is 'default'
.map (section) =>
R.section({className: 'section planTargets', key: section.get('id')},
R.h2({className: 'name'}, section.get('name'))
(if section.get('targetIds').size is 0
R.div({className: 'noTargets'},
"This #{Term 'section'} is empty."
)
)
R.div({className: 'targets'},
(section.get('targetIds')
.filter (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
return thisTarget.get('status') is 'default'
.map (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
R.div({className: 'target'},
R.h3({className: 'name'}, thisTarget.get('name'))
R.div({className: 'description'},
renderLineBreaks thisTarget.get('description')
)
R.div({className: 'metrics'},
(thisTarget.get('metricIds').map (metricId) =>
metric = @props.data.get('metrics').get(metricId)
MetricWidget({
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
key: metricId
})
).toJS()...
)
)
).toJS()...
)
)
).toJS()...
)
)
CheatSheetPlanView = React.createFactory React.createClass
displayName: 'SinglePlanView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'plan unit'},
R.div({className: 'sections'},
(@props.data.get('sections')
.filter (section) =>
section.get('status') is 'default'
.map (section) =>
R.section({className: 'section planTargets', key: section.get('id')},
R.h2({className: 'name'}, section.get('name'))
(if section.get('targetIds').size is 0
R.div({className: 'noTargets'},
"This #{Term 'section'} is empty."
)
)
R.div({className: 'targets'},
(section.get('targetIds')
.filter (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
return thisTarget.get('status') is 'default'
.map (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
R.div({className: 'target'},
R.h3({className: 'name'}, thisTarget.get('name'))
R.div({className: 'description'},
renderLineBreaks thisTarget.get('description')
)
R.div({className: 'cheatMetrics'},
(thisTarget.get('metricIds').map (metricId) =>
metric = @props.data.get('metrics').get(metricId)
ExpandedMetricWidget({
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
key: metricId
})
).toJS()...
)
)
).toJS()...
)
)
).toJS()...
)
)
return PrintPreviewPage
module.exports = {load}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# Print preview page receives data from the printButton's data,
# and matches printing components with the type(s) of data received
Imm = require 'immutable'
Moment = require 'moment'
Fs = require 'fs'
Officegen = require 'officegen'
Config = require './config'
Term = require './term'
load = (win, {dataSet}) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
R = React.DOM
Window = nw.Window.get(win)
MetricWidget = require('./metricWidget').load(win)
ProgEventWidget = require('./progEventWidget').load(win)
ExpandedMetricWidget = require('./expandedMetricWidget').load(win)
{FaIcon,renderLineBreaks, renderName,
renderRecordId, showWhen, formatTimestamp} = require('./utils').load(win)
PrintPreviewPage = React.createFactory React.createClass
displayName: 'PrintPreviewPage'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
printDataSet: Imm.fromJS JSON.parse(dataSet)
}
init: -> # Do nothing
deinit: (cb=(->)) ->
# Do nothing
cb()
suggestClose: ->
@props.closeWindow()
getPageListeners: -> {}
render: ->
new PrintPreviewPageUi {
printDataSet: @state.printDataSet
}
PrintPreviewPageUi = React.createFactory React.createClass
displayName: 'PrintPreviewPageUi'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes
getInitialState: ->
return {
previewType: 'default'
}
_printPage: ->
Window.print
autoprint: false
headerFooterEnabled: Config.printHeaderFooterEnabled
headerString: Config.printHeader
footerString: Config.printFooter
_exportPage: ->
# feature enabled/disabled via config
data = @props.printDataSet.first().get('data')
clientFile = @props.printDataSet.first().get('clientFile')
clientFirstName = clientFile.get('clientName').get('first')
clientLastName = clientFile.get('clientName').get('last')
fileName = "KN Plan " + clientFirstName + " " + clientLastName
$(@refs.nwsaveas)
.off()
.val('')
.attr('nwsaveas', fileName)
.attr('accept', ".doc")
.on('change', (event) =>
tableData = [
[
{val: 'Goals for Youth', opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Indicators', opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Intervention Method',opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Person Responsible',opts: {b: true, shd: {fill: "99ddff"}}},
{val: 'Expected Date of Completion',opts: {b: true, shd: {fill: "99ddff"}}}
]
]
data.get('sections')
.filter (section) =>
section.get('status') is 'default'
.map (section) =>
tableData.push [
{val: section.get('name'), opts: {b: true, shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}}
]
section.get('targetIds')
.filter (targetId) =>
targets = data.get('targets')
thisTarget = targets.get(targetId)
return thisTarget.get('status') is 'default'
.map (targetId) =>
targets = data.get('targets')
thisTarget = targets.get(targetId)
targetName = thisTarget.get('name')
targetDescription = thisTarget.get('description')
metrics = ''
thisTarget.get('metricIds').map (metricId) =>
metric = data.get('metrics').get(metricId)
metrics += metric.get('name') + metric.get('definition')
tableData.push [
{val: targetName, opts: {shd: {fill: 'ffffff'}}},
{val: metrics, opts: {shd: {fill: 'ffffff'}}},
{val: targetDescription, opts: {shd: {fill: 'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
{val: '', opts: {shd: {fill:'ffffff'}}},
]
tableStyle = {
tableColWidth: 4261,
tableSize: 24,
color: '000000'
tableAlign: "left",
tableFontFamily: "Segoe UI",
borders: true
}
docx = Officegen {
'type': 'docx'
'orientation': 'landscape'
}
docx.createTable(tableData, tableStyle)
header = docx.getHeader().createP()
header.addText ("PLAN FOR " + clientFirstName + " " + clientLastName).toUpperCase() + " - " + Moment().format("MMM DD YYYY")
out = Fs.createWriteStream event.target.value
out.on 'error', (err) ->
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
out.on 'close', () ->
Window.close()
docx.generate out,
'error': (err) ->
Bootbox.alert """
An error occurred. Please check your network connection and try again.
"""
return
)
.click()
render: ->
R.div({className: 'printPreview'},
(@props.printDataSet.map (printObj) =>
clientFile = printObj.get('clientFile')
data = printObj.get('data')
progEvents = printObj.get('progEvents')
title = null
R.div({className: 'printObj'},
R.div({className: 'noPrint'},
R.button({
ref: 'print'
className: 'print btn btn-primary'
onClick: @_printPage
},
FaIcon('print')
" "
"Print"
)
(if printObj.get('format') is 'plan' and Config.features.planExportToWord.isEnabled
R.button({
ref: 'export'
className: 'print btn btn-primary'
onClick: @_exportPage
},
FaIcon('download')
" "
"Export"
)
)
(if printObj.get('format') is 'plan'
R.div({className: 'toggle btn-group btn-group-sm'},
R.button({
ref: 'print'
className: 'default btn btn-primary'
onClick: @_togglePreviewType.bind null, 'default'
disabled: @state.previewType is 'default'
},
"Default"
)
R.button({
ref: 'print'
className: 'cheatSheet btn btn-primary'
onClick: @_togglePreviewType.bind null, 'cheatSheet'
disabled: @state.previewType is 'cheatSheet'
},
"Cheat Sheet"
)
R.input({
ref: 'nwsaveas'
className: 'hidden'
type: 'file'
})
)
)
)
PrintHeader({
data
format: printObj.get('format')
clientFile: clientFile
})
switch printObj.get('format')
when 'progNote'
switch data.get('type')
when 'basic'
BasicProgNoteView({
progNote: data
clientFile
progEvents
})
when 'full'
FullProgNoteView({
progNote: data
clientFile
progEvents
})
else
throw new Error "Unknown progNote type: #{progNote.get('type')}"
when 'plan'
if @state.previewType is 'default'
SinglePlanView({
title: "Care Plan"
data
clientFile
progEvents
})
else if @state.previewType is 'cheatSheet'
CheatSheetPlanView({
title: "Care Plan"
data
clientFile
progEvents
})
else
throw new Error "Unknown print-data type: #{setType}"
)
).toJS()...
)
_togglePreviewType: (t) ->
@setState {previewType: t}
PrintHeader = React.createFactory React.createClass
displayName: 'PrintHeader'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
# Calculate timestamp for backdate if exists
timestamp = formatTimestamp(@props.data.get('backdate') or @props.data.get('timestamp'))
if @props.data.get('backdate') then timestamp = "(late entry) #{timestamp}"
return R.header({className: 'header'},
R.div({className: 'basicInfo'},
R.h1({className: 'title'},
switch @props.format
when 'progNote' then "Progress Note"
when 'plan' then "Care Plan"
)
R.h3({className: 'clientName'},
renderName @props.clientFile.get('clientName')
)
R.span({className: 'clientRecordId'},
renderRecordId @props.clientFile.get('recordId')
)
)
R.div({className: 'authorInfo'},
(if @props.format isnt 'plan'
R.ul({},
R.li({},
FaIcon('user')
"Authored by: "
# TODO: Include user's full name + username ("PI:NAME:<NAME>END_PI (aappleby)")
R.span({className: 'author'}, @props.data.get('author'))
)
R.li({className: 'date'}, timestamp)
)
)
R.ul({},
R.li({},
FaIcon('print')
"Printed by: "
# TODO: Include user's full name + username ("PI:NAME:<NAME>END_PI (aappleby)")
R.span({className: 'author'}, global.ActiveSession.userName)
)
R.li({className: 'date'},
Moment().format 'Do MMM, YYYY [at] h:mma'
)
)
)
R.div({className: 'brandLogo'},
R.div({},
R.img({
className: 'logo'
src: Config.logoCustomerLg
})
)
)
)
BasicProgNoteView = React.createFactory React.createClass
displayName: 'BasicProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'basic progNote'},
R.div({className: 'notes'},
renderLineBreaks @props.progNote.get('notes')
)
)
FullProgNoteView = React.createFactory React.createClass
displayName: 'FullProgNoteView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'full progNote'},
R.div({className: 'units'},
(@props.progNote.get('units').map (unit) =>
switch unit.get('type')
when 'basic'
R.div({
className: 'basic unit'
key: unit.get('id')
},
R.h3({}, unit.get 'name')
R.div({className: "empty #{showWhen unit.get('notes').length is 0}"},
'(blank)'
)
R.div({className: 'notes'},
renderLineBreaks unit.get('notes')
)
R.div({className: 'metrics'},
(unit.get('metrics').map (metric) =>
MetricWidget({
isEditable: false
key: metric.PI:KEY:<KEY>END_PI('PI:KEY:<KEY>END_PI')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
).toJS()...
)
)
when 'plan'
R.div({className: 'plan unit', key: unit.get('id')},
(unit.get('sections').map (section) =>
R.section({},
R.h2({}, section.get 'name')
(section.get('targets').map (target) =>
R.div({
className: 'target'
key: target.get('id')
},
R.h3({}, target.get('name'))
R.div({className: "empty #{showWhen not target.get('notes')}"},
'(blank)'
)
R.div({className: 'description'},
renderLineBreaks target.get('notes')
)
R.div({className: 'metrics'},
(target.get('metrics').map (metric) =>
MetricWidget({
isEditable: false
key: metric.get('id')
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
})
).toJS()...
)
)
).toJS()...
)
).toJS()...
)
).toJS()...
)
(unless @props.progEvents.isEmpty()
R.div({className: 'progEvents'},
R.h3({}, Term 'Events')
(@props.progEvents.map (progEvent) =>
R.div({}
ProgEventWidget({
format: 'print'
progEvent
})
)
).toJS()...
)
)
)
SinglePlanView = React.createFactory React.createClass
displayName: 'SinglePlanView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'plan unit'},
R.div({className: 'sections'},
(@props.data.get('sections').filter (section) =>
section.get('status') is 'default'
.map (section) =>
R.section({className: 'section planTargets', key: section.get('id')},
R.h2({className: 'name'}, section.get('name'))
(if section.get('targetIds').size is 0
R.div({className: 'noTargets'},
"This #{Term 'section'} is empty."
)
)
R.div({className: 'targets'},
(section.get('targetIds')
.filter (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
return thisTarget.get('status') is 'default'
.map (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
R.div({className: 'target'},
R.h3({className: 'name'}, thisTarget.get('name'))
R.div({className: 'description'},
renderLineBreaks thisTarget.get('description')
)
R.div({className: 'metrics'},
(thisTarget.get('metricIds').map (metricId) =>
metric = @props.data.get('metrics').get(metricId)
MetricWidget({
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
key: metricId
})
).toJS()...
)
)
).toJS()...
)
)
).toJS()...
)
)
CheatSheetPlanView = React.createFactory React.createClass
displayName: 'SinglePlanView'
mixins: [React.addons.PureRenderMixin]
# TODO: propTypes, or make this a view
render: ->
R.div({className: 'plan unit'},
R.div({className: 'sections'},
(@props.data.get('sections')
.filter (section) =>
section.get('status') is 'default'
.map (section) =>
R.section({className: 'section planTargets', key: section.get('id')},
R.h2({className: 'name'}, section.get('name'))
(if section.get('targetIds').size is 0
R.div({className: 'noTargets'},
"This #{Term 'section'} is empty."
)
)
R.div({className: 'targets'},
(section.get('targetIds')
.filter (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
return thisTarget.get('status') is 'default'
.map (targetId) =>
targets = @props.data.get('targets')
thisTarget = targets.get(targetId)
R.div({className: 'target'},
R.h3({className: 'name'}, thisTarget.get('name'))
R.div({className: 'description'},
renderLineBreaks thisTarget.get('description')
)
R.div({className: 'cheatMetrics'},
(thisTarget.get('metricIds').map (metricId) =>
metric = @props.data.get('metrics').get(metricId)
ExpandedMetricWidget({
name: metric.get('name')
definition: metric.get('definition')
value: metric.get('value')
key: metricId
})
).toJS()...
)
)
).toJS()...
)
)
).toJS()...
)
)
return PrintPreviewPage
module.exports = {load}
|
[
{
"context": "e.Collection [\n new Backbone.Model {username: 'lar-gand', fullname: 'Mon-El', pwd: 'daxamite', email: 'da",
"end": 97,
"score": 0.9996781945228577,
"start": 89,
"tag": "USERNAME",
"value": "lar-gand"
},
{
"context": " {username: 'lar-gand', fullname: 'Mon-El', pwd: 'daxamite', email: 'daxam@gmail.com'}\n new Backbone.Mode",
"end": 134,
"score": 0.999383270740509,
"start": 126,
"tag": "PASSWORD",
"value": "daxamite"
},
{
"context": "nd', fullname: 'Mon-El', pwd: 'daxamite', email: 'daxam@gmail.com'}\n new Backbone.Model {username: 'kal-el', ful",
"end": 160,
"score": 0.9999254941940308,
"start": 145,
"tag": "EMAIL",
"value": "daxam@gmail.com"
},
{
"context": "am@gmail.com'}\n new Backbone.Model {username: 'kal-el', fullname: 'Superboy', pwd: 'kryptonian', email:",
"end": 204,
"score": 0.9996710419654846,
"start": 198,
"tag": "USERNAME",
"value": "kal-el"
},
{
"context": " {username: 'kal-el', fullname: 'Superboy', pwd: 'kryptonian', email: 'krypton@gmail.com'}\n new Backbone.Mo",
"end": 245,
"score": 0.9993894696235657,
"start": 235,
"tag": "PASSWORD",
"value": "kryptonian"
},
{
"context": " fullname: 'Superboy', pwd: 'kryptonian', email: 'krypton@gmail.com'}\n new Backbone.Model {username: 'rokk-krinn',",
"end": 273,
"score": 0.999928891658783,
"start": 256,
"tag": "EMAIL",
"value": "krypton@gmail.com"
},
{
"context": "on@gmail.com'}\n new Backbone.Model {username: 'rokk-krinn', fullname: 'Cosmic Boy', pwd: 'braalian', email:",
"end": 321,
"score": 0.9996983408927917,
"start": 311,
"tag": "USERNAME",
"value": "rokk-krinn"
},
{
"context": "name: 'rokk-krinn', fullname: 'Cosmic Boy', pwd: 'braalian', email: 'braal@gmail.com'}\n ]\n \n getUser: (us",
"end": 362,
"score": 0.9992514848709106,
"start": 354,
"tag": "PASSWORD",
"value": "braalian"
},
{
"context": " fullname: 'Cosmic Boy', pwd: 'braalian', email: 'braal@gmail.com'}\n ]\n \n getUser: (username, pwd, cb) =>\n le",
"end": 388,
"score": 0.9999232292175293,
"start": 373,
"tag": "EMAIL",
"value": "braal@gmail.com"
}
] | app/datasource.coffee | sandy98/silver-age-comics | 0 |
class DataSource
users: new Backbone.Collection [
new Backbone.Model {username: 'lar-gand', fullname: 'Mon-El', pwd: 'daxamite', email: 'daxam@gmail.com'}
new Backbone.Model {username: 'kal-el', fullname: 'Superboy', pwd: 'kryptonian', email: 'krypton@gmail.com'}
new Backbone.Model {username: 'rokk-krinn', fullname: 'Cosmic Boy', pwd: 'braalian', email: 'braal@gmail.com'}
]
getUser: (username, pwd, cb) =>
len = @users.length
for index in [0..(len - 1)]
user = @users.at(index)
if (user.get('username').toLowerCase() is username.toLowerCase() or user.get('email').toLowerCase() is username.toLowerCase()) and user.get('pwd') is pwd
if cb
cb null, user
return user
if cb
msg = 'Wrong username and/or password'
cb msg, null
return msg
getUserByCid: (cid, cb) =>
len = @users.length
for index in [0..(len - 1)]
user = @users.at(index)
if user.cid is cid
if cb
cb null, user
return user
if cb
msg = 'Cid not found'
cb msg, null
return msg
insertUser: (user, cb) =>
@users.add user
if cb
cb null, user
updateUser: (cid, userData, cb) =>
len = @users.length
for index in [0..(len - 1)]
user = @users.at(index)
if user.cid is cid
user.set userData
if cb
cb null, user
return user
if cb
cb 'Wrong user', null
null
module.exports = new DataSource | 87674 |
class DataSource
users: new Backbone.Collection [
new Backbone.Model {username: 'lar-gand', fullname: 'Mon-El', pwd: '<PASSWORD>', email: '<EMAIL>'}
new Backbone.Model {username: 'kal-el', fullname: 'Superboy', pwd: '<PASSWORD>', email: '<EMAIL>'}
new Backbone.Model {username: 'rokk-krinn', fullname: 'Cosmic Boy', pwd: '<PASSWORD>', email: '<EMAIL>'}
]
getUser: (username, pwd, cb) =>
len = @users.length
for index in [0..(len - 1)]
user = @users.at(index)
if (user.get('username').toLowerCase() is username.toLowerCase() or user.get('email').toLowerCase() is username.toLowerCase()) and user.get('pwd') is pwd
if cb
cb null, user
return user
if cb
msg = 'Wrong username and/or password'
cb msg, null
return msg
getUserByCid: (cid, cb) =>
len = @users.length
for index in [0..(len - 1)]
user = @users.at(index)
if user.cid is cid
if cb
cb null, user
return user
if cb
msg = 'Cid not found'
cb msg, null
return msg
insertUser: (user, cb) =>
@users.add user
if cb
cb null, user
updateUser: (cid, userData, cb) =>
len = @users.length
for index in [0..(len - 1)]
user = @users.at(index)
if user.cid is cid
user.set userData
if cb
cb null, user
return user
if cb
cb 'Wrong user', null
null
module.exports = new DataSource | true |
class DataSource
users: new Backbone.Collection [
new Backbone.Model {username: 'lar-gand', fullname: 'Mon-El', pwd: 'PI:PASSWORD:<PASSWORD>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
new Backbone.Model {username: 'kal-el', fullname: 'Superboy', pwd: 'PI:PASSWORD:<PASSWORD>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
new Backbone.Model {username: 'rokk-krinn', fullname: 'Cosmic Boy', pwd: 'PI:PASSWORD:<PASSWORD>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
]
getUser: (username, pwd, cb) =>
len = @users.length
for index in [0..(len - 1)]
user = @users.at(index)
if (user.get('username').toLowerCase() is username.toLowerCase() or user.get('email').toLowerCase() is username.toLowerCase()) and user.get('pwd') is pwd
if cb
cb null, user
return user
if cb
msg = 'Wrong username and/or password'
cb msg, null
return msg
getUserByCid: (cid, cb) =>
len = @users.length
for index in [0..(len - 1)]
user = @users.at(index)
if user.cid is cid
if cb
cb null, user
return user
if cb
msg = 'Cid not found'
cb msg, null
return msg
insertUser: (user, cb) =>
@users.add user
if cb
cb null, user
updateUser: (cid, userData, cb) =>
len = @users.length
for index in [0..(len - 1)]
user = @users.at(index)
if user.cid is cid
user.set userData
if cb
cb null, user
return user
if cb
cb 'Wrong user', null
null
module.exports = new DataSource |
[
{
"context": " name: 'jim'\n# password: 'abc'\n# \n# 'has 64 bytes password': ({",
"end": 440,
"score": 0.999167263507843,
"start": 437,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": " name: 'test'\n# password: 'aBc'\n# foo.save @callback\n# r",
"end": 713,
"score": 0.9993315935134888,
"start": 710,
"tag": "PASSWORD",
"value": "aBc"
},
{
"context": " name: 'test'\n# password: 'invalidpassword'\n# foo.auth @callback\n# ",
"end": 1299,
"score": 0.9994571805000305,
"start": 1284,
"tag": "PASSWORD",
"value": "invalidpassword"
},
{
"context": " name: 'test'\n# password: 'aBc'\n# foo.auth @callback\n# ",
"end": 1700,
"score": 0.9993541240692139,
"start": 1697,
"tag": "PASSWORD",
"value": "aBc"
},
{
"context": " name: 'test'\n# password: 'abc'\n# foo.auth @callback\n# ",
"end": 2291,
"score": 0.9992361068725586,
"start": 2288,
"tag": "PASSWORD",
"value": "abc"
},
{
"context": " name: 'test'\n# password: 'ABc'\n# foo.auth @callback\n# ",
"end": 2637,
"score": 0.9992143511772156,
"start": 2634,
"tag": "PASSWORD",
"value": "ABc"
}
] | test/models/plugins/auth.coffee | cncolder/vcvs | 0 | { _, assert, cwd, mongoose } = require '../../helper'
{ auth } = require "#{cwd}/models/plugins"
schema = new mongoose.Schema
name:
type: String
schema.plugin auth
Foo = mongoose.model 'Foo', schema
# vows
# .describe(auth)
# .addBatch
# teardown: ->
# Foo.remove {}, @callback
# return
#
# 'A model':
# topic: new Foo
# name: 'jim'
# password: 'abc'
#
# 'has 64 bytes password': ({ password }) ->
# assert.equal password?.length, 64
#
# 'There is a saved model.':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'aBc'
# foo.save @callback
# return
#
# 'Auth not exist name':
# topic: ->
# foo = new Foo
# name: 'nobody'
# foo.auth @callback
# return
#
# 'got name error': ({ path, type }, foo) ->
# assert.equal path, 'name'
# assert.equal type, 'exists'
#
# 'Auth invalid password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'invalidpassword'
# foo.auth @callback
# return
#
# 'got password error': ({ path, type }, foo) ->
# assert.equal path, 'password'
# assert.equal type, 'equal'
#
# 'Auth right name and password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'aBc'
# foo.auth @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# 'Auth by static method':
# topic: ->
# Foo.auth 'test', 'aBc', @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# 'Auth lower case password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'abc'
# foo.auth @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# 'Auth mixed case password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'ABc'
# foo.auth @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# .export module
| 21499 | { _, assert, cwd, mongoose } = require '../../helper'
{ auth } = require "#{cwd}/models/plugins"
schema = new mongoose.Schema
name:
type: String
schema.plugin auth
Foo = mongoose.model 'Foo', schema
# vows
# .describe(auth)
# .addBatch
# teardown: ->
# Foo.remove {}, @callback
# return
#
# 'A model':
# topic: new Foo
# name: 'jim'
# password: '<PASSWORD>'
#
# 'has 64 bytes password': ({ password }) ->
# assert.equal password?.length, 64
#
# 'There is a saved model.':
# topic: ->
# foo = new Foo
# name: 'test'
# password: '<PASSWORD>'
# foo.save @callback
# return
#
# 'Auth not exist name':
# topic: ->
# foo = new Foo
# name: 'nobody'
# foo.auth @callback
# return
#
# 'got name error': ({ path, type }, foo) ->
# assert.equal path, 'name'
# assert.equal type, 'exists'
#
# 'Auth invalid password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: '<PASSWORD>'
# foo.auth @callback
# return
#
# 'got password error': ({ path, type }, foo) ->
# assert.equal path, 'password'
# assert.equal type, 'equal'
#
# 'Auth right name and password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: '<PASSWORD>'
# foo.auth @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# 'Auth by static method':
# topic: ->
# Foo.auth 'test', 'aBc', @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# 'Auth lower case password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: '<PASSWORD>'
# foo.auth @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# 'Auth mixed case password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: '<PASSWORD>'
# foo.auth @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# .export module
| true | { _, assert, cwd, mongoose } = require '../../helper'
{ auth } = require "#{cwd}/models/plugins"
schema = new mongoose.Schema
name:
type: String
schema.plugin auth
Foo = mongoose.model 'Foo', schema
# vows
# .describe(auth)
# .addBatch
# teardown: ->
# Foo.remove {}, @callback
# return
#
# 'A model':
# topic: new Foo
# name: 'jim'
# password: 'PI:PASSWORD:<PASSWORD>END_PI'
#
# 'has 64 bytes password': ({ password }) ->
# assert.equal password?.length, 64
#
# 'There is a saved model.':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'PI:PASSWORD:<PASSWORD>END_PI'
# foo.save @callback
# return
#
# 'Auth not exist name':
# topic: ->
# foo = new Foo
# name: 'nobody'
# foo.auth @callback
# return
#
# 'got name error': ({ path, type }, foo) ->
# assert.equal path, 'name'
# assert.equal type, 'exists'
#
# 'Auth invalid password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'PI:PASSWORD:<PASSWORD>END_PI'
# foo.auth @callback
# return
#
# 'got password error': ({ path, type }, foo) ->
# assert.equal path, 'password'
# assert.equal type, 'equal'
#
# 'Auth right name and password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'PI:PASSWORD:<PASSWORD>END_PI'
# foo.auth @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# 'Auth by static method':
# topic: ->
# Foo.auth 'test', 'aBc', @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# 'Auth lower case password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'PI:PASSWORD:<PASSWORD>END_PI'
# foo.auth @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# 'Auth mixed case password':
# topic: ->
# foo = new Foo
# name: 'test'
# password: 'PI:PASSWORD:<PASSWORD>END_PI'
# foo.auth @callback
# return
#
# 'got authed foo': (err, foo) ->
# assert.instanceOf foo, Foo
#
# .export module
|
[
{
"context": "###\n input-view.coffee\n Copyright (c) 2016 Nokia\n\n Note:\n This file is part of the netconf packa",
"end": 50,
"score": 0.9758062362670898,
"start": 45,
"tag": "NAME",
"value": "Nokia"
}
] | lib/views/input-view.coffee | nokia/atom-netconf | 15 | ###
input-view.coffee
Copyright (c) 2016 Nokia
Note:
This file is part of the netconf package for the ATOM Text Editor.
Licensed under the MIT license
See LICENSE.md delivered with this project for more information.
###
{Emitter, CompositeDisposable, TextEditor} = require 'atom'
module.exports =
class InputView
constructor: ->
@view = document.createElement('div')
@title = document.createElement('div')
@editor = atom.workspace.buildTextEditor(mini: true)
@view.appendChild @title
@view.appendChild atom.views.getView(@editor)
@panel = atom.workspace.addModalPanel item: @view, visible: false
@emitter = new Emitter
@subscriptions = new CompositeDisposable
@subscriptions.add atom.commands.add 'atom-workspace', 'core:confirm': =>
@emitter.emit 'on-confirm', @editor.getText().trim()
@hide()
@subscriptions.add atom.commands.add 'atom-workspace', 'core:cancel': =>
@emitter.emit 'on-cancel'
@hide()
destroy: =>
@subscriptions.dispose()
@emitter.dispose()
delete @editor
delete @title
delete @view
onConfirm: (callback) =>
@emitter.on 'on-confirm', callback
onCancel: (callback) =>
@emitter.on 'on-cancel', callback
hide: ->
@panel.hide()
@destroy()
show: ->
@panel.show()
atom.views.getView(@editor).focus()
setCaption: (description) =>
@title.textContent = description
setDefault: (text) =>
@editor.setText text
@editor.selectAll()
getValue: =>
return @editor.getText().trim()
# EOF
| 194603 | ###
input-view.coffee
Copyright (c) 2016 <NAME>
Note:
This file is part of the netconf package for the ATOM Text Editor.
Licensed under the MIT license
See LICENSE.md delivered with this project for more information.
###
{Emitter, CompositeDisposable, TextEditor} = require 'atom'
module.exports =
class InputView
constructor: ->
@view = document.createElement('div')
@title = document.createElement('div')
@editor = atom.workspace.buildTextEditor(mini: true)
@view.appendChild @title
@view.appendChild atom.views.getView(@editor)
@panel = atom.workspace.addModalPanel item: @view, visible: false
@emitter = new Emitter
@subscriptions = new CompositeDisposable
@subscriptions.add atom.commands.add 'atom-workspace', 'core:confirm': =>
@emitter.emit 'on-confirm', @editor.getText().trim()
@hide()
@subscriptions.add atom.commands.add 'atom-workspace', 'core:cancel': =>
@emitter.emit 'on-cancel'
@hide()
destroy: =>
@subscriptions.dispose()
@emitter.dispose()
delete @editor
delete @title
delete @view
onConfirm: (callback) =>
@emitter.on 'on-confirm', callback
onCancel: (callback) =>
@emitter.on 'on-cancel', callback
hide: ->
@panel.hide()
@destroy()
show: ->
@panel.show()
atom.views.getView(@editor).focus()
setCaption: (description) =>
@title.textContent = description
setDefault: (text) =>
@editor.setText text
@editor.selectAll()
getValue: =>
return @editor.getText().trim()
# EOF
| true | ###
input-view.coffee
Copyright (c) 2016 PI:NAME:<NAME>END_PI
Note:
This file is part of the netconf package for the ATOM Text Editor.
Licensed under the MIT license
See LICENSE.md delivered with this project for more information.
###
{Emitter, CompositeDisposable, TextEditor} = require 'atom'
module.exports =
class InputView
constructor: ->
@view = document.createElement('div')
@title = document.createElement('div')
@editor = atom.workspace.buildTextEditor(mini: true)
@view.appendChild @title
@view.appendChild atom.views.getView(@editor)
@panel = atom.workspace.addModalPanel item: @view, visible: false
@emitter = new Emitter
@subscriptions = new CompositeDisposable
@subscriptions.add atom.commands.add 'atom-workspace', 'core:confirm': =>
@emitter.emit 'on-confirm', @editor.getText().trim()
@hide()
@subscriptions.add atom.commands.add 'atom-workspace', 'core:cancel': =>
@emitter.emit 'on-cancel'
@hide()
destroy: =>
@subscriptions.dispose()
@emitter.dispose()
delete @editor
delete @title
delete @view
onConfirm: (callback) =>
@emitter.on 'on-confirm', callback
onCancel: (callback) =>
@emitter.on 'on-cancel', callback
hide: ->
@panel.hide()
@destroy()
show: ->
@panel.show()
atom.views.getView(@editor).focus()
setCaption: (description) =>
@title.textContent = description
setDefault: (text) =>
@editor.setText text
@editor.selectAll()
getValue: =>
return @editor.getText().trim()
# EOF
|
[
{
"context": " for key, val of emails\n continue if key is 'anyNotes'\n if val.enabled\n consentHistory.push",
"end": 747,
"score": 0.9370666742324829,
"start": 739,
"tag": "KEY",
"value": "anyNotes"
}
] | server/commons/unsubscribe.coffee | IngJuanRuiz/codecombat | 0 | User = require '../models/User'
co = require 'co'
delighted = require '../delighted'
config = require '../../server_config'
request = require 'request'
intercom = require '../lib/intercom'
log = require 'winston'
unsubscribeEmailFromMarketingEmails = co.wrap (email) ->
log.info "Completely unsubscribing email: #{email}"
# set user to be unsubscribed forever if user exists
user = yield User.findByEmail(email)
if user
user.set('unsubscribedFromMarketingEmails', true)
emails = _.cloneDeep(user.get('emails') or {}) # necessary for saves to work
emails.generalNews ?= {}
emails.anyNotes ?= {}
consentHistory = _.cloneDeep(user.get('consentHistory') or [])
for key, val of emails
continue if key is 'anyNotes'
if val.enabled
consentHistory.push
action: 'forbid'
date: new Date()
type: 'email'
emailHash: User.hashEmail(user.get('email'))
description: key
val.enabled = false
user.set('consentHistory', consentHistory)
user.set('emails', emails)
user.set 'mailChimp', undefined
# unsubscribe user from MailChimp
yield user.save() # middleware takes care of unsubscribing MailChimp
updateConsentHistory = co.wrap (description) ->
yield user.update {$push: {'consentHistory':
action: 'forbid'
date: new Date()
type: 'email'
emailHash: User.hashEmail(user.get('email'))
description: description
}}
# unsubscribe user from delighted
delighted.unsubscribeEmail({ person_email: email })
yield updateConsentHistory('delighted')
# unsubscribe user from ZP
searchUrl = "https://www.zenprospect.com/api/v1/contacts/search?api_key=#{config.zenProspect.apiKey}&q_keywords=#{email}"
contactUrl = "https://www.zenprospect.com/api/v1/contacts?api_key=#{config.zenProspect.apiKey}"
DO_NOT_CONTACT = '57290b9c7ff0bb3b3ef2bebb'
[res] = yield request.getAsync({ url:searchUrl, json: true })
if res.statusCode is 200
if res.body.contacts.length is 0
# post a contact with status "do not contact" to prevent reaching out
json = { email, contact_stage_id: DO_NOT_CONTACT } # contact stage: do not contact
[res] = yield request.postAsync({ url:contactUrl, json })
else
# update any existing contacts "to do not contact"
for contact in res.body.contacts
if contact.contact_stage_id isnt DO_NOT_CONTACT
url = "https://www.zenprospect.com/api/v1/contacts/#{contact.id}?api_key=#{config.zenProspect.apiKey}"
json = {contact_stage_id: DO_NOT_CONTACT}
[res] = yield request.putAsync({ url, json })
yield updateConsentHistory('zenprospect')
# unsubscribe user from Intercom
tries = 0
while tries < 10
try
yield intercom.users.find({email}) # throws error if 404
# if an error hasn't been thrown, then update the user
res = yield intercom.users.update({email, unsubscribed_from_emails: true})
yield updateConsentHistory('intercom')
break
catch e
if e.statusCode is 429
# sleep, try again
yield new Promise((accept) -> setTimeout(accept, 1000))
continue
# otherwise, no user found
break
module.exports = {
unsubscribeEmailFromMarketingEmails
}
| 226171 | User = require '../models/User'
co = require 'co'
delighted = require '../delighted'
config = require '../../server_config'
request = require 'request'
intercom = require '../lib/intercom'
log = require 'winston'
unsubscribeEmailFromMarketingEmails = co.wrap (email) ->
log.info "Completely unsubscribing email: #{email}"
# set user to be unsubscribed forever if user exists
user = yield User.findByEmail(email)
if user
user.set('unsubscribedFromMarketingEmails', true)
emails = _.cloneDeep(user.get('emails') or {}) # necessary for saves to work
emails.generalNews ?= {}
emails.anyNotes ?= {}
consentHistory = _.cloneDeep(user.get('consentHistory') or [])
for key, val of emails
continue if key is '<KEY>'
if val.enabled
consentHistory.push
action: 'forbid'
date: new Date()
type: 'email'
emailHash: User.hashEmail(user.get('email'))
description: key
val.enabled = false
user.set('consentHistory', consentHistory)
user.set('emails', emails)
user.set 'mailChimp', undefined
# unsubscribe user from MailChimp
yield user.save() # middleware takes care of unsubscribing MailChimp
updateConsentHistory = co.wrap (description) ->
yield user.update {$push: {'consentHistory':
action: 'forbid'
date: new Date()
type: 'email'
emailHash: User.hashEmail(user.get('email'))
description: description
}}
# unsubscribe user from delighted
delighted.unsubscribeEmail({ person_email: email })
yield updateConsentHistory('delighted')
# unsubscribe user from ZP
searchUrl = "https://www.zenprospect.com/api/v1/contacts/search?api_key=#{config.zenProspect.apiKey}&q_keywords=#{email}"
contactUrl = "https://www.zenprospect.com/api/v1/contacts?api_key=#{config.zenProspect.apiKey}"
DO_NOT_CONTACT = '57290b9c7ff0bb3b3ef2bebb'
[res] = yield request.getAsync({ url:searchUrl, json: true })
if res.statusCode is 200
if res.body.contacts.length is 0
# post a contact with status "do not contact" to prevent reaching out
json = { email, contact_stage_id: DO_NOT_CONTACT } # contact stage: do not contact
[res] = yield request.postAsync({ url:contactUrl, json })
else
# update any existing contacts "to do not contact"
for contact in res.body.contacts
if contact.contact_stage_id isnt DO_NOT_CONTACT
url = "https://www.zenprospect.com/api/v1/contacts/#{contact.id}?api_key=#{config.zenProspect.apiKey}"
json = {contact_stage_id: DO_NOT_CONTACT}
[res] = yield request.putAsync({ url, json })
yield updateConsentHistory('zenprospect')
# unsubscribe user from Intercom
tries = 0
while tries < 10
try
yield intercom.users.find({email}) # throws error if 404
# if an error hasn't been thrown, then update the user
res = yield intercom.users.update({email, unsubscribed_from_emails: true})
yield updateConsentHistory('intercom')
break
catch e
if e.statusCode is 429
# sleep, try again
yield new Promise((accept) -> setTimeout(accept, 1000))
continue
# otherwise, no user found
break
module.exports = {
unsubscribeEmailFromMarketingEmails
}
| true | User = require '../models/User'
co = require 'co'
delighted = require '../delighted'
config = require '../../server_config'
request = require 'request'
intercom = require '../lib/intercom'
log = require 'winston'
unsubscribeEmailFromMarketingEmails = co.wrap (email) ->
log.info "Completely unsubscribing email: #{email}"
# set user to be unsubscribed forever if user exists
user = yield User.findByEmail(email)
if user
user.set('unsubscribedFromMarketingEmails', true)
emails = _.cloneDeep(user.get('emails') or {}) # necessary for saves to work
emails.generalNews ?= {}
emails.anyNotes ?= {}
consentHistory = _.cloneDeep(user.get('consentHistory') or [])
for key, val of emails
continue if key is 'PI:KEY:<KEY>END_PI'
if val.enabled
consentHistory.push
action: 'forbid'
date: new Date()
type: 'email'
emailHash: User.hashEmail(user.get('email'))
description: key
val.enabled = false
user.set('consentHistory', consentHistory)
user.set('emails', emails)
user.set 'mailChimp', undefined
# unsubscribe user from MailChimp
yield user.save() # middleware takes care of unsubscribing MailChimp
updateConsentHistory = co.wrap (description) ->
yield user.update {$push: {'consentHistory':
action: 'forbid'
date: new Date()
type: 'email'
emailHash: User.hashEmail(user.get('email'))
description: description
}}
# unsubscribe user from delighted
delighted.unsubscribeEmail({ person_email: email })
yield updateConsentHistory('delighted')
# unsubscribe user from ZP
searchUrl = "https://www.zenprospect.com/api/v1/contacts/search?api_key=#{config.zenProspect.apiKey}&q_keywords=#{email}"
contactUrl = "https://www.zenprospect.com/api/v1/contacts?api_key=#{config.zenProspect.apiKey}"
DO_NOT_CONTACT = '57290b9c7ff0bb3b3ef2bebb'
[res] = yield request.getAsync({ url:searchUrl, json: true })
if res.statusCode is 200
if res.body.contacts.length is 0
# post a contact with status "do not contact" to prevent reaching out
json = { email, contact_stage_id: DO_NOT_CONTACT } # contact stage: do not contact
[res] = yield request.postAsync({ url:contactUrl, json })
else
# update any existing contacts "to do not contact"
for contact in res.body.contacts
if contact.contact_stage_id isnt DO_NOT_CONTACT
url = "https://www.zenprospect.com/api/v1/contacts/#{contact.id}?api_key=#{config.zenProspect.apiKey}"
json = {contact_stage_id: DO_NOT_CONTACT}
[res] = yield request.putAsync({ url, json })
yield updateConsentHistory('zenprospect')
# unsubscribe user from Intercom
tries = 0
while tries < 10
try
yield intercom.users.find({email}) # throws error if 404
# if an error hasn't been thrown, then update the user
res = yield intercom.users.update({email, unsubscribed_from_emails: true})
yield updateConsentHistory('intercom')
break
catch e
if e.statusCode is 429
# sleep, try again
yield new Promise((accept) -> setTimeout(accept, 1000))
continue
# otherwise, no user found
break
module.exports = {
unsubscribeEmailFromMarketingEmails
}
|
[
{
"context": "neMatch': '[(\\\\-\\\\-)].*?\\\\b[sS]elene\\\\b'\n'name': 'Selene'\n'scopeName': 'source.lua.sel'\n'patterns': [\n {\n",
"end": 140,
"score": 0.8248387575149536,
"start": 134,
"tag": "NAME",
"value": "Selene"
}
] | grammars/selene.cson | Vexatos/atom-language-selene | 1 | 'comment': 'Selene Syntax: Version 0.1'
'fileTypes': [
'sel'
'selene'
]
'firstLineMatch': '[(\\-\\-)].*?\\b[sS]elene\\b'
'name': 'Selene'
'scopeName': 'source.lua.sel'
'patterns': [
{
'match': '(\\<\\-)'
'name': 'keyword.control.selene'
}
{
'match': '\\(\\s*([a-zA-Z_][\\w_]*(\\s*,\\s*[a-zA-Z_][\\w_]*)*)?\\s*(?=[\\-\\=]\\>)'
'captures':
'1':
'name': 'variable.parameter.function.selene'
'name': 'meta.function.selene'
}
{
'match': '\\(\\s*([a-zA-Z_][\\w_]*(\\s*,\\s*[a-zA-Z_][\\w_]*)*)?\\s*(\\!)(?=[^\n]+([\\-\\=]\\>))'
'captures':
'1':
'name': 'variable.parameter.function.selene'
'3':
'name': 'keyword.control.selene'
'name': 'meta.function.selene'
}
{
'match': '(\\?|[\\-\\=]\\>|\\$\\$)'
'name': 'keyword.control.selene'
}
{
'match': '(?<![^.]\\.|:)(checkArg|ltype|checkType|lpairs|isList|checkFunc|parCount|switch|\\$f|\\$l|\\$s|\\$o|\\$)(?=\\s*(?:[({"\']|\\[\\=*\\[))'
'name': 'support.function.selene'
}
{
'match': '(?<![^.]\\.|:)(bit32\\.(bfor|nfor)|string\\.(foreach|map|flatmap|filter|contains|count|exists|forall|drop|dropright|dropwhile|take|takeright|takewhile|fold|foldleft|foldright|reduce|reduceleft|reduceright|split|iter)|table\\.(shallowcopy|flatten|range|flip|zipped|clear|keys|values))(?=\\s*(?:[({"\']|\\[\\[))'
'name': 'support.function.library.selene'
}
{
'include': 'source.lua'
}
]
| 82697 | 'comment': 'Selene Syntax: Version 0.1'
'fileTypes': [
'sel'
'selene'
]
'firstLineMatch': '[(\\-\\-)].*?\\b[sS]elene\\b'
'name': '<NAME>'
'scopeName': 'source.lua.sel'
'patterns': [
{
'match': '(\\<\\-)'
'name': 'keyword.control.selene'
}
{
'match': '\\(\\s*([a-zA-Z_][\\w_]*(\\s*,\\s*[a-zA-Z_][\\w_]*)*)?\\s*(?=[\\-\\=]\\>)'
'captures':
'1':
'name': 'variable.parameter.function.selene'
'name': 'meta.function.selene'
}
{
'match': '\\(\\s*([a-zA-Z_][\\w_]*(\\s*,\\s*[a-zA-Z_][\\w_]*)*)?\\s*(\\!)(?=[^\n]+([\\-\\=]\\>))'
'captures':
'1':
'name': 'variable.parameter.function.selene'
'3':
'name': 'keyword.control.selene'
'name': 'meta.function.selene'
}
{
'match': '(\\?|[\\-\\=]\\>|\\$\\$)'
'name': 'keyword.control.selene'
}
{
'match': '(?<![^.]\\.|:)(checkArg|ltype|checkType|lpairs|isList|checkFunc|parCount|switch|\\$f|\\$l|\\$s|\\$o|\\$)(?=\\s*(?:[({"\']|\\[\\=*\\[))'
'name': 'support.function.selene'
}
{
'match': '(?<![^.]\\.|:)(bit32\\.(bfor|nfor)|string\\.(foreach|map|flatmap|filter|contains|count|exists|forall|drop|dropright|dropwhile|take|takeright|takewhile|fold|foldleft|foldright|reduce|reduceleft|reduceright|split|iter)|table\\.(shallowcopy|flatten|range|flip|zipped|clear|keys|values))(?=\\s*(?:[({"\']|\\[\\[))'
'name': 'support.function.library.selene'
}
{
'include': 'source.lua'
}
]
| true | 'comment': 'Selene Syntax: Version 0.1'
'fileTypes': [
'sel'
'selene'
]
'firstLineMatch': '[(\\-\\-)].*?\\b[sS]elene\\b'
'name': 'PI:NAME:<NAME>END_PI'
'scopeName': 'source.lua.sel'
'patterns': [
{
'match': '(\\<\\-)'
'name': 'keyword.control.selene'
}
{
'match': '\\(\\s*([a-zA-Z_][\\w_]*(\\s*,\\s*[a-zA-Z_][\\w_]*)*)?\\s*(?=[\\-\\=]\\>)'
'captures':
'1':
'name': 'variable.parameter.function.selene'
'name': 'meta.function.selene'
}
{
'match': '\\(\\s*([a-zA-Z_][\\w_]*(\\s*,\\s*[a-zA-Z_][\\w_]*)*)?\\s*(\\!)(?=[^\n]+([\\-\\=]\\>))'
'captures':
'1':
'name': 'variable.parameter.function.selene'
'3':
'name': 'keyword.control.selene'
'name': 'meta.function.selene'
}
{
'match': '(\\?|[\\-\\=]\\>|\\$\\$)'
'name': 'keyword.control.selene'
}
{
'match': '(?<![^.]\\.|:)(checkArg|ltype|checkType|lpairs|isList|checkFunc|parCount|switch|\\$f|\\$l|\\$s|\\$o|\\$)(?=\\s*(?:[({"\']|\\[\\=*\\[))'
'name': 'support.function.selene'
}
{
'match': '(?<![^.]\\.|:)(bit32\\.(bfor|nfor)|string\\.(foreach|map|flatmap|filter|contains|count|exists|forall|drop|dropright|dropwhile|take|takeright|takewhile|fold|foldleft|foldright|reduce|reduceleft|reduceright|split|iter)|table\\.(shallowcopy|flatten|range|flip|zipped|clear|keys|values))(?=\\s*(?:[({"\']|\\[\\[))'
'name': 'support.function.library.selene'
}
{
'include': 'source.lua'
}
]
|
[
{
"context": "gin for smart notifications\n * Copyright 2011-2013 Karpunin Dmitry (KODer) / Evrone.com\n * Licensed under the MIT li",
"end": 130,
"score": 0.9998741745948792,
"start": 115,
"tag": "NAME",
"value": "Karpunin Dmitry"
},
{
"context": "fications\n * Copyright 2011-2013 Karpunin Dmitry (KODer) / Evrone.com\n * Licensed under the MIT license: ",
"end": 137,
"score": 0.9974622130393982,
"start": 132,
"tag": "USERNAME",
"value": "KODer"
},
{
"context": " # nop\n # about 404: https://github.com/bcardarella/client_side_validations/issues/297\n return fal",
"end": 10564,
"score": 0.9997292757034302,
"start": 10553,
"tag": "USERNAME",
"value": "bcardarella"
}
] | app/assets/javascripts/ultimate/flash.js.coffee | KODerFunk/ultimate-flash | 1 | ###*
* Ultimate Flash 0.9.2 - Ruby on Rails oriented jQuery plugin for smart notifications
* Copyright 2011-2013 Karpunin Dmitry (KODer) / Evrone.com
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*
###
###*
* * * DEPRECATED syntax!
*
* $.fn.ultimateFlash() invoke Ultimate Flash functionality at first call on jQuery object
* for the first element in the set of matched elements.
* Subsequent calls forwarding on view methods or return view property.
* If last argument {Boolean} true, then returns {Flash}.
* @usage
* standart actions:
* construction .ultimateFlash([Object options = {}]) : {jQuery} jContainer
* updateOptions .pluginName({Object} options) : {Object} view options
* get options .pluginName('options') : {Object} view options
* show .ultimateFlash('show', String type, String text) : {jQuery} jFlash | {Boolean} false
* notice .ultimateFlash('notice', String text) : {jQuery} jFlash | {Boolean} false
* alert .ultimateFlash('alert', String text) : {jQuery} jFlash | {Boolean} false
* extended actions:
* auto .ultimateFlash('auto', {ArrayOrObject} obj) : {Array} ajFlashes | {Boolean} false
* ajaxSuccess .ultimateFlash('ajaxSuccess'[, Arguments successArgs = []])
* ajaxError .ultimateFlash('ajaxError'[, String text = translations.defaultErrorText][, Arguments errorArgs = []])
*
* * * USE INSTEAD
* @usage
* window.flash = new Ultimate.Plugins.Flash[(Object options = {})]
* flash.notice String text
###
# TODO improve English
# TODO jGrowl features
#= require ultimate/jquery-plugin-adapter
Ultimate.Plugins ||= {}
Ultimate.__FlashClass ||= Ultimate.Plugin
class Ultimate.Plugins.Flash extends Ultimate.__FlashClass
el: '.l-page__flashes'
flashClass: 'flash' # css-class of message container
showAjaxErrors: true # catch global jQuery.ajaxErrors(), try detect message and show it
showAjaxSuccesses: true # catch global jQuery.ajaxSuccessess(), try detect message and show it
preventUndefinedResponses: true # prevent error responses with status code < 100, often 0
detectFormErrors: true # can be function (parsedJSON)
detectPlainTextMaxLength: 200 # if response has plain text and its length fits, show it (-1 for disable)
productionMode: true
maxFlashes: 0 # maximum flash messages in one time
slideTime: 200 # show and hide animate duration
showTime: 3600 # base time for show flash message
showTimePerChar: 30 # show time per char of flash message
hiddenClass: 'hidden-flash' # class to add for hidden flashes
hideOnClick: true # click on notice fire hide()
removeAfterHide: true # remove notice DOM-element on hide
forceAddDotsAfterLastWord: false
forceRemoveDotsAfterLastWord: false
regExpLastWordWithoutDot: /[\wа-яёА-ЯЁ]{3,}$/
regExpLastWordWithDot: /([\wа-яёА-ЯЁ]{3,})\.$/
events: ->
_events = {}
_events["click .#{@flashClass}:not(:animated)"] = 'closeFlashClick'
_events
initialize: (options) ->
@_initTranslations options
# init flashes come from server in page
@jFlashes().each (index, flash) =>
jFlash = $(flash)
jFlash.html @_prepareText(jFlash.html(), jFlash)
@_setTimeout jFlash
jDocument = $(document)
# binding hook ajaxError handler
jDocument.ajaxError =>
if @showAjaxErrors
a = @_ajaxParseArguments(arguments)
@ajaxError a.data, a.jqXHR
# binding hook ajaxSuccess handler
jDocument.ajaxSuccess =>
if @showAjaxSuccesses
a = @_ajaxParseArguments(arguments)
@ajaxSuccess a.data, a.jqXHR
locale: 'en'
translations: null
@defaultLocales =
en:
defaultErrorText: 'Error'
defaultThrownError: 'server connection error'
formFieldsError: 'Form filled with errors'
ru:
defaultErrorText: 'Ошибка'
defaultThrownError: 'ошибка соединения с сервером'
formFieldsError: 'Форма заполнена с ошибками'
# use I18n, and modify locale and translations
_initTranslations: (options) ->
@translations ||= {}
if not options['locale'] and I18n?.locale of @constructor.defaultLocales
@locale = I18n.locale
_.defaults @translations, @constructor.defaultLocales[@locale]
t: (key) ->
@translations[key] or _.string.humanize(key)
# delegate event for hide on click
closeFlashClick: (event) ->
jFlash = $(event.currentTarget)
if @_getOptionOverFlash('hideOnClick', jFlash)
@hide jFlash
false
jFlashes: (filterSelector) ->
_jFlashes = @$(".#{@flashClass}")
if filterSelector then _jFlashes.filter(filterSelector) else _jFlashes
_getOptionOverFlash: (optionName, jFlashOrOptions = {}) ->
option = if jFlashOrOptions instanceof jQuery then jFlashOrOptions.data(optionName) else jFlashOrOptions[optionName]
option ? @[optionName]
_prepareText: (text, jFlashOrOptions) ->
text = _.string.clean(text)
# Add dot after last word (if word has minimum 3 characters)
if @_getOptionOverFlash('forceAddDotsAfterLastWord', jFlashOrOptions) and @_getOptionOverFlash('regExpLastWordWithoutDot', jFlashOrOptions).test(text)
text += '.'
# Remove dot after last word (if word has minimum 3 characters)
if @_getOptionOverFlash('forceRemoveDotsAfterLastWord', jFlashOrOptions)
text = text.replace(@_getOptionOverFlash('regExpLastWordWithDot', jFlashOrOptions), '$1')
text
_setTimeout: (jFlash, timeout) ->
timeout ?= @_getOptionOverFlash('showTime', jFlash) + jFlash.text().length * @_getOptionOverFlash('showTimePerChar', jFlash)
if timeout
jFlash.data 'timeoutId', setTimeout =>
jFlash.removeData 'timeoutId'
@hide jFlash
, timeout
_hide: (jFlash, slideTime) ->
jFlash.slideUp slideTime, =>
jFlash.remove() if @_getOptionOverFlash('removeAfterHide', jFlash)
hide: (jFlashes = @jFlashes()) ->
jFlashes.each (index, element) =>
jFlash = $(element)
clearTimeout jFlash.data('timeoutId')
@_hide jFlash.addClass(@hiddenClass), @_getOptionOverFlash('slideTime', jFlash)
_template: (type, text) ->
"<div class=\"#{@flashClass} #{type}\" style=\"display: none;\">#{text}</div>"
_append: (jFlash) ->
jFlash.appendTo @$el
_show: (jFlash, slideTime) ->
jFlash.slideDown slideTime
show: (type, text, timeout = null, perFlashOptions = null) ->
text = @_prepareText(text, perFlashOptions)
return false if not _.isString(text) or _.string.isBlank(text)
if @maxFlashes
jActiveFlashes = @jFlashes(":not(.#{@hiddenClass})")
excessFlashes = jActiveFlashes.length - (@maxFlashes - 1)
if excessFlashes > 0
@hide jActiveFlashes.slice(0, excessFlashes)
jFlash = $(@_template(type, text))
if perFlashOptions
jFlash.data(key, value) for key, value of perFlashOptions
@_show @_append(jFlash), @_getOptionOverFlash('slideTime', perFlashOptions)
@_setTimeout jFlash, timeout
jFlash
notice: (text, timeout = null, perFlashOptions = null) -> @show 'notice', arguments...
alert: (text, timeout = null, perFlashOptions = null) -> @show 'alert', arguments...
auto: (obj) ->
if _.isArray(obj)
@show(pair[0], pair[1]) for pair in obj
else if $.isPlainObject(obj)
@show(key, text) for key, text of obj
else false
_ajaxParseArguments: (args) ->
# detect event as first element
if args[0] instanceof jQuery.Event
# convert arguments to Array
args = _.toArray(args)
# remove event
args.shift()
# arrange arguments
if _.isString(args[0])
# from jQuery.ajax().success()
[data, _textStatus, jqXHR] = args
else
# from jQuery.ajaxSuccess() or jQuery.ajaxError()
[jqXHR, _ajaxSettings, data] = args
data: data
jqXHR: jqXHR
###*
* @param {String|Object} data some data from ajax response
* @param {jqXHR} jqXHR jQuery XHR
* @return {Boolean} статус выполнения показа сообщения
###
# MAYBE jqXHR set default as jQuery.hxr or similar
ajaxSuccess: (data, jqXHR) ->
# prevent recall
return false if jqXHR.breakFlash
jqXHR.breakFlash = true
# detect notice
if _.isString(data)
# catch plain text message
data = _.string.trim(data)
return @notice(data) if data.length <= @detectPlainTextMaxLength and not $.isHTML(data)
else if _.isObject(data)
# catch json data with flash-notice
return @auto(data['flash']) if data['flash']
false
###*
* @param {String} [text='Ошибка'] вступительный (либо полный) текст формируемой ошибки
* @param {String} thrownError some error from ajax response
* @param {jqXHR} jqXHR jQuery XHR
* @return {Boolean} статус выполнения показа сообщения
###
ajaxError: (text, thrownError, jqXHR) ->
unless _.isObject(jqXHR)
jqXHR = thrownError
thrownError = text
text = @t('defaultErrorText')
# prevent undefined responses
return false if @preventUndefinedResponses and jqXHR.status < 100
# prevent recall
return false if jqXHR.breakFlash
jqXHR.breakFlash = true
if jqXHR.responseText
try
# try parse respose as json
parsedJSON = $.parseJSON(jqXHR.responseText)
if _.isObject(parsedJSON) and not _.isEmpty(parsedJSON)
# catch 'flash' object and call auto() method with autodetecting flash-notice type
return @auto(parsedJSON['flash']) if parsedJSON['flash']
# catch 'error' object and call alert() method
return @alert(parsedJSON['error']) if parsedJSON['error']
# may be parsedJSON is form errors
if @detectFormErrors is true
# show message about form with errors
return @alert(@t('formFieldsError'))
else if _.isFunction(@detectFormErrors) and (detectedError = @detectFormErrors(parsedJSON))
# using detectFormErrors as callback
return @alert(detectedError)
else
# nothing
return false
catch e
# nop
# about 404: https://github.com/bcardarella/client_side_validations/issues/297
return false if jqXHR.status < 400 or jqXHR.status is 404
if @productionMode
thrownError = @t('defaultThrownError')
else
if jqXHR.responseText
# try detect Rails raise message
if raiseMatches = jqXHR.responseText.match(/<\/h1>\n<pre>(.+?)<\/pre>/)
thrownError = raiseMatches[1]
else
# try detect short text message as error
if not _.string.isBlank(jqXHR.responseText) and jqXHR.responseText.length <= @detectPlainTextMaxLength
thrownError = jqXHR.responseText
else if _.string.isBlank(thrownError)
thrownError = @t('defaultThrownError')
text += ': ' if text
text += "#{thrownError} [#{jqXHR.status}]"
@alert(text)
Ultimate.createJQueryPlugin 'ultimateFlash', Ultimate.Plugins.Flash
| 156695 | ###*
* Ultimate Flash 0.9.2 - Ruby on Rails oriented jQuery plugin for smart notifications
* Copyright 2011-2013 <NAME> (KODer) / Evrone.com
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*
###
###*
* * * DEPRECATED syntax!
*
* $.fn.ultimateFlash() invoke Ultimate Flash functionality at first call on jQuery object
* for the first element in the set of matched elements.
* Subsequent calls forwarding on view methods or return view property.
* If last argument {Boolean} true, then returns {Flash}.
* @usage
* standart actions:
* construction .ultimateFlash([Object options = {}]) : {jQuery} jContainer
* updateOptions .pluginName({Object} options) : {Object} view options
* get options .pluginName('options') : {Object} view options
* show .ultimateFlash('show', String type, String text) : {jQuery} jFlash | {Boolean} false
* notice .ultimateFlash('notice', String text) : {jQuery} jFlash | {Boolean} false
* alert .ultimateFlash('alert', String text) : {jQuery} jFlash | {Boolean} false
* extended actions:
* auto .ultimateFlash('auto', {ArrayOrObject} obj) : {Array} ajFlashes | {Boolean} false
* ajaxSuccess .ultimateFlash('ajaxSuccess'[, Arguments successArgs = []])
* ajaxError .ultimateFlash('ajaxError'[, String text = translations.defaultErrorText][, Arguments errorArgs = []])
*
* * * USE INSTEAD
* @usage
* window.flash = new Ultimate.Plugins.Flash[(Object options = {})]
* flash.notice String text
###
# TODO improve English
# TODO jGrowl features
#= require ultimate/jquery-plugin-adapter
Ultimate.Plugins ||= {}
Ultimate.__FlashClass ||= Ultimate.Plugin
class Ultimate.Plugins.Flash extends Ultimate.__FlashClass
el: '.l-page__flashes'
flashClass: 'flash' # css-class of message container
showAjaxErrors: true # catch global jQuery.ajaxErrors(), try detect message and show it
showAjaxSuccesses: true # catch global jQuery.ajaxSuccessess(), try detect message and show it
preventUndefinedResponses: true # prevent error responses with status code < 100, often 0
detectFormErrors: true # can be function (parsedJSON)
detectPlainTextMaxLength: 200 # if response has plain text and its length fits, show it (-1 for disable)
productionMode: true
maxFlashes: 0 # maximum flash messages in one time
slideTime: 200 # show and hide animate duration
showTime: 3600 # base time for show flash message
showTimePerChar: 30 # show time per char of flash message
hiddenClass: 'hidden-flash' # class to add for hidden flashes
hideOnClick: true # click on notice fire hide()
removeAfterHide: true # remove notice DOM-element on hide
forceAddDotsAfterLastWord: false
forceRemoveDotsAfterLastWord: false
regExpLastWordWithoutDot: /[\wа-яёА-ЯЁ]{3,}$/
regExpLastWordWithDot: /([\wа-яёА-ЯЁ]{3,})\.$/
events: ->
_events = {}
_events["click .#{@flashClass}:not(:animated)"] = 'closeFlashClick'
_events
initialize: (options) ->
@_initTranslations options
# init flashes come from server in page
@jFlashes().each (index, flash) =>
jFlash = $(flash)
jFlash.html @_prepareText(jFlash.html(), jFlash)
@_setTimeout jFlash
jDocument = $(document)
# binding hook ajaxError handler
jDocument.ajaxError =>
if @showAjaxErrors
a = @_ajaxParseArguments(arguments)
@ajaxError a.data, a.jqXHR
# binding hook ajaxSuccess handler
jDocument.ajaxSuccess =>
if @showAjaxSuccesses
a = @_ajaxParseArguments(arguments)
@ajaxSuccess a.data, a.jqXHR
locale: 'en'
translations: null
@defaultLocales =
en:
defaultErrorText: 'Error'
defaultThrownError: 'server connection error'
formFieldsError: 'Form filled with errors'
ru:
defaultErrorText: 'Ошибка'
defaultThrownError: 'ошибка соединения с сервером'
formFieldsError: 'Форма заполнена с ошибками'
# use I18n, and modify locale and translations
_initTranslations: (options) ->
@translations ||= {}
if not options['locale'] and I18n?.locale of @constructor.defaultLocales
@locale = I18n.locale
_.defaults @translations, @constructor.defaultLocales[@locale]
t: (key) ->
@translations[key] or _.string.humanize(key)
# delegate event for hide on click
closeFlashClick: (event) ->
jFlash = $(event.currentTarget)
if @_getOptionOverFlash('hideOnClick', jFlash)
@hide jFlash
false
jFlashes: (filterSelector) ->
_jFlashes = @$(".#{@flashClass}")
if filterSelector then _jFlashes.filter(filterSelector) else _jFlashes
_getOptionOverFlash: (optionName, jFlashOrOptions = {}) ->
option = if jFlashOrOptions instanceof jQuery then jFlashOrOptions.data(optionName) else jFlashOrOptions[optionName]
option ? @[optionName]
_prepareText: (text, jFlashOrOptions) ->
text = _.string.clean(text)
# Add dot after last word (if word has minimum 3 characters)
if @_getOptionOverFlash('forceAddDotsAfterLastWord', jFlashOrOptions) and @_getOptionOverFlash('regExpLastWordWithoutDot', jFlashOrOptions).test(text)
text += '.'
# Remove dot after last word (if word has minimum 3 characters)
if @_getOptionOverFlash('forceRemoveDotsAfterLastWord', jFlashOrOptions)
text = text.replace(@_getOptionOverFlash('regExpLastWordWithDot', jFlashOrOptions), '$1')
text
_setTimeout: (jFlash, timeout) ->
timeout ?= @_getOptionOverFlash('showTime', jFlash) + jFlash.text().length * @_getOptionOverFlash('showTimePerChar', jFlash)
if timeout
jFlash.data 'timeoutId', setTimeout =>
jFlash.removeData 'timeoutId'
@hide jFlash
, timeout
_hide: (jFlash, slideTime) ->
jFlash.slideUp slideTime, =>
jFlash.remove() if @_getOptionOverFlash('removeAfterHide', jFlash)
hide: (jFlashes = @jFlashes()) ->
jFlashes.each (index, element) =>
jFlash = $(element)
clearTimeout jFlash.data('timeoutId')
@_hide jFlash.addClass(@hiddenClass), @_getOptionOverFlash('slideTime', jFlash)
_template: (type, text) ->
"<div class=\"#{@flashClass} #{type}\" style=\"display: none;\">#{text}</div>"
_append: (jFlash) ->
jFlash.appendTo @$el
_show: (jFlash, slideTime) ->
jFlash.slideDown slideTime
show: (type, text, timeout = null, perFlashOptions = null) ->
text = @_prepareText(text, perFlashOptions)
return false if not _.isString(text) or _.string.isBlank(text)
if @maxFlashes
jActiveFlashes = @jFlashes(":not(.#{@hiddenClass})")
excessFlashes = jActiveFlashes.length - (@maxFlashes - 1)
if excessFlashes > 0
@hide jActiveFlashes.slice(0, excessFlashes)
jFlash = $(@_template(type, text))
if perFlashOptions
jFlash.data(key, value) for key, value of perFlashOptions
@_show @_append(jFlash), @_getOptionOverFlash('slideTime', perFlashOptions)
@_setTimeout jFlash, timeout
jFlash
notice: (text, timeout = null, perFlashOptions = null) -> @show 'notice', arguments...
alert: (text, timeout = null, perFlashOptions = null) -> @show 'alert', arguments...
auto: (obj) ->
if _.isArray(obj)
@show(pair[0], pair[1]) for pair in obj
else if $.isPlainObject(obj)
@show(key, text) for key, text of obj
else false
_ajaxParseArguments: (args) ->
# detect event as first element
if args[0] instanceof jQuery.Event
# convert arguments to Array
args = _.toArray(args)
# remove event
args.shift()
# arrange arguments
if _.isString(args[0])
# from jQuery.ajax().success()
[data, _textStatus, jqXHR] = args
else
# from jQuery.ajaxSuccess() or jQuery.ajaxError()
[jqXHR, _ajaxSettings, data] = args
data: data
jqXHR: jqXHR
###*
* @param {String|Object} data some data from ajax response
* @param {jqXHR} jqXHR jQuery XHR
* @return {Boolean} статус выполнения показа сообщения
###
# MAYBE jqXHR set default as jQuery.hxr or similar
ajaxSuccess: (data, jqXHR) ->
# prevent recall
return false if jqXHR.breakFlash
jqXHR.breakFlash = true
# detect notice
if _.isString(data)
# catch plain text message
data = _.string.trim(data)
return @notice(data) if data.length <= @detectPlainTextMaxLength and not $.isHTML(data)
else if _.isObject(data)
# catch json data with flash-notice
return @auto(data['flash']) if data['flash']
false
###*
* @param {String} [text='Ошибка'] вступительный (либо полный) текст формируемой ошибки
* @param {String} thrownError some error from ajax response
* @param {jqXHR} jqXHR jQuery XHR
* @return {Boolean} статус выполнения показа сообщения
###
ajaxError: (text, thrownError, jqXHR) ->
unless _.isObject(jqXHR)
jqXHR = thrownError
thrownError = text
text = @t('defaultErrorText')
# prevent undefined responses
return false if @preventUndefinedResponses and jqXHR.status < 100
# prevent recall
return false if jqXHR.breakFlash
jqXHR.breakFlash = true
if jqXHR.responseText
try
# try parse respose as json
parsedJSON = $.parseJSON(jqXHR.responseText)
if _.isObject(parsedJSON) and not _.isEmpty(parsedJSON)
# catch 'flash' object and call auto() method with autodetecting flash-notice type
return @auto(parsedJSON['flash']) if parsedJSON['flash']
# catch 'error' object and call alert() method
return @alert(parsedJSON['error']) if parsedJSON['error']
# may be parsedJSON is form errors
if @detectFormErrors is true
# show message about form with errors
return @alert(@t('formFieldsError'))
else if _.isFunction(@detectFormErrors) and (detectedError = @detectFormErrors(parsedJSON))
# using detectFormErrors as callback
return @alert(detectedError)
else
# nothing
return false
catch e
# nop
# about 404: https://github.com/bcardarella/client_side_validations/issues/297
return false if jqXHR.status < 400 or jqXHR.status is 404
if @productionMode
thrownError = @t('defaultThrownError')
else
if jqXHR.responseText
# try detect Rails raise message
if raiseMatches = jqXHR.responseText.match(/<\/h1>\n<pre>(.+?)<\/pre>/)
thrownError = raiseMatches[1]
else
# try detect short text message as error
if not _.string.isBlank(jqXHR.responseText) and jqXHR.responseText.length <= @detectPlainTextMaxLength
thrownError = jqXHR.responseText
else if _.string.isBlank(thrownError)
thrownError = @t('defaultThrownError')
text += ': ' if text
text += "#{thrownError} [#{jqXHR.status}]"
@alert(text)
Ultimate.createJQueryPlugin 'ultimateFlash', Ultimate.Plugins.Flash
| true | ###*
* Ultimate Flash 0.9.2 - Ruby on Rails oriented jQuery plugin for smart notifications
* Copyright 2011-2013 PI:NAME:<NAME>END_PI (KODer) / Evrone.com
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*
###
###*
* * * DEPRECATED syntax!
*
* $.fn.ultimateFlash() invoke Ultimate Flash functionality at first call on jQuery object
* for the first element in the set of matched elements.
* Subsequent calls forwarding on view methods or return view property.
* If last argument {Boolean} true, then returns {Flash}.
* @usage
* standart actions:
* construction .ultimateFlash([Object options = {}]) : {jQuery} jContainer
* updateOptions .pluginName({Object} options) : {Object} view options
* get options .pluginName('options') : {Object} view options
* show .ultimateFlash('show', String type, String text) : {jQuery} jFlash | {Boolean} false
* notice .ultimateFlash('notice', String text) : {jQuery} jFlash | {Boolean} false
* alert .ultimateFlash('alert', String text) : {jQuery} jFlash | {Boolean} false
* extended actions:
* auto .ultimateFlash('auto', {ArrayOrObject} obj) : {Array} ajFlashes | {Boolean} false
* ajaxSuccess .ultimateFlash('ajaxSuccess'[, Arguments successArgs = []])
* ajaxError .ultimateFlash('ajaxError'[, String text = translations.defaultErrorText][, Arguments errorArgs = []])
*
* * * USE INSTEAD
* @usage
* window.flash = new Ultimate.Plugins.Flash[(Object options = {})]
* flash.notice String text
###
# TODO improve English
# TODO jGrowl features
#= require ultimate/jquery-plugin-adapter
Ultimate.Plugins ||= {}
Ultimate.__FlashClass ||= Ultimate.Plugin
class Ultimate.Plugins.Flash extends Ultimate.__FlashClass
el: '.l-page__flashes'
flashClass: 'flash' # css-class of message container
showAjaxErrors: true # catch global jQuery.ajaxErrors(), try detect message and show it
showAjaxSuccesses: true # catch global jQuery.ajaxSuccessess(), try detect message and show it
preventUndefinedResponses: true # prevent error responses with status code < 100, often 0
detectFormErrors: true # can be function (parsedJSON)
detectPlainTextMaxLength: 200 # if response has plain text and its length fits, show it (-1 for disable)
productionMode: true
maxFlashes: 0 # maximum flash messages in one time
slideTime: 200 # show and hide animate duration
showTime: 3600 # base time for show flash message
showTimePerChar: 30 # show time per char of flash message
hiddenClass: 'hidden-flash' # class to add for hidden flashes
hideOnClick: true # click on notice fire hide()
removeAfterHide: true # remove notice DOM-element on hide
forceAddDotsAfterLastWord: false
forceRemoveDotsAfterLastWord: false
regExpLastWordWithoutDot: /[\wа-яёА-ЯЁ]{3,}$/
regExpLastWordWithDot: /([\wа-яёА-ЯЁ]{3,})\.$/
events: ->
_events = {}
_events["click .#{@flashClass}:not(:animated)"] = 'closeFlashClick'
_events
initialize: (options) ->
@_initTranslations options
# init flashes come from server in page
@jFlashes().each (index, flash) =>
jFlash = $(flash)
jFlash.html @_prepareText(jFlash.html(), jFlash)
@_setTimeout jFlash
jDocument = $(document)
# binding hook ajaxError handler
jDocument.ajaxError =>
if @showAjaxErrors
a = @_ajaxParseArguments(arguments)
@ajaxError a.data, a.jqXHR
# binding hook ajaxSuccess handler
jDocument.ajaxSuccess =>
if @showAjaxSuccesses
a = @_ajaxParseArguments(arguments)
@ajaxSuccess a.data, a.jqXHR
locale: 'en'
translations: null
@defaultLocales =
en:
defaultErrorText: 'Error'
defaultThrownError: 'server connection error'
formFieldsError: 'Form filled with errors'
ru:
defaultErrorText: 'Ошибка'
defaultThrownError: 'ошибка соединения с сервером'
formFieldsError: 'Форма заполнена с ошибками'
# use I18n, and modify locale and translations
_initTranslations: (options) ->
@translations ||= {}
if not options['locale'] and I18n?.locale of @constructor.defaultLocales
@locale = I18n.locale
_.defaults @translations, @constructor.defaultLocales[@locale]
t: (key) ->
@translations[key] or _.string.humanize(key)
# delegate event for hide on click
closeFlashClick: (event) ->
jFlash = $(event.currentTarget)
if @_getOptionOverFlash('hideOnClick', jFlash)
@hide jFlash
false
jFlashes: (filterSelector) ->
_jFlashes = @$(".#{@flashClass}")
if filterSelector then _jFlashes.filter(filterSelector) else _jFlashes
_getOptionOverFlash: (optionName, jFlashOrOptions = {}) ->
option = if jFlashOrOptions instanceof jQuery then jFlashOrOptions.data(optionName) else jFlashOrOptions[optionName]
option ? @[optionName]
_prepareText: (text, jFlashOrOptions) ->
text = _.string.clean(text)
# Add dot after last word (if word has minimum 3 characters)
if @_getOptionOverFlash('forceAddDotsAfterLastWord', jFlashOrOptions) and @_getOptionOverFlash('regExpLastWordWithoutDot', jFlashOrOptions).test(text)
text += '.'
# Remove dot after last word (if word has minimum 3 characters)
if @_getOptionOverFlash('forceRemoveDotsAfterLastWord', jFlashOrOptions)
text = text.replace(@_getOptionOverFlash('regExpLastWordWithDot', jFlashOrOptions), '$1')
text
_setTimeout: (jFlash, timeout) ->
timeout ?= @_getOptionOverFlash('showTime', jFlash) + jFlash.text().length * @_getOptionOverFlash('showTimePerChar', jFlash)
if timeout
jFlash.data 'timeoutId', setTimeout =>
jFlash.removeData 'timeoutId'
@hide jFlash
, timeout
_hide: (jFlash, slideTime) ->
jFlash.slideUp slideTime, =>
jFlash.remove() if @_getOptionOverFlash('removeAfterHide', jFlash)
hide: (jFlashes = @jFlashes()) ->
jFlashes.each (index, element) =>
jFlash = $(element)
clearTimeout jFlash.data('timeoutId')
@_hide jFlash.addClass(@hiddenClass), @_getOptionOverFlash('slideTime', jFlash)
_template: (type, text) ->
"<div class=\"#{@flashClass} #{type}\" style=\"display: none;\">#{text}</div>"
_append: (jFlash) ->
jFlash.appendTo @$el
_show: (jFlash, slideTime) ->
jFlash.slideDown slideTime
show: (type, text, timeout = null, perFlashOptions = null) ->
text = @_prepareText(text, perFlashOptions)
return false if not _.isString(text) or _.string.isBlank(text)
if @maxFlashes
jActiveFlashes = @jFlashes(":not(.#{@hiddenClass})")
excessFlashes = jActiveFlashes.length - (@maxFlashes - 1)
if excessFlashes > 0
@hide jActiveFlashes.slice(0, excessFlashes)
jFlash = $(@_template(type, text))
if perFlashOptions
jFlash.data(key, value) for key, value of perFlashOptions
@_show @_append(jFlash), @_getOptionOverFlash('slideTime', perFlashOptions)
@_setTimeout jFlash, timeout
jFlash
notice: (text, timeout = null, perFlashOptions = null) -> @show 'notice', arguments...
alert: (text, timeout = null, perFlashOptions = null) -> @show 'alert', arguments...
auto: (obj) ->
if _.isArray(obj)
@show(pair[0], pair[1]) for pair in obj
else if $.isPlainObject(obj)
@show(key, text) for key, text of obj
else false
_ajaxParseArguments: (args) ->
# detect event as first element
if args[0] instanceof jQuery.Event
# convert arguments to Array
args = _.toArray(args)
# remove event
args.shift()
# arrange arguments
if _.isString(args[0])
# from jQuery.ajax().success()
[data, _textStatus, jqXHR] = args
else
# from jQuery.ajaxSuccess() or jQuery.ajaxError()
[jqXHR, _ajaxSettings, data] = args
data: data
jqXHR: jqXHR
###*
* @param {String|Object} data some data from ajax response
* @param {jqXHR} jqXHR jQuery XHR
* @return {Boolean} статус выполнения показа сообщения
###
# MAYBE jqXHR set default as jQuery.hxr or similar
ajaxSuccess: (data, jqXHR) ->
# prevent recall
return false if jqXHR.breakFlash
jqXHR.breakFlash = true
# detect notice
if _.isString(data)
# catch plain text message
data = _.string.trim(data)
return @notice(data) if data.length <= @detectPlainTextMaxLength and not $.isHTML(data)
else if _.isObject(data)
# catch json data with flash-notice
return @auto(data['flash']) if data['flash']
false
###*
* @param {String} [text='Ошибка'] вступительный (либо полный) текст формируемой ошибки
* @param {String} thrownError some error from ajax response
* @param {jqXHR} jqXHR jQuery XHR
* @return {Boolean} статус выполнения показа сообщения
###
ajaxError: (text, thrownError, jqXHR) ->
unless _.isObject(jqXHR)
jqXHR = thrownError
thrownError = text
text = @t('defaultErrorText')
# prevent undefined responses
return false if @preventUndefinedResponses and jqXHR.status < 100
# prevent recall
return false if jqXHR.breakFlash
jqXHR.breakFlash = true
if jqXHR.responseText
try
# try parse respose as json
parsedJSON = $.parseJSON(jqXHR.responseText)
if _.isObject(parsedJSON) and not _.isEmpty(parsedJSON)
# catch 'flash' object and call auto() method with autodetecting flash-notice type
return @auto(parsedJSON['flash']) if parsedJSON['flash']
# catch 'error' object and call alert() method
return @alert(parsedJSON['error']) if parsedJSON['error']
# may be parsedJSON is form errors
if @detectFormErrors is true
# show message about form with errors
return @alert(@t('formFieldsError'))
else if _.isFunction(@detectFormErrors) and (detectedError = @detectFormErrors(parsedJSON))
# using detectFormErrors as callback
return @alert(detectedError)
else
# nothing
return false
catch e
# nop
# about 404: https://github.com/bcardarella/client_side_validations/issues/297
return false if jqXHR.status < 400 or jqXHR.status is 404
if @productionMode
thrownError = @t('defaultThrownError')
else
if jqXHR.responseText
# try detect Rails raise message
if raiseMatches = jqXHR.responseText.match(/<\/h1>\n<pre>(.+?)<\/pre>/)
thrownError = raiseMatches[1]
else
# try detect short text message as error
if not _.string.isBlank(jqXHR.responseText) and jqXHR.responseText.length <= @detectPlainTextMaxLength
thrownError = jqXHR.responseText
else if _.string.isBlank(thrownError)
thrownError = @t('defaultThrownError')
text += ': ' if text
text += "#{thrownError} [#{jqXHR.status}]"
@alert(text)
Ultimate.createJQueryPlugin 'ultimateFlash', Ultimate.Plugins.Flash
|
[
{
"context": " }\n }, {\n \"name\" : \"IntOne\",\n \"context\" : \"Patient\",\n ",
"end": 1998,
"score": 0.9168268442153931,
"start": 1992,
"tag": "USERNAME",
"value": "IntOne"
},
{
"context": " }\n }, {\n \"name\" : \"DecimalTenth\",\n \"context\" : \"Patient\",\n ",
"end": 2295,
"score": 0.8951564431190491,
"start": 2283,
"tag": "USERNAME",
"value": "DecimalTenth"
},
{
"context": " }\n }, {\n \"name\" : \"StringTrue\",\n \"context\" : \"Patient\",\n ",
"end": 2592,
"score": 0.9220988750457764,
"start": 2582,
"tag": "USERNAME",
"value": "StringTrue"
},
{
"context": " }\n }, {\n \"name\" : \"DateTimeX\",\n \"context\" : \"Patient\",\n ",
"end": 2887,
"score": 0.6541178226470947,
"start": 2879,
"tag": "NAME",
"value": "DateTime"
},
{
"context": " }\n }, {\n \"name\" : \"DateTimeX\",\n \"context\" : \"Patient\",\n ",
"end": 2888,
"score": 0.6733766794204712,
"start": 2887,
"tag": "USERNAME",
"value": "X"
},
{
"context": " }\n }, {\n \"name\" : \"TimeX\",\n \"context\" : \"Patient\",\n ",
"end": 4579,
"score": 0.9023430347442627,
"start": 4574,
"tag": "NAME",
"value": "TimeX"
}
] | Src/coffeescript/cql-execution/test/elm/literal/data.coffee | MeasureAuthoringTool/clinical_quality_language | 2 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### Literal
library TestSnippet version '1'
using QUICK
context Patient
define BoolTrue: true
define BoolFalse: false
define IntOne: 1
define DecimalTenth: 0.1
define StringTrue: 'true'
define DateTimeX: @2012-02-15T12:10:59.456Z
define TimeX: @T12:10:59.456Z
###
module.exports['Literal'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "BoolTrue",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Boolean",
"value" : "true",
"type" : "Literal"
}
}, {
"name" : "BoolFalse",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Boolean",
"value" : "false",
"type" : "Literal"
}
}, {
"name" : "IntOne",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}, {
"name" : "DecimalTenth",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "0.1",
"type" : "Literal"
}
}, {
"name" : "StringTrue",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "true",
"type" : "Literal"
}
}, {
"name" : "DateTimeX",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "15",
"type" : "Literal"
},
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "10",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "59",
"type" : "Literal"
},
"millisecond" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "456",
"type" : "Literal"
},
"timezoneOffset" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "0.0",
"type" : "Literal"
}
}
}, {
"name" : "TimeX",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Time",
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "10",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "59",
"type" : "Literal"
},
"millisecond" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "456",
"type" : "Literal"
},
"timezoneOffset" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "0.0",
"type" : "Literal"
}
}
} ]
}
}
}
| 25625 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### Literal
library TestSnippet version '1'
using QUICK
context Patient
define BoolTrue: true
define BoolFalse: false
define IntOne: 1
define DecimalTenth: 0.1
define StringTrue: 'true'
define DateTimeX: @2012-02-15T12:10:59.456Z
define TimeX: @T12:10:59.456Z
###
module.exports['Literal'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "BoolTrue",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Boolean",
"value" : "true",
"type" : "Literal"
}
}, {
"name" : "BoolFalse",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Boolean",
"value" : "false",
"type" : "Literal"
}
}, {
"name" : "IntOne",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}, {
"name" : "DecimalTenth",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "0.1",
"type" : "Literal"
}
}, {
"name" : "StringTrue",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "true",
"type" : "Literal"
}
}, {
"name" : "<NAME>X",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "15",
"type" : "Literal"
},
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "10",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "59",
"type" : "Literal"
},
"millisecond" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "456",
"type" : "Literal"
},
"timezoneOffset" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "0.0",
"type" : "Literal"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Time",
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "10",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "59",
"type" : "Literal"
},
"millisecond" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "456",
"type" : "Literal"
},
"timezoneOffset" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "0.0",
"type" : "Literal"
}
}
} ]
}
}
}
| true | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### Literal
library TestSnippet version '1'
using QUICK
context Patient
define BoolTrue: true
define BoolFalse: false
define IntOne: 1
define DecimalTenth: 0.1
define StringTrue: 'true'
define DateTimeX: @2012-02-15T12:10:59.456Z
define TimeX: @T12:10:59.456Z
###
module.exports['Literal'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "BoolTrue",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Boolean",
"value" : "true",
"type" : "Literal"
}
}, {
"name" : "BoolFalse",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Boolean",
"value" : "false",
"type" : "Literal"
}
}, {
"name" : "IntOne",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}, {
"name" : "DecimalTenth",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "0.1",
"type" : "Literal"
}
}, {
"name" : "StringTrue",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "true",
"type" : "Literal"
}
}, {
"name" : "PI:NAME:<NAME>END_PIX",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "15",
"type" : "Literal"
},
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "10",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "59",
"type" : "Literal"
},
"millisecond" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "456",
"type" : "Literal"
},
"timezoneOffset" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "0.0",
"type" : "Literal"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Time",
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "10",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "59",
"type" : "Literal"
},
"millisecond" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "456",
"type" : "Literal"
},
"timezoneOffset" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "0.0",
"type" : "Literal"
}
}
} ]
}
}
}
|
[
{
"context": " Set ResultOfQuestion values (e.g. Name: Mike McKay, Birthdate: 2012-11-27 or put each pair on a new ",
"end": 2905,
"score": 0.9961594343185425,
"start": 2895,
"tag": "NAME",
"value": "Mike McKay"
}
] | views/QuestionSetView.coffee | Coconut-Data/tamarind | 0 | $ = require 'jquery'
Backbone = require 'backbone'
Backbone.$ = $
_ = require 'underscore'
dasherize = require("underscore.string/dasherize")
titleize = require("underscore.string/titleize")
humanize = require("underscore.string/humanize")
slugify = require("underscore.string/slugify")
get = require 'lodash/get'
set = require 'lodash/set'
unset = require 'lodash/unset'
pullAt = require 'lodash/pullAt'
isJSON = require('is-json');
striptags = require 'striptags'
Sortable = require 'sortablejs'
global.Coffeescript = require 'coffeescript'
JsonDiffPatch = require 'jsondiffpatch'
underscored = require("underscore.string/underscored")
hljs = require 'highlight.js/lib/core';
hljs.registerLanguage('coffeescript', require ('highlight.js/lib/languages/coffeescript'))
hljs.registerLanguage('json', require ('highlight.js/lib/languages/json'))
global.QuestionSet = require '../models/QuestionSet'
class QuestionSetView extends Backbone.View
events: =>
"click .toggleNext": "toggleNext"
"click .hljs-string": "clickParent"
# Hack because json elements get a class that doesn't bubble events
clickParent: (event) =>
$(event.target).parent().click()
toggleNext: (event) =>
elementToToggle = $(event.target).next()
if elementToToggle.hasClass("questionDiv")
@activeQuestionLabel = elementToToggle.attr("data-question-label")
elementToToggle.toggle()
renderSyntaxHighlightedCodeWithTextareaForEditing: (options) =>
propertyPath = options.propertyPath
preStyle = options.preStyle or ""
example = options.example
code = if propertyPath
get(@questionSet.data, propertyPath)
else
@questionSet.data
code = JSON.stringify(code, null, 2) if _(code).isObject()
# https://stackoverflow.com/questions/19913667/javascript-regex-global-match-groups
regex = /ResultOfQuestion\("(.+?)"\)/g
matches = []
questionsReferredTo = []
while (matches = regex.exec(code))
questionsReferredTo.push("#{matches[1]}: Test Value")
questionsReferredTo = _(questionsReferredTo).unique()
"
<pre style='#{preStyle}'><code class='toggleToEdit'>#{code}</code></pre>
<div class='codeEditor' style='display:none'>
#{
if example
"Examples:<br/><code class='example'>#{example}</code><br/>"
else ""
}
<textarea style='display:block' class='code' data-property-path=#{propertyPath}>#{code}</textarea>
<button class='save'>Save</button>
<button class='cancel'>Cancel</button>
<span class='charCount' style='color:grey'></span>
#{ if propertyPath
"
<br/>
<br/>
<span style='background-color: black; color: gray; padding: 2px; border: solid 2px;' class='toggleNext'>Test It</span>
<div style='display:none'>
Set ResultOfQuestion values (e.g. Name: Mike McKay, Birthdate: 2012-11-27 or put each pair on a new line)
<br/>
<textarea style='height:60px' class='testResultOfQuestion'>#{questionsReferredTo.join("""\n""")}</textarea>
<br/>
<br/>
Set the value to use for testing the current value
<br/>
<input class='testValue'></input>
<br/>
<br/>
Test Code:
<br/>
<textarea class='testCode'></textarea>
<br/>
</div>
"
else
""
}
</div>
"
render: =>
fullQuestionSetAsPrettyPrintedJSON = JSON.stringify(@questionSet.data, null, 2)
@$el.html "
<style>
.description{
font-size: small;
color:gray
}
.questionSetProperty{
margin-top:5px;
}
textarea{
width:600px;
height:200px;
}
code, .toggleToEdit:hover, .toggleNext:hover, .clickToEdit:hover{
cursor: pointer
}
.question-label{
font-weight: bold;
font-size: large;
}
.clickToEdit{
background-color: black;
color: gray;
padding: 2px;
border: solid 2px;
}
.highlight{
background-color: yellow
}
</style>
#{
if @isTextMessageQuestionSet()
"
<div style='float:right; width:200px; border: 1px solid;'>
<a href='#messaging/#{@serverName}/#{@databaseOrGatewayName}/#{@questionSet.name()}'>Manage Messaging</a>
<br/>
<br/>
<br/>
<div style='width:200px; border: 1px solid;' id='interact'/>
</div>
<h2>Gateway: <a href='#gateway/#{@serverName}/#{@databaseOrGatewayName}'>#{@databaseOrGatewayName}</a>
"
else
"<h2>Application: <a href='#database/#{@serverName}/#{@databaseOrGatewayName}'>#{@databaseOrGatewayName}</a>"
}
</h2>
<h2>Question Set: #{titleize(@questionSet.name())} <span style='color:gray; font-size:small'>#{@questionSet.data.version or ""}</span></h2>
<div id='questionSet'>
<!--
<div class='description'>
Click on any <span style='background-color:black; color:gray; padding:2px;'>dark area</span> below to edit.
</div>
-->
<h3><a id='resultsButton' href='#results/#{@serverName}/#{@databaseOrGatewayName}/#{@questionSet.name()}'>Results</a></h3>
<div style='display:none'>
<div class='description'>These options configure the entire question set as opposed to individual questions. For example, this is where you can run code when the page loads or when the question set is marked complete.</div>
#{
_(@questionSet.data).map (value, property) =>
propertyMetadata = QuestionSet.properties[property]
if propertyMetadata
switch propertyMetadata["data-type"]
when "coffeescript", "object","text"
"
<div>
<div class='questionSetProperty'>
<div class='questionSetPropertyName'>
#{property}
<div class='description'>
#{propertyMetadata.description}
</div>
</div>
#{
@renderSyntaxHighlightedCodeWithTextareaForEditing
propertyPath: property
example: propertyMetadata.example
}
</div>
</div>
"
else
console.error "Unknown type: #{propertyMetadata["data-type"]}: #{value}"
alert "Unhandled type"
else
return if _(["_id", "label", "_rev", "isApplicationDoc", "collection", "couchapp", "questions", "version"]).contains property
console.error "Unknown question set property: #{property}: #{value}"
.join("")
}
</div>
<h2>Questions</h2>
<div class='description'>Below is a list of all of the questions in this question set.</div>
<div id='questions'>
#{
_(@questionSet.data.questions).map (question, index) =>
"
<div class='sortable' id='question-div-#{index}'>
<div class='toggleNext question-label'>
<span class='handle'>↕</span>
#{striptags(question.label)}
<div style='margin-left: 20px; font-weight:normal;font-size:small'>
#{if question["radio-options"] then "<div>#{question["radio-options"]}</div>" else ""}
#{if question["skip_logic"] then "<div>Skip if: <span style='font-family:monospace'>#{question["skip_logic"]}</span></div>" else ""}
</div>
</div>
<div class='questionDiv' data-question-label='#{question.label}' style='display:none; margin-left: 10px; padding: 5px; background-color:#DCDCDC'>
<div>Properties Configured:</div>
#{
_(question).map (value, property) =>
propertyMetadata = QuestionSet.questionProperties[property]
if propertyMetadata
dataType = propertyMetadata["data-type"]
if question.type is "autocomplete from code" and question["autocomplete-options"]
dataType = "coffeescript"
propertyPath = "questions[#{index}][#{property}]"
"
<hr/>
<div class='questionPropertyName'>
#{property}
<div class='description'>
#{propertyMetadata.description}
</div>
</div>
" + switch dataType
when "coffeescript", "text", "json"
"
<div>
<div data-type-of-code='#{property}' class='questionProperty code'>
#{
if property is "url" and value.endsWith("mp3")
"<audio controls src='#{value}'></audio>"
else
""
}
#{
@renderSyntaxHighlightedCodeWithTextareaForEditing
propertyPath: propertyPath
example: propertyMetadata.example
}
</div>
</div>
"
when "select"
"
<div>
#{property}: <span style='font-weight:bold'>#{question[property]}</span>
<div style='display:none'>
<select style='display:block' data-property-path='#{propertyPath}'>
#{
_(propertyMetadata.options).map (optionMetadata, option) =>
if _(optionMetadata).isBoolean()
"<option #{if optionMetadata is question[property] then "selected=true" else ""}>#{optionMetadata}</option>"
else
"<option #{if option is question[property] then "selected=true" else ""}>#{option}</option>"
.join ""
}
</select>
<button class='save'>Save</button>
<button class='cancel'>Cancel</button>
</div>
</div>
"
when "array"
console.log question
value = "Example Option 1, Example Option 2" unless value
"
<div>
Items:
<ul>
#{
_(value.split(/, */)).map (item) =>
"<li>#{item}</li>"
.join("")
}
</ul>
</div>
"
else
console.error "Unknown type: #{propertyMetadata["data-type"]}: #{value}"
else
console.error "Unknown property: #{property}: #{value}"
.join("")
#
#
}
<br/>
<br/>
</div>
</div>
"
.join("")
}
</div>
<hr/>
</div>
"
hljs.configure
languages: ["coffeescript", "json"]
useBR: false
@$('pre code').each (i, snippet) =>
hljs.highlightElement(snippet);
@sortable = Sortable.create document.getElementById('questions'),
handle: ".handle"
onUpdate: (event) =>
# Reorder the array
# https://stackoverflow.com/a/2440723/266111
@sortable.option("disabled", true)
@questionSet.data.questions.splice(event.newIndex, 0, @questionSet.data.questions.splice(event.oldIndex, 1)[0])
@changesWatcher.cancel()
await @questionSet.save()
@render()
@sortable.option("disabled", false)
@openActiveQuestion()
@resetChangesWatcher()
resetChangesWatcher: =>
if Tamarind.database?
Tamarind.database.changes
limit:1
descending:true
.then (change) =>
@changesWatcher = Tamarind.database.changes
live: true
doc_ids: [router.questionSetView.questionSet.data._id]
since: change.last_seq
.on "change", (change) =>
console.log change
@changesWatcher.cancel()
if confirm("This question set has changed - someone else might be working on it. Would you like to refresh?")
@questionSet.fetch().then => @render()
else
# Create an empty changesWatcher
@changesWatcher =
cancel: ->
openActiveQuestion: =>
if @activeQuestionLabel
questionElement = @$(".toggleNext.question-label:contains(#{@activeQuestionLabel})")
questionElement.click()
questionElement[0].scrollIntoView()
isTextMessageQuestionSet: =>
Tamarind.dynamoDBClient?
module.exports = QuestionSetView
| 187654 | $ = require 'jquery'
Backbone = require 'backbone'
Backbone.$ = $
_ = require 'underscore'
dasherize = require("underscore.string/dasherize")
titleize = require("underscore.string/titleize")
humanize = require("underscore.string/humanize")
slugify = require("underscore.string/slugify")
get = require 'lodash/get'
set = require 'lodash/set'
unset = require 'lodash/unset'
pullAt = require 'lodash/pullAt'
isJSON = require('is-json');
striptags = require 'striptags'
Sortable = require 'sortablejs'
global.Coffeescript = require 'coffeescript'
JsonDiffPatch = require 'jsondiffpatch'
underscored = require("underscore.string/underscored")
hljs = require 'highlight.js/lib/core';
hljs.registerLanguage('coffeescript', require ('highlight.js/lib/languages/coffeescript'))
hljs.registerLanguage('json', require ('highlight.js/lib/languages/json'))
global.QuestionSet = require '../models/QuestionSet'
class QuestionSetView extends Backbone.View
events: =>
"click .toggleNext": "toggleNext"
"click .hljs-string": "clickParent"
# Hack because json elements get a class that doesn't bubble events
clickParent: (event) =>
$(event.target).parent().click()
toggleNext: (event) =>
elementToToggle = $(event.target).next()
if elementToToggle.hasClass("questionDiv")
@activeQuestionLabel = elementToToggle.attr("data-question-label")
elementToToggle.toggle()
renderSyntaxHighlightedCodeWithTextareaForEditing: (options) =>
propertyPath = options.propertyPath
preStyle = options.preStyle or ""
example = options.example
code = if propertyPath
get(@questionSet.data, propertyPath)
else
@questionSet.data
code = JSON.stringify(code, null, 2) if _(code).isObject()
# https://stackoverflow.com/questions/19913667/javascript-regex-global-match-groups
regex = /ResultOfQuestion\("(.+?)"\)/g
matches = []
questionsReferredTo = []
while (matches = regex.exec(code))
questionsReferredTo.push("#{matches[1]}: Test Value")
questionsReferredTo = _(questionsReferredTo).unique()
"
<pre style='#{preStyle}'><code class='toggleToEdit'>#{code}</code></pre>
<div class='codeEditor' style='display:none'>
#{
if example
"Examples:<br/><code class='example'>#{example}</code><br/>"
else ""
}
<textarea style='display:block' class='code' data-property-path=#{propertyPath}>#{code}</textarea>
<button class='save'>Save</button>
<button class='cancel'>Cancel</button>
<span class='charCount' style='color:grey'></span>
#{ if propertyPath
"
<br/>
<br/>
<span style='background-color: black; color: gray; padding: 2px; border: solid 2px;' class='toggleNext'>Test It</span>
<div style='display:none'>
Set ResultOfQuestion values (e.g. Name: <NAME>, Birthdate: 2012-11-27 or put each pair on a new line)
<br/>
<textarea style='height:60px' class='testResultOfQuestion'>#{questionsReferredTo.join("""\n""")}</textarea>
<br/>
<br/>
Set the value to use for testing the current value
<br/>
<input class='testValue'></input>
<br/>
<br/>
Test Code:
<br/>
<textarea class='testCode'></textarea>
<br/>
</div>
"
else
""
}
</div>
"
render: =>
fullQuestionSetAsPrettyPrintedJSON = JSON.stringify(@questionSet.data, null, 2)
@$el.html "
<style>
.description{
font-size: small;
color:gray
}
.questionSetProperty{
margin-top:5px;
}
textarea{
width:600px;
height:200px;
}
code, .toggleToEdit:hover, .toggleNext:hover, .clickToEdit:hover{
cursor: pointer
}
.question-label{
font-weight: bold;
font-size: large;
}
.clickToEdit{
background-color: black;
color: gray;
padding: 2px;
border: solid 2px;
}
.highlight{
background-color: yellow
}
</style>
#{
if @isTextMessageQuestionSet()
"
<div style='float:right; width:200px; border: 1px solid;'>
<a href='#messaging/#{@serverName}/#{@databaseOrGatewayName}/#{@questionSet.name()}'>Manage Messaging</a>
<br/>
<br/>
<br/>
<div style='width:200px; border: 1px solid;' id='interact'/>
</div>
<h2>Gateway: <a href='#gateway/#{@serverName}/#{@databaseOrGatewayName}'>#{@databaseOrGatewayName}</a>
"
else
"<h2>Application: <a href='#database/#{@serverName}/#{@databaseOrGatewayName}'>#{@databaseOrGatewayName}</a>"
}
</h2>
<h2>Question Set: #{titleize(@questionSet.name())} <span style='color:gray; font-size:small'>#{@questionSet.data.version or ""}</span></h2>
<div id='questionSet'>
<!--
<div class='description'>
Click on any <span style='background-color:black; color:gray; padding:2px;'>dark area</span> below to edit.
</div>
-->
<h3><a id='resultsButton' href='#results/#{@serverName}/#{@databaseOrGatewayName}/#{@questionSet.name()}'>Results</a></h3>
<div style='display:none'>
<div class='description'>These options configure the entire question set as opposed to individual questions. For example, this is where you can run code when the page loads or when the question set is marked complete.</div>
#{
_(@questionSet.data).map (value, property) =>
propertyMetadata = QuestionSet.properties[property]
if propertyMetadata
switch propertyMetadata["data-type"]
when "coffeescript", "object","text"
"
<div>
<div class='questionSetProperty'>
<div class='questionSetPropertyName'>
#{property}
<div class='description'>
#{propertyMetadata.description}
</div>
</div>
#{
@renderSyntaxHighlightedCodeWithTextareaForEditing
propertyPath: property
example: propertyMetadata.example
}
</div>
</div>
"
else
console.error "Unknown type: #{propertyMetadata["data-type"]}: #{value}"
alert "Unhandled type"
else
return if _(["_id", "label", "_rev", "isApplicationDoc", "collection", "couchapp", "questions", "version"]).contains property
console.error "Unknown question set property: #{property}: #{value}"
.join("")
}
</div>
<h2>Questions</h2>
<div class='description'>Below is a list of all of the questions in this question set.</div>
<div id='questions'>
#{
_(@questionSet.data.questions).map (question, index) =>
"
<div class='sortable' id='question-div-#{index}'>
<div class='toggleNext question-label'>
<span class='handle'>↕</span>
#{striptags(question.label)}
<div style='margin-left: 20px; font-weight:normal;font-size:small'>
#{if question["radio-options"] then "<div>#{question["radio-options"]}</div>" else ""}
#{if question["skip_logic"] then "<div>Skip if: <span style='font-family:monospace'>#{question["skip_logic"]}</span></div>" else ""}
</div>
</div>
<div class='questionDiv' data-question-label='#{question.label}' style='display:none; margin-left: 10px; padding: 5px; background-color:#DCDCDC'>
<div>Properties Configured:</div>
#{
_(question).map (value, property) =>
propertyMetadata = QuestionSet.questionProperties[property]
if propertyMetadata
dataType = propertyMetadata["data-type"]
if question.type is "autocomplete from code" and question["autocomplete-options"]
dataType = "coffeescript"
propertyPath = "questions[#{index}][#{property}]"
"
<hr/>
<div class='questionPropertyName'>
#{property}
<div class='description'>
#{propertyMetadata.description}
</div>
</div>
" + switch dataType
when "coffeescript", "text", "json"
"
<div>
<div data-type-of-code='#{property}' class='questionProperty code'>
#{
if property is "url" and value.endsWith("mp3")
"<audio controls src='#{value}'></audio>"
else
""
}
#{
@renderSyntaxHighlightedCodeWithTextareaForEditing
propertyPath: propertyPath
example: propertyMetadata.example
}
</div>
</div>
"
when "select"
"
<div>
#{property}: <span style='font-weight:bold'>#{question[property]}</span>
<div style='display:none'>
<select style='display:block' data-property-path='#{propertyPath}'>
#{
_(propertyMetadata.options).map (optionMetadata, option) =>
if _(optionMetadata).isBoolean()
"<option #{if optionMetadata is question[property] then "selected=true" else ""}>#{optionMetadata}</option>"
else
"<option #{if option is question[property] then "selected=true" else ""}>#{option}</option>"
.join ""
}
</select>
<button class='save'>Save</button>
<button class='cancel'>Cancel</button>
</div>
</div>
"
when "array"
console.log question
value = "Example Option 1, Example Option 2" unless value
"
<div>
Items:
<ul>
#{
_(value.split(/, */)).map (item) =>
"<li>#{item}</li>"
.join("")
}
</ul>
</div>
"
else
console.error "Unknown type: #{propertyMetadata["data-type"]}: #{value}"
else
console.error "Unknown property: #{property}: #{value}"
.join("")
#
#
}
<br/>
<br/>
</div>
</div>
"
.join("")
}
</div>
<hr/>
</div>
"
hljs.configure
languages: ["coffeescript", "json"]
useBR: false
@$('pre code').each (i, snippet) =>
hljs.highlightElement(snippet);
@sortable = Sortable.create document.getElementById('questions'),
handle: ".handle"
onUpdate: (event) =>
# Reorder the array
# https://stackoverflow.com/a/2440723/266111
@sortable.option("disabled", true)
@questionSet.data.questions.splice(event.newIndex, 0, @questionSet.data.questions.splice(event.oldIndex, 1)[0])
@changesWatcher.cancel()
await @questionSet.save()
@render()
@sortable.option("disabled", false)
@openActiveQuestion()
@resetChangesWatcher()
resetChangesWatcher: =>
if Tamarind.database?
Tamarind.database.changes
limit:1
descending:true
.then (change) =>
@changesWatcher = Tamarind.database.changes
live: true
doc_ids: [router.questionSetView.questionSet.data._id]
since: change.last_seq
.on "change", (change) =>
console.log change
@changesWatcher.cancel()
if confirm("This question set has changed - someone else might be working on it. Would you like to refresh?")
@questionSet.fetch().then => @render()
else
# Create an empty changesWatcher
@changesWatcher =
cancel: ->
openActiveQuestion: =>
if @activeQuestionLabel
questionElement = @$(".toggleNext.question-label:contains(#{@activeQuestionLabel})")
questionElement.click()
questionElement[0].scrollIntoView()
isTextMessageQuestionSet: =>
Tamarind.dynamoDBClient?
module.exports = QuestionSetView
| true | $ = require 'jquery'
Backbone = require 'backbone'
Backbone.$ = $
_ = require 'underscore'
dasherize = require("underscore.string/dasherize")
titleize = require("underscore.string/titleize")
humanize = require("underscore.string/humanize")
slugify = require("underscore.string/slugify")
get = require 'lodash/get'
set = require 'lodash/set'
unset = require 'lodash/unset'
pullAt = require 'lodash/pullAt'
isJSON = require('is-json');
striptags = require 'striptags'
Sortable = require 'sortablejs'
global.Coffeescript = require 'coffeescript'
JsonDiffPatch = require 'jsondiffpatch'
underscored = require("underscore.string/underscored")
hljs = require 'highlight.js/lib/core';
hljs.registerLanguage('coffeescript', require ('highlight.js/lib/languages/coffeescript'))
hljs.registerLanguage('json', require ('highlight.js/lib/languages/json'))
global.QuestionSet = require '../models/QuestionSet'
class QuestionSetView extends Backbone.View
events: =>
"click .toggleNext": "toggleNext"
"click .hljs-string": "clickParent"
# Hack because json elements get a class that doesn't bubble events
clickParent: (event) =>
$(event.target).parent().click()
toggleNext: (event) =>
elementToToggle = $(event.target).next()
if elementToToggle.hasClass("questionDiv")
@activeQuestionLabel = elementToToggle.attr("data-question-label")
elementToToggle.toggle()
renderSyntaxHighlightedCodeWithTextareaForEditing: (options) =>
propertyPath = options.propertyPath
preStyle = options.preStyle or ""
example = options.example
code = if propertyPath
get(@questionSet.data, propertyPath)
else
@questionSet.data
code = JSON.stringify(code, null, 2) if _(code).isObject()
# https://stackoverflow.com/questions/19913667/javascript-regex-global-match-groups
regex = /ResultOfQuestion\("(.+?)"\)/g
matches = []
questionsReferredTo = []
while (matches = regex.exec(code))
questionsReferredTo.push("#{matches[1]}: Test Value")
questionsReferredTo = _(questionsReferredTo).unique()
"
<pre style='#{preStyle}'><code class='toggleToEdit'>#{code}</code></pre>
<div class='codeEditor' style='display:none'>
#{
if example
"Examples:<br/><code class='example'>#{example}</code><br/>"
else ""
}
<textarea style='display:block' class='code' data-property-path=#{propertyPath}>#{code}</textarea>
<button class='save'>Save</button>
<button class='cancel'>Cancel</button>
<span class='charCount' style='color:grey'></span>
#{ if propertyPath
"
<br/>
<br/>
<span style='background-color: black; color: gray; padding: 2px; border: solid 2px;' class='toggleNext'>Test It</span>
<div style='display:none'>
Set ResultOfQuestion values (e.g. Name: PI:NAME:<NAME>END_PI, Birthdate: 2012-11-27 or put each pair on a new line)
<br/>
<textarea style='height:60px' class='testResultOfQuestion'>#{questionsReferredTo.join("""\n""")}</textarea>
<br/>
<br/>
Set the value to use for testing the current value
<br/>
<input class='testValue'></input>
<br/>
<br/>
Test Code:
<br/>
<textarea class='testCode'></textarea>
<br/>
</div>
"
else
""
}
</div>
"
render: =>
fullQuestionSetAsPrettyPrintedJSON = JSON.stringify(@questionSet.data, null, 2)
@$el.html "
<style>
.description{
font-size: small;
color:gray
}
.questionSetProperty{
margin-top:5px;
}
textarea{
width:600px;
height:200px;
}
code, .toggleToEdit:hover, .toggleNext:hover, .clickToEdit:hover{
cursor: pointer
}
.question-label{
font-weight: bold;
font-size: large;
}
.clickToEdit{
background-color: black;
color: gray;
padding: 2px;
border: solid 2px;
}
.highlight{
background-color: yellow
}
</style>
#{
if @isTextMessageQuestionSet()
"
<div style='float:right; width:200px; border: 1px solid;'>
<a href='#messaging/#{@serverName}/#{@databaseOrGatewayName}/#{@questionSet.name()}'>Manage Messaging</a>
<br/>
<br/>
<br/>
<div style='width:200px; border: 1px solid;' id='interact'/>
</div>
<h2>Gateway: <a href='#gateway/#{@serverName}/#{@databaseOrGatewayName}'>#{@databaseOrGatewayName}</a>
"
else
"<h2>Application: <a href='#database/#{@serverName}/#{@databaseOrGatewayName}'>#{@databaseOrGatewayName}</a>"
}
</h2>
<h2>Question Set: #{titleize(@questionSet.name())} <span style='color:gray; font-size:small'>#{@questionSet.data.version or ""}</span></h2>
<div id='questionSet'>
<!--
<div class='description'>
Click on any <span style='background-color:black; color:gray; padding:2px;'>dark area</span> below to edit.
</div>
-->
<h3><a id='resultsButton' href='#results/#{@serverName}/#{@databaseOrGatewayName}/#{@questionSet.name()}'>Results</a></h3>
<div style='display:none'>
<div class='description'>These options configure the entire question set as opposed to individual questions. For example, this is where you can run code when the page loads or when the question set is marked complete.</div>
#{
_(@questionSet.data).map (value, property) =>
propertyMetadata = QuestionSet.properties[property]
if propertyMetadata
switch propertyMetadata["data-type"]
when "coffeescript", "object","text"
"
<div>
<div class='questionSetProperty'>
<div class='questionSetPropertyName'>
#{property}
<div class='description'>
#{propertyMetadata.description}
</div>
</div>
#{
@renderSyntaxHighlightedCodeWithTextareaForEditing
propertyPath: property
example: propertyMetadata.example
}
</div>
</div>
"
else
console.error "Unknown type: #{propertyMetadata["data-type"]}: #{value}"
alert "Unhandled type"
else
return if _(["_id", "label", "_rev", "isApplicationDoc", "collection", "couchapp", "questions", "version"]).contains property
console.error "Unknown question set property: #{property}: #{value}"
.join("")
}
</div>
<h2>Questions</h2>
<div class='description'>Below is a list of all of the questions in this question set.</div>
<div id='questions'>
#{
_(@questionSet.data.questions).map (question, index) =>
"
<div class='sortable' id='question-div-#{index}'>
<div class='toggleNext question-label'>
<span class='handle'>↕</span>
#{striptags(question.label)}
<div style='margin-left: 20px; font-weight:normal;font-size:small'>
#{if question["radio-options"] then "<div>#{question["radio-options"]}</div>" else ""}
#{if question["skip_logic"] then "<div>Skip if: <span style='font-family:monospace'>#{question["skip_logic"]}</span></div>" else ""}
</div>
</div>
<div class='questionDiv' data-question-label='#{question.label}' style='display:none; margin-left: 10px; padding: 5px; background-color:#DCDCDC'>
<div>Properties Configured:</div>
#{
_(question).map (value, property) =>
propertyMetadata = QuestionSet.questionProperties[property]
if propertyMetadata
dataType = propertyMetadata["data-type"]
if question.type is "autocomplete from code" and question["autocomplete-options"]
dataType = "coffeescript"
propertyPath = "questions[#{index}][#{property}]"
"
<hr/>
<div class='questionPropertyName'>
#{property}
<div class='description'>
#{propertyMetadata.description}
</div>
</div>
" + switch dataType
when "coffeescript", "text", "json"
"
<div>
<div data-type-of-code='#{property}' class='questionProperty code'>
#{
if property is "url" and value.endsWith("mp3")
"<audio controls src='#{value}'></audio>"
else
""
}
#{
@renderSyntaxHighlightedCodeWithTextareaForEditing
propertyPath: propertyPath
example: propertyMetadata.example
}
</div>
</div>
"
when "select"
"
<div>
#{property}: <span style='font-weight:bold'>#{question[property]}</span>
<div style='display:none'>
<select style='display:block' data-property-path='#{propertyPath}'>
#{
_(propertyMetadata.options).map (optionMetadata, option) =>
if _(optionMetadata).isBoolean()
"<option #{if optionMetadata is question[property] then "selected=true" else ""}>#{optionMetadata}</option>"
else
"<option #{if option is question[property] then "selected=true" else ""}>#{option}</option>"
.join ""
}
</select>
<button class='save'>Save</button>
<button class='cancel'>Cancel</button>
</div>
</div>
"
when "array"
console.log question
value = "Example Option 1, Example Option 2" unless value
"
<div>
Items:
<ul>
#{
_(value.split(/, */)).map (item) =>
"<li>#{item}</li>"
.join("")
}
</ul>
</div>
"
else
console.error "Unknown type: #{propertyMetadata["data-type"]}: #{value}"
else
console.error "Unknown property: #{property}: #{value}"
.join("")
#
#
}
<br/>
<br/>
</div>
</div>
"
.join("")
}
</div>
<hr/>
</div>
"
hljs.configure
languages: ["coffeescript", "json"]
useBR: false
@$('pre code').each (i, snippet) =>
hljs.highlightElement(snippet);
@sortable = Sortable.create document.getElementById('questions'),
handle: ".handle"
onUpdate: (event) =>
# Reorder the array
# https://stackoverflow.com/a/2440723/266111
@sortable.option("disabled", true)
@questionSet.data.questions.splice(event.newIndex, 0, @questionSet.data.questions.splice(event.oldIndex, 1)[0])
@changesWatcher.cancel()
await @questionSet.save()
@render()
@sortable.option("disabled", false)
@openActiveQuestion()
@resetChangesWatcher()
resetChangesWatcher: =>
if Tamarind.database?
Tamarind.database.changes
limit:1
descending:true
.then (change) =>
@changesWatcher = Tamarind.database.changes
live: true
doc_ids: [router.questionSetView.questionSet.data._id]
since: change.last_seq
.on "change", (change) =>
console.log change
@changesWatcher.cancel()
if confirm("This question set has changed - someone else might be working on it. Would you like to refresh?")
@questionSet.fetch().then => @render()
else
# Create an empty changesWatcher
@changesWatcher =
cancel: ->
openActiveQuestion: =>
if @activeQuestionLabel
questionElement = @$(".toggleNext.question-label:contains(#{@activeQuestionLabel})")
questionElement.click()
questionElement[0].scrollIntoView()
isTextMessageQuestionSet: =>
Tamarind.dynamoDBClient?
module.exports = QuestionSetView
|
[
{
"context": "module.exports =\n\tname: \"Keep Calm\"\n\turl: '/keepcalm/:reaction/:from'\n\tfields: ",
"end": 29,
"score": 0.5303601026535034,
"start": 25,
"tag": "NAME",
"value": "Keep"
}
] | lib/operations/keepcalm.coffee | brettminnie/foaas | 0 | module.exports =
name: "Keep Calm"
url: '/keepcalm/:reaction/:from'
fields: [
{ name: 'Reaction', field: 'reaction'}
{ name: 'From', field: 'from'}
]
register: (app, output) ->
app.get '/keepcalm/:reaction/:from', (req, res) ->
message = "Keep the fuck calm and #{req.params.reaction}!"
subtitle = "- #{req.params.from}"
output(req, res, message, subtitle) | 97427 | module.exports =
name: "<NAME> Calm"
url: '/keepcalm/:reaction/:from'
fields: [
{ name: 'Reaction', field: 'reaction'}
{ name: 'From', field: 'from'}
]
register: (app, output) ->
app.get '/keepcalm/:reaction/:from', (req, res) ->
message = "Keep the fuck calm and #{req.params.reaction}!"
subtitle = "- #{req.params.from}"
output(req, res, message, subtitle) | true | module.exports =
name: "PI:NAME:<NAME>END_PI Calm"
url: '/keepcalm/:reaction/:from'
fields: [
{ name: 'Reaction', field: 'reaction'}
{ name: 'From', field: 'from'}
]
register: (app, output) ->
app.get '/keepcalm/:reaction/:from', (req, res) ->
message = "Keep the fuck calm and #{req.params.reaction}!"
subtitle = "- #{req.params.from}"
output(req, res, message, subtitle) |
[
{
"context": "'\n clear_fields:\t['name', 'desc', 'password', 'opponent1', 'opponent2', 'opponent3']\n refill:\t\ttrue\n ",
"end": 405,
"score": 0.8571605682373047,
"start": 396,
"tag": "PASSWORD",
"value": "opponent1"
},
{
"context": "'name', 'desc', 'password', 'opponent1', 'opponent2', 'opponent3']\n refill:\t\ttrue\n handlers:\n ",
"end": 418,
"score": 0.5268343091011047,
"start": 417,
"tag": "PASSWORD",
"value": "2"
}
] | static/script/pages/new.coffee | happz/settlers | 1 | window.settlers.setup_forms = () ->
__setup_autocomplete = (eid) ->
options = window.settlers.autocomplete_options()
$(eid).typeahead options
__setup_autocomplete '#new_game_opponent1'
__setup_autocomplete '#new_game_opponent2'
__setup_autocomplete '#new_game_opponent3'
new window.hlib.Form
fid: 'new_game'
clear_fields: ['name', 'desc', 'password', 'opponent1', 'opponent2', 'opponent3']
refill: true
handlers:
h200: (response, form) ->
form.info.success 'Successfuly created'
$('#new_game_submit').click () ->
$('#new_game_form').attr 'action', '/game/' + $('#new_game_kind').val() + '/new'
return true
new window.hlib.Form
fid: 'new_tournament'
clear_fields: ['name', 'desc', 'password', 'num_players']
refill: true
handlers:
h200: (response, form) ->
form.info.success 'Successfuly created'
$(window).bind 'page_startup', () ->
window.settlers.setup_forms()
| 220670 | window.settlers.setup_forms = () ->
__setup_autocomplete = (eid) ->
options = window.settlers.autocomplete_options()
$(eid).typeahead options
__setup_autocomplete '#new_game_opponent1'
__setup_autocomplete '#new_game_opponent2'
__setup_autocomplete '#new_game_opponent3'
new window.hlib.Form
fid: 'new_game'
clear_fields: ['name', 'desc', 'password', '<PASSWORD>', 'opponent<PASSWORD>', 'opponent3']
refill: true
handlers:
h200: (response, form) ->
form.info.success 'Successfuly created'
$('#new_game_submit').click () ->
$('#new_game_form').attr 'action', '/game/' + $('#new_game_kind').val() + '/new'
return true
new window.hlib.Form
fid: 'new_tournament'
clear_fields: ['name', 'desc', 'password', 'num_players']
refill: true
handlers:
h200: (response, form) ->
form.info.success 'Successfuly created'
$(window).bind 'page_startup', () ->
window.settlers.setup_forms()
| true | window.settlers.setup_forms = () ->
__setup_autocomplete = (eid) ->
options = window.settlers.autocomplete_options()
$(eid).typeahead options
__setup_autocomplete '#new_game_opponent1'
__setup_autocomplete '#new_game_opponent2'
__setup_autocomplete '#new_game_opponent3'
new window.hlib.Form
fid: 'new_game'
clear_fields: ['name', 'desc', 'password', 'PI:PASSWORD:<PASSWORD>END_PI', 'opponentPI:PASSWORD:<PASSWORD>END_PI', 'opponent3']
refill: true
handlers:
h200: (response, form) ->
form.info.success 'Successfuly created'
$('#new_game_submit').click () ->
$('#new_game_form').attr 'action', '/game/' + $('#new_game_kind').val() + '/new'
return true
new window.hlib.Form
fid: 'new_tournament'
clear_fields: ['name', 'desc', 'password', 'num_players']
refill: true
handlers:
h200: (response, form) ->
form.info.success 'Successfuly created'
$(window).bind 'page_startup', () ->
window.settlers.setup_forms()
|
[
{
"context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ",
"end": 33,
"score": 0.9998638033866882,
"start": 21,
"tag": "NAME",
"value": "John Judnich"
}
] | source/xgl.coffee | anandprabhakar0507/Kosmos | 46 | # Copyright (C) 2013 John Judnich
# Released under The MIT License - see "LICENSE" file for details.
root = exports ? this
root.xgl = {}
xgl.programs = {}
xgl.degToRad = (angle) -> Math.PI * angle / 180.0
xgl.radToDeg = (angle) -> 180.0 * angle / Math.PI
xgl.error = (msg) ->
console.log(msg)
#alert(msg)
# use this to add program sources to a main dictionary
xgl.addProgram = (name, vSrc, fSrc) ->
shaderSrc = { "vertex" : vSrc, "fragment" : fSrc }
xgl.programs[name] = shaderSrc
# given a shader source and type, returns a compiled shader object
xgl.loadShader = (source, isVertex) ->
if isVertex
shader = gl.createShader(gl.VERTEX_SHADER)
else
shader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(shader, source)
gl.compileShader(shader)
if not gl.getShaderParameter(shader, gl.COMPILE_STATUS)
xgl.error(gl.getShaderInfoLog(shader))
return null
return shader;
# given vertex and fragment shader objects, returns a linked program object or null if failed
xgl.createProgram = (vertexShader, fragmentShader) ->
shaderProgram = gl.createProgram()
gl.attachShader(shaderProgram, vertexShader)
gl.attachShader(shaderProgram, fragmentShader)
gl.linkProgram(shaderProgram)
if not gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)
return null
return shaderProgram
# given <script> ids for vertex and fragment shader source, returns a linked program object
xgl.loadProgram = (programName) ->
shaderSrc = xgl.programs[programName]
if not shaderSrc
xgl.error("Sources for program \"#{programName}\" not found in xgl.programs.")
return null
vertexShader = xgl.loadShader(shaderSrc.vertex, true)
if vertexShader == null
xgl.error("Error loading vertex shader for \"#{programName}\"")
return null
fragmentShader = xgl.loadShader(shaderSrc.fragment, false)
if fragmentShader == null
xgl.error("Error loading fragment shader for \"#{programName}\"")
return null
prog = xgl.createProgram(vertexShader, fragmentShader)
if prog == null then xgl.error("Error linking program \"#{programName}\"")
return prog
# given a program object and list of attribute names, returns a mapping from attribute names to their index
xgl.getProgramAttribs = (programObject, attribNameList) ->
attribs = {}
for attrib in attribNameList
index = gl.getAttribLocation(programObject, attrib)
if index == -1 then xgl.error("Could not find attribute \"#{attrib}\"")
else attribs[attrib] = index
return attribs
# given a program object and list of uniform names, returns a mapping from uniform names to their WebGLUniformLocation
xgl.getProgramUniforms = (programObject, uniformNameList) ->
uniforms = {}
for uniform in uniformNameList
ptr = gl.getUniformLocation(programObject, uniform)
if ptr == null then xgl.error("Could not find uniform \"#{uniform}\"")
else uniforms[uniform] = ptr
return uniforms
| 120554 | # Copyright (C) 2013 <NAME>
# Released under The MIT License - see "LICENSE" file for details.
root = exports ? this
root.xgl = {}
xgl.programs = {}
xgl.degToRad = (angle) -> Math.PI * angle / 180.0
xgl.radToDeg = (angle) -> 180.0 * angle / Math.PI
xgl.error = (msg) ->
console.log(msg)
#alert(msg)
# use this to add program sources to a main dictionary
xgl.addProgram = (name, vSrc, fSrc) ->
shaderSrc = { "vertex" : vSrc, "fragment" : fSrc }
xgl.programs[name] = shaderSrc
# given a shader source and type, returns a compiled shader object
xgl.loadShader = (source, isVertex) ->
if isVertex
shader = gl.createShader(gl.VERTEX_SHADER)
else
shader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(shader, source)
gl.compileShader(shader)
if not gl.getShaderParameter(shader, gl.COMPILE_STATUS)
xgl.error(gl.getShaderInfoLog(shader))
return null
return shader;
# given vertex and fragment shader objects, returns a linked program object or null if failed
xgl.createProgram = (vertexShader, fragmentShader) ->
shaderProgram = gl.createProgram()
gl.attachShader(shaderProgram, vertexShader)
gl.attachShader(shaderProgram, fragmentShader)
gl.linkProgram(shaderProgram)
if not gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)
return null
return shaderProgram
# given <script> ids for vertex and fragment shader source, returns a linked program object
xgl.loadProgram = (programName) ->
shaderSrc = xgl.programs[programName]
if not shaderSrc
xgl.error("Sources for program \"#{programName}\" not found in xgl.programs.")
return null
vertexShader = xgl.loadShader(shaderSrc.vertex, true)
if vertexShader == null
xgl.error("Error loading vertex shader for \"#{programName}\"")
return null
fragmentShader = xgl.loadShader(shaderSrc.fragment, false)
if fragmentShader == null
xgl.error("Error loading fragment shader for \"#{programName}\"")
return null
prog = xgl.createProgram(vertexShader, fragmentShader)
if prog == null then xgl.error("Error linking program \"#{programName}\"")
return prog
# given a program object and list of attribute names, returns a mapping from attribute names to their index
xgl.getProgramAttribs = (programObject, attribNameList) ->
attribs = {}
for attrib in attribNameList
index = gl.getAttribLocation(programObject, attrib)
if index == -1 then xgl.error("Could not find attribute \"#{attrib}\"")
else attribs[attrib] = index
return attribs
# given a program object and list of uniform names, returns a mapping from uniform names to their WebGLUniformLocation
xgl.getProgramUniforms = (programObject, uniformNameList) ->
uniforms = {}
for uniform in uniformNameList
ptr = gl.getUniformLocation(programObject, uniform)
if ptr == null then xgl.error("Could not find uniform \"#{uniform}\"")
else uniforms[uniform] = ptr
return uniforms
| true | # Copyright (C) 2013 PI:NAME:<NAME>END_PI
# Released under The MIT License - see "LICENSE" file for details.
root = exports ? this
root.xgl = {}
xgl.programs = {}
xgl.degToRad = (angle) -> Math.PI * angle / 180.0
xgl.radToDeg = (angle) -> 180.0 * angle / Math.PI
xgl.error = (msg) ->
console.log(msg)
#alert(msg)
# use this to add program sources to a main dictionary
xgl.addProgram = (name, vSrc, fSrc) ->
shaderSrc = { "vertex" : vSrc, "fragment" : fSrc }
xgl.programs[name] = shaderSrc
# given a shader source and type, returns a compiled shader object
xgl.loadShader = (source, isVertex) ->
if isVertex
shader = gl.createShader(gl.VERTEX_SHADER)
else
shader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(shader, source)
gl.compileShader(shader)
if not gl.getShaderParameter(shader, gl.COMPILE_STATUS)
xgl.error(gl.getShaderInfoLog(shader))
return null
return shader;
# given vertex and fragment shader objects, returns a linked program object or null if failed
xgl.createProgram = (vertexShader, fragmentShader) ->
shaderProgram = gl.createProgram()
gl.attachShader(shaderProgram, vertexShader)
gl.attachShader(shaderProgram, fragmentShader)
gl.linkProgram(shaderProgram)
if not gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)
return null
return shaderProgram
# given <script> ids for vertex and fragment shader source, returns a linked program object
xgl.loadProgram = (programName) ->
shaderSrc = xgl.programs[programName]
if not shaderSrc
xgl.error("Sources for program \"#{programName}\" not found in xgl.programs.")
return null
vertexShader = xgl.loadShader(shaderSrc.vertex, true)
if vertexShader == null
xgl.error("Error loading vertex shader for \"#{programName}\"")
return null
fragmentShader = xgl.loadShader(shaderSrc.fragment, false)
if fragmentShader == null
xgl.error("Error loading fragment shader for \"#{programName}\"")
return null
prog = xgl.createProgram(vertexShader, fragmentShader)
if prog == null then xgl.error("Error linking program \"#{programName}\"")
return prog
# given a program object and list of attribute names, returns a mapping from attribute names to their index
xgl.getProgramAttribs = (programObject, attribNameList) ->
attribs = {}
for attrib in attribNameList
index = gl.getAttribLocation(programObject, attrib)
if index == -1 then xgl.error("Could not find attribute \"#{attrib}\"")
else attribs[attrib] = index
return attribs
# given a program object and list of uniform names, returns a mapping from uniform names to their WebGLUniformLocation
xgl.getProgramUniforms = (programObject, uniformNameList) ->
uniforms = {}
for uniform in uniformNameList
ptr = gl.getUniformLocation(programObject, uniform)
if ptr == null then xgl.error("Could not find uniform \"#{uniform}\"")
else uniforms[uniform] = ptr
return uniforms
|
[
{
"context": "#\n# Notes:\n# Beta testing of all\n#\n# Author:\n# J. Michael Browning <michael+bot@motech.io> (https://github.com/mccsi",
"end": 230,
"score": 0.9996842741966248,
"start": 211,
"tag": "NAME",
"value": "J. Michael Browning"
},
{
"context": "sting of all\n#\n# Author:\n# J. Michael Browning <michael+bot@motech.io> (https://github.com/mccsiwakuni)\n\nmodule.exports",
"end": 253,
"score": 0.9999259114265442,
"start": 232,
"tag": "EMAIL",
"value": "michael+bot@motech.io"
},
{
"context": "wning <michael+bot@motech.io> (https://github.com/mccsiwakuni)\n\nmodule.exports = (robot) ->\n robot.hear /badge",
"end": 286,
"score": 0.9990668892860413,
"start": 275,
"tag": "USERNAME",
"value": "mccsiwakuni"
}
] | src/airtable.coffee | mccsiwakuni/hubot-airtable | 0 | # Description:
# Airtable Hubot connection.
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_Airtable_Key your Airtable API Key
#
# Commands:
# Test
#
# Notes:
# Beta testing of all
#
# Author:
# J. Michael Browning <michael+bot@motech.io> (https://github.com/mccsiwakuni)
module.exports = (robot) ->
robot.hear /badger/i, (res) ->
# your code here
robot.respond /open the pod bay doors/i, (res) ->
# your code here
| 156007 | # Description:
# Airtable Hubot connection.
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_Airtable_Key your Airtable API Key
#
# Commands:
# Test
#
# Notes:
# Beta testing of all
#
# Author:
# <NAME> <<EMAIL>> (https://github.com/mccsiwakuni)
module.exports = (robot) ->
robot.hear /badger/i, (res) ->
# your code here
robot.respond /open the pod bay doors/i, (res) ->
# your code here
| true | # Description:
# Airtable Hubot connection.
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_Airtable_Key your Airtable API Key
#
# Commands:
# Test
#
# Notes:
# Beta testing of all
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://github.com/mccsiwakuni)
module.exports = (robot) ->
robot.hear /badger/i, (res) ->
# your code here
robot.respond /open the pod bay doors/i, (res) ->
# your code here
|
[
{
"context": "l depuis votre adresse universitaire à l'adresse `bot.sorbonne.jussieu@gmail.com`.**\n Attention : __Le sujet du mail doit o",
"end": 3611,
"score": 0.9998412728309631,
"start": 3581,
"tag": "EMAIL",
"value": "bot.sorbonne.jussieu@gmail.com"
},
{
"context": "\"with your data 👀\"\n url: \"https://gitlab.com/Speykious/sorbot\"\n }\n \n logf LOG.INIT, {\n embed:\n ",
"end": 4463,
"score": 0.997847855091095,
"start": 4454,
"tag": "USERNAME",
"value": "Speykious"
}
] | src/index.coffee | Speykious/sorbot | 2 | loading = require "./loading"
loading.step "Loading dotenv-flow...", 0
loading.startDisplaying()
require "dotenv-flow"
.config()
loading.step "Loading nodejs dependencies..."
{ join } = require "path"
YAML = require "yaml"
{ UniqueConstraintError } = require "sequelize"
loading.step "Loading discord.js..."
{ Client } = require "discord.js"
loading.step "Loading generic utils..."
{ relative, delay, readf
removeElement } = require "./helpers"
{ logf, formatCrisis, formatGuild
LOG, formatUser, botCache } = require "./logging"
{ CROSSMARK, SERVERS, BYEBYES,
GUILDS, TESTERS, FOOTER } = require "./constants"
{ encryptid, decryptid } = require "./encryption"
{ updateMemberRoles } = require "./roles"
touchMember = require "./touchMember"
loading.step "Loading gmailer and email crisis handler..."
GMailer = require "./mail/gmailer"
EmailCrisisHandler = require "./mail/crisisHandler"
{ handleVerification } = require "./mail/verificationHandler"
loading.step "Loading frontend functions..."
syscall = require "./frontend/syscall"
RTFM = require "./frontend/RTFM"
loading.step "Loading dbhelpers..."
{ getdbUser, getdbGuild } = require "./db/dbhelpers"
loading.step "Initializing database..."
{ User, FederatedMetadata } = require "./db/initdb"
loading.step "Instantiating Discord client..."
bot = new Client {
disableMentions: "everyone"
partials: ["MESSAGE", "CHANNEL", "REACTION", "GUILD_MEMBER"]
restTimeOffset: 100
}
loading.step "Instantiating new GMailer and EmailCrisisHandler..."
gmailer = new GMailer ["readonly", "modify", "compose", "send"], "credentials.yaml", loading
# - slowT {number} - period for the slow read mode, in seconds
# - fastT {number} - period for the fast read mode, in seconds
# - maxThreads {number} - Maximum number of threads globally
# - maxThreadsSlow {number} - Maximum number of threads only for slow mode
# - maxThreadsFast {number} - Maximum number of threads only for fast mode
# - guild {Guild} - The main discord guild to handle the crisis with
# - gmailer {GMailer} - The gmailer to read the email threads with
# - embedUEC {Embed} - The embed error report for Unread Existential Crisis
# - embedUSC {Embed} - The embed error report for Unread Sorbonne Crisis
emailCH = new EmailCrisisHandler {
bot
gmailer
# About those embeds, I'm probably gonna isolate
# them in a yaml file somewhere in resources/...
embedUEC: (th) ->
embed:
title: "Existential Crisis : Adresse Introuvable"
description:
"""
L'adresse que vous avez renseignée, `#{th[0].to}`, semble ne pas exister.
Nous vous invitons à réessayer avec une autre adresse mail universitaire.
"""
fields: [
{
name: "Headers du mail envoyé",
value: "```yaml\n#{YAML.stringify th[0]}```"
},
{
name: "Headers de la notification de fail"
value: "```yaml\n#{YAML.stringify th[1]}```"
}
]
color: 0xff6432
footer: FOOTER
embedUSC: (th) ->
embed:
title: "Sorbonne Crisis : Retour à l'envoyeur"
description:
"""
Pour une raison ou une autre, nous n'avons pas réussi à envoyer un mail à l'adresse `#{th[0].to}`.
**Nous vous invitons donc à envoyer un mail depuis votre adresse universitaire à l'adresse `bot.sorbonne.jussieu@gmail.com`.**
Attention : __Le sujet du mail doit obligatoirement être votre tag discord__, à savoir de la forme `pseudo#1234`, sinon il nous sera impossible de vous vérifier.
Vous êtes libre d'écrire ce que vous voulez dans le corps du mail.
"""
fields: [
{
name: "Headers du mail envoyé",
value: "```yaml\n#{YAML.stringify th[0]}```"
},
{
name: "Headers de la notification de fail"
value: "```yaml\n#{YAML.stringify th[1]}```"
}
]
color: 0xa3334c
footer: FOOTER
}
loading.step "Preparing the cup of coffee..."
bot.on "ready", ->
botCache.bot = bot
await bot.user.setPresence {
activity:
type: "PLAYING"
name: if process.env.LOCAL then "Coucou humain 👀" else "with your data 👀"
url: "https://gitlab.com/Speykious/sorbot"
}
logf LOG.INIT, {
embed:
title: "Ready to sip. 茶 ☕"
description: "Let's play with even more dynamically-typed ***DATA*** <a:eyeshake:691797273147080714>"
color: 0x34d9ff
footer: FOOTER
}
loading.step "Authorizing the gmailer..."
await gmailer.authorize "token.yaml"
loading.step "Bot started successfully."
setTimeout (-> emailCH.activate()), 100
bot.on "guildCreate", (guild) ->
try
dbGuild = await FederatedMetadata.create { id: guild.id }
logf LOG.DATABASE, "New guild #{formatGuild guild} has been added to the database"
catch e
unless e instanceof UniqueConstraintError
logf LOG.WTF, "**WTF ?!** Unexpected error when creating guild! Please check the console log."
console.log "\x1b[1mUNEXPECTED ERROR WHEN CREATING GUILD\x1b[0m"
console.log e
return
logf LOG.DATABASE, "Guild #{formatGuild guild} already existed in the database"
RTFM.fetch bot, guild.id
bot.on "guildDelete", (guild) ->
dbGuild = await getdbGuild guild
unless dbGuild then return
await dbGuild.destroy()
logf LOG.DATABASE, "Guild #{formatGuild guild} removed"
bot.on "guildMemberAdd", (member) ->
# I don't care about bots lol
if member.user.bot
logf LOG.MODERATION, "Bot #{formatUser member.user} just arrived"
return
# Praise shared auth !
logf LOG.MODERATION, "User #{formatUser member.user} joined guild #{formatGuild member.guild}"
await touchMember member
bot.on "guildMemberRemove", (member) ->
# I don't care about bots lol
if member.user.bot
logf LOG.MODERATION, "Bot #{formatUser member.user} left guild #{formatGuild member.guild}"
return
logf LOG.MODERATION, "User #{formatUser member.user} left guild #{formatGuild member.guild}"
dbUser = await getdbUser member.user
unless dbUser then return
# Yeeting dbUser out when it isn't present in any other server
removeElement dbUser.servers, member.guild.id
if dbUser.servers.length > 0
await dbUser.update { servers: dbUser.servers }
logf LOG.DATABASE, "User #{formatUser member.user} removed from guild #{formatGuild member.guild}"
else
await dbUser.destroy()
logf LOG.DATABASE, "User #{formatUser member.user} removed"
unless process.env.LOCAL
unless member.guild.id is "672479260899803147" then return
bye = BYEBYES[Math.floor (Math.random() * BYEBYES.length - 1e-6)]
bye = bye.replace "{name}", member.displayName
auRevoir = await bot.channels.fetch '672502429836640267'
await auRevoir.send bye
bot.on "message", (msg) ->
# I don't care about myself lol
if msg.author.bot then return
# We STILL don't care about messages that don't come from dms
# Although we will care a bit later when introducing admin commands
if msg.channel.type isnt "dm"
if msg.author.id in TESTERS then syscall msg
return
# Note: we'll have to fetch every federated server
# to see if the member exists in our discord network
dbUser = await getdbUser msg.author
unless dbUser then return
unless await handleVerification gmailer, emailCH, dbUser, msg.author, msg.content
# More stuff is gonna go here probably
# like user commands to request your
# decrypted data from the database
if /^(get|give)\s+(me\s+)?(my\s+)?(user\s+)?data/i.test msg.content
# nssData, standing for Not So Sensible Data
nssData = { dbUser.dataValues... }
nssData.id = decryptid nssData.id
msg.author.send {
embed:
title: "Vos données sous forme YAML"
description:
"""
Voici vos données sous forme d'un objet YAML.
```yaml
#{YAML.stringify nssData}```
"""
color: 0x34d9ff
footer: FOOTER
}
else
msg.author.send "Vous êtes vérifié(e), vous n'avez plus rien à craindre."
bot.on "messageReactionAdd", (reaction, user) ->
# I still don't care about myself lol
if user.bot then return
if reaction.partial then await reaction.fetch()
# I don't care about anything else apart from DMs
if reaction.message.channel.type isnt "dm" then return
dbUser = await getdbUser user
unless dbUser then return
unless reaction.message.id is dbUser.reactor then return
switch reaction.emoji.name
when "⏪"
dbUser.code = null
dbUser.email = null
await dbUser.save()
await user.send {
embed:
title: "Adresse mail effacée"
description: "Vous pouvez désormais renseigner une nouvelle adresse mail."
color: 0x32ff64
footer: FOOTER
}
when "🔁"
gmailer.verifyEmail dbUser, user, dbUser.email, emailCH
else return
setTimeout (-> reaction.message.delete()), 3000
bot.on "guildMemberUpdate", (_, member) ->
levelRoles = ["licence_1", "licence_2", "licence_3", "master_1", "master_2", "doctorat", "professeur"]
if levelRoles.some (lr) -> member.roles.cache.has SERVERS.main.roles[lr]
member.roles.remove SERVERS.main.roles.indecis
bot.login process.env.SORBOT_TOKEN
| 182426 | loading = require "./loading"
loading.step "Loading dotenv-flow...", 0
loading.startDisplaying()
require "dotenv-flow"
.config()
loading.step "Loading nodejs dependencies..."
{ join } = require "path"
YAML = require "yaml"
{ UniqueConstraintError } = require "sequelize"
loading.step "Loading discord.js..."
{ Client } = require "discord.js"
loading.step "Loading generic utils..."
{ relative, delay, readf
removeElement } = require "./helpers"
{ logf, formatCrisis, formatGuild
LOG, formatUser, botCache } = require "./logging"
{ CROSSMARK, SERVERS, BYEBYES,
GUILDS, TESTERS, FOOTER } = require "./constants"
{ encryptid, decryptid } = require "./encryption"
{ updateMemberRoles } = require "./roles"
touchMember = require "./touchMember"
loading.step "Loading gmailer and email crisis handler..."
GMailer = require "./mail/gmailer"
EmailCrisisHandler = require "./mail/crisisHandler"
{ handleVerification } = require "./mail/verificationHandler"
loading.step "Loading frontend functions..."
syscall = require "./frontend/syscall"
RTFM = require "./frontend/RTFM"
loading.step "Loading dbhelpers..."
{ getdbUser, getdbGuild } = require "./db/dbhelpers"
loading.step "Initializing database..."
{ User, FederatedMetadata } = require "./db/initdb"
loading.step "Instantiating Discord client..."
bot = new Client {
disableMentions: "everyone"
partials: ["MESSAGE", "CHANNEL", "REACTION", "GUILD_MEMBER"]
restTimeOffset: 100
}
loading.step "Instantiating new GMailer and EmailCrisisHandler..."
gmailer = new GMailer ["readonly", "modify", "compose", "send"], "credentials.yaml", loading
# - slowT {number} - period for the slow read mode, in seconds
# - fastT {number} - period for the fast read mode, in seconds
# - maxThreads {number} - Maximum number of threads globally
# - maxThreadsSlow {number} - Maximum number of threads only for slow mode
# - maxThreadsFast {number} - Maximum number of threads only for fast mode
# - guild {Guild} - The main discord guild to handle the crisis with
# - gmailer {GMailer} - The gmailer to read the email threads with
# - embedUEC {Embed} - The embed error report for Unread Existential Crisis
# - embedUSC {Embed} - The embed error report for Unread Sorbonne Crisis
emailCH = new EmailCrisisHandler {
bot
gmailer
# About those embeds, I'm probably gonna isolate
# them in a yaml file somewhere in resources/...
embedUEC: (th) ->
embed:
title: "Existential Crisis : Adresse Introuvable"
description:
"""
L'adresse que vous avez renseignée, `#{th[0].to}`, semble ne pas exister.
Nous vous invitons à réessayer avec une autre adresse mail universitaire.
"""
fields: [
{
name: "Headers du mail envoyé",
value: "```yaml\n#{YAML.stringify th[0]}```"
},
{
name: "Headers de la notification de fail"
value: "```yaml\n#{YAML.stringify th[1]}```"
}
]
color: 0xff6432
footer: FOOTER
embedUSC: (th) ->
embed:
title: "Sorbonne Crisis : Retour à l'envoyeur"
description:
"""
Pour une raison ou une autre, nous n'avons pas réussi à envoyer un mail à l'adresse `#{th[0].to}`.
**Nous vous invitons donc à envoyer un mail depuis votre adresse universitaire à l'adresse `<EMAIL>`.**
Attention : __Le sujet du mail doit obligatoirement être votre tag discord__, à savoir de la forme `pseudo#1234`, sinon il nous sera impossible de vous vérifier.
Vous êtes libre d'écrire ce que vous voulez dans le corps du mail.
"""
fields: [
{
name: "Headers du mail envoyé",
value: "```yaml\n#{YAML.stringify th[0]}```"
},
{
name: "Headers de la notification de fail"
value: "```yaml\n#{YAML.stringify th[1]}```"
}
]
color: 0xa3334c
footer: FOOTER
}
loading.step "Preparing the cup of coffee..."
bot.on "ready", ->
botCache.bot = bot
await bot.user.setPresence {
activity:
type: "PLAYING"
name: if process.env.LOCAL then "Coucou humain 👀" else "with your data 👀"
url: "https://gitlab.com/Speykious/sorbot"
}
logf LOG.INIT, {
embed:
title: "Ready to sip. 茶 ☕"
description: "Let's play with even more dynamically-typed ***DATA*** <a:eyeshake:691797273147080714>"
color: 0x34d9ff
footer: FOOTER
}
loading.step "Authorizing the gmailer..."
await gmailer.authorize "token.yaml"
loading.step "Bot started successfully."
setTimeout (-> emailCH.activate()), 100
bot.on "guildCreate", (guild) ->
try
dbGuild = await FederatedMetadata.create { id: guild.id }
logf LOG.DATABASE, "New guild #{formatGuild guild} has been added to the database"
catch e
unless e instanceof UniqueConstraintError
logf LOG.WTF, "**WTF ?!** Unexpected error when creating guild! Please check the console log."
console.log "\x1b[1mUNEXPECTED ERROR WHEN CREATING GUILD\x1b[0m"
console.log e
return
logf LOG.DATABASE, "Guild #{formatGuild guild} already existed in the database"
RTFM.fetch bot, guild.id
bot.on "guildDelete", (guild) ->
dbGuild = await getdbGuild guild
unless dbGuild then return
await dbGuild.destroy()
logf LOG.DATABASE, "Guild #{formatGuild guild} removed"
bot.on "guildMemberAdd", (member) ->
# I don't care about bots lol
if member.user.bot
logf LOG.MODERATION, "Bot #{formatUser member.user} just arrived"
return
# Praise shared auth !
logf LOG.MODERATION, "User #{formatUser member.user} joined guild #{formatGuild member.guild}"
await touchMember member
bot.on "guildMemberRemove", (member) ->
# I don't care about bots lol
if member.user.bot
logf LOG.MODERATION, "Bot #{formatUser member.user} left guild #{formatGuild member.guild}"
return
logf LOG.MODERATION, "User #{formatUser member.user} left guild #{formatGuild member.guild}"
dbUser = await getdbUser member.user
unless dbUser then return
# Yeeting dbUser out when it isn't present in any other server
removeElement dbUser.servers, member.guild.id
if dbUser.servers.length > 0
await dbUser.update { servers: dbUser.servers }
logf LOG.DATABASE, "User #{formatUser member.user} removed from guild #{formatGuild member.guild}"
else
await dbUser.destroy()
logf LOG.DATABASE, "User #{formatUser member.user} removed"
unless process.env.LOCAL
unless member.guild.id is "672479260899803147" then return
bye = BYEBYES[Math.floor (Math.random() * BYEBYES.length - 1e-6)]
bye = bye.replace "{name}", member.displayName
auRevoir = await bot.channels.fetch '672502429836640267'
await auRevoir.send bye
bot.on "message", (msg) ->
# I don't care about myself lol
if msg.author.bot then return
# We STILL don't care about messages that don't come from dms
# Although we will care a bit later when introducing admin commands
if msg.channel.type isnt "dm"
if msg.author.id in TESTERS then syscall msg
return
# Note: we'll have to fetch every federated server
# to see if the member exists in our discord network
dbUser = await getdbUser msg.author
unless dbUser then return
unless await handleVerification gmailer, emailCH, dbUser, msg.author, msg.content
# More stuff is gonna go here probably
# like user commands to request your
# decrypted data from the database
if /^(get|give)\s+(me\s+)?(my\s+)?(user\s+)?data/i.test msg.content
# nssData, standing for Not So Sensible Data
nssData = { dbUser.dataValues... }
nssData.id = decryptid nssData.id
msg.author.send {
embed:
title: "Vos données sous forme YAML"
description:
"""
Voici vos données sous forme d'un objet YAML.
```yaml
#{YAML.stringify nssData}```
"""
color: 0x34d9ff
footer: FOOTER
}
else
msg.author.send "Vous êtes vérifié(e), vous n'avez plus rien à craindre."
bot.on "messageReactionAdd", (reaction, user) ->
# I still don't care about myself lol
if user.bot then return
if reaction.partial then await reaction.fetch()
# I don't care about anything else apart from DMs
if reaction.message.channel.type isnt "dm" then return
dbUser = await getdbUser user
unless dbUser then return
unless reaction.message.id is dbUser.reactor then return
switch reaction.emoji.name
when "⏪"
dbUser.code = null
dbUser.email = null
await dbUser.save()
await user.send {
embed:
title: "Adresse mail effacée"
description: "Vous pouvez désormais renseigner une nouvelle adresse mail."
color: 0x32ff64
footer: FOOTER
}
when "🔁"
gmailer.verifyEmail dbUser, user, dbUser.email, emailCH
else return
setTimeout (-> reaction.message.delete()), 3000
bot.on "guildMemberUpdate", (_, member) ->
levelRoles = ["licence_1", "licence_2", "licence_3", "master_1", "master_2", "doctorat", "professeur"]
if levelRoles.some (lr) -> member.roles.cache.has SERVERS.main.roles[lr]
member.roles.remove SERVERS.main.roles.indecis
bot.login process.env.SORBOT_TOKEN
| true | loading = require "./loading"
loading.step "Loading dotenv-flow...", 0
loading.startDisplaying()
require "dotenv-flow"
.config()
loading.step "Loading nodejs dependencies..."
{ join } = require "path"
YAML = require "yaml"
{ UniqueConstraintError } = require "sequelize"
loading.step "Loading discord.js..."
{ Client } = require "discord.js"
loading.step "Loading generic utils..."
{ relative, delay, readf
removeElement } = require "./helpers"
{ logf, formatCrisis, formatGuild
LOG, formatUser, botCache } = require "./logging"
{ CROSSMARK, SERVERS, BYEBYES,
GUILDS, TESTERS, FOOTER } = require "./constants"
{ encryptid, decryptid } = require "./encryption"
{ updateMemberRoles } = require "./roles"
touchMember = require "./touchMember"
loading.step "Loading gmailer and email crisis handler..."
GMailer = require "./mail/gmailer"
EmailCrisisHandler = require "./mail/crisisHandler"
{ handleVerification } = require "./mail/verificationHandler"
loading.step "Loading frontend functions..."
syscall = require "./frontend/syscall"
RTFM = require "./frontend/RTFM"
loading.step "Loading dbhelpers..."
{ getdbUser, getdbGuild } = require "./db/dbhelpers"
loading.step "Initializing database..."
{ User, FederatedMetadata } = require "./db/initdb"
loading.step "Instantiating Discord client..."
bot = new Client {
disableMentions: "everyone"
partials: ["MESSAGE", "CHANNEL", "REACTION", "GUILD_MEMBER"]
restTimeOffset: 100
}
loading.step "Instantiating new GMailer and EmailCrisisHandler..."
gmailer = new GMailer ["readonly", "modify", "compose", "send"], "credentials.yaml", loading
# - slowT {number} - period for the slow read mode, in seconds
# - fastT {number} - period for the fast read mode, in seconds
# - maxThreads {number} - Maximum number of threads globally
# - maxThreadsSlow {number} - Maximum number of threads only for slow mode
# - maxThreadsFast {number} - Maximum number of threads only for fast mode
# - guild {Guild} - The main discord guild to handle the crisis with
# - gmailer {GMailer} - The gmailer to read the email threads with
# - embedUEC {Embed} - The embed error report for Unread Existential Crisis
# - embedUSC {Embed} - The embed error report for Unread Sorbonne Crisis
emailCH = new EmailCrisisHandler {
bot
gmailer
# About those embeds, I'm probably gonna isolate
# them in a yaml file somewhere in resources/...
embedUEC: (th) ->
embed:
title: "Existential Crisis : Adresse Introuvable"
description:
"""
L'adresse que vous avez renseignée, `#{th[0].to}`, semble ne pas exister.
Nous vous invitons à réessayer avec une autre adresse mail universitaire.
"""
fields: [
{
name: "Headers du mail envoyé",
value: "```yaml\n#{YAML.stringify th[0]}```"
},
{
name: "Headers de la notification de fail"
value: "```yaml\n#{YAML.stringify th[1]}```"
}
]
color: 0xff6432
footer: FOOTER
embedUSC: (th) ->
embed:
title: "Sorbonne Crisis : Retour à l'envoyeur"
description:
"""
Pour une raison ou une autre, nous n'avons pas réussi à envoyer un mail à l'adresse `#{th[0].to}`.
**Nous vous invitons donc à envoyer un mail depuis votre adresse universitaire à l'adresse `PI:EMAIL:<EMAIL>END_PI`.**
Attention : __Le sujet du mail doit obligatoirement être votre tag discord__, à savoir de la forme `pseudo#1234`, sinon il nous sera impossible de vous vérifier.
Vous êtes libre d'écrire ce que vous voulez dans le corps du mail.
"""
fields: [
{
name: "Headers du mail envoyé",
value: "```yaml\n#{YAML.stringify th[0]}```"
},
{
name: "Headers de la notification de fail"
value: "```yaml\n#{YAML.stringify th[1]}```"
}
]
color: 0xa3334c
footer: FOOTER
}
loading.step "Preparing the cup of coffee..."
bot.on "ready", ->
botCache.bot = bot
await bot.user.setPresence {
activity:
type: "PLAYING"
name: if process.env.LOCAL then "Coucou humain 👀" else "with your data 👀"
url: "https://gitlab.com/Speykious/sorbot"
}
logf LOG.INIT, {
embed:
title: "Ready to sip. 茶 ☕"
description: "Let's play with even more dynamically-typed ***DATA*** <a:eyeshake:691797273147080714>"
color: 0x34d9ff
footer: FOOTER
}
loading.step "Authorizing the gmailer..."
await gmailer.authorize "token.yaml"
loading.step "Bot started successfully."
setTimeout (-> emailCH.activate()), 100
bot.on "guildCreate", (guild) ->
try
dbGuild = await FederatedMetadata.create { id: guild.id }
logf LOG.DATABASE, "New guild #{formatGuild guild} has been added to the database"
catch e
unless e instanceof UniqueConstraintError
logf LOG.WTF, "**WTF ?!** Unexpected error when creating guild! Please check the console log."
console.log "\x1b[1mUNEXPECTED ERROR WHEN CREATING GUILD\x1b[0m"
console.log e
return
logf LOG.DATABASE, "Guild #{formatGuild guild} already existed in the database"
RTFM.fetch bot, guild.id
bot.on "guildDelete", (guild) ->
dbGuild = await getdbGuild guild
unless dbGuild then return
await dbGuild.destroy()
logf LOG.DATABASE, "Guild #{formatGuild guild} removed"
bot.on "guildMemberAdd", (member) ->
# I don't care about bots lol
if member.user.bot
logf LOG.MODERATION, "Bot #{formatUser member.user} just arrived"
return
# Praise shared auth !
logf LOG.MODERATION, "User #{formatUser member.user} joined guild #{formatGuild member.guild}"
await touchMember member
bot.on "guildMemberRemove", (member) ->
# I don't care about bots lol
if member.user.bot
logf LOG.MODERATION, "Bot #{formatUser member.user} left guild #{formatGuild member.guild}"
return
logf LOG.MODERATION, "User #{formatUser member.user} left guild #{formatGuild member.guild}"
dbUser = await getdbUser member.user
unless dbUser then return
# Yeeting dbUser out when it isn't present in any other server
removeElement dbUser.servers, member.guild.id
if dbUser.servers.length > 0
await dbUser.update { servers: dbUser.servers }
logf LOG.DATABASE, "User #{formatUser member.user} removed from guild #{formatGuild member.guild}"
else
await dbUser.destroy()
logf LOG.DATABASE, "User #{formatUser member.user} removed"
unless process.env.LOCAL
unless member.guild.id is "672479260899803147" then return
bye = BYEBYES[Math.floor (Math.random() * BYEBYES.length - 1e-6)]
bye = bye.replace "{name}", member.displayName
auRevoir = await bot.channels.fetch '672502429836640267'
await auRevoir.send bye
bot.on "message", (msg) ->
# I don't care about myself lol
if msg.author.bot then return
# We STILL don't care about messages that don't come from dms
# Although we will care a bit later when introducing admin commands
if msg.channel.type isnt "dm"
if msg.author.id in TESTERS then syscall msg
return
# Note: we'll have to fetch every federated server
# to see if the member exists in our discord network
dbUser = await getdbUser msg.author
unless dbUser then return
unless await handleVerification gmailer, emailCH, dbUser, msg.author, msg.content
# More stuff is gonna go here probably
# like user commands to request your
# decrypted data from the database
if /^(get|give)\s+(me\s+)?(my\s+)?(user\s+)?data/i.test msg.content
# nssData, standing for Not So Sensible Data
nssData = { dbUser.dataValues... }
nssData.id = decryptid nssData.id
msg.author.send {
embed:
title: "Vos données sous forme YAML"
description:
"""
Voici vos données sous forme d'un objet YAML.
```yaml
#{YAML.stringify nssData}```
"""
color: 0x34d9ff
footer: FOOTER
}
else
msg.author.send "Vous êtes vérifié(e), vous n'avez plus rien à craindre."
bot.on "messageReactionAdd", (reaction, user) ->
# I still don't care about myself lol
if user.bot then return
if reaction.partial then await reaction.fetch()
# I don't care about anything else apart from DMs
if reaction.message.channel.type isnt "dm" then return
dbUser = await getdbUser user
unless dbUser then return
unless reaction.message.id is dbUser.reactor then return
switch reaction.emoji.name
when "⏪"
dbUser.code = null
dbUser.email = null
await dbUser.save()
await user.send {
embed:
title: "Adresse mail effacée"
description: "Vous pouvez désormais renseigner une nouvelle adresse mail."
color: 0x32ff64
footer: FOOTER
}
when "🔁"
gmailer.verifyEmail dbUser, user, dbUser.email, emailCH
else return
setTimeout (-> reaction.message.delete()), 3000
bot.on "guildMemberUpdate", (_, member) ->
levelRoles = ["licence_1", "licence_2", "licence_3", "master_1", "master_2", "doctorat", "professeur"]
if levelRoles.some (lr) -> member.roles.cache.has SERVERS.main.roles[lr]
member.roles.remove SERVERS.main.roles.indecis
bot.login process.env.SORBOT_TOKEN
|
[
{
"context": " item.isMnemonic = true\n\n slugname = @slugify(item.name)\n commandName = \"character-table",
"end": 2284,
"score": 0.9991695284843445,
"start": 2276,
"tag": "USERNAME",
"value": "@slugify"
},
{
"context": "\n codePoint = \"U+\"+codePoint\n\n key = \"#{codePoint} #{mnemonic} #{name}\"\n\n char_data.push {char, codePoint, mnemoni",
"end": 4268,
"score": 0.9973911643028259,
"start": 4234,
"tag": "KEY",
"value": "\"#{codePoint} #{mnemonic} #{name}\""
}
] | lib/character-data.coffee | threadless-screw/atom-character-table-plus | 0 | Q = require "q"
fs = require 'fs'
path = require 'path'
class CharacterData
constructor: (opts) ->
{autoload} = opts || {}
autoload ?= true
@initialize() if autoload
initialize: ->
@initialized = @loadCharacters().then (chardata) =>
@characterData = chardata
true
slugify: (s) ->
s.replace(/[^A-Za-z0-9_]/g, "-").toLowerCase()
getAll: (filter) ->
if filter?
@characterData.filter filter
else
@characterData
getMnemonics: ->
@characterData.filter (item) -> item.isMnemonic
setupMnemonics: (opts) ->
@initialized.then =>
{mnemonicRegex, charNameRegex, addCommand} = opts
{addKeymap, digraphKey, allowReversed, count} = opts
mnemonics = @mnemonics
reverse_mnemonic = null
_getReverseMnemonic = (char2, char1) ->
result = null
if allowReversed
result = char2+char1
if result of mnemonics
result = null
return result
_mnemonicMatch = (item, reverse_mnemonic) ->
result = true
if mnemonicRegex
result = item.mnemonic.match mnemonicRegex
if reverse_mnemonic?
result |= reverse_mnemonic.match mnemonicRegex
return result
_charNameMatch = (item) ->
result = true
if charNameRegex
result = item.name.match charNameRegex
return result
_getExtraChars = (char3, char4) ->
result = ""
if char3 is " "
result += " space"
else if char3
result += " #{char3}"
if char4 is " "
result += " space"
else if char4
result += " #{char4}"
return result
keymap = {}
lastIndex = @characterData.length - 1
@characterData.forEach (item,i) =>
return unless item.mnemonic
if count?
return unless i < count
[char1, char2, char3, char4] = item.mnemonic.split("")
reverse_mnemonic = _getReverseMnemonic(char2, char1)
mnemonicMatched = _mnemonicMatch item, reverse_mnemonic
charNameMatched = _charNameMatch item
item.isMnemonic = false
return unless charNameMatched and mnemonicMatched
item.isMnemonic = true
slugname = @slugify(item.name)
commandName = "character-table:insert-#{slugname}"
addCommand commandName, item
char1 = "space" if char1 is " "
char2 = "space" if char2 is " "
extra = _getExtraChars(char3, char4)
keymap["#{digraphKey} #{char1} #{char2}#{extra}"] = commandName
unless extra
if reverse_mnemonic?
keymap["#{digraphKey} #{char2} #{char1}"] = commandName
try
addKeymap keymap
catch e
console.log e
loadCharacters: ->
Q.fcall =>
rfc1345_data = fs.readFileSync path.resolve __dirname, "..", "rfc1345.txt"
unicode_data = fs.readFileSync path.resolve __dirname, "..", "UnicodeData.txt"
rfc1345_data = rfc1345_data.toString()
unicode_data = unicode_data.toString()
char_data = []
@mnemonics = {}
for line in rfc1345_data.split /\n/
continue if line.length < 4
continue if line[0] != " "
continue if line[1] == " "
[mnemonic, number, iso_name] = line[1..].split(/\s+/, 2)
mnemonic += " " if mnemonic.length == 1
try
char = String.fromCodePoint("0x"+number)
catch e
console.warn "Error decoding #{number}, #{iso_name}"
continue
@mnemonics[char] = mnemonic
for line in unicode_data.split /\n/
row = line.split /;/
[codePoint, name, category] = row[..2]
#canonClass, bidiCategory, decomp, decimal,
#digit, numeric, unicode1, comment, upperMapping, lowerMapping, titleMapping]
unless category
continue
continue if category.match /^C/
try
char = String.fromCodePoint("0x"+codePoint)
catch e
console.warn "Error decoding #{number}, #{iso_name}"
continue
mnemonic = ""
if char of @mnemonics
mnemonic = @mnemonics[char]
codePoint = "U+"+codePoint
key = "#{codePoint} #{mnemonic} #{name}"
char_data.push {char, codePoint, mnemonic, name, key}
char_data
module.exports = {CharacterData}
| 39808 | Q = require "q"
fs = require 'fs'
path = require 'path'
class CharacterData
constructor: (opts) ->
{autoload} = opts || {}
autoload ?= true
@initialize() if autoload
initialize: ->
@initialized = @loadCharacters().then (chardata) =>
@characterData = chardata
true
slugify: (s) ->
s.replace(/[^A-Za-z0-9_]/g, "-").toLowerCase()
getAll: (filter) ->
if filter?
@characterData.filter filter
else
@characterData
getMnemonics: ->
@characterData.filter (item) -> item.isMnemonic
setupMnemonics: (opts) ->
@initialized.then =>
{mnemonicRegex, charNameRegex, addCommand} = opts
{addKeymap, digraphKey, allowReversed, count} = opts
mnemonics = @mnemonics
reverse_mnemonic = null
_getReverseMnemonic = (char2, char1) ->
result = null
if allowReversed
result = char2+char1
if result of mnemonics
result = null
return result
_mnemonicMatch = (item, reverse_mnemonic) ->
result = true
if mnemonicRegex
result = item.mnemonic.match mnemonicRegex
if reverse_mnemonic?
result |= reverse_mnemonic.match mnemonicRegex
return result
_charNameMatch = (item) ->
result = true
if charNameRegex
result = item.name.match charNameRegex
return result
_getExtraChars = (char3, char4) ->
result = ""
if char3 is " "
result += " space"
else if char3
result += " #{char3}"
if char4 is " "
result += " space"
else if char4
result += " #{char4}"
return result
keymap = {}
lastIndex = @characterData.length - 1
@characterData.forEach (item,i) =>
return unless item.mnemonic
if count?
return unless i < count
[char1, char2, char3, char4] = item.mnemonic.split("")
reverse_mnemonic = _getReverseMnemonic(char2, char1)
mnemonicMatched = _mnemonicMatch item, reverse_mnemonic
charNameMatched = _charNameMatch item
item.isMnemonic = false
return unless charNameMatched and mnemonicMatched
item.isMnemonic = true
slugname = @slugify(item.name)
commandName = "character-table:insert-#{slugname}"
addCommand commandName, item
char1 = "space" if char1 is " "
char2 = "space" if char2 is " "
extra = _getExtraChars(char3, char4)
keymap["#{digraphKey} #{char1} #{char2}#{extra}"] = commandName
unless extra
if reverse_mnemonic?
keymap["#{digraphKey} #{char2} #{char1}"] = commandName
try
addKeymap keymap
catch e
console.log e
loadCharacters: ->
Q.fcall =>
rfc1345_data = fs.readFileSync path.resolve __dirname, "..", "rfc1345.txt"
unicode_data = fs.readFileSync path.resolve __dirname, "..", "UnicodeData.txt"
rfc1345_data = rfc1345_data.toString()
unicode_data = unicode_data.toString()
char_data = []
@mnemonics = {}
for line in rfc1345_data.split /\n/
continue if line.length < 4
continue if line[0] != " "
continue if line[1] == " "
[mnemonic, number, iso_name] = line[1..].split(/\s+/, 2)
mnemonic += " " if mnemonic.length == 1
try
char = String.fromCodePoint("0x"+number)
catch e
console.warn "Error decoding #{number}, #{iso_name}"
continue
@mnemonics[char] = mnemonic
for line in unicode_data.split /\n/
row = line.split /;/
[codePoint, name, category] = row[..2]
#canonClass, bidiCategory, decomp, decimal,
#digit, numeric, unicode1, comment, upperMapping, lowerMapping, titleMapping]
unless category
continue
continue if category.match /^C/
try
char = String.fromCodePoint("0x"+codePoint)
catch e
console.warn "Error decoding #{number}, #{iso_name}"
continue
mnemonic = ""
if char of @mnemonics
mnemonic = @mnemonics[char]
codePoint = "U+"+codePoint
key = <KEY>
char_data.push {char, codePoint, mnemonic, name, key}
char_data
module.exports = {CharacterData}
| true | Q = require "q"
fs = require 'fs'
path = require 'path'
class CharacterData
constructor: (opts) ->
{autoload} = opts || {}
autoload ?= true
@initialize() if autoload
initialize: ->
@initialized = @loadCharacters().then (chardata) =>
@characterData = chardata
true
slugify: (s) ->
s.replace(/[^A-Za-z0-9_]/g, "-").toLowerCase()
getAll: (filter) ->
if filter?
@characterData.filter filter
else
@characterData
getMnemonics: ->
@characterData.filter (item) -> item.isMnemonic
setupMnemonics: (opts) ->
@initialized.then =>
{mnemonicRegex, charNameRegex, addCommand} = opts
{addKeymap, digraphKey, allowReversed, count} = opts
mnemonics = @mnemonics
reverse_mnemonic = null
_getReverseMnemonic = (char2, char1) ->
result = null
if allowReversed
result = char2+char1
if result of mnemonics
result = null
return result
_mnemonicMatch = (item, reverse_mnemonic) ->
result = true
if mnemonicRegex
result = item.mnemonic.match mnemonicRegex
if reverse_mnemonic?
result |= reverse_mnemonic.match mnemonicRegex
return result
_charNameMatch = (item) ->
result = true
if charNameRegex
result = item.name.match charNameRegex
return result
_getExtraChars = (char3, char4) ->
result = ""
if char3 is " "
result += " space"
else if char3
result += " #{char3}"
if char4 is " "
result += " space"
else if char4
result += " #{char4}"
return result
keymap = {}
lastIndex = @characterData.length - 1
@characterData.forEach (item,i) =>
return unless item.mnemonic
if count?
return unless i < count
[char1, char2, char3, char4] = item.mnemonic.split("")
reverse_mnemonic = _getReverseMnemonic(char2, char1)
mnemonicMatched = _mnemonicMatch item, reverse_mnemonic
charNameMatched = _charNameMatch item
item.isMnemonic = false
return unless charNameMatched and mnemonicMatched
item.isMnemonic = true
slugname = @slugify(item.name)
commandName = "character-table:insert-#{slugname}"
addCommand commandName, item
char1 = "space" if char1 is " "
char2 = "space" if char2 is " "
extra = _getExtraChars(char3, char4)
keymap["#{digraphKey} #{char1} #{char2}#{extra}"] = commandName
unless extra
if reverse_mnemonic?
keymap["#{digraphKey} #{char2} #{char1}"] = commandName
try
addKeymap keymap
catch e
console.log e
loadCharacters: ->
Q.fcall =>
rfc1345_data = fs.readFileSync path.resolve __dirname, "..", "rfc1345.txt"
unicode_data = fs.readFileSync path.resolve __dirname, "..", "UnicodeData.txt"
rfc1345_data = rfc1345_data.toString()
unicode_data = unicode_data.toString()
char_data = []
@mnemonics = {}
for line in rfc1345_data.split /\n/
continue if line.length < 4
continue if line[0] != " "
continue if line[1] == " "
[mnemonic, number, iso_name] = line[1..].split(/\s+/, 2)
mnemonic += " " if mnemonic.length == 1
try
char = String.fromCodePoint("0x"+number)
catch e
console.warn "Error decoding #{number}, #{iso_name}"
continue
@mnemonics[char] = mnemonic
for line in unicode_data.split /\n/
row = line.split /;/
[codePoint, name, category] = row[..2]
#canonClass, bidiCategory, decomp, decimal,
#digit, numeric, unicode1, comment, upperMapping, lowerMapping, titleMapping]
unless category
continue
continue if category.match /^C/
try
char = String.fromCodePoint("0x"+codePoint)
catch e
console.warn "Error decoding #{number}, #{iso_name}"
continue
mnemonic = ""
if char of @mnemonics
mnemonic = @mnemonics[char]
codePoint = "U+"+codePoint
key = PI:KEY:<KEY>END_PI
char_data.push {char, codePoint, mnemonic, name, key}
char_data
module.exports = {CharacterData}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.