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": "ructor: (@localStorage=localStorage, @storageKey='eutaxia-cart') ->\n @contents = []\n @key_",
"end": 730,
"score": 0.9635370373725891,
"start": 718,
"tag": "KEY",
"value": "eutaxia-cart"
}
] | clients/data/webshop/cart.coffee | jacob22/accounting | 0 | /*
Copyright 2019 Open End AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
define(['iter', 'signals', 'utils'], ->
[iter, signals, utils] = arguments
class Cart
constructor: (@localStorage=localStorage, @storageKey='eutaxia-cart') ->
@contents = []
@key_counter = iter.count(1)
load: ->
serialized = @localStorage.getItem(@storageKey)
unless serialized
return
try
data = JSON.parse(serialized)
catch
return # Corrupt data, give up
if data?
@contents = data.contents
@key_counter = iter.count(data.current)
save: ->
@localStorage.setItem(@storageKey, JSON.stringify(
contents: @contents
counter: @key_counter.current)
)
clear: ->
@localStorage.removeItem(@storageKey)
add: (item) ->
unless item.count?
item.count = 1
unless item.options?
item.options = []
unless item.price?
item.price = 0
item.total = item.price * item.count
push = true
for prev in @contents
if @_compare_items(prev, item)
prev.count += item.count
prev.total = prev.price * prev.count
key = prev.key
push = false
break
if push
item.key = key = @key_counter.next()
@contents.push(item)
signals.signal(@, 'changed')
@save()
return key
set_item_count: (key, count) ->
for item in @contents
if item.key is key
if count == 0
@contents.splice(@contents.indexOf(item), 1)
else
item.count = count
item.total = item.price * count
signals.signal(@, 'changed')
@save()
return
throw "No such item: #{key}"
get_data: ->
items = []
for item in @contents
options = []
for [label, value] in item.options
if value?
value = value.toString()
else
value = ''
options.push(value)
items.push(
product: item.id
quantity: item.count
options: options
)
return items
_compare_items: (a, b) ->
return a.id is b.id and utils.array_equal(a.options, b.options, true)
module =
Cart: Cart
)
| 73759 | /*
Copyright 2019 Open End AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
define(['iter', 'signals', 'utils'], ->
[iter, signals, utils] = arguments
class Cart
constructor: (@localStorage=localStorage, @storageKey='<KEY>') ->
@contents = []
@key_counter = iter.count(1)
load: ->
serialized = @localStorage.getItem(@storageKey)
unless serialized
return
try
data = JSON.parse(serialized)
catch
return # Corrupt data, give up
if data?
@contents = data.contents
@key_counter = iter.count(data.current)
save: ->
@localStorage.setItem(@storageKey, JSON.stringify(
contents: @contents
counter: @key_counter.current)
)
clear: ->
@localStorage.removeItem(@storageKey)
add: (item) ->
unless item.count?
item.count = 1
unless item.options?
item.options = []
unless item.price?
item.price = 0
item.total = item.price * item.count
push = true
for prev in @contents
if @_compare_items(prev, item)
prev.count += item.count
prev.total = prev.price * prev.count
key = prev.key
push = false
break
if push
item.key = key = @key_counter.next()
@contents.push(item)
signals.signal(@, 'changed')
@save()
return key
set_item_count: (key, count) ->
for item in @contents
if item.key is key
if count == 0
@contents.splice(@contents.indexOf(item), 1)
else
item.count = count
item.total = item.price * count
signals.signal(@, 'changed')
@save()
return
throw "No such item: #{key}"
get_data: ->
items = []
for item in @contents
options = []
for [label, value] in item.options
if value?
value = value.toString()
else
value = ''
options.push(value)
items.push(
product: item.id
quantity: item.count
options: options
)
return items
_compare_items: (a, b) ->
return a.id is b.id and utils.array_equal(a.options, b.options, true)
module =
Cart: Cart
)
| true | /*
Copyright 2019 Open End AB
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
define(['iter', 'signals', 'utils'], ->
[iter, signals, utils] = arguments
class Cart
constructor: (@localStorage=localStorage, @storageKey='PI:KEY:<KEY>END_PI') ->
@contents = []
@key_counter = iter.count(1)
load: ->
serialized = @localStorage.getItem(@storageKey)
unless serialized
return
try
data = JSON.parse(serialized)
catch
return # Corrupt data, give up
if data?
@contents = data.contents
@key_counter = iter.count(data.current)
save: ->
@localStorage.setItem(@storageKey, JSON.stringify(
contents: @contents
counter: @key_counter.current)
)
clear: ->
@localStorage.removeItem(@storageKey)
add: (item) ->
unless item.count?
item.count = 1
unless item.options?
item.options = []
unless item.price?
item.price = 0
item.total = item.price * item.count
push = true
for prev in @contents
if @_compare_items(prev, item)
prev.count += item.count
prev.total = prev.price * prev.count
key = prev.key
push = false
break
if push
item.key = key = @key_counter.next()
@contents.push(item)
signals.signal(@, 'changed')
@save()
return key
set_item_count: (key, count) ->
for item in @contents
if item.key is key
if count == 0
@contents.splice(@contents.indexOf(item), 1)
else
item.count = count
item.total = item.price * count
signals.signal(@, 'changed')
@save()
return
throw "No such item: #{key}"
get_data: ->
items = []
for item in @contents
options = []
for [label, value] in item.options
if value?
value = value.toString()
else
value = ''
options.push(value)
items.push(
product: item.id
quantity: item.count
options: options
)
return items
_compare_items: (a, b) ->
return a.id is b.id and utils.array_equal(a.options, b.options, true)
module =
Cart: Cart
)
|
[
{
"context": "parsedUrl = null\n client = new Client {apiKey:'TESTKEY'}\n client._request = (opts, cb) ->\n u =",
"end": 392,
"score": 0.8631480932235718,
"start": 385,
"tag": "KEY",
"value": "TESTKEY"
},
{
"context": "ludeTimeline: false\n api_key: 'T... | test/clientTest.coffee | jwalton/lol-js | 30 | url = require 'url'
querystring = require 'querystring'
{expect} = require 'chai'
testUtils = require './testUtils'
Client = require '../src/client'
LRUCache = require '../src/cache/lruCache'
testMethod = (callClientFn, data, expected) ->
{expectedHost, expectedPathname, expectedQueryParams} = expected
parsedUrl = null
client = new Client {apiKey:'TESTKEY'}
client._request = (opts, cb) ->
u = opts.uri
parsedUrl = url.parse u
cb null, {statusCode: 200}, data
callClientFn client
.then (value) ->
expect(parsedUrl.protocol).to.equal('https:')
expect(parsedUrl.host).to.equal(expectedHost)
expect(parsedUrl.pathname).to.equal(expectedPathname)
queryParams = querystring.parse(parsedUrl.query)
expect(queryParams['api_key']).to.equal('TESTKEY')
for expectedParamName, expectedParamValue of expectedQueryParams
expect(queryParams[expectedParamName]).to.equal("#{expectedParamValue}", expectedParamName)
return value
describe 'Client', ->
it 'should generate the correct URL and parameters', ->
testMethod(
( (client) -> client.getMatch('eune', 1234) ),
'{"fakeData": true}',
{
expectedHost: 'eune.api.pvp.net'
expectedPathname: '/api/lol/eune/v2.2/match/1234'
expectedQueryParams: {
includeTimeline: false
api_key: 'TESTKEY'
}
})
.then (value) ->
expect(value).to.eql({fakeData: true})
it 'should transparently retry if we hit the rate limit', ->
reqCount = 0
client = new Client {apiKey:'TESTKEY'}
client._request = (u, cb) ->
reqCount++
switch reqCount
when 1 then cb null, {statusCode: 429}, ""
when 2 then cb null, {statusCode: 200}, '{"fakeData": true}'
client.getMatch 'na', 1234
.then (value) ->
expect(reqCount).to.equal 2
expect(value).to.exist
it 'should transparently retry if the Riot API is unavailable', ->
reqCount = 0
client = new Client {apiKey:'TESTKEY'}
client._request = (u, cb) ->
reqCount++
switch reqCount
when 1 then cb null, {statusCode: 503}, ""
when 2 then cb null, {statusCode: 200}, '{"fakeData": true}'
client.getMatch 'na', 1234
.then (value) ->
expect(reqCount).to.equal 2
expect(value).to.exist
it 'should not transparently retry if the Riot API is unavailable and we have a cached copy available', ->
reqCount = 0
client = new Client {apiKey:'TESTKEY'}
client._request = (u, cb) ->
reqCount++
cb null, {statusCode: 503}, ""
passed = false
return client._doRequest {
url: 'https://na.api.pvp.net/api/lol/na/v2.2/match/1234?includeTimeline=false&api_key=TESTKEY'
caller: 'clientTest'
allowRetries: false
}
.catch (err) ->
passed = err.statusCode is 503
.then ->
expect(reqCount).to.equal 1
if !passed then throw new Error "Expected exception"
it 'should work out that two requests are the same request', ->
reqCount = 0
client = new Client {apiKey:'TESTKEY'}
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/SummonerA,summonerb"
body: '{"fakeData": true}'
}
]
client._request = (u, cb) ->
reqCount++
switch reqCount
when 1 then cb null, {statusCode: 200}, '{"fakeData": true}'
p1 = client.getMatch 'na', 1234
p2 = client.getMatch 'na', 1234
p1Result = null
p1.then (r) ->
p1Result = r
expect(p1Result).to.exist
return p2
.then (p2Result) ->
expect(p2Result).to.exist
expect(p1Result).to.equal(p2Result)
it 'should fetch from the cache immediately', ->
client = new Client {
apiKey: 'TESTKEY'
cache: new LRUCache(50)
}
cacheParams = {
key: 'myobject',
ttl: 100
api: {name: 'myapi', version: 'v2.2'}
objectType: 'object'
region: 'na'
params: {foo: 'bar'}
}
client.cache.set cacheParams, {foo: 'bar'}
client.cache.get(cacheParams)
.then (result) ->
expect(result.value).to.eql {foo: 'bar'}
| 92194 | url = require 'url'
querystring = require 'querystring'
{expect} = require 'chai'
testUtils = require './testUtils'
Client = require '../src/client'
LRUCache = require '../src/cache/lruCache'
testMethod = (callClientFn, data, expected) ->
{expectedHost, expectedPathname, expectedQueryParams} = expected
parsedUrl = null
client = new Client {apiKey:'<KEY>'}
client._request = (opts, cb) ->
u = opts.uri
parsedUrl = url.parse u
cb null, {statusCode: 200}, data
callClientFn client
.then (value) ->
expect(parsedUrl.protocol).to.equal('https:')
expect(parsedUrl.host).to.equal(expectedHost)
expect(parsedUrl.pathname).to.equal(expectedPathname)
queryParams = querystring.parse(parsedUrl.query)
expect(queryParams['api_key']).to.equal('TESTKEY')
for expectedParamName, expectedParamValue of expectedQueryParams
expect(queryParams[expectedParamName]).to.equal("#{expectedParamValue}", expectedParamName)
return value
describe 'Client', ->
it 'should generate the correct URL and parameters', ->
testMethod(
( (client) -> client.getMatch('eune', 1234) ),
'{"fakeData": true}',
{
expectedHost: 'eune.api.pvp.net'
expectedPathname: '/api/lol/eune/v2.2/match/1234'
expectedQueryParams: {
includeTimeline: false
api_key: '<KEY>'
}
})
.then (value) ->
expect(value).to.eql({fakeData: true})
it 'should transparently retry if we hit the rate limit', ->
reqCount = 0
client = new Client {apiKey:'<KEY>'}
client._request = (u, cb) ->
reqCount++
switch reqCount
when 1 then cb null, {statusCode: 429}, ""
when 2 then cb null, {statusCode: 200}, '{"fakeData": true}'
client.getMatch 'na', 1234
.then (value) ->
expect(reqCount).to.equal 2
expect(value).to.exist
it 'should transparently retry if the Riot API is unavailable', ->
reqCount = 0
client = new Client {apiKey:'<KEY>'}
client._request = (u, cb) ->
reqCount++
switch reqCount
when 1 then cb null, {statusCode: 503}, ""
when 2 then cb null, {statusCode: 200}, '{"fakeData": true}'
client.getMatch 'na', 1234
.then (value) ->
expect(reqCount).to.equal 2
expect(value).to.exist
it 'should not transparently retry if the Riot API is unavailable and we have a cached copy available', ->
reqCount = 0
client = new Client {apiKey:'TESTKEY'}
client._request = (u, cb) ->
reqCount++
cb null, {statusCode: 503}, ""
passed = false
return client._doRequest {
url: 'https://na.api.pvp.net/api/lol/na/v2.2/match/1234?includeTimeline=false&api_key=TESTKEY'
caller: 'clientTest'
allowRetries: false
}
.catch (err) ->
passed = err.statusCode is 503
.then ->
expect(reqCount).to.equal 1
if !passed then throw new Error "Expected exception"
it 'should work out that two requests are the same request', ->
reqCount = 0
client = new Client {apiKey:'TESTKEY'}
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/SummonerA,summonerb"
body: '{"fakeData": true}'
}
]
client._request = (u, cb) ->
reqCount++
switch reqCount
when 1 then cb null, {statusCode: 200}, '{"fakeData": true}'
p1 = client.getMatch 'na', 1234
p2 = client.getMatch 'na', 1234
p1Result = null
p1.then (r) ->
p1Result = r
expect(p1Result).to.exist
return p2
.then (p2Result) ->
expect(p2Result).to.exist
expect(p1Result).to.equal(p2Result)
it 'should fetch from the cache immediately', ->
client = new Client {
apiKey: '<KEY>'
cache: new LRUCache(50)
}
cacheParams = {
key: '<KEY>',
ttl: 100
api: {name: 'myapi', version: 'v2.2'}
objectType: 'object'
region: 'na'
params: {foo: 'bar'}
}
client.cache.set cacheParams, {foo: 'bar'}
client.cache.get(cacheParams)
.then (result) ->
expect(result.value).to.eql {foo: 'bar'}
| true | url = require 'url'
querystring = require 'querystring'
{expect} = require 'chai'
testUtils = require './testUtils'
Client = require '../src/client'
LRUCache = require '../src/cache/lruCache'
testMethod = (callClientFn, data, expected) ->
{expectedHost, expectedPathname, expectedQueryParams} = expected
parsedUrl = null
client = new Client {apiKey:'PI:KEY:<KEY>END_PI'}
client._request = (opts, cb) ->
u = opts.uri
parsedUrl = url.parse u
cb null, {statusCode: 200}, data
callClientFn client
.then (value) ->
expect(parsedUrl.protocol).to.equal('https:')
expect(parsedUrl.host).to.equal(expectedHost)
expect(parsedUrl.pathname).to.equal(expectedPathname)
queryParams = querystring.parse(parsedUrl.query)
expect(queryParams['api_key']).to.equal('TESTKEY')
for expectedParamName, expectedParamValue of expectedQueryParams
expect(queryParams[expectedParamName]).to.equal("#{expectedParamValue}", expectedParamName)
return value
describe 'Client', ->
it 'should generate the correct URL and parameters', ->
testMethod(
( (client) -> client.getMatch('eune', 1234) ),
'{"fakeData": true}',
{
expectedHost: 'eune.api.pvp.net'
expectedPathname: '/api/lol/eune/v2.2/match/1234'
expectedQueryParams: {
includeTimeline: false
api_key: 'PI:KEY:<KEY>END_PI'
}
})
.then (value) ->
expect(value).to.eql({fakeData: true})
it 'should transparently retry if we hit the rate limit', ->
reqCount = 0
client = new Client {apiKey:'PI:KEY:<KEY>END_PI'}
client._request = (u, cb) ->
reqCount++
switch reqCount
when 1 then cb null, {statusCode: 429}, ""
when 2 then cb null, {statusCode: 200}, '{"fakeData": true}'
client.getMatch 'na', 1234
.then (value) ->
expect(reqCount).to.equal 2
expect(value).to.exist
it 'should transparently retry if the Riot API is unavailable', ->
reqCount = 0
client = new Client {apiKey:'PI:KEY:<KEY>END_PI'}
client._request = (u, cb) ->
reqCount++
switch reqCount
when 1 then cb null, {statusCode: 503}, ""
when 2 then cb null, {statusCode: 200}, '{"fakeData": true}'
client.getMatch 'na', 1234
.then (value) ->
expect(reqCount).to.equal 2
expect(value).to.exist
it 'should not transparently retry if the Riot API is unavailable and we have a cached copy available', ->
reqCount = 0
client = new Client {apiKey:'TESTKEY'}
client._request = (u, cb) ->
reqCount++
cb null, {statusCode: 503}, ""
passed = false
return client._doRequest {
url: 'https://na.api.pvp.net/api/lol/na/v2.2/match/1234?includeTimeline=false&api_key=TESTKEY'
caller: 'clientTest'
allowRetries: false
}
.catch (err) ->
passed = err.statusCode is 503
.then ->
expect(reqCount).to.equal 1
if !passed then throw new Error "Expected exception"
it 'should work out that two requests are the same request', ->
reqCount = 0
client = new Client {apiKey:'TESTKEY'}
testUtils.expectRequests client, [
{
url: "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/SummonerA,summonerb"
body: '{"fakeData": true}'
}
]
client._request = (u, cb) ->
reqCount++
switch reqCount
when 1 then cb null, {statusCode: 200}, '{"fakeData": true}'
p1 = client.getMatch 'na', 1234
p2 = client.getMatch 'na', 1234
p1Result = null
p1.then (r) ->
p1Result = r
expect(p1Result).to.exist
return p2
.then (p2Result) ->
expect(p2Result).to.exist
expect(p1Result).to.equal(p2Result)
it 'should fetch from the cache immediately', ->
client = new Client {
apiKey: 'PI:KEY:<KEY>END_PI'
cache: new LRUCache(50)
}
cacheParams = {
key: 'PI:KEY:<KEY>END_PI',
ttl: 100
api: {name: 'myapi', version: 'v2.2'}
objectType: 'object'
region: 'na'
params: {foo: 'bar'}
}
client.cache.set cacheParams, {foo: 'bar'}
client.cache.get(cacheParams)
.then (result) ->
expect(result.value).to.eql {foo: 'bar'}
|
[
{
"context": "host'\n port: 8086\n auth:\n type: 'auth_basic \"alcarruth\"'\n path: 'auth_basic_user_file /etc/nginx/htpa",
"end": 1140,
"score": 0.7114983201026917,
"start": 1131,
"tag": "PASSWORD",
"value": "alcarruth"
}
] | src/nginx_app_conf.coffee | alcarruth/ipc-rmi | 1 | #!/usr/bin/env coffee
#
generate_nginx_conf = (spec) ->
# required
name = spec.name
path = spec.path
access_log = spec.access_log
error_log = spec.error_log
# optional
host = spec.host || 'localhost'
port = spec.port || 8080
auth = spec.auth || { type: null, path: null }
return """
location #{path} {
#{auth.type};
#{auth.path};
# mozilla sends a different origin than chrome
proxy_http_version 1.1;
proxy_read_timeout 3600s;
# proxy to port #{port}
proxy_pass http://#{host}:#{port}/;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_redirect http://#{host}:#{port}/ #{path};
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
access_log #{access_log};
error_log #{error_log};
}
"""
spec =
name: 'web-tix'
path: '/wss/tickets_coffee'
access_log: '/var/log/alcarruth/tickets.log'
error_log: '/var/log/alcarruth/tickets.err'
host: 'localhost'
port: 8086
auth:
type: 'auth_basic "alcarruth"'
path: 'auth_basic_user_file /etc/nginx/htpasswd'
if module.parent
exports.generate_nginx_conf = generate_nginx_conf
else
conf = generate_nginx_conf(spec)
console.log conf
| 90261 | #!/usr/bin/env coffee
#
generate_nginx_conf = (spec) ->
# required
name = spec.name
path = spec.path
access_log = spec.access_log
error_log = spec.error_log
# optional
host = spec.host || 'localhost'
port = spec.port || 8080
auth = spec.auth || { type: null, path: null }
return """
location #{path} {
#{auth.type};
#{auth.path};
# mozilla sends a different origin than chrome
proxy_http_version 1.1;
proxy_read_timeout 3600s;
# proxy to port #{port}
proxy_pass http://#{host}:#{port}/;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_redirect http://#{host}:#{port}/ #{path};
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
access_log #{access_log};
error_log #{error_log};
}
"""
spec =
name: 'web-tix'
path: '/wss/tickets_coffee'
access_log: '/var/log/alcarruth/tickets.log'
error_log: '/var/log/alcarruth/tickets.err'
host: 'localhost'
port: 8086
auth:
type: 'auth_basic "<PASSWORD>"'
path: 'auth_basic_user_file /etc/nginx/htpasswd'
if module.parent
exports.generate_nginx_conf = generate_nginx_conf
else
conf = generate_nginx_conf(spec)
console.log conf
| true | #!/usr/bin/env coffee
#
generate_nginx_conf = (spec) ->
# required
name = spec.name
path = spec.path
access_log = spec.access_log
error_log = spec.error_log
# optional
host = spec.host || 'localhost'
port = spec.port || 8080
auth = spec.auth || { type: null, path: null }
return """
location #{path} {
#{auth.type};
#{auth.path};
# mozilla sends a different origin than chrome
proxy_http_version 1.1;
proxy_read_timeout 3600s;
# proxy to port #{port}
proxy_pass http://#{host}:#{port}/;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_redirect http://#{host}:#{port}/ #{path};
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
access_log #{access_log};
error_log #{error_log};
}
"""
spec =
name: 'web-tix'
path: '/wss/tickets_coffee'
access_log: '/var/log/alcarruth/tickets.log'
error_log: '/var/log/alcarruth/tickets.err'
host: 'localhost'
port: 8086
auth:
type: 'auth_basic "PI:PASSWORD:<PASSWORD>END_PI"'
path: 'auth_basic_user_file /etc/nginx/htpasswd'
if module.parent
exports.generate_nginx_conf = generate_nginx_conf
else
conf = generate_nginx_conf(spec)
console.log conf
|
[
{
"context": "expire 'afterSignUpAction'\n\n# TODO: Follow up with Christina about this functionality\ncheckForPersonalizeFlash",
"end": 1346,
"score": 0.8563318848609924,
"start": 1337,
"tag": "NAME",
"value": "Christina"
}
] | src/desktop/components/main_layout/client.coffee | dzucconi/force | 0 | { globalClientSetup } = require '../../lib/global_client_setup'
HeaderView = require './header/view.coffee'
FooterView = require './footer/view.coffee'
CurrentUser = require '../../models/current_user.coffee'
FlashMessage = require '../flash/index.coffee'
Cookies = require 'cookies-js'
{ triggerMarketingModal } = require '../marketing_signup_modal/triggerMarketingModal.ts'
{ AuthIntent } = require "@artsy/cohesion"
module.exports = ->
globalClientSetup()
checkForAfterSignUpAction()
checkForPersonalizeFlash()
new HeaderView el: $('#main-layout-header')
new FooterView el: $('#main-layout-footer')
triggerMarketingModal(AuthIntent.viewFair, true)
checkForAfterSignUpAction = ->
currentUser = CurrentUser.orNull()
afterSignUpAction = Cookies.get 'afterSignUpAction'
if afterSignUpAction
return unless @currentUser
{ action, objectId, kind } = JSON.parse(afterSignUpAction)
operations =
save: (currentUser, objectId, kind) ->
currentUser.initializeDefaultArtworkCollection()
currentUser.defaultArtworkCollection().saveArtwork objectId
follow: (currentUser, objectId, kind) ->
kind? and currentUser.follow(objectId, kind)
ops = operations[action]
ops and ops(@currentUser, objectId, kind)
Cookies.expire 'afterSignUpAction'
# TODO: Follow up with Christina about this functionality
checkForPersonalizeFlash = ->
# Sometime '/personalize/' can exist as a redirect parameter in the URL.
# This causes the flash message to display at unexpected times.
# This ensures we check for personalize in the pathname.
if document.referrer.split('?')[0].match '^/personalize.*'
new FlashMessage message: 'Thank you for personalizing your profile'
| 224243 | { globalClientSetup } = require '../../lib/global_client_setup'
HeaderView = require './header/view.coffee'
FooterView = require './footer/view.coffee'
CurrentUser = require '../../models/current_user.coffee'
FlashMessage = require '../flash/index.coffee'
Cookies = require 'cookies-js'
{ triggerMarketingModal } = require '../marketing_signup_modal/triggerMarketingModal.ts'
{ AuthIntent } = require "@artsy/cohesion"
module.exports = ->
globalClientSetup()
checkForAfterSignUpAction()
checkForPersonalizeFlash()
new HeaderView el: $('#main-layout-header')
new FooterView el: $('#main-layout-footer')
triggerMarketingModal(AuthIntent.viewFair, true)
checkForAfterSignUpAction = ->
currentUser = CurrentUser.orNull()
afterSignUpAction = Cookies.get 'afterSignUpAction'
if afterSignUpAction
return unless @currentUser
{ action, objectId, kind } = JSON.parse(afterSignUpAction)
operations =
save: (currentUser, objectId, kind) ->
currentUser.initializeDefaultArtworkCollection()
currentUser.defaultArtworkCollection().saveArtwork objectId
follow: (currentUser, objectId, kind) ->
kind? and currentUser.follow(objectId, kind)
ops = operations[action]
ops and ops(@currentUser, objectId, kind)
Cookies.expire 'afterSignUpAction'
# TODO: Follow up with <NAME> about this functionality
checkForPersonalizeFlash = ->
# Sometime '/personalize/' can exist as a redirect parameter in the URL.
# This causes the flash message to display at unexpected times.
# This ensures we check for personalize in the pathname.
if document.referrer.split('?')[0].match '^/personalize.*'
new FlashMessage message: 'Thank you for personalizing your profile'
| true | { globalClientSetup } = require '../../lib/global_client_setup'
HeaderView = require './header/view.coffee'
FooterView = require './footer/view.coffee'
CurrentUser = require '../../models/current_user.coffee'
FlashMessage = require '../flash/index.coffee'
Cookies = require 'cookies-js'
{ triggerMarketingModal } = require '../marketing_signup_modal/triggerMarketingModal.ts'
{ AuthIntent } = require "@artsy/cohesion"
module.exports = ->
globalClientSetup()
checkForAfterSignUpAction()
checkForPersonalizeFlash()
new HeaderView el: $('#main-layout-header')
new FooterView el: $('#main-layout-footer')
triggerMarketingModal(AuthIntent.viewFair, true)
checkForAfterSignUpAction = ->
currentUser = CurrentUser.orNull()
afterSignUpAction = Cookies.get 'afterSignUpAction'
if afterSignUpAction
return unless @currentUser
{ action, objectId, kind } = JSON.parse(afterSignUpAction)
operations =
save: (currentUser, objectId, kind) ->
currentUser.initializeDefaultArtworkCollection()
currentUser.defaultArtworkCollection().saveArtwork objectId
follow: (currentUser, objectId, kind) ->
kind? and currentUser.follow(objectId, kind)
ops = operations[action]
ops and ops(@currentUser, objectId, kind)
Cookies.expire 'afterSignUpAction'
# TODO: Follow up with PI:NAME:<NAME>END_PI about this functionality
checkForPersonalizeFlash = ->
# Sometime '/personalize/' can exist as a redirect parameter in the URL.
# This causes the flash message to display at unexpected times.
# This ensures we check for personalize in the pathname.
if document.referrer.split('?')[0].match '^/personalize.*'
new FlashMessage message: 'Thank you for personalizing your profile'
|
[
{
"context": "\n # The website author's email\n email: \"info@pencilcode.net\"\n\n # cache-busting timestamp\n timestamp",
"end": 609,
"score": 0.9999203681945801,
"start": 590,
"tag": "EMAIL",
"value": "info@pencilcode.net"
},
{
"context": "\n\n # Discus.com s... | docpad.coffee | cacticouncil/blog | 0 | # DocPad Configuration File
# http://docpad.org/docs/config
cheerio = require('cheerio')
url = require('url')
path = require('path')
# Define the DocPad Configuration
docpadConfig = {
srcPath: ''
ignorePaths: [path.join(process.cwd(), 'out')]
templateData:
# Specify some site properties
site:
# The production url of our website
url: "http://blog.pencilcode.net"
# The default title of our website
title: "Pencil Code Blog"
# The website author's name
author: "Pencil Code Foundation"
# The website author's email
email: "info@pencilcode.net"
# cache-busting timestamp
timestamp: new Date().getTime()
# -----------------------------
# Helper Functions
# Get the prepared site/document title
# Often we would like to specify particular formatting to our page's title
# we can apply that formatting here
getPreparedTitle: ->
# if we have a document title, then we should use that and suffix the site's title onto it
if @document.title
"#{@document.title} - #{@site.title}"
# if our document does not have it's own title, then we should just use the site's title
else
@site.title
getPageUrlWithHostname: ->
"#{@site.url}#{@document.url}"
getIdForDocument: (document) ->
hostname = url.parse(@site.url).hostname
date = document.date.toISOString().split('T')[0]
path = document.url
"tag:#{hostname},#{date},#{path}"
fixLinks: (content) ->
if not content? then return ''
baseUrl = @site.url
regex = /^(http|https|ftp|mailto):/
$ = cheerio.load(content)
$('img').each ->
$img = $(@)
src = $img.attr('src')
$img.attr('src', baseUrl + src) unless regex.test(src)
$('a').each ->
$a = $(@)
href = $a.attr('href')
$a.attr('href', baseUrl + href) unless regex.test(href)
$.html()
moment: require('moment')
# Discus.com settings
disqusShortName: 'pencilcode'
# Google+ settings
# googlePlusId: '?????'
getTagUrl: (tag) ->
slug = tag.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '')
"/tags/#{slug}/"
collections:
posts: ->
@getCollection('documents').findAllLive({relativeDirPath: 'posts'}, [date: -1])
cleanurls: ->
@getCollection('html').findAllLive(skipCleanUrls: $ne: true)
environments:
development:
collections:
posts: ->
@getCollection('documents').findAllLive({relativeDirPath: {'$in' : ['posts', 'drafts']}}, [relativeDirPath: 1, date: -1])
regenerateDelay: 1000
watchOptions:
interval: 2007
catchupDelay: 2000
preferredMethods: ['watchFile','watch']
plugins:
tags:
findCollectionName: 'posts'
extension: '.html'
injectDocumentHelper: (document) ->
document.setMeta(
layout: 'tags'
)
dateurls:
cleanurl: true
trailingSlashes: true
keepOriginalUrls: false
collectionName: 'posts'
dateIncludesTime: true
paged:
cleanurl: true
startingPageNumber: 2
cleanurls:
trailingSlashes: true
collectionName: 'cleanurls'
}
# Export the DocPad Configuration
module.exports = docpadConfig
| 180082 | # DocPad Configuration File
# http://docpad.org/docs/config
cheerio = require('cheerio')
url = require('url')
path = require('path')
# Define the DocPad Configuration
docpadConfig = {
srcPath: ''
ignorePaths: [path.join(process.cwd(), 'out')]
templateData:
# Specify some site properties
site:
# The production url of our website
url: "http://blog.pencilcode.net"
# The default title of our website
title: "Pencil Code Blog"
# The website author's name
author: "Pencil Code Foundation"
# The website author's email
email: "<EMAIL>"
# cache-busting timestamp
timestamp: new Date().getTime()
# -----------------------------
# Helper Functions
# Get the prepared site/document title
# Often we would like to specify particular formatting to our page's title
# we can apply that formatting here
getPreparedTitle: ->
# if we have a document title, then we should use that and suffix the site's title onto it
if @document.title
"#{@document.title} - #{@site.title}"
# if our document does not have it's own title, then we should just use the site's title
else
@site.title
getPageUrlWithHostname: ->
"#{@site.url}#{@document.url}"
getIdForDocument: (document) ->
hostname = url.parse(@site.url).hostname
date = document.date.toISOString().split('T')[0]
path = document.url
"tag:#{hostname},#{date},#{path}"
fixLinks: (content) ->
if not content? then return ''
baseUrl = @site.url
regex = /^(http|https|ftp|mailto):/
$ = cheerio.load(content)
$('img').each ->
$img = $(@)
src = $img.attr('src')
$img.attr('src', baseUrl + src) unless regex.test(src)
$('a').each ->
$a = $(@)
href = $a.attr('href')
$a.attr('href', baseUrl + href) unless regex.test(href)
$.html()
moment: require('moment')
# Discus.com settings
disqusShortName: 'pencilcode'
# Google+ settings
# googlePlusId: '?????'
getTagUrl: (tag) ->
slug = tag.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '')
"/tags/#{slug}/"
collections:
posts: ->
@getCollection('documents').findAllLive({relativeDirPath: 'posts'}, [date: -1])
cleanurls: ->
@getCollection('html').findAllLive(skipCleanUrls: $ne: true)
environments:
development:
collections:
posts: ->
@getCollection('documents').findAllLive({relativeDirPath: {'$in' : ['posts', 'drafts']}}, [relativeDirPath: 1, date: -1])
regenerateDelay: 1000
watchOptions:
interval: 2007
catchupDelay: 2000
preferredMethods: ['watchFile','watch']
plugins:
tags:
findCollectionName: 'posts'
extension: '.html'
injectDocumentHelper: (document) ->
document.setMeta(
layout: 'tags'
)
dateurls:
cleanurl: true
trailingSlashes: true
keepOriginalUrls: false
collectionName: 'posts'
dateIncludesTime: true
paged:
cleanurl: true
startingPageNumber: 2
cleanurls:
trailingSlashes: true
collectionName: 'cleanurls'
}
# Export the DocPad Configuration
module.exports = docpadConfig
| true | # DocPad Configuration File
# http://docpad.org/docs/config
cheerio = require('cheerio')
url = require('url')
path = require('path')
# Define the DocPad Configuration
docpadConfig = {
srcPath: ''
ignorePaths: [path.join(process.cwd(), 'out')]
templateData:
# Specify some site properties
site:
# The production url of our website
url: "http://blog.pencilcode.net"
# The default title of our website
title: "Pencil Code Blog"
# The website author's name
author: "Pencil Code Foundation"
# The website author's email
email: "PI:EMAIL:<EMAIL>END_PI"
# cache-busting timestamp
timestamp: new Date().getTime()
# -----------------------------
# Helper Functions
# Get the prepared site/document title
# Often we would like to specify particular formatting to our page's title
# we can apply that formatting here
getPreparedTitle: ->
# if we have a document title, then we should use that and suffix the site's title onto it
if @document.title
"#{@document.title} - #{@site.title}"
# if our document does not have it's own title, then we should just use the site's title
else
@site.title
getPageUrlWithHostname: ->
"#{@site.url}#{@document.url}"
getIdForDocument: (document) ->
hostname = url.parse(@site.url).hostname
date = document.date.toISOString().split('T')[0]
path = document.url
"tag:#{hostname},#{date},#{path}"
fixLinks: (content) ->
if not content? then return ''
baseUrl = @site.url
regex = /^(http|https|ftp|mailto):/
$ = cheerio.load(content)
$('img').each ->
$img = $(@)
src = $img.attr('src')
$img.attr('src', baseUrl + src) unless regex.test(src)
$('a').each ->
$a = $(@)
href = $a.attr('href')
$a.attr('href', baseUrl + href) unless regex.test(href)
$.html()
moment: require('moment')
# Discus.com settings
disqusShortName: 'pencilcode'
# Google+ settings
# googlePlusId: '?????'
getTagUrl: (tag) ->
slug = tag.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '')
"/tags/#{slug}/"
collections:
posts: ->
@getCollection('documents').findAllLive({relativeDirPath: 'posts'}, [date: -1])
cleanurls: ->
@getCollection('html').findAllLive(skipCleanUrls: $ne: true)
environments:
development:
collections:
posts: ->
@getCollection('documents').findAllLive({relativeDirPath: {'$in' : ['posts', 'drafts']}}, [relativeDirPath: 1, date: -1])
regenerateDelay: 1000
watchOptions:
interval: 2007
catchupDelay: 2000
preferredMethods: ['watchFile','watch']
plugins:
tags:
findCollectionName: 'posts'
extension: '.html'
injectDocumentHelper: (document) ->
document.setMeta(
layout: 'tags'
)
dateurls:
cleanurl: true
trailingSlashes: true
keepOriginalUrls: false
collectionName: 'posts'
dateIncludesTime: true
paged:
cleanurl: true
startingPageNumber: 2
cleanurls:
trailingSlashes: true
collectionName: 'cleanurls'
}
# Export the DocPad Configuration
module.exports = docpadConfig
|
[
{
"context": "><code>\"bugs\": {\n \"url\": \"https://github.com/owner/project/issues\",\n \"email\": \"project@hostname",
"end": 3605,
"score": 0.9649602174758911,
"start": 3600,
"tag": "USERNAME",
"value": "owner"
},
{
"context": "github.com/owner/project/issues\",\n ... | coffee/formats/package.coffee | jsoref/JSON.is | 271 | depInfo = (propertyName) -> """
<p>The format is <code>"PACKAGE_NAME": "VERSION"</code>, for example:</p>
<pre><code>"#{ propertyName }": {
"coffee-script": "1.6.1",
"gulp": "~3.6.2"
}</code></pre>
<p>Packages can be found using the <code>npm search</code> command, or on <a href="http://npmjs.com">npmjs.com</a>.</p>
<p>Version requirements are specified using <a href="http://ricostacruz.com/cheatsheets/semver.html">semver</a>.</p>
"""
context =
'': '''
<h4>package.json</h4>
<p>All npm packages contain a file, usually in the project root, called package.json - this file holds various metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies. It can also contain other metadata such as a project description, the version of the project in a particular distribution, license information, even configuration data - all of which can be vital to both npm and to the end users of the package. The package.json file is normally located at the root directory of a Node.js project.</p>
<pre><code>{
"name": "App",
"version": "1.3.0",
"main": "app.js",
"devDependencies": {
"dependencyOne": "~1.0.2",
"dependencyTwo": "~0.0.4"
}
}</code></pre>
'''
'name': '''
<h4>Name</h4>
<p>The name is what your thing is called.</p>
<p>Some rules:</p>
<ul>
<li>The name must be shorter than 214 characters. This includes the scope for scoped packages.
<li>The name can’t start with a dot or an underscore.
<li>New packages must not have uppercase letters in the name.
<li>The name ends up being part of a URL, an argument on the command line, and a folder name. Therefore, the name can’t contain any non-URL-safe characters.
</ul>
<p>Some tips:</p>
<ul>
<li>Don’t use the same name as a core Node module.
<li>Don’t put “js” or “node” in the name. It’s assumed that it’s js, since you’re writing a package.json file, and you can specify the engine using the “engines” field.
<li>The name will probably be passed as an argument to require(), so it should be something short, but also reasonably descriptive.
<li>You may want to check the <a href="https://npmjs.com">npm registry</a> to see if there’s something by that name already, before you get too attached to it.
</ul>
<p>A name can be optionally prefixed by a scope, e.g. <code>@myorg/mypackage</code>.</p>
'''
'version': '''
<h4>Version</h4>
<p>The version must be a <a href="http://ricostacruz.com/cheatsheets/semver.html">semver</a> version identifier. Changes to the package should come along with changes to the version.</p>
'''
'description': '''
<h4>Description</h4>
<p>The description should be a string of human-readable information about the package. It’s listed on <a href="https://npmjs.com">npmjs.com</a> and in the output of <code>npm search</code>.</p>
'''
'keywords(\.INDEX)?': '''
<h4>Keywords</h4>
<p>An array of strings which are used to help people find your package.</p>
'''
'homepage': '''
<h4>Homepage</h4>
<p>The URL of the project’s homepage, if it has one.</p>
'''
'bugs(\.PROPERTY)?': '''
<h4>Bugs</h4>
<p>The url to your project’s issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.</p>
<p>It should look like this:</p>
<pre><code>"bugs": {
"url": "https://github.com/owner/project/issues",
"email": "project@hostname.com"
}</code></pre>
<p>You can specify either one or both values. If you want to provide only a url, you can specify the value for “bugs” as a simple string instead of an object.</p>
<pre><code>"bugs": "https://github.com/owner/project/issues"</code></pre>
<p>If a url is provided, it will be used by the <code>npm bugs</code> command.</p>
'''
'license': '''
<h4>License</h4>
<p>You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it.</p>
<p>If you're using a common license such as BSD-2-Clause or MIT, add a current SPDX license identifier for the license you're using, like this:</p>
<pre><code>"license": "BSD-3-Clause"</code></pre>
<p>You can check <a href="https://spdx.org/licenses/">the full list of SPDX license IDs</a>.
<p>If your package is licensed under multiple common licenses, use an <a href="http://npmjs.com/package/spdx">SPDX license expression syntax version 2.0 string</a>, like this:</p>
<pre><code>"license": "(ISC OR GPL-3.0)"</code></pre>
<p>If you are using a license that hasn't been assigned an SPDX identifier, or if you are using a custom license, use the following valid SPDX expression:</p>
<pre><code>"license": "SEE LICENSE IN <filename>"</code></pre>
<p>Then include a file named <code><filename></code> at the top level of the package.</p>
<p>If you do not wish to grant others the right to use a private or unpublished package under any terms:</p>
<pre><code>"license": "UNLICENSED"</code></pre>
'''
'(author|contributors)': '''
<h4>Author / Contributors</h4>
<p>Who created and maintains this project? Provide a single person as the <code>author</code> field or an array of multiple people as the <code>contributors</code> field.</p>
<p>Each person may be described as with object:</p>
<pre><code>{
"name": "Barney Rubble",
"email": "b@rubble.com",
"url": "http://barnyrubble.tumblr.com/"
}</code></pre>
<p>Or a string:</p>
<pre><code>"Barney Rubble <b@rubble.com> (http://barnyrubble.tumblr.com/)"</code></pre>
<p>Only name is required, both email and url are optional.</p>
'''
'contributors\.INDEX': '''
<h4>Contributor</h4>
<p>Each contributor may be described as with object:</p>
<pre><code>{
"name": "Barney Rubble",
"email": "b@rubble.com",
"url": "http://barnyrubble.tumblr.com/"
}</code></pre>
<p>Or a string:</p>
<pre><code>"Barney Rubble <b@rubble.com> (http://barnyrubble.tumblr.com/)"</code></pre>
<p>Only name is required, both email and url are optional.</p>
'''
'files': '''
<h4>Files</h4>
<p>The files field allows you to provide an array of files and folders which should be uploaded to npm when this package is published.</p>
<p>You may use glob patterns like <code>*.js</code>, and specify folders like <code>src/</code>.</p>
<p>You can also provide a <code>.npmignore</code> file in the root of your package, which will keep files from being included, even if they would be picked up by the files array.</p>
'''
'files\.INDEX': '''
<h4>File</h4>
<p>Each file may be specified as the path to a file or folder, or with a glob pattern.</p>
<p>For example, <code>src/</code>, <code>README.md</code>, or <code>lib/*.js</code>.</p>
'''
'main': '''
<h4>Main</h4>
<p>The main field informs npm which file should be loaded when a user attempts to <code>require()</code> your package.</p>
<p>For example, if your package is called <code>app</code> and you specify the main property as <code>"main.js"</code>, when the user runs <code>require('app')</code>, your <code>main.js</code> file will be loaded.</p>
'''
'bin(\.PROPERTY)?': '''
<h4>Bin</h4>
<p><code>bin</code> allows you to install one or more executable files onto the <code>PATH</code> of this machine so they can be executed from the terminal.</p>
<p>For example, if you’d like your <code>cli.js</code> file to be executed when the user runs <code>myapp</code> on the command line, you could specify:</p>
<pre><code>"bin": { "myapp": "./cli.js" }</code></pre>
<p>If you only have a single executable, and you’d like the command line program to have the same name as your package, you can just specify the file to be executed as a string:</p>
<pre><code>"bin": "./path/to/program"</code></pre>
'''
'man': '''
<h4>Man</h4>
<p>The man program is used by many UNIX-y operating systems to help users access documentation. If you have one or more man pages for your project, specify them with the <code>man</code> option.</p>
<p>The option can either be specified as a single filepath, or as an array of files.</p>
'''
'repository(\.PROPERTY)?': '''
<h4>Repository</h4>
<p>Specify the place where your code lives.</p>
<p>For example:</p>
<pre><code>{
"type": "git",
"url": "https://github.com/npm/npm.git"
}</code></pre>
<p>The URL should be a publicly available (perhaps read-only) url that can be handed
directly to a VCS program without any modification. It should not be a url to an
html project page that you put in your browser. It’s for computers.</p>
<p>For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the same
shortcut syntax you use for <code>npm install</code>:</p>
<pre><code>"repository": "npm/npm"
"repository": "gist:11081aaa281"
"repository": "bitbucket:example/repo"
"repository": "gitlab:another/repo"
</code></pre>
'''
'scripts(\.PROPERTY)?': '''
<h4>Scripts</h4>
<p>Commands to be executed at various points in the package lifecycle.</p>
<p>The full list of lifecycle events you can target:</p>
<ul>
<li><code>prepublish</code>: Run BEFORE the package is published. (Also run on local npm install without any arguments.)
<li><code>publish</code>, <code>postpublish</code>: Run AFTER the package is published.
<li><code>preinstall</code>: Run BEFORE the package is installed
<li><code>install</code>, <code>postinstall</code>: Run AFTER the package is installed.
<li><code>preuninstall</code>, <code>uninstall</code>: Run BEFORE the package is uninstalled.
<li><code>postuninstall</code>: Run AFTER the package is uninstalled.
<li><code>preversion</code>, <code>version</code>: Run BEFORE bump the package version.
<li><code>postversion</code>: Run AFTER bump the package version.
<li><code>pretest</code>, <code>test</code>, <code>posttest</code>: Run by the npm test command.
<li><code>prestop</code>, <code>stop</code>, <code>poststop</code>: Run by the npm stop command.
<li><code>prestart</code>, <code>start</code>, <code>poststart</code>: Run by the npm start command.
<li><code>prerestart</code>, <code>restart</code>, <code>postrestart</code>: Run by the npm restart command. Note: npm restart will run the stop and start scripts if no restart script is provided.
</ul>
<p>The command can be any executable:</p>
<pre><code>"scripts": {
"prepublish": "rm -r build; gulp build"
}</code></pre>
<p>You can also create a script with any name you like, and run it with <code>npm run SCRIPT_NAME</code>.</p>
<p><a href="https://docs.npmjs.com/misc/scripts">More information</a> about scripts</p>
'''
'config(\.PROPERTY)?': '''
<h4>Config</h4>
<p>npm supports configuration variables which can be set by the user using <code>npm config</code>. The <code>config</code> option can be used to set defaults for these options.</p>
<p>Config variables are available as environment variables. For example, if you had the config:</p>
<pre><code>"config": {
"port": 8080
}</code></pre>
<p>It would be available as the <code>npm_package_config_port</code> environment variable in your scripts, and could be overrode by the user with:</p>
<pre><code>npm config set foo:port 8001</code></pre>
'''
'dependencies': '''
<h4>Dependencies</h4>
<p>Dependencies allow you to specify what other npm packages your code requires, and at which versions.</p>
''' + depInfo('dependencies')
'devDependencies': '''
<h4>Dev Dependencies</h4>
<p>Dev dependencies work exactly as <code>dependencies</code>, but they are not installed when a user installs your package without downloading the source (unless they provide the <code>--dev</code> option).</p>
<p>It often makes sense to include build and test tools as dev dependencies, so end users don’t have to install them if they aren't required to use the package.</p>
''' + depInfo('devDependencies')
'peerDependencies': '''
<h4>Peer Dependencies</h4>
<p>If you’re building a plugin which interacts with another package, it’s often valuable to express what versions of that package you support.</p>
<p>Peer dependencies allow you to express this compatibility. Be as broad as you can, as npm will error if the user tries to use your plugin with an incompatible version.</p>
''' + depInfo('peerDependencies')
'optionalDependencies': '''
<h4>Optional Dependencies</h4>
<p>If a package in <code>dependencies</code> fails to install, the installation of your package will be aborted. If you do not wish this to happen for some dependencies (i.e. your package can run without them), include them as optional dependencies.</p>
''' + depInfo('optionalDependencies')
'engines(\.PROPERTY)?': '''
<h4>Engines</h4>
<p><code>engines</code> allows you to specify which versions of node or npm this package works with.</p>
<p>For example:</p>
<pre><code>"engines": {
"node": ">=0.10.3 <0.12"
}</code></pre>
'''
'(dependencies|optionalDependencies|peerDependencies|devDependencies)\.PROPERTY': '''
<h4>Dependency</h4>
<p>A dependency specifies a package which this project utilizes. It is usually a package which is published to the npm registry, but it can also be anything hosted on the internet or even a local folder.</p>
<p>When using the npm registry, specify a package name and a version string:</p>
<pre><code>"vex": "1.4.3"</code></pre>
<p>The version string should use <a href="http://ricostacruz.com/cheatsheets/semver.html">semver</a>. You can use <code><</code> and <code>></code> to specify ranges, for example:
<pre><code>"vex": ">1.2.3 <2.0.0"</code></pre>
The <code>~</code> and <code>^</code> shorthands are also available:
<pre><code>~1.2.3 : is >=1.2.3 <1.3.0
^1.2.3 : is >=1.2.3 <2.0.0
^0.2.3 : is >=0.2.3 <0.3.0 (0.x.x is special)
^0.0.1 : is =0.0.1 (0.0.x is special)
</code></pre>
<p>In the version field you can also specify:</p>
<ul>
<li>The URL to a tarball
<li>The URL to a git repo: <code>git://github.com/user/project.git#commit</code>
<li>A GitHub repo: <code>visionmedia/mocha#4727d357ea</code>
</ul>
<p>As in those examples, it’s usually a good idea to specify a specific commit or tag when using git URLs (by appending the identifier after the “#” symbol).</p>
'''
'bundledDependencies(\.INDEX)?': '''
<h4>Bundled Dependencies</h4>
<p>Occasionally it’s helpful to include a local copy of a dependency (it’s folder in <code>node_modules/</code>) with the project when it’s published.</p>
<p>Bundled dependencies are specified as an array of package names, like:</p>
<pre><code>["gulp", "gulp-concat"]</code></pre>
<p>Note that another option is to fork the package and refer to it using a git URL.</p>
'''
'os(\.INDEX)?': '''
<h4>OS</h4>
<p><code>os</code> allows you to specify which operating systems your package will run on.</p>
<p>You can specify a list of OS’ it works on:</p>
<pre><code>["darwin", "linux"]</code></pre>
<p>Or a list it doesn’t work on:</p>
<pre><code>["!win32"]</code></pre>
<p>The current host operating system is provided by <code>process.platform</code></p>
'''
'cpu(\.INDEX)?': '''
<h4>CPU</h4>
<p><code>CPU</code> allows you to specify which processor architectures your package will run on.</p>
<p>You can specify a list of architectures it works on:</p>
<pre><code>["x64", "ia32"]</code></pre>
<p>Or a list it doesn’t work on:</p>
<pre><code>["!mips"]</code></pre>
<p>The current architecture is provided by <code>process.arch</code></p>
'''
'preferGlobal': '''
<h4>Prefer Global</h4>
<p>If your package is primarily a command-line application that should be installed globally, then set this value to <code>true</code> to provide a warning if it is installed locally.</p>
'''
'private': '''
<h4>Private</h4>
<p>If you set <code>"private": true</code> in your package.json, then npm will refuse to publish it.</p>
<p>This is a way to prevent accidental publication of private repositories. If you would like to ensure that a given package is only ever published to a specific registry (for example, an internal registry), then use the <code>publishConfig</code> dictionary to specify the registry.</p>
'''
'publishConfig': '''
<h4>Publish Config</h4>
<p>This is a set of config values that will be used at publish-time. It’s especially handy if you want to set the tag or registry, so that you can ensure that a given package is not tagged with “latest” or published to the global public registry by default.</p>
<p>See <code>npm help config</code> to see the list of config options that can be overridden.</p>
'''
# Browserify
'browser': '''
<h4>Browser</h4>
<p><em><a href="https://github.com/substack/node-browserify">Browserify</a> specific</em></p>
<p>The <code>browser</code> field allows you to specify browser-specific versions of your files. Rather than your <code>main</code> file, you might wish to have browserify use a different entry point when this module is bundled for the browser:</p>
<pre><code>"browser": "./browser.js"<code></pre>
<p>You can also override multiple files:</p>
<pre><code>"browser": {
"fs": "level-fs",
"./lib/ops.js": "./browser/opts.js"
}
</code></pre>
'''
'browserify\.transform(\.INDEX)?': '''
<h4>Transform</h4>
<p><em><a href="http://browserify.org/">Browserify</a> specific</em></p>
<p>Transforms are applied to your modules during the Browserify bundling process. You can use them to do things like <a href="https://www.npmjs.com/package/brfs">include file contents</a> or <a href="https://github.com/jnordberg/coffeeify">compile CoffeeScript</a>.</p>
<p>For example, to enable the <code>brfs</code> transform:</p>
<pre><code>"browserify": {"transform": ["brfs"]}</code></pre>
<p>Be sure to include the necessary module in your <code>dependencies</code> or <code>devDependencies</code> as well.</p>
'''
'browserify': '''
<h4>Browserify</h4>
<p>The <code>browserify</code> section allows you to provide specific configuration to the <a href="http://browserify.org/">Browserify</a> bundler.</p>
<pre><code>"browserify": {
"transform": [
"coffeeify"
]
},
</code></pre>
'''
module.exports = context
| 74234 | depInfo = (propertyName) -> """
<p>The format is <code>"PACKAGE_NAME": "VERSION"</code>, for example:</p>
<pre><code>"#{ propertyName }": {
"coffee-script": "1.6.1",
"gulp": "~3.6.2"
}</code></pre>
<p>Packages can be found using the <code>npm search</code> command, or on <a href="http://npmjs.com">npmjs.com</a>.</p>
<p>Version requirements are specified using <a href="http://ricostacruz.com/cheatsheets/semver.html">semver</a>.</p>
"""
context =
'': '''
<h4>package.json</h4>
<p>All npm packages contain a file, usually in the project root, called package.json - this file holds various metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies. It can also contain other metadata such as a project description, the version of the project in a particular distribution, license information, even configuration data - all of which can be vital to both npm and to the end users of the package. The package.json file is normally located at the root directory of a Node.js project.</p>
<pre><code>{
"name": "App",
"version": "1.3.0",
"main": "app.js",
"devDependencies": {
"dependencyOne": "~1.0.2",
"dependencyTwo": "~0.0.4"
}
}</code></pre>
'''
'name': '''
<h4>Name</h4>
<p>The name is what your thing is called.</p>
<p>Some rules:</p>
<ul>
<li>The name must be shorter than 214 characters. This includes the scope for scoped packages.
<li>The name can’t start with a dot or an underscore.
<li>New packages must not have uppercase letters in the name.
<li>The name ends up being part of a URL, an argument on the command line, and a folder name. Therefore, the name can’t contain any non-URL-safe characters.
</ul>
<p>Some tips:</p>
<ul>
<li>Don’t use the same name as a core Node module.
<li>Don’t put “js” or “node” in the name. It’s assumed that it’s js, since you’re writing a package.json file, and you can specify the engine using the “engines” field.
<li>The name will probably be passed as an argument to require(), so it should be something short, but also reasonably descriptive.
<li>You may want to check the <a href="https://npmjs.com">npm registry</a> to see if there’s something by that name already, before you get too attached to it.
</ul>
<p>A name can be optionally prefixed by a scope, e.g. <code>@myorg/mypackage</code>.</p>
'''
'version': '''
<h4>Version</h4>
<p>The version must be a <a href="http://ricostacruz.com/cheatsheets/semver.html">semver</a> version identifier. Changes to the package should come along with changes to the version.</p>
'''
'description': '''
<h4>Description</h4>
<p>The description should be a string of human-readable information about the package. It’s listed on <a href="https://npmjs.com">npmjs.com</a> and in the output of <code>npm search</code>.</p>
'''
'keywords(\.INDEX)?': '''
<h4>Keywords</h4>
<p>An array of strings which are used to help people find your package.</p>
'''
'homepage': '''
<h4>Homepage</h4>
<p>The URL of the project’s homepage, if it has one.</p>
'''
'bugs(\.PROPERTY)?': '''
<h4>Bugs</h4>
<p>The url to your project’s issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.</p>
<p>It should look like this:</p>
<pre><code>"bugs": {
"url": "https://github.com/owner/project/issues",
"email": "<EMAIL>"
}</code></pre>
<p>You can specify either one or both values. If you want to provide only a url, you can specify the value for “bugs” as a simple string instead of an object.</p>
<pre><code>"bugs": "https://github.com/owner/project/issues"</code></pre>
<p>If a url is provided, it will be used by the <code>npm bugs</code> command.</p>
'''
'license': '''
<h4>License</h4>
<p>You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it.</p>
<p>If you're using a common license such as BSD-2-Clause or MIT, add a current SPDX license identifier for the license you're using, like this:</p>
<pre><code>"license": "BSD-3-Clause"</code></pre>
<p>You can check <a href="https://spdx.org/licenses/">the full list of SPDX license IDs</a>.
<p>If your package is licensed under multiple common licenses, use an <a href="http://npmjs.com/package/spdx">SPDX license expression syntax version 2.0 string</a>, like this:</p>
<pre><code>"license": "(ISC OR GPL-3.0)"</code></pre>
<p>If you are using a license that hasn't been assigned an SPDX identifier, or if you are using a custom license, use the following valid SPDX expression:</p>
<pre><code>"license": "SEE LICENSE IN <filename>"</code></pre>
<p>Then include a file named <code><filename></code> at the top level of the package.</p>
<p>If you do not wish to grant others the right to use a private or unpublished package under any terms:</p>
<pre><code>"license": "UNLICENSED"</code></pre>
'''
'(author|contributors)': '''
<h4>Author / Contributors</h4>
<p>Who created and maintains this project? Provide a single person as the <code>author</code> field or an array of multiple people as the <code>contributors</code> field.</p>
<p>Each person may be described as with object:</p>
<pre><code>{
"name": "<NAME>",
"email": "<EMAIL>",
"url": "http://barnyrubble.tumblr.com/"
}</code></pre>
<p>Or a string:</p>
<pre><code>"<NAME> <<EMAIL>> (http://barnyrubble.tumblr.com/)"</code></pre>
<p>Only name is required, both email and url are optional.</p>
'''
'contributors\.INDEX': '''
<h4>Contributor</h4>
<p>Each contributor may be described as with object:</p>
<pre><code>{
"name": "<NAME>",
"email": "<EMAIL>",
"url": "http://barnyrubble.tumblr.com/"
}</code></pre>
<p>Or a string:</p>
<pre><code>"<NAME> <<EMAIL>> (http://barnyrubble.tumblr.com/)"</code></pre>
<p>Only name is required, both email and url are optional.</p>
'''
'files': '''
<h4>Files</h4>
<p>The files field allows you to provide an array of files and folders which should be uploaded to npm when this package is published.</p>
<p>You may use glob patterns like <code>*.js</code>, and specify folders like <code>src/</code>.</p>
<p>You can also provide a <code>.npmignore</code> file in the root of your package, which will keep files from being included, even if they would be picked up by the files array.</p>
'''
'files\.INDEX': '''
<h4>File</h4>
<p>Each file may be specified as the path to a file or folder, or with a glob pattern.</p>
<p>For example, <code>src/</code>, <code>README.md</code>, or <code>lib/*.js</code>.</p>
'''
'main': '''
<h4>Main</h4>
<p>The main field informs npm which file should be loaded when a user attempts to <code>require()</code> your package.</p>
<p>For example, if your package is called <code>app</code> and you specify the main property as <code>"main.js"</code>, when the user runs <code>require('app')</code>, your <code>main.js</code> file will be loaded.</p>
'''
'bin(\.PROPERTY)?': '''
<h4>Bin</h4>
<p><code>bin</code> allows you to install one or more executable files onto the <code>PATH</code> of this machine so they can be executed from the terminal.</p>
<p>For example, if you’d like your <code>cli.js</code> file to be executed when the user runs <code>myapp</code> on the command line, you could specify:</p>
<pre><code>"bin": { "myapp": "./cli.js" }</code></pre>
<p>If you only have a single executable, and you’d like the command line program to have the same name as your package, you can just specify the file to be executed as a string:</p>
<pre><code>"bin": "./path/to/program"</code></pre>
'''
'man': '''
<h4>Man</h4>
<p>The man program is used by many UNIX-y operating systems to help users access documentation. If you have one or more man pages for your project, specify them with the <code>man</code> option.</p>
<p>The option can either be specified as a single filepath, or as an array of files.</p>
'''
'repository(\.PROPERTY)?': '''
<h4>Repository</h4>
<p>Specify the place where your code lives.</p>
<p>For example:</p>
<pre><code>{
"type": "git",
"url": "https://github.com/npm/npm.git"
}</code></pre>
<p>The URL should be a publicly available (perhaps read-only) url that can be handed
directly to a VCS program without any modification. It should not be a url to an
html project page that you put in your browser. It’s for computers.</p>
<p>For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the same
shortcut syntax you use for <code>npm install</code>:</p>
<pre><code>"repository": "npm/npm"
"repository": "gist:11081aaa281"
"repository": "bitbucket:example/repo"
"repository": "gitlab:another/repo"
</code></pre>
'''
'scripts(\.PROPERTY)?': '''
<h4>Scripts</h4>
<p>Commands to be executed at various points in the package lifecycle.</p>
<p>The full list of lifecycle events you can target:</p>
<ul>
<li><code>prepublish</code>: Run BEFORE the package is published. (Also run on local npm install without any arguments.)
<li><code>publish</code>, <code>postpublish</code>: Run AFTER the package is published.
<li><code>preinstall</code>: Run BEFORE the package is installed
<li><code>install</code>, <code>postinstall</code>: Run AFTER the package is installed.
<li><code>preuninstall</code>, <code>uninstall</code>: Run BEFORE the package is uninstalled.
<li><code>postuninstall</code>: Run AFTER the package is uninstalled.
<li><code>preversion</code>, <code>version</code>: Run BEFORE bump the package version.
<li><code>postversion</code>: Run AFTER bump the package version.
<li><code>pretest</code>, <code>test</code>, <code>posttest</code>: Run by the npm test command.
<li><code>prestop</code>, <code>stop</code>, <code>poststop</code>: Run by the npm stop command.
<li><code>prestart</code>, <code>start</code>, <code>poststart</code>: Run by the npm start command.
<li><code>prerestart</code>, <code>restart</code>, <code>postrestart</code>: Run by the npm restart command. Note: npm restart will run the stop and start scripts if no restart script is provided.
</ul>
<p>The command can be any executable:</p>
<pre><code>"scripts": {
"prepublish": "rm -r build; gulp build"
}</code></pre>
<p>You can also create a script with any name you like, and run it with <code>npm run SCRIPT_NAME</code>.</p>
<p><a href="https://docs.npmjs.com/misc/scripts">More information</a> about scripts</p>
'''
'config(\.PROPERTY)?': '''
<h4>Config</h4>
<p>npm supports configuration variables which can be set by the user using <code>npm config</code>. The <code>config</code> option can be used to set defaults for these options.</p>
<p>Config variables are available as environment variables. For example, if you had the config:</p>
<pre><code>"config": {
"port": 8080
}</code></pre>
<p>It would be available as the <code>npm_package_config_port</code> environment variable in your scripts, and could be overrode by the user with:</p>
<pre><code>npm config set foo:port 8001</code></pre>
'''
'dependencies': '''
<h4>Dependencies</h4>
<p>Dependencies allow you to specify what other npm packages your code requires, and at which versions.</p>
''' + depInfo('dependencies')
'devDependencies': '''
<h4>Dev Dependencies</h4>
<p>Dev dependencies work exactly as <code>dependencies</code>, but they are not installed when a user installs your package without downloading the source (unless they provide the <code>--dev</code> option).</p>
<p>It often makes sense to include build and test tools as dev dependencies, so end users don’t have to install them if they aren't required to use the package.</p>
''' + depInfo('devDependencies')
'peerDependencies': '''
<h4>Peer Dependencies</h4>
<p>If you’re building a plugin which interacts with another package, it’s often valuable to express what versions of that package you support.</p>
<p>Peer dependencies allow you to express this compatibility. Be as broad as you can, as npm will error if the user tries to use your plugin with an incompatible version.</p>
''' + depInfo('peerDependencies')
'optionalDependencies': '''
<h4>Optional Dependencies</h4>
<p>If a package in <code>dependencies</code> fails to install, the installation of your package will be aborted. If you do not wish this to happen for some dependencies (i.e. your package can run without them), include them as optional dependencies.</p>
''' + depInfo('optionalDependencies')
'engines(\.PROPERTY)?': '''
<h4>Engines</h4>
<p><code>engines</code> allows you to specify which versions of node or npm this package works with.</p>
<p>For example:</p>
<pre><code>"engines": {
"node": ">=0.10.3 <0.12"
}</code></pre>
'''
'(dependencies|optionalDependencies|peerDependencies|devDependencies)\.PROPERTY': '''
<h4>Dependency</h4>
<p>A dependency specifies a package which this project utilizes. It is usually a package which is published to the npm registry, but it can also be anything hosted on the internet or even a local folder.</p>
<p>When using the npm registry, specify a package name and a version string:</p>
<pre><code>"vex": "1.4.3"</code></pre>
<p>The version string should use <a href="http://ricostacruz.com/cheatsheets/semver.html">semver</a>. You can use <code><</code> and <code>></code> to specify ranges, for example:
<pre><code>"vex": ">1.2.3 <2.0.0"</code></pre>
The <code>~</code> and <code>^</code> shorthands are also available:
<pre><code>~1.2.3 : is >=1.2.3 <1.3.0
^1.2.3 : is >=1.2.3 <2.0.0
^0.2.3 : is >=0.2.3 <0.3.0 (0.x.x is special)
^0.0.1 : is =0.0.1 (0.0.x is special)
</code></pre>
<p>In the version field you can also specify:</p>
<ul>
<li>The URL to a tarball
<li>The URL to a git repo: <code>git://github.com/user/project.git#commit</code>
<li>A GitHub repo: <code>visionmedia/mocha#4727d357ea</code>
</ul>
<p>As in those examples, it’s usually a good idea to specify a specific commit or tag when using git URLs (by appending the identifier after the “#” symbol).</p>
'''
'bundledDependencies(\.INDEX)?': '''
<h4>Bundled Dependencies</h4>
<p>Occasionally it’s helpful to include a local copy of a dependency (it’s folder in <code>node_modules/</code>) with the project when it’s published.</p>
<p>Bundled dependencies are specified as an array of package names, like:</p>
<pre><code>["gulp", "gulp-concat"]</code></pre>
<p>Note that another option is to fork the package and refer to it using a git URL.</p>
'''
'os(\.INDEX)?': '''
<h4>OS</h4>
<p><code>os</code> allows you to specify which operating systems your package will run on.</p>
<p>You can specify a list of OS’ it works on:</p>
<pre><code>["darwin", "linux"]</code></pre>
<p>Or a list it doesn’t work on:</p>
<pre><code>["!win32"]</code></pre>
<p>The current host operating system is provided by <code>process.platform</code></p>
'''
'cpu(\.INDEX)?': '''
<h4>CPU</h4>
<p><code>CPU</code> allows you to specify which processor architectures your package will run on.</p>
<p>You can specify a list of architectures it works on:</p>
<pre><code>["x64", "ia32"]</code></pre>
<p>Or a list it doesn’t work on:</p>
<pre><code>["!mips"]</code></pre>
<p>The current architecture is provided by <code>process.arch</code></p>
'''
'preferGlobal': '''
<h4>Prefer Global</h4>
<p>If your package is primarily a command-line application that should be installed globally, then set this value to <code>true</code> to provide a warning if it is installed locally.</p>
'''
'private': '''
<h4>Private</h4>
<p>If you set <code>"private": true</code> in your package.json, then npm will refuse to publish it.</p>
<p>This is a way to prevent accidental publication of private repositories. If you would like to ensure that a given package is only ever published to a specific registry (for example, an internal registry), then use the <code>publishConfig</code> dictionary to specify the registry.</p>
'''
'publishConfig': '''
<h4>Publish Config</h4>
<p>This is a set of config values that will be used at publish-time. It’s especially handy if you want to set the tag or registry, so that you can ensure that a given package is not tagged with “latest” or published to the global public registry by default.</p>
<p>See <code>npm help config</code> to see the list of config options that can be overridden.</p>
'''
# Browserify
'browser': '''
<h4>Browser</h4>
<p><em><a href="https://github.com/substack/node-browserify">Browserify</a> specific</em></p>
<p>The <code>browser</code> field allows you to specify browser-specific versions of your files. Rather than your <code>main</code> file, you might wish to have browserify use a different entry point when this module is bundled for the browser:</p>
<pre><code>"browser": "./browser.js"<code></pre>
<p>You can also override multiple files:</p>
<pre><code>"browser": {
"fs": "level-fs",
"./lib/ops.js": "./browser/opts.js"
}
</code></pre>
'''
'browserify\.transform(\.INDEX)?': '''
<h4>Transform</h4>
<p><em><a href="http://browserify.org/">Browserify</a> specific</em></p>
<p>Transforms are applied to your modules during the Browserify bundling process. You can use them to do things like <a href="https://www.npmjs.com/package/brfs">include file contents</a> or <a href="https://github.com/jnordberg/coffeeify">compile CoffeeScript</a>.</p>
<p>For example, to enable the <code>brfs</code> transform:</p>
<pre><code>"browserify": {"transform": ["brfs"]}</code></pre>
<p>Be sure to include the necessary module in your <code>dependencies</code> or <code>devDependencies</code> as well.</p>
'''
'browserify': '''
<h4>Browserify</h4>
<p>The <code>browserify</code> section allows you to provide specific configuration to the <a href="http://browserify.org/">Browserify</a> bundler.</p>
<pre><code>"browserify": {
"transform": [
"coffeeify"
]
},
</code></pre>
'''
module.exports = context
| true | depInfo = (propertyName) -> """
<p>The format is <code>"PACKAGE_NAME": "VERSION"</code>, for example:</p>
<pre><code>"#{ propertyName }": {
"coffee-script": "1.6.1",
"gulp": "~3.6.2"
}</code></pre>
<p>Packages can be found using the <code>npm search</code> command, or on <a href="http://npmjs.com">npmjs.com</a>.</p>
<p>Version requirements are specified using <a href="http://ricostacruz.com/cheatsheets/semver.html">semver</a>.</p>
"""
context =
'': '''
<h4>package.json</h4>
<p>All npm packages contain a file, usually in the project root, called package.json - this file holds various metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies. It can also contain other metadata such as a project description, the version of the project in a particular distribution, license information, even configuration data - all of which can be vital to both npm and to the end users of the package. The package.json file is normally located at the root directory of a Node.js project.</p>
<pre><code>{
"name": "App",
"version": "1.3.0",
"main": "app.js",
"devDependencies": {
"dependencyOne": "~1.0.2",
"dependencyTwo": "~0.0.4"
}
}</code></pre>
'''
'name': '''
<h4>Name</h4>
<p>The name is what your thing is called.</p>
<p>Some rules:</p>
<ul>
<li>The name must be shorter than 214 characters. This includes the scope for scoped packages.
<li>The name can’t start with a dot or an underscore.
<li>New packages must not have uppercase letters in the name.
<li>The name ends up being part of a URL, an argument on the command line, and a folder name. Therefore, the name can’t contain any non-URL-safe characters.
</ul>
<p>Some tips:</p>
<ul>
<li>Don’t use the same name as a core Node module.
<li>Don’t put “js” or “node” in the name. It’s assumed that it’s js, since you’re writing a package.json file, and you can specify the engine using the “engines” field.
<li>The name will probably be passed as an argument to require(), so it should be something short, but also reasonably descriptive.
<li>You may want to check the <a href="https://npmjs.com">npm registry</a> to see if there’s something by that name already, before you get too attached to it.
</ul>
<p>A name can be optionally prefixed by a scope, e.g. <code>@myorg/mypackage</code>.</p>
'''
'version': '''
<h4>Version</h4>
<p>The version must be a <a href="http://ricostacruz.com/cheatsheets/semver.html">semver</a> version identifier. Changes to the package should come along with changes to the version.</p>
'''
'description': '''
<h4>Description</h4>
<p>The description should be a string of human-readable information about the package. It’s listed on <a href="https://npmjs.com">npmjs.com</a> and in the output of <code>npm search</code>.</p>
'''
'keywords(\.INDEX)?': '''
<h4>Keywords</h4>
<p>An array of strings which are used to help people find your package.</p>
'''
'homepage': '''
<h4>Homepage</h4>
<p>The URL of the project’s homepage, if it has one.</p>
'''
'bugs(\.PROPERTY)?': '''
<h4>Bugs</h4>
<p>The url to your project’s issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.</p>
<p>It should look like this:</p>
<pre><code>"bugs": {
"url": "https://github.com/owner/project/issues",
"email": "PI:EMAIL:<EMAIL>END_PI"
}</code></pre>
<p>You can specify either one or both values. If you want to provide only a url, you can specify the value for “bugs” as a simple string instead of an object.</p>
<pre><code>"bugs": "https://github.com/owner/project/issues"</code></pre>
<p>If a url is provided, it will be used by the <code>npm bugs</code> command.</p>
'''
'license': '''
<h4>License</h4>
<p>You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it.</p>
<p>If you're using a common license such as BSD-2-Clause or MIT, add a current SPDX license identifier for the license you're using, like this:</p>
<pre><code>"license": "BSD-3-Clause"</code></pre>
<p>You can check <a href="https://spdx.org/licenses/">the full list of SPDX license IDs</a>.
<p>If your package is licensed under multiple common licenses, use an <a href="http://npmjs.com/package/spdx">SPDX license expression syntax version 2.0 string</a>, like this:</p>
<pre><code>"license": "(ISC OR GPL-3.0)"</code></pre>
<p>If you are using a license that hasn't been assigned an SPDX identifier, or if you are using a custom license, use the following valid SPDX expression:</p>
<pre><code>"license": "SEE LICENSE IN <filename>"</code></pre>
<p>Then include a file named <code><filename></code> at the top level of the package.</p>
<p>If you do not wish to grant others the right to use a private or unpublished package under any terms:</p>
<pre><code>"license": "UNLICENSED"</code></pre>
'''
'(author|contributors)': '''
<h4>Author / Contributors</h4>
<p>Who created and maintains this project? Provide a single person as the <code>author</code> field or an array of multiple people as the <code>contributors</code> field.</p>
<p>Each person may be described as with object:</p>
<pre><code>{
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI",
"url": "http://barnyrubble.tumblr.com/"
}</code></pre>
<p>Or a string:</p>
<pre><code>"PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (http://barnyrubble.tumblr.com/)"</code></pre>
<p>Only name is required, both email and url are optional.</p>
'''
'contributors\.INDEX': '''
<h4>Contributor</h4>
<p>Each contributor may be described as with object:</p>
<pre><code>{
"name": "PI:NAME:<NAME>END_PI",
"email": "PI:EMAIL:<EMAIL>END_PI",
"url": "http://barnyrubble.tumblr.com/"
}</code></pre>
<p>Or a string:</p>
<pre><code>"PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (http://barnyrubble.tumblr.com/)"</code></pre>
<p>Only name is required, both email and url are optional.</p>
'''
'files': '''
<h4>Files</h4>
<p>The files field allows you to provide an array of files and folders which should be uploaded to npm when this package is published.</p>
<p>You may use glob patterns like <code>*.js</code>, and specify folders like <code>src/</code>.</p>
<p>You can also provide a <code>.npmignore</code> file in the root of your package, which will keep files from being included, even if they would be picked up by the files array.</p>
'''
'files\.INDEX': '''
<h4>File</h4>
<p>Each file may be specified as the path to a file or folder, or with a glob pattern.</p>
<p>For example, <code>src/</code>, <code>README.md</code>, or <code>lib/*.js</code>.</p>
'''
'main': '''
<h4>Main</h4>
<p>The main field informs npm which file should be loaded when a user attempts to <code>require()</code> your package.</p>
<p>For example, if your package is called <code>app</code> and you specify the main property as <code>"main.js"</code>, when the user runs <code>require('app')</code>, your <code>main.js</code> file will be loaded.</p>
'''
'bin(\.PROPERTY)?': '''
<h4>Bin</h4>
<p><code>bin</code> allows you to install one or more executable files onto the <code>PATH</code> of this machine so they can be executed from the terminal.</p>
<p>For example, if you’d like your <code>cli.js</code> file to be executed when the user runs <code>myapp</code> on the command line, you could specify:</p>
<pre><code>"bin": { "myapp": "./cli.js" }</code></pre>
<p>If you only have a single executable, and you’d like the command line program to have the same name as your package, you can just specify the file to be executed as a string:</p>
<pre><code>"bin": "./path/to/program"</code></pre>
'''
'man': '''
<h4>Man</h4>
<p>The man program is used by many UNIX-y operating systems to help users access documentation. If you have one or more man pages for your project, specify them with the <code>man</code> option.</p>
<p>The option can either be specified as a single filepath, or as an array of files.</p>
'''
'repository(\.PROPERTY)?': '''
<h4>Repository</h4>
<p>Specify the place where your code lives.</p>
<p>For example:</p>
<pre><code>{
"type": "git",
"url": "https://github.com/npm/npm.git"
}</code></pre>
<p>The URL should be a publicly available (perhaps read-only) url that can be handed
directly to a VCS program without any modification. It should not be a url to an
html project page that you put in your browser. It’s for computers.</p>
<p>For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the same
shortcut syntax you use for <code>npm install</code>:</p>
<pre><code>"repository": "npm/npm"
"repository": "gist:11081aaa281"
"repository": "bitbucket:example/repo"
"repository": "gitlab:another/repo"
</code></pre>
'''
'scripts(\.PROPERTY)?': '''
<h4>Scripts</h4>
<p>Commands to be executed at various points in the package lifecycle.</p>
<p>The full list of lifecycle events you can target:</p>
<ul>
<li><code>prepublish</code>: Run BEFORE the package is published. (Also run on local npm install without any arguments.)
<li><code>publish</code>, <code>postpublish</code>: Run AFTER the package is published.
<li><code>preinstall</code>: Run BEFORE the package is installed
<li><code>install</code>, <code>postinstall</code>: Run AFTER the package is installed.
<li><code>preuninstall</code>, <code>uninstall</code>: Run BEFORE the package is uninstalled.
<li><code>postuninstall</code>: Run AFTER the package is uninstalled.
<li><code>preversion</code>, <code>version</code>: Run BEFORE bump the package version.
<li><code>postversion</code>: Run AFTER bump the package version.
<li><code>pretest</code>, <code>test</code>, <code>posttest</code>: Run by the npm test command.
<li><code>prestop</code>, <code>stop</code>, <code>poststop</code>: Run by the npm stop command.
<li><code>prestart</code>, <code>start</code>, <code>poststart</code>: Run by the npm start command.
<li><code>prerestart</code>, <code>restart</code>, <code>postrestart</code>: Run by the npm restart command. Note: npm restart will run the stop and start scripts if no restart script is provided.
</ul>
<p>The command can be any executable:</p>
<pre><code>"scripts": {
"prepublish": "rm -r build; gulp build"
}</code></pre>
<p>You can also create a script with any name you like, and run it with <code>npm run SCRIPT_NAME</code>.</p>
<p><a href="https://docs.npmjs.com/misc/scripts">More information</a> about scripts</p>
'''
'config(\.PROPERTY)?': '''
<h4>Config</h4>
<p>npm supports configuration variables which can be set by the user using <code>npm config</code>. The <code>config</code> option can be used to set defaults for these options.</p>
<p>Config variables are available as environment variables. For example, if you had the config:</p>
<pre><code>"config": {
"port": 8080
}</code></pre>
<p>It would be available as the <code>npm_package_config_port</code> environment variable in your scripts, and could be overrode by the user with:</p>
<pre><code>npm config set foo:port 8001</code></pre>
'''
'dependencies': '''
<h4>Dependencies</h4>
<p>Dependencies allow you to specify what other npm packages your code requires, and at which versions.</p>
''' + depInfo('dependencies')
'devDependencies': '''
<h4>Dev Dependencies</h4>
<p>Dev dependencies work exactly as <code>dependencies</code>, but they are not installed when a user installs your package without downloading the source (unless they provide the <code>--dev</code> option).</p>
<p>It often makes sense to include build and test tools as dev dependencies, so end users don’t have to install them if they aren't required to use the package.</p>
''' + depInfo('devDependencies')
'peerDependencies': '''
<h4>Peer Dependencies</h4>
<p>If you’re building a plugin which interacts with another package, it’s often valuable to express what versions of that package you support.</p>
<p>Peer dependencies allow you to express this compatibility. Be as broad as you can, as npm will error if the user tries to use your plugin with an incompatible version.</p>
''' + depInfo('peerDependencies')
'optionalDependencies': '''
<h4>Optional Dependencies</h4>
<p>If a package in <code>dependencies</code> fails to install, the installation of your package will be aborted. If you do not wish this to happen for some dependencies (i.e. your package can run without them), include them as optional dependencies.</p>
''' + depInfo('optionalDependencies')
'engines(\.PROPERTY)?': '''
<h4>Engines</h4>
<p><code>engines</code> allows you to specify which versions of node or npm this package works with.</p>
<p>For example:</p>
<pre><code>"engines": {
"node": ">=0.10.3 <0.12"
}</code></pre>
'''
'(dependencies|optionalDependencies|peerDependencies|devDependencies)\.PROPERTY': '''
<h4>Dependency</h4>
<p>A dependency specifies a package which this project utilizes. It is usually a package which is published to the npm registry, but it can also be anything hosted on the internet or even a local folder.</p>
<p>When using the npm registry, specify a package name and a version string:</p>
<pre><code>"vex": "1.4.3"</code></pre>
<p>The version string should use <a href="http://ricostacruz.com/cheatsheets/semver.html">semver</a>. You can use <code><</code> and <code>></code> to specify ranges, for example:
<pre><code>"vex": ">1.2.3 <2.0.0"</code></pre>
The <code>~</code> and <code>^</code> shorthands are also available:
<pre><code>~1.2.3 : is >=1.2.3 <1.3.0
^1.2.3 : is >=1.2.3 <2.0.0
^0.2.3 : is >=0.2.3 <0.3.0 (0.x.x is special)
^0.0.1 : is =0.0.1 (0.0.x is special)
</code></pre>
<p>In the version field you can also specify:</p>
<ul>
<li>The URL to a tarball
<li>The URL to a git repo: <code>git://github.com/user/project.git#commit</code>
<li>A GitHub repo: <code>visionmedia/mocha#4727d357ea</code>
</ul>
<p>As in those examples, it’s usually a good idea to specify a specific commit or tag when using git URLs (by appending the identifier after the “#” symbol).</p>
'''
'bundledDependencies(\.INDEX)?': '''
<h4>Bundled Dependencies</h4>
<p>Occasionally it’s helpful to include a local copy of a dependency (it’s folder in <code>node_modules/</code>) with the project when it’s published.</p>
<p>Bundled dependencies are specified as an array of package names, like:</p>
<pre><code>["gulp", "gulp-concat"]</code></pre>
<p>Note that another option is to fork the package and refer to it using a git URL.</p>
'''
'os(\.INDEX)?': '''
<h4>OS</h4>
<p><code>os</code> allows you to specify which operating systems your package will run on.</p>
<p>You can specify a list of OS’ it works on:</p>
<pre><code>["darwin", "linux"]</code></pre>
<p>Or a list it doesn’t work on:</p>
<pre><code>["!win32"]</code></pre>
<p>The current host operating system is provided by <code>process.platform</code></p>
'''
'cpu(\.INDEX)?': '''
<h4>CPU</h4>
<p><code>CPU</code> allows you to specify which processor architectures your package will run on.</p>
<p>You can specify a list of architectures it works on:</p>
<pre><code>["x64", "ia32"]</code></pre>
<p>Or a list it doesn’t work on:</p>
<pre><code>["!mips"]</code></pre>
<p>The current architecture is provided by <code>process.arch</code></p>
'''
'preferGlobal': '''
<h4>Prefer Global</h4>
<p>If your package is primarily a command-line application that should be installed globally, then set this value to <code>true</code> to provide a warning if it is installed locally.</p>
'''
'private': '''
<h4>Private</h4>
<p>If you set <code>"private": true</code> in your package.json, then npm will refuse to publish it.</p>
<p>This is a way to prevent accidental publication of private repositories. If you would like to ensure that a given package is only ever published to a specific registry (for example, an internal registry), then use the <code>publishConfig</code> dictionary to specify the registry.</p>
'''
'publishConfig': '''
<h4>Publish Config</h4>
<p>This is a set of config values that will be used at publish-time. It’s especially handy if you want to set the tag or registry, so that you can ensure that a given package is not tagged with “latest” or published to the global public registry by default.</p>
<p>See <code>npm help config</code> to see the list of config options that can be overridden.</p>
'''
# Browserify
'browser': '''
<h4>Browser</h4>
<p><em><a href="https://github.com/substack/node-browserify">Browserify</a> specific</em></p>
<p>The <code>browser</code> field allows you to specify browser-specific versions of your files. Rather than your <code>main</code> file, you might wish to have browserify use a different entry point when this module is bundled for the browser:</p>
<pre><code>"browser": "./browser.js"<code></pre>
<p>You can also override multiple files:</p>
<pre><code>"browser": {
"fs": "level-fs",
"./lib/ops.js": "./browser/opts.js"
}
</code></pre>
'''
'browserify\.transform(\.INDEX)?': '''
<h4>Transform</h4>
<p><em><a href="http://browserify.org/">Browserify</a> specific</em></p>
<p>Transforms are applied to your modules during the Browserify bundling process. You can use them to do things like <a href="https://www.npmjs.com/package/brfs">include file contents</a> or <a href="https://github.com/jnordberg/coffeeify">compile CoffeeScript</a>.</p>
<p>For example, to enable the <code>brfs</code> transform:</p>
<pre><code>"browserify": {"transform": ["brfs"]}</code></pre>
<p>Be sure to include the necessary module in your <code>dependencies</code> or <code>devDependencies</code> as well.</p>
'''
'browserify': '''
<h4>Browserify</h4>
<p>The <code>browserify</code> section allows you to provide specific configuration to the <a href="http://browserify.org/">Browserify</a> bundler.</p>
<pre><code>"browserify": {
"transform": [
"coffeeify"
]
},
</code></pre>
'''
module.exports = context
|
[
{
"context": "nal notes required for the script>\n#\n# Author:\n# Sandy <amwelch@umich.edu>\n\npython_shell = require(\"pyth",
"end": 293,
"score": 0.99922776222229,
"start": 288,
"tag": "NAME",
"value": "Sandy"
},
{
"context": "s required for the script>\n#\n# Author:\n# Sandy <... | src/room-stats.coffee | amwelch/hubot-room-stats | 0 | # Description
# Periodically collect/report on room statistics
#
# Configuration:
# LIST_OF_ENV_VARS_TO_SET
#
# Commands:
# hubot hello - <what the respond trigger does>
# orly - <what the hear trigger does>
#
# Notes:
# <optional notes required for the script>
#
# Author:
# Sandy <amwelch@umich.edu>
python_shell = require("python-shell")
module.exports = (robot) ->
robot.hear /stats/, (msg) ->
msg.reply "hello!"
console.log(python_shell)
options =
args: [
'--token'
'HIPCHAT TOKEN HERE'
'--room'
'ROOM NAME HERE'
]
scriptPath: "#{__dirname}/python"
python_shell.run('readroom.py', options, (err, results) ->
if err
console.log(err)
throw err
console.log(results)
res = JSON.parse(results)
)
robot.hear /orly/, (msg)->
msg.send "yarly"
| 34832 | # Description
# Periodically collect/report on room statistics
#
# Configuration:
# LIST_OF_ENV_VARS_TO_SET
#
# Commands:
# hubot hello - <what the respond trigger does>
# orly - <what the hear trigger does>
#
# Notes:
# <optional notes required for the script>
#
# Author:
# <NAME> <<EMAIL>>
python_shell = require("python-shell")
module.exports = (robot) ->
robot.hear /stats/, (msg) ->
msg.reply "hello!"
console.log(python_shell)
options =
args: [
'--token'
'HIPCHAT TOKEN HERE'
'--room'
'ROOM NAME HERE'
]
scriptPath: "#{__dirname}/python"
python_shell.run('readroom.py', options, (err, results) ->
if err
console.log(err)
throw err
console.log(results)
res = JSON.parse(results)
)
robot.hear /orly/, (msg)->
msg.send "yarly"
| true | # Description
# Periodically collect/report on room statistics
#
# Configuration:
# LIST_OF_ENV_VARS_TO_SET
#
# Commands:
# hubot hello - <what the respond trigger does>
# orly - <what the hear trigger does>
#
# Notes:
# <optional notes required for the script>
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
python_shell = require("python-shell")
module.exports = (robot) ->
robot.hear /stats/, (msg) ->
msg.reply "hello!"
console.log(python_shell)
options =
args: [
'--token'
'HIPCHAT TOKEN HERE'
'--room'
'ROOM NAME HERE'
]
scriptPath: "#{__dirname}/python"
python_shell.run('readroom.py', options, (err, results) ->
if err
console.log(err)
throw err
console.log(results)
res = JSON.parse(results)
)
robot.hear /orly/, (msg)->
msg.send "yarly"
|
[
{
"context": "###*\n *\n * dialog\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{View} = req",
"end": 35,
"score": 0.9987025260925293,
"start": 29,
"tag": "USERNAME",
"value": "vfasky"
},
{
"context": "###*\n *\n * dialog\n * @author vfasky <vfasky@gmail.com>\n###\n'use... | example/src/dialog.coffee | vfasky/mcore-weui | 0 | ###*
*
* dialog
* @author vfasky <vfasky@gmail.com>
###
'use strict'
{View} = require 'mcoreapp'
weui = require 'mcore-weui'
class Dialog extends View
run: ->
@render require('../tpl/dialog.html')
showAlert: ->
weui.Dialog.alert 'hello'
false
showConfirm: ->
weui.Dialog.confirm '你的选择是?', (ok)->
weui.Dialog.alert ok and '你点了“确定”' or '你点了“取消”'
module.exports = Dialog
module.exports.viewName = 'dialog'
| 94757 | ###*
*
* dialog
* @author vfasky <<EMAIL>>
###
'use strict'
{View} = require 'mcoreapp'
weui = require 'mcore-weui'
class Dialog extends View
run: ->
@render require('../tpl/dialog.html')
showAlert: ->
weui.Dialog.alert 'hello'
false
showConfirm: ->
weui.Dialog.confirm '你的选择是?', (ok)->
weui.Dialog.alert ok and '你点了“确定”' or '你点了“取消”'
module.exports = Dialog
module.exports.viewName = 'dialog'
| true | ###*
*
* dialog
* @author vfasky <PI:EMAIL:<EMAIL>END_PI>
###
'use strict'
{View} = require 'mcoreapp'
weui = require 'mcore-weui'
class Dialog extends View
run: ->
@render require('../tpl/dialog.html')
showAlert: ->
weui.Dialog.alert 'hello'
false
showConfirm: ->
weui.Dialog.confirm '你的选择是?', (ok)->
weui.Dialog.alert ok and '你点了“确定”' or '你点了“取消”'
module.exports = Dialog
module.exports.viewName = 'dialog'
|
[
{
"context": ".\n# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/\n\nclass window.MeetingSh",
"end": 202,
"score": 0.9815793037414551,
"start": 193,
"tag": "USERNAME",
"value": "jashkenas"
},
{
"context": "eScript in this file: http://jashkenas.gith... | app/assets/javascripts/meetings.js.coffee | LasVegasRubyGroup/soapbox | 0 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
class window.MeetingShow
constructor: ->
@wireKudoButtons()
wireKudoButtons: ->
$('.btn-kudo').on 'click', (e) ->
e.preventDefault()
url = $(e.target).data('url') + '.json'
$.ajax url,
type: 'put'
statusCode:
200: ->
$('.btn-kudo').remove()
class window.MeetingForm
constructor: ->
@wireTopics()
@wireTimeSlots()
@wirePresenters()
@fillExistingData()
wireTopics: ->
$('li.simple_topic').draggable({ revert: true })
$('li.simple_topic').popover
placement: 'left'
trigger: 'hover'
wireTimeSlots: =>
$('fieldset.time_slot').droppable(
drop: @topic_dropper
)
wirePresenters: =>
$('select').on 'change', (e) ->
# console.log $($(@).parent().find('.presenter_id'))
$(@).parent().find('.presenter_id').val($(@).val())
fillExistingData: =>
topics = $('.topic_id')
for topic in topics
topic_id = $(topic).val()
if topic_id.length > 0
t = $(".simple_topic[data-id=#{topic_id}]")
name = $(t).find('.topic_title').text()
volunteers = $(t).data('volunteers')
$(topic).parent().find('.topic_title').text(name)
options_string = for volunteer in volunteers
"<option value='#{volunteer.id}'>#{volunteer.name}</option>"
$(topic).parents('.time_slot').find('select').html(options_string.join("\n"))
presenters = $('.presenter_id')
for presenter in presenters
presenter_id = $(presenter).val()
if presenter_id.length > 0
$(presenter).parents('.time_slot').find('select').val(presenter_id)
topic_dropper: (e,ui) ->
id = $(ui.draggable).data('id')
name = $(ui.draggable).find('.topic_title').text()
volunteers = $(ui.draggable).data('volunteers')
unless volunteers.length > 0
volunteers = window.all_users
$(@).find('.topic_id').val(id)
$(@).find('.topic_title').text(name)
options_string = for volunteer in volunteers
"<option value='#{volunteer.id}'>#{volunteer.name}</option>"
$(@).find('select').html(options_string.join("\n"))
$(@).find('.presenter_id').val(volunteers[0].id)
$ ->
if $('.meeting_form').length > 0
new window.MeetingForm()
if $('.btn-kudo').length > 0
new window.MeetingShow()
if ($("#kudos_graph").length > 0)
Morris.Bar
element: 'kudos_graph'
data: $('#kudos_graph').data('subjects')
xkey: 'presenter'
ykeys: ['kudos']
labels: ['Kudos']
gridTextSize: 25
barColors: ['#ae1833']
gridTextColor: ['#ae1833']
| 141757 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
class window.MeetingShow
constructor: ->
@wireKudoButtons()
wireKudoButtons: ->
$('.btn-kudo').on 'click', (e) ->
e.preventDefault()
url = $(e.target).data('url') + '.json'
$.ajax url,
type: 'put'
statusCode:
200: ->
$('.btn-kudo').remove()
class window.MeetingForm
constructor: ->
@wireTopics()
@wireTimeSlots()
@wirePresenters()
@fillExistingData()
wireTopics: ->
$('li.simple_topic').draggable({ revert: true })
$('li.simple_topic').popover
placement: 'left'
trigger: 'hover'
wireTimeSlots: =>
$('fieldset.time_slot').droppable(
drop: @topic_dropper
)
wirePresenters: =>
$('select').on 'change', (e) ->
# console.log $($(@).parent().find('.presenter_id'))
$(@).parent().find('.presenter_id').val($(@).val())
fillExistingData: =>
topics = $('.topic_id')
for topic in topics
topic_id = $(topic).val()
if topic_id.length > 0
t = $(".simple_topic[data-id=#{topic_id}]")
name = $(t).find('.topic_title').text()
volunteers = $(t).data('volunteers')
$(topic).parent().find('.topic_title').text(name)
options_string = for volunteer in volunteers
"<option value='#{volunteer.id}'>#{volunteer.name}</option>"
$(topic).parents('.time_slot').find('select').html(options_string.join("\n"))
presenters = $('.presenter_id')
for presenter in presenters
presenter_id = $(presenter).val()
if presenter_id.length > 0
$(presenter).parents('.time_slot').find('select').val(presenter_id)
topic_dropper: (e,ui) ->
id = $(ui.draggable).data('id')
name = $(ui.draggable).find('.topic_title').text()
volunteers = $(ui.draggable).data('volunteers')
unless volunteers.length > 0
volunteers = window.all_users
$(@).find('.topic_id').val(id)
$(@).find('.topic_title').text(name)
options_string = for volunteer in volunteers
"<option value='#{volunteer.id}'>#{volunteer.name}</option>"
$(@).find('select').html(options_string.join("\n"))
$(@).find('.presenter_id').val(volunteers[0].id)
$ ->
if $('.meeting_form').length > 0
new window.MeetingForm()
if $('.btn-kudo').length > 0
new window.MeetingShow()
if ($("#kudos_graph").length > 0)
Morris.Bar
element: 'kudos_graph'
data: $('#kudos_graph').data('subjects')
xkey: 'presenter'
ykeys: ['<KEY>']
labels: ['Kudos']
gridTextSize: 25
barColors: ['#ae1833']
gridTextColor: ['#ae1833']
| true | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
class window.MeetingShow
constructor: ->
@wireKudoButtons()
wireKudoButtons: ->
$('.btn-kudo').on 'click', (e) ->
e.preventDefault()
url = $(e.target).data('url') + '.json'
$.ajax url,
type: 'put'
statusCode:
200: ->
$('.btn-kudo').remove()
class window.MeetingForm
constructor: ->
@wireTopics()
@wireTimeSlots()
@wirePresenters()
@fillExistingData()
wireTopics: ->
$('li.simple_topic').draggable({ revert: true })
$('li.simple_topic').popover
placement: 'left'
trigger: 'hover'
wireTimeSlots: =>
$('fieldset.time_slot').droppable(
drop: @topic_dropper
)
wirePresenters: =>
$('select').on 'change', (e) ->
# console.log $($(@).parent().find('.presenter_id'))
$(@).parent().find('.presenter_id').val($(@).val())
fillExistingData: =>
topics = $('.topic_id')
for topic in topics
topic_id = $(topic).val()
if topic_id.length > 0
t = $(".simple_topic[data-id=#{topic_id}]")
name = $(t).find('.topic_title').text()
volunteers = $(t).data('volunteers')
$(topic).parent().find('.topic_title').text(name)
options_string = for volunteer in volunteers
"<option value='#{volunteer.id}'>#{volunteer.name}</option>"
$(topic).parents('.time_slot').find('select').html(options_string.join("\n"))
presenters = $('.presenter_id')
for presenter in presenters
presenter_id = $(presenter).val()
if presenter_id.length > 0
$(presenter).parents('.time_slot').find('select').val(presenter_id)
topic_dropper: (e,ui) ->
id = $(ui.draggable).data('id')
name = $(ui.draggable).find('.topic_title').text()
volunteers = $(ui.draggable).data('volunteers')
unless volunteers.length > 0
volunteers = window.all_users
$(@).find('.topic_id').val(id)
$(@).find('.topic_title').text(name)
options_string = for volunteer in volunteers
"<option value='#{volunteer.id}'>#{volunteer.name}</option>"
$(@).find('select').html(options_string.join("\n"))
$(@).find('.presenter_id').val(volunteers[0].id)
$ ->
if $('.meeting_form').length > 0
new window.MeetingForm()
if $('.btn-kudo').length > 0
new window.MeetingShow()
if ($("#kudos_graph").length > 0)
Morris.Bar
element: 'kudos_graph'
data: $('#kudos_graph').data('subjects')
xkey: 'presenter'
ykeys: ['PI:KEY:<KEY>END_PI']
labels: ['Kudos']
gridTextSize: 25
barColors: ['#ae1833']
gridTextColor: ['#ae1833']
|
[
{
"context": "hello derek how is it going?\nfor c, i in \"Hello World!\"\n k",
"end": 13,
"score": 0.9957613348960876,
"start": 8,
"tag": "NAME",
"value": "derek"
}
] | examples/simple-jsbeautifyrc/coffeescript/original/test.coffee | MetaMemoryT/atom-beautify | 0 | hello derek how is it going?
for c, i in "Hello World!"
k = 1+1- 2>=3<= 4>5 <6
for c, i in "Hello World"
k = (a,b)-> if b? return a
f = b()[0]
for c, i in "Hello World"
f(b())
| 184512 | hello <NAME> how is it going?
for c, i in "Hello World!"
k = 1+1- 2>=3<= 4>5 <6
for c, i in "Hello World"
k = (a,b)-> if b? return a
f = b()[0]
for c, i in "Hello World"
f(b())
| true | hello PI:NAME:<NAME>END_PI how is it going?
for c, i in "Hello World!"
k = 1+1- 2>=3<= 4>5 <6
for c, i in "Hello World"
k = (a,b)-> if b? return a
f = b()[0]
for c, i in "Hello World"
f(b())
|
[
{
"context": " algo_version : 3\n generation : 1\n email : \"themax@gmail.com\"\n length : 12\n num_symbols : 0\n security",
"end": 645,
"score": 0.9999204277992249,
"start": 629,
"tag": "EMAIL",
"value": "themax@gmail.com"
},
{
"context": " num_symbols : 0\n secu... | node_modules/purepack/test/pack/input.iced | AngelKey/Angelkey.nodeclient | 151 | exports.data =
s1 : "hello"
o1 : { hi : "mom", bye : "dad" }
r1: [-100..100]
r2: [-1000..1000]
r3: [-32800...-32700]
r4: [-2147483668...-2147483628]
r5: [0xfff0...0x1000f]
r6: [0xfffffff0...0x10000000f]
i1: -2147483649
f1: [ 1.1, 10.1, 20.333, 44.44444, 5.555555]
f2: [ -1.1, -10.1, -20.333, -44.44444, -5.555555]
o2:
foo : [0..10]
bar :
bizzle : null
jam : true
jim : false
jupiter : "abc ABC 123"
saturn : 6
bam :
boom :
yam :
potato : [10..20]
o3:
notes : null
algo_version : 3
generation : 1
email : "themax@gmail.com"
length : 12
num_symbols : 0
security_bits : 8
s2: "themax@gmail.com"
u1: {}.yuck
s3: (i for i in [1...100]).join ' '
o4 : obj : (i for i in [1...100]).join ' '
o5:
email : "themax@gmail.com"
notes : "not active yet, still using old medium security. update this note when fixed."
algo_version : 3,
length : 12
num_symbols : 0
generation : 1
security_bits : 8
japanese0 : "メ"
japanese1 : "hello メインページ"
japanese2 : "この説明へのリンクにアクセスできる方法はいくつかあり、このエリアに至るまでの経路もいくつかあ"
korean1 : "다국어 최상위 도메인 중 하나의 평가 영역입니다"
bad_utf1 : "\xaa\xbc\xce\xfe"
gothic: "𐌼𐌰𐌲 𐌲𐌻𐌴𐍃 𐌹̈𐍄𐌰𐌽, 𐌽𐌹 𐌼𐌹𐍃 𐍅𐌿 𐌽𐌳𐌰𐌽 𐌱𐍂𐌹𐌲𐌲𐌹𐌸"
| 23620 | exports.data =
s1 : "hello"
o1 : { hi : "mom", bye : "dad" }
r1: [-100..100]
r2: [-1000..1000]
r3: [-32800...-32700]
r4: [-2147483668...-2147483628]
r5: [0xfff0...0x1000f]
r6: [0xfffffff0...0x10000000f]
i1: -2147483649
f1: [ 1.1, 10.1, 20.333, 44.44444, 5.555555]
f2: [ -1.1, -10.1, -20.333, -44.44444, -5.555555]
o2:
foo : [0..10]
bar :
bizzle : null
jam : true
jim : false
jupiter : "abc ABC 123"
saturn : 6
bam :
boom :
yam :
potato : [10..20]
o3:
notes : null
algo_version : 3
generation : 1
email : "<EMAIL>"
length : 12
num_symbols : 0
security_bits : 8
s2: "<EMAIL>"
u1: {}.yuck
s3: (i for i in [1...100]).join ' '
o4 : obj : (i for i in [1...100]).join ' '
o5:
email : "<EMAIL>"
notes : "not active yet, still using old medium security. update this note when fixed."
algo_version : 3,
length : 12
num_symbols : 0
generation : 1
security_bits : 8
japanese0 : "メ"
japanese1 : "hello メインページ"
japanese2 : "この説明へのリンクにアクセスできる方法はいくつかあり、このエリアに至るまでの経路もいくつかあ"
korean1 : "다국어 최상위 도메인 중 하나의 평가 영역입니다"
bad_utf1 : "\xaa\xbc\xce\xfe"
gothic: "𐌼𐌰𐌲 𐌲𐌻𐌴𐍃 𐌹̈𐍄𐌰𐌽, 𐌽𐌹 𐌼𐌹𐍃 𐍅𐌿 𐌽𐌳𐌰𐌽 𐌱𐍂𐌹𐌲𐌲𐌹𐌸"
| true | exports.data =
s1 : "hello"
o1 : { hi : "mom", bye : "dad" }
r1: [-100..100]
r2: [-1000..1000]
r3: [-32800...-32700]
r4: [-2147483668...-2147483628]
r5: [0xfff0...0x1000f]
r6: [0xfffffff0...0x10000000f]
i1: -2147483649
f1: [ 1.1, 10.1, 20.333, 44.44444, 5.555555]
f2: [ -1.1, -10.1, -20.333, -44.44444, -5.555555]
o2:
foo : [0..10]
bar :
bizzle : null
jam : true
jim : false
jupiter : "abc ABC 123"
saturn : 6
bam :
boom :
yam :
potato : [10..20]
o3:
notes : null
algo_version : 3
generation : 1
email : "PI:EMAIL:<EMAIL>END_PI"
length : 12
num_symbols : 0
security_bits : 8
s2: "PI:EMAIL:<EMAIL>END_PI"
u1: {}.yuck
s3: (i for i in [1...100]).join ' '
o4 : obj : (i for i in [1...100]).join ' '
o5:
email : "PI:EMAIL:<EMAIL>END_PI"
notes : "not active yet, still using old medium security. update this note when fixed."
algo_version : 3,
length : 12
num_symbols : 0
generation : 1
security_bits : 8
japanese0 : "メ"
japanese1 : "hello メインページ"
japanese2 : "この説明へのリンクにアクセスできる方法はいくつかあり、このエリアに至るまでの経路もいくつかあ"
korean1 : "다국어 최상위 도메인 중 하나의 평가 영역입니다"
bad_utf1 : "\xaa\xbc\xce\xfe"
gothic: "𐌼𐌰𐌲 𐌲𐌻𐌴𐍃 𐌹̈𐍄𐌰𐌽, 𐌽𐌹 𐌼𐌹𐍃 𐍅𐌿 𐌽𐌳𐌰𐌽 𐌱𐍂𐌹𐌲𐌲𐌹𐌸"
|
[
{
"context": "alert \"Hello, minoJiro!\"\n",
"end": 22,
"score": 0.998431384563446,
"start": 14,
"tag": "NAME",
"value": "minoJiro"
}
] | HelloWorld.coffee | minojiro/Hello-World | 0 | alert "Hello, minoJiro!"
| 164016 | alert "Hello, <NAME>!"
| true | alert "Hello, PI:NAME:<NAME>END_PI!"
|
[
{
"context": "\" })\n (new Proof { key : \"twitter\", value : \"bbbbb\" })\n (new Proof { key : \"fingerprint\", value :",
"end": 941,
"score": 0.6316211223602295,
"start": 938,
"tag": "KEY",
"value": "bbb"
},
{
"context": "})\n (new Proof { key : \"fingerprint\", value : \"... | node_modules/libkeybase/test/files/33_assertion.iced | AngelKey/Angelkey.nodeclient | 151 |
{URI,parse,Proof,ProofSet} = require('../../').assertion
expr = null
exports.parse_0 = (T,cb) ->
expr = parse "reddit://a && twitter://bb"
cb()
exports.match_0 = (T,cb) ->
ps = new ProofSet [(new Proof { key : "reddit", value : "a" })]
T.assert not expr.match_set(ps), "shouldn't match"
cb()
exports.parse_1 = (T,cb) ->
expr = parse """
web://foo.io || (reddit://a && twitter://bbbbb && fingerprint://aabbcc)
"""
T.equal expr.toString(), '(web://foo.io || ((reddit://a && twitter://bbbbb) && fingerprint://aabbcc))'
cb()
exports.match_1 = (T,cb) ->
ps = new ProofSet [(new Proof { key : "https", value : "foo.io" }) ]
T.assert expr.match_set(ps), "first one matched"
ps = new ProofSet [(new Proof { key : "https", value : "foob.io" }) ]
T.assert not(expr.match_set(ps)), "second didn't"
ps = new ProofSet [
(new Proof { key : "reddit", value : "a" })
(new Proof { key : "twitter", value : "bbbbb" })
(new Proof { key : "fingerprint", value : "001122aabbcc" })
]
T.assert expr.match_set(ps), "third one matched"
ps = new ProofSet [
(new Proof { key : "reddit", value : "a" })
(new Proof { key : "fingerprint", value : "001122aabbcc" })
]
T.assert not expr.match_set(ps), "fourth one didn't"
ps = new ProofSet [
(new Proof { key : "reddit", value : "a" })
(new Proof { key : "twitter", value : "bbbbb" })
(new Proof { key : "fingerprint", value : "aabbcc4" })
]
T.assert not expr.match_set(ps), "fifth didn't"
cb()
exports.parse_2 = (T,cb) ->
expr = parse "http://foo.com"
ps = new ProofSet [(new Proof { key : 'http', value : 'foo.com'})]
T.assert expr.match_set(ps), "first one matched"
ps = new ProofSet [(new Proof { key : 'https', value : 'foo.com'})]
T.assert expr.match_set(ps), "second one matched"
ps = new ProofSet [(new Proof { key : 'dns', value : 'foo.com'})]
T.assert not expr.match_set(ps), "third didnt"
cb()
exports.parse_bad_1 = (T,cb) ->
bads = [
"reddit"
"reddit://"
"reddit://aa ||"
"reddit://aa &&"
"reddit:// && ()"
"fingerprint://aaXXxx"
"dns://shoot"
"http://nothing"
"foo://bar"
"keybase://ok || dns://fine.io || (twitter://still_good || bad://one)"
]
for bad in bads
try
parse bad
T.assert false, "#{bad}: shouldn't have parsed"
catch error
T.assert error?, "we got an error"
cb()
exports.parse_URI = (T,cb) ->
r = URI.parse { s : "max", strict : false }
T.assert r?, "got something back without strict mode"
try
URI.parse { s : "max", strict : true }
T.assert false, "should not have worked with strict mode"
catch err
T.assert err?, "error on strict mode without key"
cb()
| 92029 |
{URI,parse,Proof,ProofSet} = require('../../').assertion
expr = null
exports.parse_0 = (T,cb) ->
expr = parse "reddit://a && twitter://bb"
cb()
exports.match_0 = (T,cb) ->
ps = new ProofSet [(new Proof { key : "reddit", value : "a" })]
T.assert not expr.match_set(ps), "shouldn't match"
cb()
exports.parse_1 = (T,cb) ->
expr = parse """
web://foo.io || (reddit://a && twitter://bbbbb && fingerprint://aabbcc)
"""
T.equal expr.toString(), '(web://foo.io || ((reddit://a && twitter://bbbbb) && fingerprint://aabbcc))'
cb()
exports.match_1 = (T,cb) ->
ps = new ProofSet [(new Proof { key : "https", value : "foo.io" }) ]
T.assert expr.match_set(ps), "first one matched"
ps = new ProofSet [(new Proof { key : "https", value : "foob.io" }) ]
T.assert not(expr.match_set(ps)), "second didn't"
ps = new ProofSet [
(new Proof { key : "reddit", value : "a" })
(new Proof { key : "twitter", value : "bb<KEY>" })
(new Proof { key : "fingerprint", value : "001122aabbcc" })
]
T.assert expr.match_set(ps), "third one matched"
ps = new ProofSet [
(new Proof { key : "reddit", value : "a" })
(new Proof { key : "fingerprint", value : "001122aabbcc" })
]
T.assert not expr.match_set(ps), "fourth one didn't"
ps = new ProofSet [
(new Proof { key : "reddit", value : "a" })
(new Proof { key : "twitter", value : "bbbbb" })
(new Proof { key : "fingerprint", value : "<KEY>" })
]
T.assert not expr.match_set(ps), "fifth didn't"
cb()
exports.parse_2 = (T,cb) ->
expr = parse "http://foo.com"
ps = new ProofSet [(new Proof { key : 'http', value : 'foo.com'})]
T.assert expr.match_set(ps), "first one matched"
ps = new ProofSet [(new Proof { key : 'https', value : 'foo.com'})]
T.assert expr.match_set(ps), "second one matched"
ps = new ProofSet [(new Proof { key : 'dns', value : 'foo.com'})]
T.assert not expr.match_set(ps), "third didnt"
cb()
exports.parse_bad_1 = (T,cb) ->
bads = [
"reddit"
"reddit://"
"reddit://aa ||"
"reddit://aa &&"
"reddit:// && ()"
"fingerprint://aaXXxx"
"dns://shoot"
"http://nothing"
"foo://bar"
"keybase://ok || dns://fine.io || (twitter://still_good || bad://one)"
]
for bad in bads
try
parse bad
T.assert false, "#{bad}: shouldn't have parsed"
catch error
T.assert error?, "we got an error"
cb()
exports.parse_URI = (T,cb) ->
r = URI.parse { s : "max", strict : false }
T.assert r?, "got something back without strict mode"
try
URI.parse { s : "max", strict : true }
T.assert false, "should not have worked with strict mode"
catch err
T.assert err?, "error on strict mode without key"
cb()
| true |
{URI,parse,Proof,ProofSet} = require('../../').assertion
expr = null
exports.parse_0 = (T,cb) ->
expr = parse "reddit://a && twitter://bb"
cb()
exports.match_0 = (T,cb) ->
ps = new ProofSet [(new Proof { key : "reddit", value : "a" })]
T.assert not expr.match_set(ps), "shouldn't match"
cb()
exports.parse_1 = (T,cb) ->
expr = parse """
web://foo.io || (reddit://a && twitter://bbbbb && fingerprint://aabbcc)
"""
T.equal expr.toString(), '(web://foo.io || ((reddit://a && twitter://bbbbb) && fingerprint://aabbcc))'
cb()
exports.match_1 = (T,cb) ->
ps = new ProofSet [(new Proof { key : "https", value : "foo.io" }) ]
T.assert expr.match_set(ps), "first one matched"
ps = new ProofSet [(new Proof { key : "https", value : "foob.io" }) ]
T.assert not(expr.match_set(ps)), "second didn't"
ps = new ProofSet [
(new Proof { key : "reddit", value : "a" })
(new Proof { key : "twitter", value : "bbPI:KEY:<KEY>END_PI" })
(new Proof { key : "fingerprint", value : "001122aabbcc" })
]
T.assert expr.match_set(ps), "third one matched"
ps = new ProofSet [
(new Proof { key : "reddit", value : "a" })
(new Proof { key : "fingerprint", value : "001122aabbcc" })
]
T.assert not expr.match_set(ps), "fourth one didn't"
ps = new ProofSet [
(new Proof { key : "reddit", value : "a" })
(new Proof { key : "twitter", value : "bbbbb" })
(new Proof { key : "fingerprint", value : "PI:KEY:<KEY>END_PI" })
]
T.assert not expr.match_set(ps), "fifth didn't"
cb()
exports.parse_2 = (T,cb) ->
expr = parse "http://foo.com"
ps = new ProofSet [(new Proof { key : 'http', value : 'foo.com'})]
T.assert expr.match_set(ps), "first one matched"
ps = new ProofSet [(new Proof { key : 'https', value : 'foo.com'})]
T.assert expr.match_set(ps), "second one matched"
ps = new ProofSet [(new Proof { key : 'dns', value : 'foo.com'})]
T.assert not expr.match_set(ps), "third didnt"
cb()
exports.parse_bad_1 = (T,cb) ->
bads = [
"reddit"
"reddit://"
"reddit://aa ||"
"reddit://aa &&"
"reddit:// && ()"
"fingerprint://aaXXxx"
"dns://shoot"
"http://nothing"
"foo://bar"
"keybase://ok || dns://fine.io || (twitter://still_good || bad://one)"
]
for bad in bads
try
parse bad
T.assert false, "#{bad}: shouldn't have parsed"
catch error
T.assert error?, "we got an error"
cb()
exports.parse_URI = (T,cb) ->
r = URI.parse { s : "max", strict : false }
T.assert r?, "got something back without strict mode"
try
URI.parse { s : "max", strict : true }
T.assert false, "should not have worked with strict mode"
catch err
T.assert err?, "error on strict mode without key"
cb()
|
[
{
"context": " E Dialog, props,\n E 'iframe', \n key: Date.now().toString()\n src: @url()\n frameBorder: 0\n ",
"end": 710,
"score": 0.9864128232002258,
"start": 689,
"tag": "KEY",
"value": "Date.now().toString()"
}
] | index.coffee | twhtanghk/rc-oauth2 | 0 | require 'rc-dialog/assets/index.css'
require './index.css'
React = require 'react'
E = require 'react-script'
Dialog = require('rc-dialog').default
url = require 'url'
class Auth extends React.Component
@cb: null
@defaultProps:
title: 'Login'
style:
height: "80%"
bodyStyle:
padding: 0
position: 'relative'
flexGrow: 1
url: ->
query = url.format query:
client_id: @props.CLIENT_ID
scope: @props.SCOPE
response_type: 'token'
"#{@props.AUTHURL}#{query}"
render: =>
props = Object.assign {}, @props,
onClose: =>
@props.loginReject 'access_denied'
E Dialog, props,
E 'iframe',
key: Date.now().toString()
src: @url()
frameBorder: 0
style:
height: '100%'
width: '100%'
position: 'absolute'
borderRadius: '6px'
componentDidMount: ->
Auth.cb = (event) =>
@auth event
window.addEventListener 'message', Auth.cb
componentWillUnmount: ->
window.removeEventListener Auth.cb
auth: (e) =>
auth = e.data.auth || {}
if 'error' of auth
@props.loginReject auth.error
else if 'access_token' of auth
@props.loginResolve auth.access_token
initState =
visible: false
token: null
error: null
reducer = (state, action) ->
switch action.type
when 'login'
visible: true
token: null
error: null
when 'loginReject'
visible: false
token: null
error: action.error
when 'loginResolve'
visible: false
token: action.token
error: null
when 'logout'
visible: false
token: null
error: null
else
state || initState
actionCreator = (dispatch) ->
login: ->
dispatch type: 'login'
loginReject: (err) ->
dispatch type: 'loginReject', error: err
loginResolve: (token) ->
dispatch type: 'loginResolve', token: token
logout: ->
dispatch type: 'logout'
module.exports =
component: Auth
state: initState
reducer: reducer
actionCreator: actionCreator
| 46815 | require 'rc-dialog/assets/index.css'
require './index.css'
React = require 'react'
E = require 'react-script'
Dialog = require('rc-dialog').default
url = require 'url'
class Auth extends React.Component
@cb: null
@defaultProps:
title: 'Login'
style:
height: "80%"
bodyStyle:
padding: 0
position: 'relative'
flexGrow: 1
url: ->
query = url.format query:
client_id: @props.CLIENT_ID
scope: @props.SCOPE
response_type: 'token'
"#{@props.AUTHURL}#{query}"
render: =>
props = Object.assign {}, @props,
onClose: =>
@props.loginReject 'access_denied'
E Dialog, props,
E 'iframe',
key: <KEY>
src: @url()
frameBorder: 0
style:
height: '100%'
width: '100%'
position: 'absolute'
borderRadius: '6px'
componentDidMount: ->
Auth.cb = (event) =>
@auth event
window.addEventListener 'message', Auth.cb
componentWillUnmount: ->
window.removeEventListener Auth.cb
auth: (e) =>
auth = e.data.auth || {}
if 'error' of auth
@props.loginReject auth.error
else if 'access_token' of auth
@props.loginResolve auth.access_token
initState =
visible: false
token: null
error: null
reducer = (state, action) ->
switch action.type
when 'login'
visible: true
token: null
error: null
when 'loginReject'
visible: false
token: null
error: action.error
when 'loginResolve'
visible: false
token: action.token
error: null
when 'logout'
visible: false
token: null
error: null
else
state || initState
actionCreator = (dispatch) ->
login: ->
dispatch type: 'login'
loginReject: (err) ->
dispatch type: 'loginReject', error: err
loginResolve: (token) ->
dispatch type: 'loginResolve', token: token
logout: ->
dispatch type: 'logout'
module.exports =
component: Auth
state: initState
reducer: reducer
actionCreator: actionCreator
| true | require 'rc-dialog/assets/index.css'
require './index.css'
React = require 'react'
E = require 'react-script'
Dialog = require('rc-dialog').default
url = require 'url'
class Auth extends React.Component
@cb: null
@defaultProps:
title: 'Login'
style:
height: "80%"
bodyStyle:
padding: 0
position: 'relative'
flexGrow: 1
url: ->
query = url.format query:
client_id: @props.CLIENT_ID
scope: @props.SCOPE
response_type: 'token'
"#{@props.AUTHURL}#{query}"
render: =>
props = Object.assign {}, @props,
onClose: =>
@props.loginReject 'access_denied'
E Dialog, props,
E 'iframe',
key: PI:KEY:<KEY>END_PI
src: @url()
frameBorder: 0
style:
height: '100%'
width: '100%'
position: 'absolute'
borderRadius: '6px'
componentDidMount: ->
Auth.cb = (event) =>
@auth event
window.addEventListener 'message', Auth.cb
componentWillUnmount: ->
window.removeEventListener Auth.cb
auth: (e) =>
auth = e.data.auth || {}
if 'error' of auth
@props.loginReject auth.error
else if 'access_token' of auth
@props.loginResolve auth.access_token
initState =
visible: false
token: null
error: null
reducer = (state, action) ->
switch action.type
when 'login'
visible: true
token: null
error: null
when 'loginReject'
visible: false
token: null
error: action.error
when 'loginResolve'
visible: false
token: action.token
error: null
when 'logout'
visible: false
token: null
error: null
else
state || initState
actionCreator = (dispatch) ->
login: ->
dispatch type: 'login'
loginReject: (err) ->
dispatch type: 'loginReject', error: err
loginResolve: (token) ->
dispatch type: 'loginResolve', token: token
logout: ->
dispatch type: 'logout'
module.exports =
component: Auth
state: initState
reducer: reducer
actionCreator: actionCreator
|
[
{
"context": " is too \n# smart to do right... sigh.\n#\n# Based on Colin Snover's implementation which can be found at https://gi",
"end": 187,
"score": 0.9313719868659973,
"start": 175,
"tag": "NAME",
"value": "Colin Snover"
},
{
"context": "entation which can be found at https://g... | lib/date_from_json.js.coffee | charypar/cyclical-js | 2 | # this is here to correctly parse dates provided by the server in ISO 8601 date format, which apparently the date.js library is too
# smart to do right... sigh.
#
# Based on Colin Snover's implementation which can be found at https://github.com/csnover/js-iso8601
Date.parseISO8601 = (string) ->
regex = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/
return null unless parts = regex.exec(string)
for i in [1,4,5,6,7,10,11]
parts[i] = +parts[i] || 0 # convert to numbers and put zeros for undefined
parts[2] = (+parts[2] || 1) - 1; # empty month
parts[3] = (+parts[3] || 1); # empty day
# handle timzeone ofset
if parts[8] isnt 'Z' and parts[9]?
minutes = parts[10]*60 + parts[11]
minutes = -minutes if parts[9] is '+'
parts[5] += minutes
# create date
new Date(Date.UTC(parts[1..7]...))
| 176631 | # this is here to correctly parse dates provided by the server in ISO 8601 date format, which apparently the date.js library is too
# smart to do right... sigh.
#
# Based on <NAME>'s implementation which can be found at https://github.com/csnover/js-iso8601
Date.parseISO8601 = (string) ->
regex = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/
return null unless parts = regex.exec(string)
for i in [1,4,5,6,7,10,11]
parts[i] = +parts[i] || 0 # convert to numbers and put zeros for undefined
parts[2] = (+parts[2] || 1) - 1; # empty month
parts[3] = (+parts[3] || 1); # empty day
# handle timzeone ofset
if parts[8] isnt 'Z' and parts[9]?
minutes = parts[10]*60 + parts[11]
minutes = -minutes if parts[9] is '+'
parts[5] += minutes
# create date
new Date(Date.UTC(parts[1..7]...))
| true | # this is here to correctly parse dates provided by the server in ISO 8601 date format, which apparently the date.js library is too
# smart to do right... sigh.
#
# Based on PI:NAME:<NAME>END_PI's implementation which can be found at https://github.com/csnover/js-iso8601
Date.parseISO8601 = (string) ->
regex = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/
return null unless parts = regex.exec(string)
for i in [1,4,5,6,7,10,11]
parts[i] = +parts[i] || 0 # convert to numbers and put zeros for undefined
parts[2] = (+parts[2] || 1) - 1; # empty month
parts[3] = (+parts[3] || 1); # empty day
# handle timzeone ofset
if parts[8] isnt 'Z' and parts[9]?
minutes = parts[10]*60 + parts[11]
minutes = -minutes if parts[9] is '+'
parts[5] += minutes
# create date
new Date(Date.UTC(parts[1..7]...))
|
[
{
"context": "IGH guy\n#\n# Good news everyone! <news> - Generates Professor Farnsworth\n\nmodule.exports = (robot) ->\n robot.r",
"end": 614,
"score": 0.8189399242401123,
"start": 605,
"tag": "NAME",
"value": "Professor"
},
{
"context": "# Good news everyone! <news> - Generates Pro... | src/scripts/meme_generator.coffee | mxenabled/hubot-scripts | 1 | # Integrates with memegenerator.net
#
# Y U NO <text> - Generates the Y U NO GUY with the bottom caption
# of <text>
#
# I don't always <something> but when i do <text> - Generates The Most Interesting man in the World
#
# <text> ORLY? - Generates the ORLY? owl with the top caption of <text>
#
# <text> (SUCCESS|NAILED IT) - Generates success kid with the top caption of <text>
#
# <text> ALL the <things> - Generates ALL THE THINGS
#
# <text> TOO DAMN <high> - Generates THE RENT IS TOO DAMN HIGH guy
#
# Good news everyone! <news> - Generates Professor Farnsworth
module.exports = (robot) ->
robot.respond /Y U NO (.+)/i, (msg) ->
caption = msg.match[1] || ""
memeGenerator msg, 2, 166088, "Y U NO", caption, (url) ->
msg.send url
robot.respond /(I DON'?T ALWAYS .*) (BUT WHEN I DO,? .*)/i, (msg) ->
memeGenerator msg, 74, 2485, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*)(O\s?RLY\??.*)/i, (msg) ->
memeGenerator msg, 920, 117049, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*)(SUCCESS|NAILED IT.*)/i, (msg) ->
memeGenerator msg, 121, 1031, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*) (ALL the .*)/, (msg) ->
memeGenerator msg, 6013, 1121885, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*) (\w+\sTOO DAMN .*)/i, (msg) ->
memeGenerator msg, 998, 203665, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(GOOD NEWS EVERYONE[,.!]?) (.*)/i, (msg) ->
memeGenerator msg, 1591, 112464, msg.match[1], msg.match[2], (url) ->
msg.send url
memeGenerator = (msg, generatorID, imageID, text0, text1, callback) ->
username = process.env.HUBOT_MEMEGEN_USERNAME
password = process.env.HUBOT_MEMEGEN_PASSWORD
unless username
msg.send "MemeGenerator username isn't set. Sign up at http://memegenerator.net"
msg.send "Then set the HUBOT_MEMEGEN_USERNAME environment variable"
return
unless password
msg.send "MemeGenerator password isn't set. Sign up at http://memegenerator.net"
msg.send "Then set the HUBOT_MEMEGEN_PASSWORD environment variable"
return
msg.http('http://version1.api.memegenerator.net/Instance_Create')
.query
username: username,
password: password,
languageCode: 'en',
generatorID: generatorID,
imageID: imageID,
text0: text0,
text1: text1
.get() (err, res, body) ->
result = JSON.parse(body)['result']
if result? and result['instanceUrl']? and result['instanceImageUrl']?
instanceURL = result['instanceUrl']
img = "http://memegenerator.net" + result['instanceImageUrl']
msg.http(instanceURL).get() (err, res, body) ->
# Need to hit instanceURL so that image gets generated
callback img
else
msg.reply "Sorry, I couldn't generate that image."
| 21645 | # Integrates with memegenerator.net
#
# Y U NO <text> - Generates the Y U NO GUY with the bottom caption
# of <text>
#
# I don't always <something> but when i do <text> - Generates The Most Interesting man in the World
#
# <text> ORLY? - Generates the ORLY? owl with the top caption of <text>
#
# <text> (SUCCESS|NAILED IT) - Generates success kid with the top caption of <text>
#
# <text> ALL the <things> - Generates ALL THE THINGS
#
# <text> TOO DAMN <high> - Generates THE RENT IS TOO DAMN HIGH guy
#
# Good news everyone! <news> - Generates <NAME> <NAME>
module.exports = (robot) ->
robot.respond /Y U NO (.+)/i, (msg) ->
caption = msg.match[1] || ""
memeGenerator msg, 2, 166088, "Y U NO", caption, (url) ->
msg.send url
robot.respond /(I DON'?T ALWAYS .*) (BUT WHEN I DO,? .*)/i, (msg) ->
memeGenerator msg, 74, 2485, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*)(O\s?RLY\??.*)/i, (msg) ->
memeGenerator msg, 920, 117049, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*)(SUCCESS|NAILED IT.*)/i, (msg) ->
memeGenerator msg, 121, 1031, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*) (ALL the .*)/, (msg) ->
memeGenerator msg, 6013, 1121885, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*) (\w+\sTOO DAMN .*)/i, (msg) ->
memeGenerator msg, 998, 203665, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(GOOD NEWS EVERYONE[,.!]?) (.*)/i, (msg) ->
memeGenerator msg, 1591, 112464, msg.match[1], msg.match[2], (url) ->
msg.send url
memeGenerator = (msg, generatorID, imageID, text0, text1, callback) ->
username = process.env.HUBOT_MEMEGEN_USERNAME
password = process.<PASSWORD>.HUBOT_MEMEGEN_PASSWORD
unless username
msg.send "MemeGenerator username isn't set. Sign up at http://memegenerator.net"
msg.send "Then set the HUBOT_MEMEGEN_USERNAME environment variable"
return
unless password
msg.send "MemeGenerator password isn't set. Sign up at http://memegenerator.net"
msg.send "Then set the HUBOT_MEMEGEN_PASSWORD environment variable"
return
msg.http('http://version1.api.memegenerator.net/Instance_Create')
.query
username: username,
password: <PASSWORD>,
languageCode: 'en',
generatorID: generatorID,
imageID: imageID,
text0: text0,
text1: text1
.get() (err, res, body) ->
result = JSON.parse(body)['result']
if result? and result['instanceUrl']? and result['instanceImageUrl']?
instanceURL = result['instanceUrl']
img = "http://memegenerator.net" + result['instanceImageUrl']
msg.http(instanceURL).get() (err, res, body) ->
# Need to hit instanceURL so that image gets generated
callback img
else
msg.reply "Sorry, I couldn't generate that image."
| true | # Integrates with memegenerator.net
#
# Y U NO <text> - Generates the Y U NO GUY with the bottom caption
# of <text>
#
# I don't always <something> but when i do <text> - Generates The Most Interesting man in the World
#
# <text> ORLY? - Generates the ORLY? owl with the top caption of <text>
#
# <text> (SUCCESS|NAILED IT) - Generates success kid with the top caption of <text>
#
# <text> ALL the <things> - Generates ALL THE THINGS
#
# <text> TOO DAMN <high> - Generates THE RENT IS TOO DAMN HIGH guy
#
# Good news everyone! <news> - Generates PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI
module.exports = (robot) ->
robot.respond /Y U NO (.+)/i, (msg) ->
caption = msg.match[1] || ""
memeGenerator msg, 2, 166088, "Y U NO", caption, (url) ->
msg.send url
robot.respond /(I DON'?T ALWAYS .*) (BUT WHEN I DO,? .*)/i, (msg) ->
memeGenerator msg, 74, 2485, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*)(O\s?RLY\??.*)/i, (msg) ->
memeGenerator msg, 920, 117049, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*)(SUCCESS|NAILED IT.*)/i, (msg) ->
memeGenerator msg, 121, 1031, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*) (ALL the .*)/, (msg) ->
memeGenerator msg, 6013, 1121885, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(.*) (\w+\sTOO DAMN .*)/i, (msg) ->
memeGenerator msg, 998, 203665, msg.match[1], msg.match[2], (url) ->
msg.send url
robot.respond /(GOOD NEWS EVERYONE[,.!]?) (.*)/i, (msg) ->
memeGenerator msg, 1591, 112464, msg.match[1], msg.match[2], (url) ->
msg.send url
memeGenerator = (msg, generatorID, imageID, text0, text1, callback) ->
username = process.env.HUBOT_MEMEGEN_USERNAME
password = process.PI:PASSWORD:<PASSWORD>END_PI.HUBOT_MEMEGEN_PASSWORD
unless username
msg.send "MemeGenerator username isn't set. Sign up at http://memegenerator.net"
msg.send "Then set the HUBOT_MEMEGEN_USERNAME environment variable"
return
unless password
msg.send "MemeGenerator password isn't set. Sign up at http://memegenerator.net"
msg.send "Then set the HUBOT_MEMEGEN_PASSWORD environment variable"
return
msg.http('http://version1.api.memegenerator.net/Instance_Create')
.query
username: username,
password: PI:PASSWORD:<PASSWORD>END_PI,
languageCode: 'en',
generatorID: generatorID,
imageID: imageID,
text0: text0,
text1: text1
.get() (err, res, body) ->
result = JSON.parse(body)['result']
if result? and result['instanceUrl']? and result['instanceImageUrl']?
instanceURL = result['instanceUrl']
img = "http://memegenerator.net" + result['instanceImageUrl']
msg.http(instanceURL).get() (err, res, body) ->
# Need to hit instanceURL so that image gets generated
callback img
else
msg.reply "Sorry, I couldn't generate that image."
|
[
{
"context": "override -->'\n passwordagain:\n name: 'Passwordagain'\n type: 'match'\n match: 'passw",
"end": 28821,
"score": 0.8436954021453857,
"start": 28813,
"tag": "NAME",
"value": "Password"
},
{
"context": " -->'\n passwordagain:\n name: '... | app/assets/javascripts/jqBootstrapValidation.coffee | ubik86/blog | 0 | ### jqBootstrapValidation
# A plugin for automating validation on Twitter Bootstrap formatted forms.
#
# v1.3.6
#
# License: MIT <http://opensource.org/licenses/mit-license.php> - see LICENSE file
#
# http://ReactiveRaven.github.com/jqBootstrapValidation/
###
(($) ->
createdElements = []
defaults =
options:
prependExistingHelpBlock: false
sniffHtml: true
preventSubmit: true
submitError: false
submitSuccess: false
semanticallyStrict: false
autoAdd: helpBlocks: true
filter: ->
# return $(this).is(":visible"); // only validate elements you can see
true
# validate everything
methods:
init: (options) ->
settings = $.extend(true, {}, defaults)
settings.options = $.extend(true, settings.options, options)
$siblingElements = this
uniqueForms = $.unique($siblingElements.map(->
$(this).parents('form')[0]
).toArray())
$(uniqueForms).bind 'submit', (e) ->
$form = $(this)
warningsFound = 0
$inputs = $form.find('input,textarea,select').not('[type=submit],[type=image]').filter(settings.options.filter)
$inputs.trigger('submit.validation').trigger 'validationLostFocus.validation'
$inputs.each (i, el) ->
$this = $(el)
$controlGroup = $this.parents('.form-group').first()
if $controlGroup.hasClass('warning')
$controlGroup.removeClass('warning').addClass 'error'
warningsFound++
return
$inputs.trigger 'validationLostFocus.validation'
if warningsFound
if settings.options.preventSubmit
e.preventDefault()
$form.addClass 'error'
if $.isFunction(settings.options.submitError)
settings.options.submitError $form, e, $inputs.jqBootstrapValidation('collectErrors', true)
else
$form.removeClass 'error'
if $.isFunction(settings.options.submitSuccess)
settings.options.submitSuccess $form, e
return
@each ->
# Get references to everything we're interested in
$this = $(this)
$controlGroup = $this.parents('.form-group').first()
$helpBlock = $controlGroup.find('.help-block').first()
$form = $this.parents('form').first()
validatorNames = []
# create message container if not exists
if !$helpBlock.length and settings.options.autoAdd and settings.options.autoAdd.helpBlocks
$helpBlock = $('<div class="help-block" />')
$controlGroup.find('.controls').append $helpBlock
createdElements.push $helpBlock[0]
# =============================================================
# SNIFF HTML FOR VALIDATORS
# =============================================================
# *snort sniff snuffle*
if settings.options.sniffHtml
message = ''
# ---------------------------------------------------------
# PATTERN
# ---------------------------------------------------------
if $this.attr('pattern') != undefined
message = 'Not in the expected format<!-- data-validation-pattern-message to override -->'
if $this.data('validationPatternMessage')
message = $this.data('validationPatternMessage')
$this.data 'validationPatternMessage', message
$this.data 'validationPatternRegex', $this.attr('pattern')
# ---------------------------------------------------------
# MAX
# ---------------------------------------------------------
if $this.attr('max') != undefined or $this.attr('aria-valuemax') != undefined
max = if $this.attr('max') != undefined then $this.attr('max') else $this.attr('aria-valuemax')
message = 'Too high: Maximum of \'' + max + '\'<!-- data-validation-max-message to override -->'
if $this.data('validationMaxMessage')
message = $this.data('validationMaxMessage')
$this.data 'validationMaxMessage', message
$this.data 'validationMaxMax', max
# ---------------------------------------------------------
# MIN
# ---------------------------------------------------------
if $this.attr('min') != undefined or $this.attr('aria-valuemin') != undefined
min = if $this.attr('min') != undefined then $this.attr('min') else $this.attr('aria-valuemin')
message = 'Too low: Minimum of \'' + min + '\'<!-- data-validation-min-message to override -->'
if $this.data('validationMinMessage')
message = $this.data('validationMinMessage')
$this.data 'validationMinMessage', message
$this.data 'validationMinMin', min
# ---------------------------------------------------------
# MAXLENGTH
# ---------------------------------------------------------
if $this.attr('maxlength') != undefined
message = 'Too long: Maximum of \'' + $this.attr('maxlength') + '\' characters<!-- data-validation-maxlength-message to override -->'
if $this.data('validationMaxlengthMessage')
message = $this.data('validationMaxlengthMessage')
$this.data 'validationMaxlengthMessage', message
$this.data 'validationMaxlengthMaxlength', $this.attr('maxlength')
# ---------------------------------------------------------
# MINLENGTH
# ---------------------------------------------------------
if $this.attr('minlength') != undefined
message = 'Too short: Minimum of \'' + $this.attr('minlength') + '\' characters<!-- data-validation-minlength-message to override -->'
if $this.data('validationMinlengthMessage')
message = $this.data('validationMinlengthMessage')
$this.data 'validationMinlengthMessage', message
$this.data 'validationMinlengthMinlength', $this.attr('minlength')
# ---------------------------------------------------------
# REQUIRED
# ---------------------------------------------------------
if $this.attr('required') != undefined or $this.attr('aria-required') != undefined
message = settings.builtInValidators.required.message
if $this.data('validationRequiredMessage')
message = $this.data('validationRequiredMessage')
$this.data 'validationRequiredMessage', message
# ---------------------------------------------------------
# NUMBER
# ---------------------------------------------------------
if $this.attr('type') != undefined and $this.attr('type').toLowerCase() == 'number'
message = settings.builtInValidators.number.message
if $this.data('validationNumberMessage')
message = $this.data('validationNumberMessage')
$this.data 'validationNumberMessage', message
# ---------------------------------------------------------
# EMAIL
# ---------------------------------------------------------
if $this.attr('type') != undefined and $this.attr('type').toLowerCase() == 'email'
message = 'Not a valid email address<!-- data-validator-validemail-message to override -->'
if $this.data('validationValidemailMessage')
message = $this.data('validationValidemailMessage')
else if $this.data('validationEmailMessage')
message = $this.data('validationEmailMessage')
$this.data 'validationValidemailMessage', message
# ---------------------------------------------------------
# MINCHECKED
# ---------------------------------------------------------
if $this.attr('minchecked') != undefined
message = 'Not enough options checked; Minimum of \'' + $this.attr('minchecked') + '\' required<!-- data-validation-minchecked-message to override -->'
if $this.data('validationMincheckedMessage')
message = $this.data('validationMincheckedMessage')
$this.data 'validationMincheckedMessage', message
$this.data 'validationMincheckedMinchecked', $this.attr('minchecked')
# ---------------------------------------------------------
# MAXCHECKED
# ---------------------------------------------------------
if $this.attr('maxchecked') != undefined
message = 'Too many options checked; Maximum of \'' + $this.attr('maxchecked') + '\' required<!-- data-validation-maxchecked-message to override -->'
if $this.data('validationMaxcheckedMessage')
message = $this.data('validationMaxcheckedMessage')
$this.data 'validationMaxcheckedMessage', message
$this.data 'validationMaxcheckedMaxchecked', $this.attr('maxchecked')
# =============================================================
# COLLECT VALIDATOR NAMES
# =============================================================
# Get named validators
if $this.data('validation') != undefined
validatorNames = $this.data('validation').split(',')
# Get extra ones defined on the element's data attributes
$.each $this.data(), (i, el) ->
parts = i.replace(/([A-Z])/g, ',$1').split(',')
if parts[0] == 'validation' and parts[1]
validatorNames.push parts[1]
return
# =============================================================
# NORMALISE VALIDATOR NAMES
# =============================================================
validatorNamesToInspect = validatorNames
newValidatorNamesToInspect = []
loop
# Uppercase only the first letter of each name
$.each validatorNames, (i, el) ->
validatorNames[i] = formatValidatorName(el)
return
# Remove duplicate validator names
validatorNames = $.unique(validatorNames)
# Pull out the new validator names from each shortcut
newValidatorNamesToInspect = []
$.each validatorNamesToInspect, (i, el) ->
if $this.data('validation' + el + 'Shortcut') != undefined
# Are these custom validators?
# Pull them out!
$.each $this.data('validation' + el + 'Shortcut').split(','), (i2, el2) ->
newValidatorNamesToInspect.push el2
return
else if settings.builtInValidators[el.toLowerCase()]
# Is this a recognised built-in?
# Pull it out!
validator = settings.builtInValidators[el.toLowerCase()]
if validator.type.toLowerCase() == 'shortcut'
$.each validator.shortcut.split(','), (i, el) ->
el = formatValidatorName(el)
newValidatorNamesToInspect.push el
validatorNames.push el
return
return
validatorNamesToInspect = newValidatorNamesToInspect
unless validatorNamesToInspect.length > 0
break
# =============================================================
# SET UP VALIDATOR ARRAYS
# =============================================================
validators = {}
$.each validatorNames, (i, el) ->
`var message`
# Set up the 'override' message
message = $this.data('validation' + el + 'Message')
hasOverrideMessage = message != undefined
foundValidator = false
message = if message then message else '\'' + el + '\' validation failed <!-- Add attribute \'data-validation-' + el.toLowerCase() + '-message\' to input to change this message -->'
$.each settings.validatorTypes, (validatorType, validatorTemplate) ->
if validators[validatorType] == undefined
validators[validatorType] = []
if !foundValidator and $this.data('validation' + el + formatValidatorName(validatorTemplate.name)) != undefined
validators[validatorType].push $.extend(true, {
name: formatValidatorName(validatorTemplate.name)
message: message
}, validatorTemplate.init($this, el))
foundValidator = true
return
if !foundValidator and settings.builtInValidators[el.toLowerCase()]
validator = $.extend(true, {}, settings.builtInValidators[el.toLowerCase()])
if hasOverrideMessage
validator.message = message
validatorType = validator.type.toLowerCase()
if validatorType == 'shortcut'
foundValidator = true
else
$.each settings.validatorTypes, (validatorTemplateType, validatorTemplate) ->
if validators[validatorTemplateType] == undefined
validators[validatorTemplateType] = []
if !foundValidator and validatorType == validatorTemplateType.toLowerCase()
$this.data 'validation' + el + formatValidatorName(validatorTemplate.name), validator[validatorTemplate.name.toLowerCase()]
validators[validatorType].push $.extend(validator, validatorTemplate.init($this, el))
foundValidator = true
return
if !foundValidator
$.error 'Cannot find validation info for \'' + el + '\''
return
# =============================================================
# STORE FALLBACK VALUES
# =============================================================
$helpBlock.data 'original-contents', if $helpBlock.data('original-contents') then $helpBlock.data('original-contents') else $helpBlock.html()
$helpBlock.data 'original-role', if $helpBlock.data('original-role') then $helpBlock.data('original-role') else $helpBlock.attr('role')
$controlGroup.data 'original-classes', if $controlGroup.data('original-clases') then $controlGroup.data('original-classes') else $controlGroup.attr('class')
$this.data 'original-aria-invalid', if $this.data('original-aria-invalid') then $this.data('original-aria-invalid') else $this.attr('aria-invalid')
# =============================================================
# VALIDATION
# =============================================================
$this.bind 'validation.validation', (event, params) ->
value = getValue($this)
# Get a list of the errors to apply
errorsFound = []
$.each validators, (validatorType, validatorTypeArray) ->
if value or value.length or params and params.includeEmpty or ! !settings.validatorTypes[validatorType].blockSubmit and params and ! !params.submitting
$.each validatorTypeArray, (i, validator) ->
if settings.validatorTypes[validatorType].validate($this, value, validator)
errorsFound.push validator.message
return
return
errorsFound
$this.bind 'getValidators.validation', ->
validators
# =============================================================
# WATCH FOR CHANGES
# =============================================================
$this.bind 'submit.validation', ->
$this.triggerHandler 'change.validation', submitting: true
$this.bind [
'keyup'
'focus'
'blur'
'click'
'keydown'
'keypress'
'change'
].join('.validation ') + '.validation', (e, params) ->
value = getValue($this)
errorsFound = []
$controlGroup.find('input,textarea,select').each (i, el) ->
oldCount = errorsFound.length
$.each $(el).triggerHandler('validation.validation', params), (j, message) ->
errorsFound.push message
return
if errorsFound.length > oldCount
$(el).attr 'aria-invalid', 'true'
else
original = $this.data('original-aria-invalid')
$(el).attr 'aria-invalid', if original != undefined then original else false
return
$form.find('input,select,textarea').not($this).not('[name="' + $this.attr('name') + '"]').trigger 'validationLostFocus.validation'
errorsFound = $.unique(errorsFound.sort())
# Were there any errors?
if errorsFound.length
# Better flag it up as a warning.
$controlGroup.removeClass('success error').addClass 'warning'
# How many errors did we find?
if settings.options.semanticallyStrict and errorsFound.length == 1
# Only one? Being strict? Just output it.
$helpBlock.html errorsFound[0] + (if settings.options.prependExistingHelpBlock then $helpBlock.data('original-contents') else '')
else
# Multiple? Being sloppy? Glue them together into an UL.
$helpBlock.html '<ul role="alert"><li>' + errorsFound.join('</li><li>') + '</li></ul>' + (if settings.options.prependExistingHelpBlock then $helpBlock.data('original-contents') else '')
else
$controlGroup.removeClass 'warning error success'
if value.length > 0
$controlGroup.addClass 'success'
$helpBlock.html $helpBlock.data('original-contents')
if e.type == 'blur'
$controlGroup.removeClass 'success'
return
$this.bind 'validationLostFocus.validation', ->
$controlGroup.removeClass 'success'
return
return
destroy: ->
@each ->
$this = $(this)
$controlGroup = $this.parents('.form-group').first()
$helpBlock = $controlGroup.find('.help-block').first()
# remove our events
$this.unbind '.validation'
# events are namespaced.
# reset help text
$helpBlock.html $helpBlock.data('original-contents')
# reset classes
$controlGroup.attr 'class', $controlGroup.data('original-classes')
# reset aria
$this.attr 'aria-invalid', $this.data('original-aria-invalid')
# reset role
$helpBlock.attr 'role', $this.data('original-role')
# remove all elements we created
if createdElements.indexOf($helpBlock[0]) > -1
$helpBlock.remove()
return
collectErrors: (includeEmpty) ->
errorMessages = {}
@each (i, el) ->
$el = $(el)
name = $el.attr('name')
errors = $el.triggerHandler('validation.validation', includeEmpty: true)
errorMessages[name] = $.extend(true, errors, errorMessages[name])
return
$.each errorMessages, (i, el) ->
if el.length == 0
delete errorMessages[i]
return
errorMessages
hasErrors: ->
errorMessages = []
@each (i, el) ->
errorMessages = errorMessages.concat(if $(el).triggerHandler('getValidators.validation') then $(el).triggerHandler('validation.validation', submitting: true) else [])
return
errorMessages.length > 0
override: (newDefaults) ->
defaults = $.extend(true, defaults, newDefaults)
return
validatorTypes:
callback:
name: 'callback'
init: ($this, name) ->
{
validatorName: name
callback: $this.data('validation' + name + 'Callback')
lastValue: $this.val()
lastValid: true
lastFinished: true
}
validate: ($this, value, validator) ->
if validator.lastValue == value and validator.lastFinished
return !validator.lastValid
if validator.lastFinished == true
validator.lastValue = value
validator.lastValid = true
validator.lastFinished = false
rrjqbvValidator = validator
rrjqbvThis = $this
executeFunctionByName validator.callback, window, $this, value, (data) ->
if rrjqbvValidator.lastValue == data.value
rrjqbvValidator.lastValid = data.valid
if data.message
rrjqbvValidator.message = data.message
rrjqbvValidator.lastFinished = true
rrjqbvThis.data 'validation' + rrjqbvValidator.validatorName + 'Message', rrjqbvValidator.message
# Timeout is set to avoid problems with the events being considered 'already fired'
setTimeout (->
rrjqbvThis.trigger 'change.validation'
return
), 1
# doesn't need a long timeout, just long enough for the event bubble to burst
return
false
ajax:
name: 'ajax'
init: ($this, name) ->
{
validatorName: name
url: $this.data('validation' + name + 'Ajax')
lastValue: $this.val()
lastValid: true
lastFinished: true
}
validate: ($this, value, validator) ->
if '' + validator.lastValue == '' + value and validator.lastFinished == true
return validator.lastValid == false
if validator.lastFinished == true
validator.lastValue = value
validator.lastValid = true
validator.lastFinished = false
$.ajax
url: validator.url
data: 'value=' + value + '&field=' + $this.attr('name')
dataType: 'json'
success: (data) ->
if '' + validator.lastValue == '' + data.value
validator.lastValid = ! !data.valid
if data.message
validator.message = data.message
validator.lastFinished = true
$this.data 'validation' + validator.validatorName + 'Message', validator.message
# Timeout is set to avoid problems with the events being considered 'already fired'
setTimeout (->
$this.trigger 'change.validation'
return
), 1
# doesn't need a long timeout, just long enough for the event bubble to burst
return
failure: ->
validator.lastValid = true
validator.message = 'ajax call failed'
validator.lastFinished = true
$this.data 'validation' + validator.validatorName + 'Message', validator.message
# Timeout is set to avoid problems with the events being considered 'already fired'
setTimeout (->
$this.trigger 'change.validation'
return
), 1
# doesn't need a long timeout, just long enough for the event bubble to burst
return
false
regex:
name: 'regex'
init: ($this, name) ->
{ regex: regexFromString($this.data('validation' + name + 'Regex')) }
validate: ($this, value, validator) ->
!validator.regex.test(value) and !validator.negative or validator.regex.test(value) and validator.negative
required:
name: 'required'
init: ($this, name) ->
{}
validate: ($this, value, validator) ->
! !(value.length == 0 and !validator.negative) or ! !(value.length > 0 and validator.negative)
blockSubmit: true
match:
name: 'match'
init: ($this, name) ->
element = $this.parents('form').first().find('[name="' + $this.data('validation' + name + 'Match') + '"]').first()
element.bind 'validation.validation', ->
$this.trigger 'change.validation', submitting: true
return
{ 'element': element }
validate: ($this, value, validator) ->
value != validator.element.val() and !validator.negative or value == validator.element.val() and validator.negative
blockSubmit: true
max:
name: 'max'
init: ($this, name) ->
{ max: $this.data('validation' + name + 'Max') }
validate: ($this, value, validator) ->
parseFloat(value, 10) > parseFloat(validator.max, 10) and !validator.negative or parseFloat(value, 10) <= parseFloat(validator.max, 10) and validator.negative
min:
name: 'min'
init: ($this, name) ->
{ min: $this.data('validation' + name + 'Min') }
validate: ($this, value, validator) ->
parseFloat(value) < parseFloat(validator.min) and !validator.negative or parseFloat(value) >= parseFloat(validator.min) and validator.negative
maxlength:
name: 'maxlength'
init: ($this, name) ->
{ maxlength: $this.data('validation' + name + 'Maxlength') }
validate: ($this, value, validator) ->
value.length > validator.maxlength and !validator.negative or value.length <= validator.maxlength and validator.negative
minlength:
name: 'minlength'
init: ($this, name) ->
{ minlength: $this.data('validation' + name + 'Minlength') }
validate: ($this, value, validator) ->
value.length < validator.minlength and !validator.negative or value.length >= validator.minlength and validator.negative
maxchecked:
name: 'maxchecked'
init: ($this, name) ->
elements = $this.parents('form').first().find('[name="' + $this.attr('name') + '"]')
elements.bind 'click.validation', ->
$this.trigger 'change.validation', includeEmpty: true
return
{
maxchecked: $this.data('validation' + name + 'Maxchecked')
elements: elements
}
validate: ($this, value, validator) ->
validator.elements.filter(':checked').length > validator.maxchecked and !validator.negative or validator.elements.filter(':checked').length <= validator.maxchecked and validator.negative
blockSubmit: true
minchecked:
name: 'minchecked'
init: ($this, name) ->
elements = $this.parents('form').first().find('[name="' + $this.attr('name') + '"]')
elements.bind 'click.validation', ->
$this.trigger 'change.validation', includeEmpty: true
return
{
minchecked: $this.data('validation' + name + 'Minchecked')
elements: elements
}
validate: ($this, value, validator) ->
validator.elements.filter(':checked').length < validator.minchecked and !validator.negative or validator.elements.filter(':checked').length >= validator.minchecked and validator.negative
blockSubmit: true
builtInValidators:
email:
name: 'Email'
type: 'shortcut'
shortcut: 'validemail'
validemail:
name: 'Validemail'
type: 'regex'
regex: '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}'
message: 'Not a valid email address<!-- data-validator-validemail-message to override -->'
passwordagain:
name: 'Passwordagain'
type: 'match'
match: 'password'
message: 'Does not match the given password<!-- data-validator-paswordagain-message to override -->'
positive:
name: 'Positive'
type: 'shortcut'
shortcut: 'number,positivenumber'
negative:
name: 'Negative'
type: 'shortcut'
shortcut: 'number,negativenumber'
number:
name: 'Number'
type: 'regex'
regex: '([+-]?\\d+(\\.\\d*)?([eE][+-]?[0-9]+)?)?'
message: 'Must be a number<!-- data-validator-number-message to override -->'
integer:
name: 'Integer'
type: 'regex'
regex: '[+-]?\\d+'
message: 'No decimal places allowed<!-- data-validator-integer-message to override -->'
positivenumber:
name: 'Positivenumber'
type: 'min'
min: 0
message: 'Must be a positive number<!-- data-validator-positivenumber-message to override -->'
negativenumber:
name: 'Negativenumber'
type: 'max'
max: 0
message: 'Must be a negative number<!-- data-validator-negativenumber-message to override -->'
required:
name: 'Required'
type: 'required'
message: 'This is required<!-- data-validator-required-message to override -->'
checkone:
name: 'Checkone'
type: 'minchecked'
minchecked: 1
message: 'Check at least one option<!-- data-validation-checkone-message to override -->'
formatValidatorName = (name) ->
name.toLowerCase().replace /(^|\s)([a-z])/g, (m, p1, p2) ->
p1 + p2.toUpperCase()
getValue = ($this) ->
# Extract the value we're talking about
value = $this.val()
type = $this.attr('type')
if type == 'checkbox'
value = if $this.is(':checked') then value else ''
if type == 'radio'
value = if $('input[name="' + $this.attr('name') + '"]:checked').length > 0 then value else ''
value
regexFromString = (inputstring) ->
new RegExp('^' + inputstring + '$')
###*
# Thanks to Jason Bunting via StackOverflow.com
#
# http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string#answer-359910
# Short link: http://tinyurl.com/executeFunctionByName
*
###
executeFunctionByName = (functionName, context) ->
args = Array::slice.call(arguments).splice(2)
namespaces = functionName.split('.')
func = namespaces.pop()
i = 0
while i < namespaces.length
context = context[namespaces[i]]
i++
context[func].apply this, args
$.fn.jqBootstrapValidation = (method) ->
if defaults.methods[method]
defaults.methods[method].apply this, Array::slice.call(arguments, 1)
else if typeof method == 'object' or !method
defaults.methods.init.apply this, arguments
else
$.error 'Method ' + method + ' does not exist on jQuery.jqBootstrapValidation'
null
$.jqBootstrapValidation = (options) ->
$(':input').not('[type=image],[type=submit]').jqBootstrapValidation.apply this, arguments
return
return
) jQuery
| 63240 | ### jqBootstrapValidation
# A plugin for automating validation on Twitter Bootstrap formatted forms.
#
# v1.3.6
#
# License: MIT <http://opensource.org/licenses/mit-license.php> - see LICENSE file
#
# http://ReactiveRaven.github.com/jqBootstrapValidation/
###
(($) ->
createdElements = []
defaults =
options:
prependExistingHelpBlock: false
sniffHtml: true
preventSubmit: true
submitError: false
submitSuccess: false
semanticallyStrict: false
autoAdd: helpBlocks: true
filter: ->
# return $(this).is(":visible"); // only validate elements you can see
true
# validate everything
methods:
init: (options) ->
settings = $.extend(true, {}, defaults)
settings.options = $.extend(true, settings.options, options)
$siblingElements = this
uniqueForms = $.unique($siblingElements.map(->
$(this).parents('form')[0]
).toArray())
$(uniqueForms).bind 'submit', (e) ->
$form = $(this)
warningsFound = 0
$inputs = $form.find('input,textarea,select').not('[type=submit],[type=image]').filter(settings.options.filter)
$inputs.trigger('submit.validation').trigger 'validationLostFocus.validation'
$inputs.each (i, el) ->
$this = $(el)
$controlGroup = $this.parents('.form-group').first()
if $controlGroup.hasClass('warning')
$controlGroup.removeClass('warning').addClass 'error'
warningsFound++
return
$inputs.trigger 'validationLostFocus.validation'
if warningsFound
if settings.options.preventSubmit
e.preventDefault()
$form.addClass 'error'
if $.isFunction(settings.options.submitError)
settings.options.submitError $form, e, $inputs.jqBootstrapValidation('collectErrors', true)
else
$form.removeClass 'error'
if $.isFunction(settings.options.submitSuccess)
settings.options.submitSuccess $form, e
return
@each ->
# Get references to everything we're interested in
$this = $(this)
$controlGroup = $this.parents('.form-group').first()
$helpBlock = $controlGroup.find('.help-block').first()
$form = $this.parents('form').first()
validatorNames = []
# create message container if not exists
if !$helpBlock.length and settings.options.autoAdd and settings.options.autoAdd.helpBlocks
$helpBlock = $('<div class="help-block" />')
$controlGroup.find('.controls').append $helpBlock
createdElements.push $helpBlock[0]
# =============================================================
# SNIFF HTML FOR VALIDATORS
# =============================================================
# *snort sniff snuffle*
if settings.options.sniffHtml
message = ''
# ---------------------------------------------------------
# PATTERN
# ---------------------------------------------------------
if $this.attr('pattern') != undefined
message = 'Not in the expected format<!-- data-validation-pattern-message to override -->'
if $this.data('validationPatternMessage')
message = $this.data('validationPatternMessage')
$this.data 'validationPatternMessage', message
$this.data 'validationPatternRegex', $this.attr('pattern')
# ---------------------------------------------------------
# MAX
# ---------------------------------------------------------
if $this.attr('max') != undefined or $this.attr('aria-valuemax') != undefined
max = if $this.attr('max') != undefined then $this.attr('max') else $this.attr('aria-valuemax')
message = 'Too high: Maximum of \'' + max + '\'<!-- data-validation-max-message to override -->'
if $this.data('validationMaxMessage')
message = $this.data('validationMaxMessage')
$this.data 'validationMaxMessage', message
$this.data 'validationMaxMax', max
# ---------------------------------------------------------
# MIN
# ---------------------------------------------------------
if $this.attr('min') != undefined or $this.attr('aria-valuemin') != undefined
min = if $this.attr('min') != undefined then $this.attr('min') else $this.attr('aria-valuemin')
message = 'Too low: Minimum of \'' + min + '\'<!-- data-validation-min-message to override -->'
if $this.data('validationMinMessage')
message = $this.data('validationMinMessage')
$this.data 'validationMinMessage', message
$this.data 'validationMinMin', min
# ---------------------------------------------------------
# MAXLENGTH
# ---------------------------------------------------------
if $this.attr('maxlength') != undefined
message = 'Too long: Maximum of \'' + $this.attr('maxlength') + '\' characters<!-- data-validation-maxlength-message to override -->'
if $this.data('validationMaxlengthMessage')
message = $this.data('validationMaxlengthMessage')
$this.data 'validationMaxlengthMessage', message
$this.data 'validationMaxlengthMaxlength', $this.attr('maxlength')
# ---------------------------------------------------------
# MINLENGTH
# ---------------------------------------------------------
if $this.attr('minlength') != undefined
message = 'Too short: Minimum of \'' + $this.attr('minlength') + '\' characters<!-- data-validation-minlength-message to override -->'
if $this.data('validationMinlengthMessage')
message = $this.data('validationMinlengthMessage')
$this.data 'validationMinlengthMessage', message
$this.data 'validationMinlengthMinlength', $this.attr('minlength')
# ---------------------------------------------------------
# REQUIRED
# ---------------------------------------------------------
if $this.attr('required') != undefined or $this.attr('aria-required') != undefined
message = settings.builtInValidators.required.message
if $this.data('validationRequiredMessage')
message = $this.data('validationRequiredMessage')
$this.data 'validationRequiredMessage', message
# ---------------------------------------------------------
# NUMBER
# ---------------------------------------------------------
if $this.attr('type') != undefined and $this.attr('type').toLowerCase() == 'number'
message = settings.builtInValidators.number.message
if $this.data('validationNumberMessage')
message = $this.data('validationNumberMessage')
$this.data 'validationNumberMessage', message
# ---------------------------------------------------------
# EMAIL
# ---------------------------------------------------------
if $this.attr('type') != undefined and $this.attr('type').toLowerCase() == 'email'
message = 'Not a valid email address<!-- data-validator-validemail-message to override -->'
if $this.data('validationValidemailMessage')
message = $this.data('validationValidemailMessage')
else if $this.data('validationEmailMessage')
message = $this.data('validationEmailMessage')
$this.data 'validationValidemailMessage', message
# ---------------------------------------------------------
# MINCHECKED
# ---------------------------------------------------------
if $this.attr('minchecked') != undefined
message = 'Not enough options checked; Minimum of \'' + $this.attr('minchecked') + '\' required<!-- data-validation-minchecked-message to override -->'
if $this.data('validationMincheckedMessage')
message = $this.data('validationMincheckedMessage')
$this.data 'validationMincheckedMessage', message
$this.data 'validationMincheckedMinchecked', $this.attr('minchecked')
# ---------------------------------------------------------
# MAXCHECKED
# ---------------------------------------------------------
if $this.attr('maxchecked') != undefined
message = 'Too many options checked; Maximum of \'' + $this.attr('maxchecked') + '\' required<!-- data-validation-maxchecked-message to override -->'
if $this.data('validationMaxcheckedMessage')
message = $this.data('validationMaxcheckedMessage')
$this.data 'validationMaxcheckedMessage', message
$this.data 'validationMaxcheckedMaxchecked', $this.attr('maxchecked')
# =============================================================
# COLLECT VALIDATOR NAMES
# =============================================================
# Get named validators
if $this.data('validation') != undefined
validatorNames = $this.data('validation').split(',')
# Get extra ones defined on the element's data attributes
$.each $this.data(), (i, el) ->
parts = i.replace(/([A-Z])/g, ',$1').split(',')
if parts[0] == 'validation' and parts[1]
validatorNames.push parts[1]
return
# =============================================================
# NORMALISE VALIDATOR NAMES
# =============================================================
validatorNamesToInspect = validatorNames
newValidatorNamesToInspect = []
loop
# Uppercase only the first letter of each name
$.each validatorNames, (i, el) ->
validatorNames[i] = formatValidatorName(el)
return
# Remove duplicate validator names
validatorNames = $.unique(validatorNames)
# Pull out the new validator names from each shortcut
newValidatorNamesToInspect = []
$.each validatorNamesToInspect, (i, el) ->
if $this.data('validation' + el + 'Shortcut') != undefined
# Are these custom validators?
# Pull them out!
$.each $this.data('validation' + el + 'Shortcut').split(','), (i2, el2) ->
newValidatorNamesToInspect.push el2
return
else if settings.builtInValidators[el.toLowerCase()]
# Is this a recognised built-in?
# Pull it out!
validator = settings.builtInValidators[el.toLowerCase()]
if validator.type.toLowerCase() == 'shortcut'
$.each validator.shortcut.split(','), (i, el) ->
el = formatValidatorName(el)
newValidatorNamesToInspect.push el
validatorNames.push el
return
return
validatorNamesToInspect = newValidatorNamesToInspect
unless validatorNamesToInspect.length > 0
break
# =============================================================
# SET UP VALIDATOR ARRAYS
# =============================================================
validators = {}
$.each validatorNames, (i, el) ->
`var message`
# Set up the 'override' message
message = $this.data('validation' + el + 'Message')
hasOverrideMessage = message != undefined
foundValidator = false
message = if message then message else '\'' + el + '\' validation failed <!-- Add attribute \'data-validation-' + el.toLowerCase() + '-message\' to input to change this message -->'
$.each settings.validatorTypes, (validatorType, validatorTemplate) ->
if validators[validatorType] == undefined
validators[validatorType] = []
if !foundValidator and $this.data('validation' + el + formatValidatorName(validatorTemplate.name)) != undefined
validators[validatorType].push $.extend(true, {
name: formatValidatorName(validatorTemplate.name)
message: message
}, validatorTemplate.init($this, el))
foundValidator = true
return
if !foundValidator and settings.builtInValidators[el.toLowerCase()]
validator = $.extend(true, {}, settings.builtInValidators[el.toLowerCase()])
if hasOverrideMessage
validator.message = message
validatorType = validator.type.toLowerCase()
if validatorType == 'shortcut'
foundValidator = true
else
$.each settings.validatorTypes, (validatorTemplateType, validatorTemplate) ->
if validators[validatorTemplateType] == undefined
validators[validatorTemplateType] = []
if !foundValidator and validatorType == validatorTemplateType.toLowerCase()
$this.data 'validation' + el + formatValidatorName(validatorTemplate.name), validator[validatorTemplate.name.toLowerCase()]
validators[validatorType].push $.extend(validator, validatorTemplate.init($this, el))
foundValidator = true
return
if !foundValidator
$.error 'Cannot find validation info for \'' + el + '\''
return
# =============================================================
# STORE FALLBACK VALUES
# =============================================================
$helpBlock.data 'original-contents', if $helpBlock.data('original-contents') then $helpBlock.data('original-contents') else $helpBlock.html()
$helpBlock.data 'original-role', if $helpBlock.data('original-role') then $helpBlock.data('original-role') else $helpBlock.attr('role')
$controlGroup.data 'original-classes', if $controlGroup.data('original-clases') then $controlGroup.data('original-classes') else $controlGroup.attr('class')
$this.data 'original-aria-invalid', if $this.data('original-aria-invalid') then $this.data('original-aria-invalid') else $this.attr('aria-invalid')
# =============================================================
# VALIDATION
# =============================================================
$this.bind 'validation.validation', (event, params) ->
value = getValue($this)
# Get a list of the errors to apply
errorsFound = []
$.each validators, (validatorType, validatorTypeArray) ->
if value or value.length or params and params.includeEmpty or ! !settings.validatorTypes[validatorType].blockSubmit and params and ! !params.submitting
$.each validatorTypeArray, (i, validator) ->
if settings.validatorTypes[validatorType].validate($this, value, validator)
errorsFound.push validator.message
return
return
errorsFound
$this.bind 'getValidators.validation', ->
validators
# =============================================================
# WATCH FOR CHANGES
# =============================================================
$this.bind 'submit.validation', ->
$this.triggerHandler 'change.validation', submitting: true
$this.bind [
'keyup'
'focus'
'blur'
'click'
'keydown'
'keypress'
'change'
].join('.validation ') + '.validation', (e, params) ->
value = getValue($this)
errorsFound = []
$controlGroup.find('input,textarea,select').each (i, el) ->
oldCount = errorsFound.length
$.each $(el).triggerHandler('validation.validation', params), (j, message) ->
errorsFound.push message
return
if errorsFound.length > oldCount
$(el).attr 'aria-invalid', 'true'
else
original = $this.data('original-aria-invalid')
$(el).attr 'aria-invalid', if original != undefined then original else false
return
$form.find('input,select,textarea').not($this).not('[name="' + $this.attr('name') + '"]').trigger 'validationLostFocus.validation'
errorsFound = $.unique(errorsFound.sort())
# Were there any errors?
if errorsFound.length
# Better flag it up as a warning.
$controlGroup.removeClass('success error').addClass 'warning'
# How many errors did we find?
if settings.options.semanticallyStrict and errorsFound.length == 1
# Only one? Being strict? Just output it.
$helpBlock.html errorsFound[0] + (if settings.options.prependExistingHelpBlock then $helpBlock.data('original-contents') else '')
else
# Multiple? Being sloppy? Glue them together into an UL.
$helpBlock.html '<ul role="alert"><li>' + errorsFound.join('</li><li>') + '</li></ul>' + (if settings.options.prependExistingHelpBlock then $helpBlock.data('original-contents') else '')
else
$controlGroup.removeClass 'warning error success'
if value.length > 0
$controlGroup.addClass 'success'
$helpBlock.html $helpBlock.data('original-contents')
if e.type == 'blur'
$controlGroup.removeClass 'success'
return
$this.bind 'validationLostFocus.validation', ->
$controlGroup.removeClass 'success'
return
return
destroy: ->
@each ->
$this = $(this)
$controlGroup = $this.parents('.form-group').first()
$helpBlock = $controlGroup.find('.help-block').first()
# remove our events
$this.unbind '.validation'
# events are namespaced.
# reset help text
$helpBlock.html $helpBlock.data('original-contents')
# reset classes
$controlGroup.attr 'class', $controlGroup.data('original-classes')
# reset aria
$this.attr 'aria-invalid', $this.data('original-aria-invalid')
# reset role
$helpBlock.attr 'role', $this.data('original-role')
# remove all elements we created
if createdElements.indexOf($helpBlock[0]) > -1
$helpBlock.remove()
return
collectErrors: (includeEmpty) ->
errorMessages = {}
@each (i, el) ->
$el = $(el)
name = $el.attr('name')
errors = $el.triggerHandler('validation.validation', includeEmpty: true)
errorMessages[name] = $.extend(true, errors, errorMessages[name])
return
$.each errorMessages, (i, el) ->
if el.length == 0
delete errorMessages[i]
return
errorMessages
hasErrors: ->
errorMessages = []
@each (i, el) ->
errorMessages = errorMessages.concat(if $(el).triggerHandler('getValidators.validation') then $(el).triggerHandler('validation.validation', submitting: true) else [])
return
errorMessages.length > 0
override: (newDefaults) ->
defaults = $.extend(true, defaults, newDefaults)
return
validatorTypes:
callback:
name: 'callback'
init: ($this, name) ->
{
validatorName: name
callback: $this.data('validation' + name + 'Callback')
lastValue: $this.val()
lastValid: true
lastFinished: true
}
validate: ($this, value, validator) ->
if validator.lastValue == value and validator.lastFinished
return !validator.lastValid
if validator.lastFinished == true
validator.lastValue = value
validator.lastValid = true
validator.lastFinished = false
rrjqbvValidator = validator
rrjqbvThis = $this
executeFunctionByName validator.callback, window, $this, value, (data) ->
if rrjqbvValidator.lastValue == data.value
rrjqbvValidator.lastValid = data.valid
if data.message
rrjqbvValidator.message = data.message
rrjqbvValidator.lastFinished = true
rrjqbvThis.data 'validation' + rrjqbvValidator.validatorName + 'Message', rrjqbvValidator.message
# Timeout is set to avoid problems with the events being considered 'already fired'
setTimeout (->
rrjqbvThis.trigger 'change.validation'
return
), 1
# doesn't need a long timeout, just long enough for the event bubble to burst
return
false
ajax:
name: 'ajax'
init: ($this, name) ->
{
validatorName: name
url: $this.data('validation' + name + 'Ajax')
lastValue: $this.val()
lastValid: true
lastFinished: true
}
validate: ($this, value, validator) ->
if '' + validator.lastValue == '' + value and validator.lastFinished == true
return validator.lastValid == false
if validator.lastFinished == true
validator.lastValue = value
validator.lastValid = true
validator.lastFinished = false
$.ajax
url: validator.url
data: 'value=' + value + '&field=' + $this.attr('name')
dataType: 'json'
success: (data) ->
if '' + validator.lastValue == '' + data.value
validator.lastValid = ! !data.valid
if data.message
validator.message = data.message
validator.lastFinished = true
$this.data 'validation' + validator.validatorName + 'Message', validator.message
# Timeout is set to avoid problems with the events being considered 'already fired'
setTimeout (->
$this.trigger 'change.validation'
return
), 1
# doesn't need a long timeout, just long enough for the event bubble to burst
return
failure: ->
validator.lastValid = true
validator.message = 'ajax call failed'
validator.lastFinished = true
$this.data 'validation' + validator.validatorName + 'Message', validator.message
# Timeout is set to avoid problems with the events being considered 'already fired'
setTimeout (->
$this.trigger 'change.validation'
return
), 1
# doesn't need a long timeout, just long enough for the event bubble to burst
return
false
regex:
name: 'regex'
init: ($this, name) ->
{ regex: regexFromString($this.data('validation' + name + 'Regex')) }
validate: ($this, value, validator) ->
!validator.regex.test(value) and !validator.negative or validator.regex.test(value) and validator.negative
required:
name: 'required'
init: ($this, name) ->
{}
validate: ($this, value, validator) ->
! !(value.length == 0 and !validator.negative) or ! !(value.length > 0 and validator.negative)
blockSubmit: true
match:
name: 'match'
init: ($this, name) ->
element = $this.parents('form').first().find('[name="' + $this.data('validation' + name + 'Match') + '"]').first()
element.bind 'validation.validation', ->
$this.trigger 'change.validation', submitting: true
return
{ 'element': element }
validate: ($this, value, validator) ->
value != validator.element.val() and !validator.negative or value == validator.element.val() and validator.negative
blockSubmit: true
max:
name: 'max'
init: ($this, name) ->
{ max: $this.data('validation' + name + 'Max') }
validate: ($this, value, validator) ->
parseFloat(value, 10) > parseFloat(validator.max, 10) and !validator.negative or parseFloat(value, 10) <= parseFloat(validator.max, 10) and validator.negative
min:
name: 'min'
init: ($this, name) ->
{ min: $this.data('validation' + name + 'Min') }
validate: ($this, value, validator) ->
parseFloat(value) < parseFloat(validator.min) and !validator.negative or parseFloat(value) >= parseFloat(validator.min) and validator.negative
maxlength:
name: 'maxlength'
init: ($this, name) ->
{ maxlength: $this.data('validation' + name + 'Maxlength') }
validate: ($this, value, validator) ->
value.length > validator.maxlength and !validator.negative or value.length <= validator.maxlength and validator.negative
minlength:
name: 'minlength'
init: ($this, name) ->
{ minlength: $this.data('validation' + name + 'Minlength') }
validate: ($this, value, validator) ->
value.length < validator.minlength and !validator.negative or value.length >= validator.minlength and validator.negative
maxchecked:
name: 'maxchecked'
init: ($this, name) ->
elements = $this.parents('form').first().find('[name="' + $this.attr('name') + '"]')
elements.bind 'click.validation', ->
$this.trigger 'change.validation', includeEmpty: true
return
{
maxchecked: $this.data('validation' + name + 'Maxchecked')
elements: elements
}
validate: ($this, value, validator) ->
validator.elements.filter(':checked').length > validator.maxchecked and !validator.negative or validator.elements.filter(':checked').length <= validator.maxchecked and validator.negative
blockSubmit: true
minchecked:
name: 'minchecked'
init: ($this, name) ->
elements = $this.parents('form').first().find('[name="' + $this.attr('name') + '"]')
elements.bind 'click.validation', ->
$this.trigger 'change.validation', includeEmpty: true
return
{
minchecked: $this.data('validation' + name + 'Minchecked')
elements: elements
}
validate: ($this, value, validator) ->
validator.elements.filter(':checked').length < validator.minchecked and !validator.negative or validator.elements.filter(':checked').length >= validator.minchecked and validator.negative
blockSubmit: true
builtInValidators:
email:
name: 'Email'
type: 'shortcut'
shortcut: 'validemail'
validemail:
name: 'Validemail'
type: 'regex'
regex: '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}'
message: 'Not a valid email address<!-- data-validator-validemail-message to override -->'
passwordagain:
name: '<NAME>again'
type: 'match'
match: 'password'
message: 'Does not match the given password<!-- data-validator-paswordagain-message to override -->'
positive:
name: 'Positive'
type: 'shortcut'
shortcut: 'number,positivenumber'
negative:
name: 'Negative'
type: 'shortcut'
shortcut: 'number,negativenumber'
number:
name: 'Number'
type: 'regex'
regex: '([+-]?\\d+(\\.\\d*)?([eE][+-]?[0-9]+)?)?'
message: 'Must be a number<!-- data-validator-number-message to override -->'
integer:
name: 'Integer'
type: 'regex'
regex: '[+-]?\\d+'
message: 'No decimal places allowed<!-- data-validator-integer-message to override -->'
positivenumber:
name: '<NAME>'
type: 'min'
min: 0
message: 'Must be a positive number<!-- data-validator-positivenumber-message to override -->'
negativenumber:
name: '<NAME>'
type: 'max'
max: 0
message: 'Must be a negative number<!-- data-validator-negativenumber-message to override -->'
required:
name: '<NAME>'
type: 'required'
message: 'This is required<!-- data-validator-required-message to override -->'
checkone:
name: '<NAME>'
type: 'minchecked'
minchecked: 1
message: 'Check at least one option<!-- data-validation-checkone-message to override -->'
formatValidatorName = (name) ->
name.toLowerCase().replace /(^|\s)([a-z])/g, (m, p1, p2) ->
p1 + p2.toUpperCase()
getValue = ($this) ->
# Extract the value we're talking about
value = $this.val()
type = $this.attr('type')
if type == 'checkbox'
value = if $this.is(':checked') then value else ''
if type == 'radio'
value = if $('input[name="' + $this.attr('name') + '"]:checked').length > 0 then value else ''
value
regexFromString = (inputstring) ->
new RegExp('^' + inputstring + '$')
###*
# Thanks to <NAME> via StackOverflow.com
#
# http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string#answer-359910
# Short link: http://tinyurl.com/executeFunctionByName
*
###
executeFunctionByName = (functionName, context) ->
args = Array::slice.call(arguments).splice(2)
namespaces = functionName.split('.')
func = namespaces.pop()
i = 0
while i < namespaces.length
context = context[namespaces[i]]
i++
context[func].apply this, args
$.fn.jqBootstrapValidation = (method) ->
if defaults.methods[method]
defaults.methods[method].apply this, Array::slice.call(arguments, 1)
else if typeof method == 'object' or !method
defaults.methods.init.apply this, arguments
else
$.error 'Method ' + method + ' does not exist on jQuery.jqBootstrapValidation'
null
$.jqBootstrapValidation = (options) ->
$(':input').not('[type=image],[type=submit]').jqBootstrapValidation.apply this, arguments
return
return
) jQuery
| true | ### jqBootstrapValidation
# A plugin for automating validation on Twitter Bootstrap formatted forms.
#
# v1.3.6
#
# License: MIT <http://opensource.org/licenses/mit-license.php> - see LICENSE file
#
# http://ReactiveRaven.github.com/jqBootstrapValidation/
###
(($) ->
createdElements = []
defaults =
options:
prependExistingHelpBlock: false
sniffHtml: true
preventSubmit: true
submitError: false
submitSuccess: false
semanticallyStrict: false
autoAdd: helpBlocks: true
filter: ->
# return $(this).is(":visible"); // only validate elements you can see
true
# validate everything
methods:
init: (options) ->
settings = $.extend(true, {}, defaults)
settings.options = $.extend(true, settings.options, options)
$siblingElements = this
uniqueForms = $.unique($siblingElements.map(->
$(this).parents('form')[0]
).toArray())
$(uniqueForms).bind 'submit', (e) ->
$form = $(this)
warningsFound = 0
$inputs = $form.find('input,textarea,select').not('[type=submit],[type=image]').filter(settings.options.filter)
$inputs.trigger('submit.validation').trigger 'validationLostFocus.validation'
$inputs.each (i, el) ->
$this = $(el)
$controlGroup = $this.parents('.form-group').first()
if $controlGroup.hasClass('warning')
$controlGroup.removeClass('warning').addClass 'error'
warningsFound++
return
$inputs.trigger 'validationLostFocus.validation'
if warningsFound
if settings.options.preventSubmit
e.preventDefault()
$form.addClass 'error'
if $.isFunction(settings.options.submitError)
settings.options.submitError $form, e, $inputs.jqBootstrapValidation('collectErrors', true)
else
$form.removeClass 'error'
if $.isFunction(settings.options.submitSuccess)
settings.options.submitSuccess $form, e
return
@each ->
# Get references to everything we're interested in
$this = $(this)
$controlGroup = $this.parents('.form-group').first()
$helpBlock = $controlGroup.find('.help-block').first()
$form = $this.parents('form').first()
validatorNames = []
# create message container if not exists
if !$helpBlock.length and settings.options.autoAdd and settings.options.autoAdd.helpBlocks
$helpBlock = $('<div class="help-block" />')
$controlGroup.find('.controls').append $helpBlock
createdElements.push $helpBlock[0]
# =============================================================
# SNIFF HTML FOR VALIDATORS
# =============================================================
# *snort sniff snuffle*
if settings.options.sniffHtml
message = ''
# ---------------------------------------------------------
# PATTERN
# ---------------------------------------------------------
if $this.attr('pattern') != undefined
message = 'Not in the expected format<!-- data-validation-pattern-message to override -->'
if $this.data('validationPatternMessage')
message = $this.data('validationPatternMessage')
$this.data 'validationPatternMessage', message
$this.data 'validationPatternRegex', $this.attr('pattern')
# ---------------------------------------------------------
# MAX
# ---------------------------------------------------------
if $this.attr('max') != undefined or $this.attr('aria-valuemax') != undefined
max = if $this.attr('max') != undefined then $this.attr('max') else $this.attr('aria-valuemax')
message = 'Too high: Maximum of \'' + max + '\'<!-- data-validation-max-message to override -->'
if $this.data('validationMaxMessage')
message = $this.data('validationMaxMessage')
$this.data 'validationMaxMessage', message
$this.data 'validationMaxMax', max
# ---------------------------------------------------------
# MIN
# ---------------------------------------------------------
if $this.attr('min') != undefined or $this.attr('aria-valuemin') != undefined
min = if $this.attr('min') != undefined then $this.attr('min') else $this.attr('aria-valuemin')
message = 'Too low: Minimum of \'' + min + '\'<!-- data-validation-min-message to override -->'
if $this.data('validationMinMessage')
message = $this.data('validationMinMessage')
$this.data 'validationMinMessage', message
$this.data 'validationMinMin', min
# ---------------------------------------------------------
# MAXLENGTH
# ---------------------------------------------------------
if $this.attr('maxlength') != undefined
message = 'Too long: Maximum of \'' + $this.attr('maxlength') + '\' characters<!-- data-validation-maxlength-message to override -->'
if $this.data('validationMaxlengthMessage')
message = $this.data('validationMaxlengthMessage')
$this.data 'validationMaxlengthMessage', message
$this.data 'validationMaxlengthMaxlength', $this.attr('maxlength')
# ---------------------------------------------------------
# MINLENGTH
# ---------------------------------------------------------
if $this.attr('minlength') != undefined
message = 'Too short: Minimum of \'' + $this.attr('minlength') + '\' characters<!-- data-validation-minlength-message to override -->'
if $this.data('validationMinlengthMessage')
message = $this.data('validationMinlengthMessage')
$this.data 'validationMinlengthMessage', message
$this.data 'validationMinlengthMinlength', $this.attr('minlength')
# ---------------------------------------------------------
# REQUIRED
# ---------------------------------------------------------
if $this.attr('required') != undefined or $this.attr('aria-required') != undefined
message = settings.builtInValidators.required.message
if $this.data('validationRequiredMessage')
message = $this.data('validationRequiredMessage')
$this.data 'validationRequiredMessage', message
# ---------------------------------------------------------
# NUMBER
# ---------------------------------------------------------
if $this.attr('type') != undefined and $this.attr('type').toLowerCase() == 'number'
message = settings.builtInValidators.number.message
if $this.data('validationNumberMessage')
message = $this.data('validationNumberMessage')
$this.data 'validationNumberMessage', message
# ---------------------------------------------------------
# EMAIL
# ---------------------------------------------------------
if $this.attr('type') != undefined and $this.attr('type').toLowerCase() == 'email'
message = 'Not a valid email address<!-- data-validator-validemail-message to override -->'
if $this.data('validationValidemailMessage')
message = $this.data('validationValidemailMessage')
else if $this.data('validationEmailMessage')
message = $this.data('validationEmailMessage')
$this.data 'validationValidemailMessage', message
# ---------------------------------------------------------
# MINCHECKED
# ---------------------------------------------------------
if $this.attr('minchecked') != undefined
message = 'Not enough options checked; Minimum of \'' + $this.attr('minchecked') + '\' required<!-- data-validation-minchecked-message to override -->'
if $this.data('validationMincheckedMessage')
message = $this.data('validationMincheckedMessage')
$this.data 'validationMincheckedMessage', message
$this.data 'validationMincheckedMinchecked', $this.attr('minchecked')
# ---------------------------------------------------------
# MAXCHECKED
# ---------------------------------------------------------
if $this.attr('maxchecked') != undefined
message = 'Too many options checked; Maximum of \'' + $this.attr('maxchecked') + '\' required<!-- data-validation-maxchecked-message to override -->'
if $this.data('validationMaxcheckedMessage')
message = $this.data('validationMaxcheckedMessage')
$this.data 'validationMaxcheckedMessage', message
$this.data 'validationMaxcheckedMaxchecked', $this.attr('maxchecked')
# =============================================================
# COLLECT VALIDATOR NAMES
# =============================================================
# Get named validators
if $this.data('validation') != undefined
validatorNames = $this.data('validation').split(',')
# Get extra ones defined on the element's data attributes
$.each $this.data(), (i, el) ->
parts = i.replace(/([A-Z])/g, ',$1').split(',')
if parts[0] == 'validation' and parts[1]
validatorNames.push parts[1]
return
# =============================================================
# NORMALISE VALIDATOR NAMES
# =============================================================
validatorNamesToInspect = validatorNames
newValidatorNamesToInspect = []
loop
# Uppercase only the first letter of each name
$.each validatorNames, (i, el) ->
validatorNames[i] = formatValidatorName(el)
return
# Remove duplicate validator names
validatorNames = $.unique(validatorNames)
# Pull out the new validator names from each shortcut
newValidatorNamesToInspect = []
$.each validatorNamesToInspect, (i, el) ->
if $this.data('validation' + el + 'Shortcut') != undefined
# Are these custom validators?
# Pull them out!
$.each $this.data('validation' + el + 'Shortcut').split(','), (i2, el2) ->
newValidatorNamesToInspect.push el2
return
else if settings.builtInValidators[el.toLowerCase()]
# Is this a recognised built-in?
# Pull it out!
validator = settings.builtInValidators[el.toLowerCase()]
if validator.type.toLowerCase() == 'shortcut'
$.each validator.shortcut.split(','), (i, el) ->
el = formatValidatorName(el)
newValidatorNamesToInspect.push el
validatorNames.push el
return
return
validatorNamesToInspect = newValidatorNamesToInspect
unless validatorNamesToInspect.length > 0
break
# =============================================================
# SET UP VALIDATOR ARRAYS
# =============================================================
validators = {}
$.each validatorNames, (i, el) ->
`var message`
# Set up the 'override' message
message = $this.data('validation' + el + 'Message')
hasOverrideMessage = message != undefined
foundValidator = false
message = if message then message else '\'' + el + '\' validation failed <!-- Add attribute \'data-validation-' + el.toLowerCase() + '-message\' to input to change this message -->'
$.each settings.validatorTypes, (validatorType, validatorTemplate) ->
if validators[validatorType] == undefined
validators[validatorType] = []
if !foundValidator and $this.data('validation' + el + formatValidatorName(validatorTemplate.name)) != undefined
validators[validatorType].push $.extend(true, {
name: formatValidatorName(validatorTemplate.name)
message: message
}, validatorTemplate.init($this, el))
foundValidator = true
return
if !foundValidator and settings.builtInValidators[el.toLowerCase()]
validator = $.extend(true, {}, settings.builtInValidators[el.toLowerCase()])
if hasOverrideMessage
validator.message = message
validatorType = validator.type.toLowerCase()
if validatorType == 'shortcut'
foundValidator = true
else
$.each settings.validatorTypes, (validatorTemplateType, validatorTemplate) ->
if validators[validatorTemplateType] == undefined
validators[validatorTemplateType] = []
if !foundValidator and validatorType == validatorTemplateType.toLowerCase()
$this.data 'validation' + el + formatValidatorName(validatorTemplate.name), validator[validatorTemplate.name.toLowerCase()]
validators[validatorType].push $.extend(validator, validatorTemplate.init($this, el))
foundValidator = true
return
if !foundValidator
$.error 'Cannot find validation info for \'' + el + '\''
return
# =============================================================
# STORE FALLBACK VALUES
# =============================================================
$helpBlock.data 'original-contents', if $helpBlock.data('original-contents') then $helpBlock.data('original-contents') else $helpBlock.html()
$helpBlock.data 'original-role', if $helpBlock.data('original-role') then $helpBlock.data('original-role') else $helpBlock.attr('role')
$controlGroup.data 'original-classes', if $controlGroup.data('original-clases') then $controlGroup.data('original-classes') else $controlGroup.attr('class')
$this.data 'original-aria-invalid', if $this.data('original-aria-invalid') then $this.data('original-aria-invalid') else $this.attr('aria-invalid')
# =============================================================
# VALIDATION
# =============================================================
$this.bind 'validation.validation', (event, params) ->
value = getValue($this)
# Get a list of the errors to apply
errorsFound = []
$.each validators, (validatorType, validatorTypeArray) ->
if value or value.length or params and params.includeEmpty or ! !settings.validatorTypes[validatorType].blockSubmit and params and ! !params.submitting
$.each validatorTypeArray, (i, validator) ->
if settings.validatorTypes[validatorType].validate($this, value, validator)
errorsFound.push validator.message
return
return
errorsFound
$this.bind 'getValidators.validation', ->
validators
# =============================================================
# WATCH FOR CHANGES
# =============================================================
$this.bind 'submit.validation', ->
$this.triggerHandler 'change.validation', submitting: true
$this.bind [
'keyup'
'focus'
'blur'
'click'
'keydown'
'keypress'
'change'
].join('.validation ') + '.validation', (e, params) ->
value = getValue($this)
errorsFound = []
$controlGroup.find('input,textarea,select').each (i, el) ->
oldCount = errorsFound.length
$.each $(el).triggerHandler('validation.validation', params), (j, message) ->
errorsFound.push message
return
if errorsFound.length > oldCount
$(el).attr 'aria-invalid', 'true'
else
original = $this.data('original-aria-invalid')
$(el).attr 'aria-invalid', if original != undefined then original else false
return
$form.find('input,select,textarea').not($this).not('[name="' + $this.attr('name') + '"]').trigger 'validationLostFocus.validation'
errorsFound = $.unique(errorsFound.sort())
# Were there any errors?
if errorsFound.length
# Better flag it up as a warning.
$controlGroup.removeClass('success error').addClass 'warning'
# How many errors did we find?
if settings.options.semanticallyStrict and errorsFound.length == 1
# Only one? Being strict? Just output it.
$helpBlock.html errorsFound[0] + (if settings.options.prependExistingHelpBlock then $helpBlock.data('original-contents') else '')
else
# Multiple? Being sloppy? Glue them together into an UL.
$helpBlock.html '<ul role="alert"><li>' + errorsFound.join('</li><li>') + '</li></ul>' + (if settings.options.prependExistingHelpBlock then $helpBlock.data('original-contents') else '')
else
$controlGroup.removeClass 'warning error success'
if value.length > 0
$controlGroup.addClass 'success'
$helpBlock.html $helpBlock.data('original-contents')
if e.type == 'blur'
$controlGroup.removeClass 'success'
return
$this.bind 'validationLostFocus.validation', ->
$controlGroup.removeClass 'success'
return
return
destroy: ->
@each ->
$this = $(this)
$controlGroup = $this.parents('.form-group').first()
$helpBlock = $controlGroup.find('.help-block').first()
# remove our events
$this.unbind '.validation'
# events are namespaced.
# reset help text
$helpBlock.html $helpBlock.data('original-contents')
# reset classes
$controlGroup.attr 'class', $controlGroup.data('original-classes')
# reset aria
$this.attr 'aria-invalid', $this.data('original-aria-invalid')
# reset role
$helpBlock.attr 'role', $this.data('original-role')
# remove all elements we created
if createdElements.indexOf($helpBlock[0]) > -1
$helpBlock.remove()
return
collectErrors: (includeEmpty) ->
errorMessages = {}
@each (i, el) ->
$el = $(el)
name = $el.attr('name')
errors = $el.triggerHandler('validation.validation', includeEmpty: true)
errorMessages[name] = $.extend(true, errors, errorMessages[name])
return
$.each errorMessages, (i, el) ->
if el.length == 0
delete errorMessages[i]
return
errorMessages
hasErrors: ->
errorMessages = []
@each (i, el) ->
errorMessages = errorMessages.concat(if $(el).triggerHandler('getValidators.validation') then $(el).triggerHandler('validation.validation', submitting: true) else [])
return
errorMessages.length > 0
override: (newDefaults) ->
defaults = $.extend(true, defaults, newDefaults)
return
validatorTypes:
callback:
name: 'callback'
init: ($this, name) ->
{
validatorName: name
callback: $this.data('validation' + name + 'Callback')
lastValue: $this.val()
lastValid: true
lastFinished: true
}
validate: ($this, value, validator) ->
if validator.lastValue == value and validator.lastFinished
return !validator.lastValid
if validator.lastFinished == true
validator.lastValue = value
validator.lastValid = true
validator.lastFinished = false
rrjqbvValidator = validator
rrjqbvThis = $this
executeFunctionByName validator.callback, window, $this, value, (data) ->
if rrjqbvValidator.lastValue == data.value
rrjqbvValidator.lastValid = data.valid
if data.message
rrjqbvValidator.message = data.message
rrjqbvValidator.lastFinished = true
rrjqbvThis.data 'validation' + rrjqbvValidator.validatorName + 'Message', rrjqbvValidator.message
# Timeout is set to avoid problems with the events being considered 'already fired'
setTimeout (->
rrjqbvThis.trigger 'change.validation'
return
), 1
# doesn't need a long timeout, just long enough for the event bubble to burst
return
false
ajax:
name: 'ajax'
init: ($this, name) ->
{
validatorName: name
url: $this.data('validation' + name + 'Ajax')
lastValue: $this.val()
lastValid: true
lastFinished: true
}
validate: ($this, value, validator) ->
if '' + validator.lastValue == '' + value and validator.lastFinished == true
return validator.lastValid == false
if validator.lastFinished == true
validator.lastValue = value
validator.lastValid = true
validator.lastFinished = false
$.ajax
url: validator.url
data: 'value=' + value + '&field=' + $this.attr('name')
dataType: 'json'
success: (data) ->
if '' + validator.lastValue == '' + data.value
validator.lastValid = ! !data.valid
if data.message
validator.message = data.message
validator.lastFinished = true
$this.data 'validation' + validator.validatorName + 'Message', validator.message
# Timeout is set to avoid problems with the events being considered 'already fired'
setTimeout (->
$this.trigger 'change.validation'
return
), 1
# doesn't need a long timeout, just long enough for the event bubble to burst
return
failure: ->
validator.lastValid = true
validator.message = 'ajax call failed'
validator.lastFinished = true
$this.data 'validation' + validator.validatorName + 'Message', validator.message
# Timeout is set to avoid problems with the events being considered 'already fired'
setTimeout (->
$this.trigger 'change.validation'
return
), 1
# doesn't need a long timeout, just long enough for the event bubble to burst
return
false
regex:
name: 'regex'
init: ($this, name) ->
{ regex: regexFromString($this.data('validation' + name + 'Regex')) }
validate: ($this, value, validator) ->
!validator.regex.test(value) and !validator.negative or validator.regex.test(value) and validator.negative
required:
name: 'required'
init: ($this, name) ->
{}
validate: ($this, value, validator) ->
! !(value.length == 0 and !validator.negative) or ! !(value.length > 0 and validator.negative)
blockSubmit: true
match:
name: 'match'
init: ($this, name) ->
element = $this.parents('form').first().find('[name="' + $this.data('validation' + name + 'Match') + '"]').first()
element.bind 'validation.validation', ->
$this.trigger 'change.validation', submitting: true
return
{ 'element': element }
validate: ($this, value, validator) ->
value != validator.element.val() and !validator.negative or value == validator.element.val() and validator.negative
blockSubmit: true
max:
name: 'max'
init: ($this, name) ->
{ max: $this.data('validation' + name + 'Max') }
validate: ($this, value, validator) ->
parseFloat(value, 10) > parseFloat(validator.max, 10) and !validator.negative or parseFloat(value, 10) <= parseFloat(validator.max, 10) and validator.negative
min:
name: 'min'
init: ($this, name) ->
{ min: $this.data('validation' + name + 'Min') }
validate: ($this, value, validator) ->
parseFloat(value) < parseFloat(validator.min) and !validator.negative or parseFloat(value) >= parseFloat(validator.min) and validator.negative
maxlength:
name: 'maxlength'
init: ($this, name) ->
{ maxlength: $this.data('validation' + name + 'Maxlength') }
validate: ($this, value, validator) ->
value.length > validator.maxlength and !validator.negative or value.length <= validator.maxlength and validator.negative
minlength:
name: 'minlength'
init: ($this, name) ->
{ minlength: $this.data('validation' + name + 'Minlength') }
validate: ($this, value, validator) ->
value.length < validator.minlength and !validator.negative or value.length >= validator.minlength and validator.negative
maxchecked:
name: 'maxchecked'
init: ($this, name) ->
elements = $this.parents('form').first().find('[name="' + $this.attr('name') + '"]')
elements.bind 'click.validation', ->
$this.trigger 'change.validation', includeEmpty: true
return
{
maxchecked: $this.data('validation' + name + 'Maxchecked')
elements: elements
}
validate: ($this, value, validator) ->
validator.elements.filter(':checked').length > validator.maxchecked and !validator.negative or validator.elements.filter(':checked').length <= validator.maxchecked and validator.negative
blockSubmit: true
minchecked:
name: 'minchecked'
init: ($this, name) ->
elements = $this.parents('form').first().find('[name="' + $this.attr('name') + '"]')
elements.bind 'click.validation', ->
$this.trigger 'change.validation', includeEmpty: true
return
{
minchecked: $this.data('validation' + name + 'Minchecked')
elements: elements
}
validate: ($this, value, validator) ->
validator.elements.filter(':checked').length < validator.minchecked and !validator.negative or validator.elements.filter(':checked').length >= validator.minchecked and validator.negative
blockSubmit: true
builtInValidators:
email:
name: 'Email'
type: 'shortcut'
shortcut: 'validemail'
validemail:
name: 'Validemail'
type: 'regex'
regex: '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}'
message: 'Not a valid email address<!-- data-validator-validemail-message to override -->'
passwordagain:
name: 'PI:NAME:<NAME>END_PIagain'
type: 'match'
match: 'password'
message: 'Does not match the given password<!-- data-validator-paswordagain-message to override -->'
positive:
name: 'Positive'
type: 'shortcut'
shortcut: 'number,positivenumber'
negative:
name: 'Negative'
type: 'shortcut'
shortcut: 'number,negativenumber'
number:
name: 'Number'
type: 'regex'
regex: '([+-]?\\d+(\\.\\d*)?([eE][+-]?[0-9]+)?)?'
message: 'Must be a number<!-- data-validator-number-message to override -->'
integer:
name: 'Integer'
type: 'regex'
regex: '[+-]?\\d+'
message: 'No decimal places allowed<!-- data-validator-integer-message to override -->'
positivenumber:
name: 'PI:NAME:<NAME>END_PI'
type: 'min'
min: 0
message: 'Must be a positive number<!-- data-validator-positivenumber-message to override -->'
negativenumber:
name: 'PI:NAME:<NAME>END_PI'
type: 'max'
max: 0
message: 'Must be a negative number<!-- data-validator-negativenumber-message to override -->'
required:
name: 'PI:NAME:<NAME>END_PI'
type: 'required'
message: 'This is required<!-- data-validator-required-message to override -->'
checkone:
name: 'PI:NAME:<NAME>END_PI'
type: 'minchecked'
minchecked: 1
message: 'Check at least one option<!-- data-validation-checkone-message to override -->'
formatValidatorName = (name) ->
name.toLowerCase().replace /(^|\s)([a-z])/g, (m, p1, p2) ->
p1 + p2.toUpperCase()
getValue = ($this) ->
# Extract the value we're talking about
value = $this.val()
type = $this.attr('type')
if type == 'checkbox'
value = if $this.is(':checked') then value else ''
if type == 'radio'
value = if $('input[name="' + $this.attr('name') + '"]:checked').length > 0 then value else ''
value
regexFromString = (inputstring) ->
new RegExp('^' + inputstring + '$')
###*
# Thanks to PI:NAME:<NAME>END_PI via StackOverflow.com
#
# http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string#answer-359910
# Short link: http://tinyurl.com/executeFunctionByName
*
###
executeFunctionByName = (functionName, context) ->
args = Array::slice.call(arguments).splice(2)
namespaces = functionName.split('.')
func = namespaces.pop()
i = 0
while i < namespaces.length
context = context[namespaces[i]]
i++
context[func].apply this, args
$.fn.jqBootstrapValidation = (method) ->
if defaults.methods[method]
defaults.methods[method].apply this, Array::slice.call(arguments, 1)
else if typeof method == 'object' or !method
defaults.methods.init.apply this, arguments
else
$.error 'Method ' + method + ' does not exist on jQuery.jqBootstrapValidation'
null
$.jqBootstrapValidation = (options) ->
$(':input').not('[type=image],[type=submit]').jqBootstrapValidation.apply this, arguments
return
return
) jQuery
|
[
{
"context": "oGLib\n# Module | Stat Methods\n# Author | Sherif Emabrak\n# Description | functionj return median array of ",
"end": 163,
"score": 0.9998729825019836,
"start": 149,
"tag": "NAME",
"value": "Sherif Emabrak"
}
] | src/lib/statistics/smooth/median.coffee | Sherif-Embarak/gp-test | 0 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | Sherif Emabrak
# Description | functionj return median array of inputs
# ------------------------------------------------------------------------------
median = (input_array...) ->
size = input_array.length
posetion = 0
result = 0
if size%2 isnt 0
posetion = (size-1)/2
result = input_array[posetion]
else
posetion = size / 2
result = (input_array[posetion]+input_array[posetion-1])/2
result | 5309 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | <NAME>
# Description | functionj return median array of inputs
# ------------------------------------------------------------------------------
median = (input_array...) ->
size = input_array.length
posetion = 0
result = 0
if size%2 isnt 0
posetion = (size-1)/2
result = input_array[posetion]
else
posetion = size / 2
result = (input_array[posetion]+input_array[posetion-1])/2
result | true | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | PI:NAME:<NAME>END_PI
# Description | functionj return median array of inputs
# ------------------------------------------------------------------------------
median = (input_array...) ->
size = input_array.length
posetion = 0
result = 0
if size%2 isnt 0
posetion = (size-1)/2
result = input_array[posetion]
else
posetion = size / 2
result = (input_array[posetion]+input_array[posetion-1])/2
result |
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998569488525391,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
},
{
"context": "escription,nugget)\n edit_action: jQ... | src/plugins/citehandler.coffee | git-j/hallo | 0 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
# citehandler
# common functions for citation/publication/sourcedescription handling
# this is a singleton class that needs to be initialized outside of hallo and does
# heavy usage of non-hallo infrastructure
# creates a tooltip when hovering a '.cite' span that displays more information about the cite
# this functions require to work even if hallo is not enabled
# uses citeproc-js to produce a full-bibliography and adds buttons for edit/remove
# requires: DOMNugget
# SettingsModelConnector (omc_settings)
# hallotipoverlay (tipoverlay.coffee)
# ObjectContextConnector (GotoObject)
# utils.correctAndOpenFilepath
# wke.openUrlInBrowser
# uses ??? to s????
root = exports ? this
# singleton interface
class root.citehandler
_instance = undefined # Must be declared here to force the closure on the class
window.citehandler = @ # export for initialisation in edit*
@get: (args) -> # Must be a static method
_instance ?= new _Citehandler args
# private class
class _Citehandler
tips: null
editable: null
tipping_element: null
tip_element: null
constructor: (@args) ->
@settings = {}
@citation_data = {}
@tips = jQuery('<span></span>')
@overlay_id = 'cite_overlay'
@_makeTip()
# remove all editable sourcedescription and recreate them with the current data
# called from the toolbar
setupSourceDescriptions: (target, editable, add_element_cb) ->
# debug.log('setup sourcedescriptions...')
target.find('.SourceDescription').remove()
domnugget = new DOMNugget();
omc_settings.getSettings().done (settings) =>
domnugget.getDOMSourceDescriptions(editable.element.closest('.nugget'),settings).done (sourcedescriptions) =>
jQuery.each sourcedescriptions, (index,item) =>
# debug.log('setup sourcedescriptions...',index,item)
target.append(add_element_cb(item.title,null,item.type,item.loid).addClass('SourceDescription'))
# update settings from the current application settings
# usualy the relevant change may be the citation-style
_updateSettings: ->
if ( omc_settings )
omc_settings.getSettings().done (current_settings) =>
@settings = current_settings
# with multiple editables, the given element (usualy triggered by mouseover)
# must find its parent editable in order to perform correctly
# updates the @editable accordingly and falls back to finding the @editable
# when hallo was never initialized
_sync_editable: (element, change_focus) ->
@editable = window.hallo_current_instance.editable
tip_nugget = element.closest('.nugget');
if ( @editable && @editable.closest('.nugget')[0] != tip_nugget)
@editable = null
if ( typeof @editable == 'undefined' || ! @editable )
@editable = {}
@editable.element = element.closest('[contenteditable="true"]')
if ( !@editable.element.length )
@editable.element = element.closest('.nugget').find('>.content').eq(0)
@editable.is_auto_editable = true
if ( change_focus )
@editable.element.hallo('enable')
@editable.element.focus()
@editable.nugget_only = true
# create the HTML for the hallotip by evaluating the nugget sourcedescription, the citation data
# and creating bibliographies
_makeTip: () -> # (target, element) -> # target: jq-dom-node (tip), element: jq-dom-node (tipping element)
@_updateSettings()
is_auto_cite = false
if ( typeof @editable == 'object' && null != @editable && @editable.element )
if ( @tipping_element.closest('.Z3988').hasClass('auto-cite') )
is_auto_cite = true;
if ( window.citeproc )
citation_processor = window.citeproc
else
citation_processor = new ICiteProc()
nugget = new DOMNugget();
jQuery('body').citationPopup (
citation_processor: citation_processor
class_name: 'hallo_sourcedescription_popup'
goto_action: (publication_loid) =>
occ.GotoObject(publication_loid)
# activity_router.gotoInstance(publication_loid)
goto_url_action: (url) =>
wke.openUrlInBrowser(url)
goto_file_action: (filename) =>
utils.correctAndOpenFilePath(filename)
save_action: jQuery.proxy(nugget.addSourceDescription,nugget)
edit_action: jQuery.proxy(@_sourcedescriptioneditorAction,@)
remove_action: jQuery.proxy(@_removeAction,@)
remove_from_nugget_action: jQuery.proxy(@_removeAction,@)
get_source_description_data: jQuery.proxy(nugget.getSourceDescriptionData,nugget)
citation_selector: '.cite > .csl'
citation_data_selector: '.cite'
)
_sourcedescriptioneditorAction: (citation_data, tip_element, tipping_element) =>
@_sync_editable(tipping_element,true)
dom_nugget = tipping_element.closest('.nugget')
if ( typeof UndoManager != 'undefined' && typeof @editable.undoWaypointIdentifier == 'function' )
wpid = @editable.undoWaypointIdentifier(dom_nugget)
undo_stack = (new UndoManager()).getStack(wpid)
undo_stack.clear()
jQuery('body').hallosourcedescriptioneditor
'loid': citation_data.loid
'data': citation_data
'element': tipping_element
'tip_element': tip_element
'back':true
'nugget_loid':@editable.element.closest('.Text').attr('id')
_removeAction: (citation_data, tip_element, tipping_element) =>
nugget = new DOMNugget();
@_sync_editable(tipping_element,true)
loid = tipping_element.closest('.cite').attr('class').replace(/^.*sourcedescription-(\d*).*$/,'$1')
#console.log(loid);
citation = tipping_element.closest('.cite').prev('.citation')
is_auto_cite = tipping_element.closest('.cite').hasClass('auto-cite')
citation_html = ''
if ( !citation_data.processed )
loid = tipping_element.closest('.cite').attr('class').replace(/^.*sourcedescription-(\d*).*$/,'$1')
citation = tipping_element.closest('.cite').prev('.citation')
if ( citation.length )
citation_html = citation.html()
#not that simple: citation.selectText()
citation.contents().unwrap();
#console.log(citation.html())
if ( tipping_element.closest('.cite').length )
cite = tipping_element.closest('.cite')
#not that simple: @tipping_element.closest('.cite').selectText()
cite.remove()
jQuery('#' + @overlay_id).remove()
return
if ( citation.length )
citation_html = citation.html()
#not that simple: citation.selectText()
citation.contents().unwrap();
#console.log(citation.html())
if ( is_auto_cite )
sd_loid = citation_data.loid
nugget.removeSourceDescription(@editable.element,sd_loid)
if ( tipping_element.closest('.cite').length )
cite = tipping_element.closest('.cite')
#not that simple: @tipping_element.closest('.cite').selectText()
cite.remove()
$('.sourcedescription-' + loid).prev('.citation').replaceWith(citation_html)
$('.sourcedescription-' + loid).remove()
#console.log('citation removed')
$('.cite').attr('contenteditable',false)
@editable.element.hallo('enable')
@editable.element.focus()
@editable.element.hallo('setModified')
@editable.element.blur()
jQuery('#' + @overlay_id).remove()
#console.log(@editable.element.html());
if ( is_auto_cite )
publication_loid = citation_data.ploid
dom_nugget = @editable.element.closest('.nugget')
if ( typeof UndoManager != 'undefined' && typeof @editable.undoWaypointIdentifier == 'function' )
wpid = @editable.undoWaypointIdentifier(dom_nugget)
undo_stack = (new UndoManager()).getStack(wpid)
undo_stack.clear()
#undo_command.undo = (event) =>
# undo_command.dfd = omc.AssociatePublication(nugget_loid,publication_loid)
# undo_command.postdo()
#undo_command.redo = (event) =>
# undo_command.dfd = nugget.removeSourceDescription(@editable.element,sd_loid)
# undo_command.postdo()
#undo_command.postdo = (event) =>
# nothing
if ( @editable.element )
@editable.element.closest('.nugget').find('.auto-cite').remove()
nugget.prepareTextForEdit(@editable.element)
nugget.updateSourceDescriptionData(@editable.element).done =>
nugget.resetCitations(@editable.element).done =>
#@editable.element.hallo('disable')
#console.warn('@editable.undoWaypoint()')
if ( typeof MathJax != 'undefined' )
MathJax.Hub.Queue(['Typeset',MathJax.Hub]) | 119538 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
# citehandler
# common functions for citation/publication/sourcedescription handling
# this is a singleton class that needs to be initialized outside of hallo and does
# heavy usage of non-hallo infrastructure
# creates a tooltip when hovering a '.cite' span that displays more information about the cite
# this functions require to work even if hallo is not enabled
# uses citeproc-js to produce a full-bibliography and adds buttons for edit/remove
# requires: DOMNugget
# SettingsModelConnector (omc_settings)
# hallotipoverlay (tipoverlay.coffee)
# ObjectContextConnector (GotoObject)
# utils.correctAndOpenFilepath
# wke.openUrlInBrowser
# uses ??? to s????
root = exports ? this
# singleton interface
class root.citehandler
_instance = undefined # Must be declared here to force the closure on the class
window.citehandler = @ # export for initialisation in edit*
@get: (args) -> # Must be a static method
_instance ?= new _Citehandler args
# private class
class _Citehandler
tips: null
editable: null
tipping_element: null
tip_element: null
constructor: (@args) ->
@settings = {}
@citation_data = {}
@tips = jQuery('<span></span>')
@overlay_id = 'cite_overlay'
@_makeTip()
# remove all editable sourcedescription and recreate them with the current data
# called from the toolbar
setupSourceDescriptions: (target, editable, add_element_cb) ->
# debug.log('setup sourcedescriptions...')
target.find('.SourceDescription').remove()
domnugget = new DOMNugget();
omc_settings.getSettings().done (settings) =>
domnugget.getDOMSourceDescriptions(editable.element.closest('.nugget'),settings).done (sourcedescriptions) =>
jQuery.each sourcedescriptions, (index,item) =>
# debug.log('setup sourcedescriptions...',index,item)
target.append(add_element_cb(item.title,null,item.type,item.loid).addClass('SourceDescription'))
# update settings from the current application settings
# usualy the relevant change may be the citation-style
_updateSettings: ->
if ( omc_settings )
omc_settings.getSettings().done (current_settings) =>
@settings = current_settings
# with multiple editables, the given element (usualy triggered by mouseover)
# must find its parent editable in order to perform correctly
# updates the @editable accordingly and falls back to finding the @editable
# when hallo was never initialized
_sync_editable: (element, change_focus) ->
@editable = window.hallo_current_instance.editable
tip_nugget = element.closest('.nugget');
if ( @editable && @editable.closest('.nugget')[0] != tip_nugget)
@editable = null
if ( typeof @editable == 'undefined' || ! @editable )
@editable = {}
@editable.element = element.closest('[contenteditable="true"]')
if ( !@editable.element.length )
@editable.element = element.closest('.nugget').find('>.content').eq(0)
@editable.is_auto_editable = true
if ( change_focus )
@editable.element.hallo('enable')
@editable.element.focus()
@editable.nugget_only = true
# create the HTML for the hallotip by evaluating the nugget sourcedescription, the citation data
# and creating bibliographies
_makeTip: () -> # (target, element) -> # target: jq-dom-node (tip), element: jq-dom-node (tipping element)
@_updateSettings()
is_auto_cite = false
if ( typeof @editable == 'object' && null != @editable && @editable.element )
if ( @tipping_element.closest('.Z3988').hasClass('auto-cite') )
is_auto_cite = true;
if ( window.citeproc )
citation_processor = window.citeproc
else
citation_processor = new ICiteProc()
nugget = new DOMNugget();
jQuery('body').citationPopup (
citation_processor: citation_processor
class_name: 'hallo_sourcedescription_popup'
goto_action: (publication_loid) =>
occ.GotoObject(publication_loid)
# activity_router.gotoInstance(publication_loid)
goto_url_action: (url) =>
wke.openUrlInBrowser(url)
goto_file_action: (filename) =>
utils.correctAndOpenFilePath(filename)
save_action: jQuery.proxy(nugget.addSourceDescription,nugget)
edit_action: jQuery.proxy(@_sourcedescriptioneditorAction,@)
remove_action: jQuery.proxy(@_removeAction,@)
remove_from_nugget_action: jQuery.proxy(@_removeAction,@)
get_source_description_data: jQuery.proxy(nugget.getSourceDescriptionData,nugget)
citation_selector: '.cite > .csl'
citation_data_selector: '.cite'
)
_sourcedescriptioneditorAction: (citation_data, tip_element, tipping_element) =>
@_sync_editable(tipping_element,true)
dom_nugget = tipping_element.closest('.nugget')
if ( typeof UndoManager != 'undefined' && typeof @editable.undoWaypointIdentifier == 'function' )
wpid = @editable.undoWaypointIdentifier(dom_nugget)
undo_stack = (new UndoManager()).getStack(wpid)
undo_stack.clear()
jQuery('body').hallosourcedescriptioneditor
'loid': citation_data.loid
'data': citation_data
'element': tipping_element
'tip_element': tip_element
'back':true
'nugget_loid':@editable.element.closest('.Text').attr('id')
_removeAction: (citation_data, tip_element, tipping_element) =>
nugget = new DOMNugget();
@_sync_editable(tipping_element,true)
loid = tipping_element.closest('.cite').attr('class').replace(/^.*sourcedescription-(\d*).*$/,'$1')
#console.log(loid);
citation = tipping_element.closest('.cite').prev('.citation')
is_auto_cite = tipping_element.closest('.cite').hasClass('auto-cite')
citation_html = ''
if ( !citation_data.processed )
loid = tipping_element.closest('.cite').attr('class').replace(/^.*sourcedescription-(\d*).*$/,'$1')
citation = tipping_element.closest('.cite').prev('.citation')
if ( citation.length )
citation_html = citation.html()
#not that simple: citation.selectText()
citation.contents().unwrap();
#console.log(citation.html())
if ( tipping_element.closest('.cite').length )
cite = tipping_element.closest('.cite')
#not that simple: @tipping_element.closest('.cite').selectText()
cite.remove()
jQuery('#' + @overlay_id).remove()
return
if ( citation.length )
citation_html = citation.html()
#not that simple: citation.selectText()
citation.contents().unwrap();
#console.log(citation.html())
if ( is_auto_cite )
sd_loid = citation_data.loid
nugget.removeSourceDescription(@editable.element,sd_loid)
if ( tipping_element.closest('.cite').length )
cite = tipping_element.closest('.cite')
#not that simple: @tipping_element.closest('.cite').selectText()
cite.remove()
$('.sourcedescription-' + loid).prev('.citation').replaceWith(citation_html)
$('.sourcedescription-' + loid).remove()
#console.log('citation removed')
$('.cite').attr('contenteditable',false)
@editable.element.hallo('enable')
@editable.element.focus()
@editable.element.hallo('setModified')
@editable.element.blur()
jQuery('#' + @overlay_id).remove()
#console.log(@editable.element.html());
if ( is_auto_cite )
publication_loid = citation_data.ploid
dom_nugget = @editable.element.closest('.nugget')
if ( typeof UndoManager != 'undefined' && typeof @editable.undoWaypointIdentifier == 'function' )
wpid = @editable.undoWaypointIdentifier(dom_nugget)
undo_stack = (new UndoManager()).getStack(wpid)
undo_stack.clear()
#undo_command.undo = (event) =>
# undo_command.dfd = omc.AssociatePublication(nugget_loid,publication_loid)
# undo_command.postdo()
#undo_command.redo = (event) =>
# undo_command.dfd = nugget.removeSourceDescription(@editable.element,sd_loid)
# undo_command.postdo()
#undo_command.postdo = (event) =>
# nothing
if ( @editable.element )
@editable.element.closest('.nugget').find('.auto-cite').remove()
nugget.prepareTextForEdit(@editable.element)
nugget.updateSourceDescriptionData(@editable.element).done =>
nugget.resetCitations(@editable.element).done =>
#@editable.element.hallo('disable')
#console.warn('@editable.undoWaypoint()')
if ( typeof MathJax != 'undefined' )
MathJax.Hub.Queue(['Typeset',MathJax.Hub]) | true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
# citehandler
# common functions for citation/publication/sourcedescription handling
# this is a singleton class that needs to be initialized outside of hallo and does
# heavy usage of non-hallo infrastructure
# creates a tooltip when hovering a '.cite' span that displays more information about the cite
# this functions require to work even if hallo is not enabled
# uses citeproc-js to produce a full-bibliography and adds buttons for edit/remove
# requires: DOMNugget
# SettingsModelConnector (omc_settings)
# hallotipoverlay (tipoverlay.coffee)
# ObjectContextConnector (GotoObject)
# utils.correctAndOpenFilepath
# wke.openUrlInBrowser
# uses ??? to s????
root = exports ? this
# singleton interface
class root.citehandler
_instance = undefined # Must be declared here to force the closure on the class
window.citehandler = @ # export for initialisation in edit*
@get: (args) -> # Must be a static method
_instance ?= new _Citehandler args
# private class
class _Citehandler
tips: null
editable: null
tipping_element: null
tip_element: null
constructor: (@args) ->
@settings = {}
@citation_data = {}
@tips = jQuery('<span></span>')
@overlay_id = 'cite_overlay'
@_makeTip()
# remove all editable sourcedescription and recreate them with the current data
# called from the toolbar
setupSourceDescriptions: (target, editable, add_element_cb) ->
# debug.log('setup sourcedescriptions...')
target.find('.SourceDescription').remove()
domnugget = new DOMNugget();
omc_settings.getSettings().done (settings) =>
domnugget.getDOMSourceDescriptions(editable.element.closest('.nugget'),settings).done (sourcedescriptions) =>
jQuery.each sourcedescriptions, (index,item) =>
# debug.log('setup sourcedescriptions...',index,item)
target.append(add_element_cb(item.title,null,item.type,item.loid).addClass('SourceDescription'))
# update settings from the current application settings
# usualy the relevant change may be the citation-style
_updateSettings: ->
if ( omc_settings )
omc_settings.getSettings().done (current_settings) =>
@settings = current_settings
# with multiple editables, the given element (usualy triggered by mouseover)
# must find its parent editable in order to perform correctly
# updates the @editable accordingly and falls back to finding the @editable
# when hallo was never initialized
_sync_editable: (element, change_focus) ->
@editable = window.hallo_current_instance.editable
tip_nugget = element.closest('.nugget');
if ( @editable && @editable.closest('.nugget')[0] != tip_nugget)
@editable = null
if ( typeof @editable == 'undefined' || ! @editable )
@editable = {}
@editable.element = element.closest('[contenteditable="true"]')
if ( !@editable.element.length )
@editable.element = element.closest('.nugget').find('>.content').eq(0)
@editable.is_auto_editable = true
if ( change_focus )
@editable.element.hallo('enable')
@editable.element.focus()
@editable.nugget_only = true
# create the HTML for the hallotip by evaluating the nugget sourcedescription, the citation data
# and creating bibliographies
_makeTip: () -> # (target, element) -> # target: jq-dom-node (tip), element: jq-dom-node (tipping element)
@_updateSettings()
is_auto_cite = false
if ( typeof @editable == 'object' && null != @editable && @editable.element )
if ( @tipping_element.closest('.Z3988').hasClass('auto-cite') )
is_auto_cite = true;
if ( window.citeproc )
citation_processor = window.citeproc
else
citation_processor = new ICiteProc()
nugget = new DOMNugget();
jQuery('body').citationPopup (
citation_processor: citation_processor
class_name: 'hallo_sourcedescription_popup'
goto_action: (publication_loid) =>
occ.GotoObject(publication_loid)
# activity_router.gotoInstance(publication_loid)
goto_url_action: (url) =>
wke.openUrlInBrowser(url)
goto_file_action: (filename) =>
utils.correctAndOpenFilePath(filename)
save_action: jQuery.proxy(nugget.addSourceDescription,nugget)
edit_action: jQuery.proxy(@_sourcedescriptioneditorAction,@)
remove_action: jQuery.proxy(@_removeAction,@)
remove_from_nugget_action: jQuery.proxy(@_removeAction,@)
get_source_description_data: jQuery.proxy(nugget.getSourceDescriptionData,nugget)
citation_selector: '.cite > .csl'
citation_data_selector: '.cite'
)
_sourcedescriptioneditorAction: (citation_data, tip_element, tipping_element) =>
@_sync_editable(tipping_element,true)
dom_nugget = tipping_element.closest('.nugget')
if ( typeof UndoManager != 'undefined' && typeof @editable.undoWaypointIdentifier == 'function' )
wpid = @editable.undoWaypointIdentifier(dom_nugget)
undo_stack = (new UndoManager()).getStack(wpid)
undo_stack.clear()
jQuery('body').hallosourcedescriptioneditor
'loid': citation_data.loid
'data': citation_data
'element': tipping_element
'tip_element': tip_element
'back':true
'nugget_loid':@editable.element.closest('.Text').attr('id')
_removeAction: (citation_data, tip_element, tipping_element) =>
nugget = new DOMNugget();
@_sync_editable(tipping_element,true)
loid = tipping_element.closest('.cite').attr('class').replace(/^.*sourcedescription-(\d*).*$/,'$1')
#console.log(loid);
citation = tipping_element.closest('.cite').prev('.citation')
is_auto_cite = tipping_element.closest('.cite').hasClass('auto-cite')
citation_html = ''
if ( !citation_data.processed )
loid = tipping_element.closest('.cite').attr('class').replace(/^.*sourcedescription-(\d*).*$/,'$1')
citation = tipping_element.closest('.cite').prev('.citation')
if ( citation.length )
citation_html = citation.html()
#not that simple: citation.selectText()
citation.contents().unwrap();
#console.log(citation.html())
if ( tipping_element.closest('.cite').length )
cite = tipping_element.closest('.cite')
#not that simple: @tipping_element.closest('.cite').selectText()
cite.remove()
jQuery('#' + @overlay_id).remove()
return
if ( citation.length )
citation_html = citation.html()
#not that simple: citation.selectText()
citation.contents().unwrap();
#console.log(citation.html())
if ( is_auto_cite )
sd_loid = citation_data.loid
nugget.removeSourceDescription(@editable.element,sd_loid)
if ( tipping_element.closest('.cite').length )
cite = tipping_element.closest('.cite')
#not that simple: @tipping_element.closest('.cite').selectText()
cite.remove()
$('.sourcedescription-' + loid).prev('.citation').replaceWith(citation_html)
$('.sourcedescription-' + loid).remove()
#console.log('citation removed')
$('.cite').attr('contenteditable',false)
@editable.element.hallo('enable')
@editable.element.focus()
@editable.element.hallo('setModified')
@editable.element.blur()
jQuery('#' + @overlay_id).remove()
#console.log(@editable.element.html());
if ( is_auto_cite )
publication_loid = citation_data.ploid
dom_nugget = @editable.element.closest('.nugget')
if ( typeof UndoManager != 'undefined' && typeof @editable.undoWaypointIdentifier == 'function' )
wpid = @editable.undoWaypointIdentifier(dom_nugget)
undo_stack = (new UndoManager()).getStack(wpid)
undo_stack.clear()
#undo_command.undo = (event) =>
# undo_command.dfd = omc.AssociatePublication(nugget_loid,publication_loid)
# undo_command.postdo()
#undo_command.redo = (event) =>
# undo_command.dfd = nugget.removeSourceDescription(@editable.element,sd_loid)
# undo_command.postdo()
#undo_command.postdo = (event) =>
# nothing
if ( @editable.element )
@editable.element.closest('.nugget').find('.auto-cite').remove()
nugget.prepareTextForEdit(@editable.element)
nugget.updateSourceDescriptionData(@editable.element).done =>
nugget.resetCitations(@editable.element).done =>
#@editable.element.hallo('disable')
#console.warn('@editable.undoWaypoint()')
if ( typeof MathJax != 'undefined' )
MathJax.Hub.Queue(['Typeset',MathJax.Hub]) |
[
{
"context": "es.end((i++).toString()))\n\n @server.listen(0, '127.0.0.1', =>\n @port = @server.address().port\n p",
"end": 597,
"score": 0.9994227886199951,
"start": 588,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "\n\n 'open urls': (done) ->\n @page.... | node_modules/grunt-mocha-debug/node_modules/phantomjs-wrapper/test/index.coffee | bbuchsbaum/psycloud | 0 | http = require('http')
path = require('path')
phantomjs = require('../src')
suite =
'*suiteSetup': (done) ->
i = 1
@server = http.createServer((req, res) =>
if req.url == '/reloadcb'
res.writeHead(200, 'Content-Type': 'text/html')
return res.end(
"""
<html>
<body>
<script>
callPhantom('hi');
</script>
</body>
</html>
"""
)
res.writeHead(200, 'Content-Type': 'text/plain')
res.end((i++).toString()))
@server.listen(0, '127.0.0.1', =>
@port = @server.address().port
phantomjs(debug: false, timeout: 5000, (err, phantom) =>
@phantom = phantom
done()))
'*suiteTeardown': (done) ->
@phantom.close(=>
@server.close(=>
done()))
'*setup': (done) ->
@phantom.createPage((err, page) =>
@page = page
done())
'*teardown': (done) ->
@page.close(done)
'create pages': (done) ->
expect(@page.id).to.eql(0)
@phantom.createPage((err, page) =>
expect(page.id).to.eql(1)
page.close(done))
'open urls': (done) ->
@page.open("http://127.0.0.1:#{@port}", (err) =>
@page.get('plainText', (err, val) =>
expect(val).to.eql('1')
done()))
'evaluate and callback': (done) ->
@page.open("http://127.0.0.1:#{@port}", (err) =>
@page.get('plainText', (err, val) =>
expect(val).to.eql('2')
@page.on('callback', (msg) =>
expect(msg).to.deep.eql(name: 'msg')
done())
@page.evaluateJavaScript('(function() { callPhantom({name: "msg"}) })')
)
)
'inject and callback': (done) ->
@page.open("http://127.0.0.1:#{@port}", (err) =>
@page.get('plainText', (err, val) =>
expect(val).to.eql('3')
@page.on('callback', (msg) =>
expect(msg).to.deep.eql('Injected script!')
done())
injectPath = path.resolve(path.join(__dirname, '../../test/inject.js'))
@page.injectJs(injectPath, -> )))
'reload': (done) ->
i = 0
@page.on('callback', (msg) =>
i++
expect(msg).to.eql('hi')
if i == 3
done()
)
@page.open("http://127.0.0.1:#{@port}/reloadcb", (err) =>
# @page.reload(=> @page.reload(-> )))
@page.reload(=> @page.reload())
)
run(suite)
| 137225 | http = require('http')
path = require('path')
phantomjs = require('../src')
suite =
'*suiteSetup': (done) ->
i = 1
@server = http.createServer((req, res) =>
if req.url == '/reloadcb'
res.writeHead(200, 'Content-Type': 'text/html')
return res.end(
"""
<html>
<body>
<script>
callPhantom('hi');
</script>
</body>
</html>
"""
)
res.writeHead(200, 'Content-Type': 'text/plain')
res.end((i++).toString()))
@server.listen(0, '127.0.0.1', =>
@port = @server.address().port
phantomjs(debug: false, timeout: 5000, (err, phantom) =>
@phantom = phantom
done()))
'*suiteTeardown': (done) ->
@phantom.close(=>
@server.close(=>
done()))
'*setup': (done) ->
@phantom.createPage((err, page) =>
@page = page
done())
'*teardown': (done) ->
@page.close(done)
'create pages': (done) ->
expect(@page.id).to.eql(0)
@phantom.createPage((err, page) =>
expect(page.id).to.eql(1)
page.close(done))
'open urls': (done) ->
@page.open("http://127.0.0.1:#{@port}", (err) =>
@page.get('plainText', (err, val) =>
expect(val).to.eql('1')
done()))
'evaluate and callback': (done) ->
@page.open("http://127.0.0.1:#{@port}", (err) =>
@page.get('plainText', (err, val) =>
expect(val).to.eql('2')
@page.on('callback', (msg) =>
expect(msg).to.deep.eql(name: 'msg')
done())
@page.evaluateJavaScript('(function() { callPhantom({name: "msg"}) })')
)
)
'inject and callback': (done) ->
@page.open("http://127.0.0.1:#{@port}", (err) =>
@page.get('plainText', (err, val) =>
expect(val).to.eql('3')
@page.on('callback', (msg) =>
expect(msg).to.deep.eql('Injected script!')
done())
injectPath = path.resolve(path.join(__dirname, '../../test/inject.js'))
@page.injectJs(injectPath, -> )))
'reload': (done) ->
i = 0
@page.on('callback', (msg) =>
i++
expect(msg).to.eql('hi')
if i == 3
done()
)
@page.open("http://1192.168.127.12:#{@port}/reloadcb", (err) =>
# @page.reload(=> @page.reload(-> )))
@page.reload(=> @page.reload())
)
run(suite)
| true | http = require('http')
path = require('path')
phantomjs = require('../src')
suite =
'*suiteSetup': (done) ->
i = 1
@server = http.createServer((req, res) =>
if req.url == '/reloadcb'
res.writeHead(200, 'Content-Type': 'text/html')
return res.end(
"""
<html>
<body>
<script>
callPhantom('hi');
</script>
</body>
</html>
"""
)
res.writeHead(200, 'Content-Type': 'text/plain')
res.end((i++).toString()))
@server.listen(0, '127.0.0.1', =>
@port = @server.address().port
phantomjs(debug: false, timeout: 5000, (err, phantom) =>
@phantom = phantom
done()))
'*suiteTeardown': (done) ->
@phantom.close(=>
@server.close(=>
done()))
'*setup': (done) ->
@phantom.createPage((err, page) =>
@page = page
done())
'*teardown': (done) ->
@page.close(done)
'create pages': (done) ->
expect(@page.id).to.eql(0)
@phantom.createPage((err, page) =>
expect(page.id).to.eql(1)
page.close(done))
'open urls': (done) ->
@page.open("http://127.0.0.1:#{@port}", (err) =>
@page.get('plainText', (err, val) =>
expect(val).to.eql('1')
done()))
'evaluate and callback': (done) ->
@page.open("http://127.0.0.1:#{@port}", (err) =>
@page.get('plainText', (err, val) =>
expect(val).to.eql('2')
@page.on('callback', (msg) =>
expect(msg).to.deep.eql(name: 'msg')
done())
@page.evaluateJavaScript('(function() { callPhantom({name: "msg"}) })')
)
)
'inject and callback': (done) ->
@page.open("http://127.0.0.1:#{@port}", (err) =>
@page.get('plainText', (err, val) =>
expect(val).to.eql('3')
@page.on('callback', (msg) =>
expect(msg).to.deep.eql('Injected script!')
done())
injectPath = path.resolve(path.join(__dirname, '../../test/inject.js'))
@page.injectJs(injectPath, -> )))
'reload': (done) ->
i = 0
@page.on('callback', (msg) =>
i++
expect(msg).to.eql('hi')
if i == 3
done()
)
@page.open("http://1PI:IP_ADDRESS:192.168.127.12END_PI:#{@port}/reloadcb", (err) =>
# @page.reload(=> @page.reload(-> )))
@page.reload(=> @page.reload())
)
run(suite)
|
[
{
"context": "\n\nPrint something like\n\n```javascript\n[ { key: 'my_key_1',\n , column: 'my_column_family:my_column'\n ",
"end": 2521,
"score": 0.6496736407279968,
"start": 2521,
"tag": "KEY",
"value": ""
},
{
"context": "85942781739\n , '$': 'my value 1'\n }\n, { key: 'my_key_2... | src/row.coffee | LiveTex/node-hbase | 0 | utils = require("./utils")
Table = require("./table")
###
Row operations: CRUD operation on rows and columns
==================================================
Row objects provide access and multipulation on colunns and rows. Single and multiple operations are available and are documented below.
Grab an instance of "Row"
-------------------------
```javascript
var myRow = hbase({}).getRow('my_table','my_row');
```
Or
```javascript
var myRow = hbase({}).getTable('my_table').getRow('my_row');
```
Or
```javascript
var client = new hbase.Client({});
var myRow = new hbase.Row(client, 'my_table', 'my_row');
```
###
Row = (client, table, key) ->
@client = client
@table = (if typeof table is "string" then table else table.name)
@key = key
@
###
Retrieve values from HBase
--------------------------
```javascript
myRow.get([column], [options], [callback]);
```
Column is optional and corresponds to a column family optionnally followed by a column name separated with a column (":").
An optional object of options may contains the following properties:
- start: timestamp indicating the minimal version date
- end: timestamp indicating the maximal version date
- v: maximum number of returned versions
Callback is required and receive two arguments, an error object if any and the column value.
```javascript
hbase()
.getRow('my_table','my_row')
.get('my_column_family', {from: 1285942515900}, function(error, value){
console.log(value);
});
```
Print something like
```json
[ { column: 'my_column_family:'
, timestamp: 1285942722246
, '$': 'my value 1'
}
, { column: 'my_column_family:'
, timestamp: 1285942705504
, '$': 'my value 2'
}
, { column: 'my_column_family:my_column'
, timestamp: 1285942515955
, '$': 'my value 3'
}
]
```
Attempting to retrieve a column which does not exist in HBase will return a null value and an error whose code property is set to 404.
```javascript
hbase()
.getRow('my_table','my_row')
.get('my_column_family:my_column', function(error, value){
assert.strictEqual(404, error.code);
assert.strictEqual(null, value);
});
```
Retrieve values from multiple rows
----------------------------------
Values from multiple rows is achieved by appending a suffix glob on the row key. Note the new "key" property present in the returned objects.
```javascript
hbase()
.getRow('my_table','my_key_*')
.get('my_column_family:my_column', function(error, value){
console.log(value);
});
```
Print something like
```javascript
[ { key: 'my_key_1',
, column: 'my_column_family:my_column'
, timestamp: 1285942781739
, '$': 'my value 1'
}
, { key: 'my_key_2',
, column: 'my_column_family:my_column'
, timestamp: 12859425923984
, '$': 'my value 2'
}
]
```
###
# myRow.get([column], [callback])
Row::get = (column, callback) ->
self = this
args = Array::slice.call(arguments)
key = "/" + @table + "/" + @key
isGlob = @key.substr(-1, 1) is "*"
options = {}
columns = null
start = null
end = null
params = {}
columns = args.shift() if typeof args[0] is "string" or (typeof args[0] is "object" and args[0] instanceof Array)
options = args.shift() if typeof args[0] is "object"
start = options.start if options.start
end = options.end if options.end
params.v = options.v if options.v
url = utils.url.encode(@table, @key, columns, start, end, params)
@client.connection.get url, (error, data) ->
return args[0].apply(self, [error, null]) if error
cells = []
data.Row.forEach (row) ->
key = utils.base64.decode(row.key)
row.Cell.forEach (cell) ->
data = {}
data.key = key if isGlob
data.column = utils.base64.decode(cell.column)
data.timestamp = cell.timestamp
data.$ = utils.base64.decode(cell.$)
cells.push data
args[0].apply self, [null, cells]
###
Insert and update a column value
--------------------------------
```javascript
myRow.put(column, data, [timestamp], [callback]);
```
Column is required and corresponds to a column family optionnally followed by a column name separated with a column (":").
Callback is optional and receive two arguments, an error object if any and a boolean indicating whether the column was inserted/updated or not.
```javascript
hbase()
.getRow('my_table', 'my_row')
.put('my_column_family:my_column', 'my value', function(error, success){
assert.strictEqual(true, success);
});
```
Insert and update multiple column values
----------------------------------------
```javascript
myRow.put(columns, values, [timestamps], [callback]);
myRow.put(data, [callback]);
```
Inserting values into multiple columns is achieved the same way as for a single column but the column and data arguments must be an array of the same length.
```javascript
hbase()
.getRow('my_table', 'my_row')
.put(
['my_column_family:my_column_1', 'my_column_family:my_column_2'],
['my value 1', 'my value 2'],
function(error, success){
assert.strictEqual(true, success);
}
);
```
Alternatively, you could provide an array of cells as below:
```javascript
var cells =
[ { column: 'cf:c1', timestamp: Date.now(), $: 'my value' }
, { column: 'cf:c2', timestamp: Date.now(), $: 'my value' }
, { column: 'cf:c1', timestamp: Date.now()+1, $: 'my value' }
];
hbase()
.getRow('my_table', 'my_row')
.put(cells, function(error, success){
assert.strictEqual(true, success);
});
```
Insert and update multiple rows
-------------------------------
```javascript
myRow.put(data, [callback]);
```
HBase allows us to send multiple cells from multiple rows in batch. To achieve it, construct a new row with a null key and provide the `put` function with an array of cells. Each cell objects must include the row `key`, `column` and `$` properties while `timestamp` is optional.
```javascript
var rows =
[ { key: 'row_1', column: 'cf:c1', timestamp: Date.now(), $: 'my value' }
, { key: 'row_1', column: 'cf:c2', timestamp: Date.now(), $: 'my value' }
, { key: 'row_2', column: 'cf:c1', timestamp: Date.now()+1, $: 'my value' }
];
hbase()
.getRow('my_table', null)
.put(rows, function(error,success){
assert.strictEqual(true, success);
});
```
###
# myRow.put(column(s), value(s), [timestamp(s)], [callback])
# myRow.put(data, [callback])
Row::put = (columns, values, callback) ->
self = this
args = Array::slice.call(arguments)
url = undefined
body = undefined
bodyRow = undefined
if args.length > 2
columns = args.shift()
values = args.shift()
timestamps = undefined
timestamps = args.shift() if typeof args[0] isnt "function"
callback = args.shift()
if typeof columns is "string"
columns = [columns]
values = [values]
else throw new Error("Columns count must match values count") if columns.length isnt values.length
body = Row: []
bodyRow =
key: utils.base64.encode(self.key)
Cell: []
columns.forEach (column, i) ->
bodyCell = {}
bodyCell.timestamp = timestamps[i] if timestamps
bodyCell.column = utils.base64.encode(column)
bodyCell.$ = utils.base64.encode(values[i])
bodyRow.Cell.push bodyCell
body.Row.push bodyRow
url = utils.url.encode(@table, @key or "___false-row-key___", columns)
else
data = args.shift()
callback = args.shift()
body = Row: []
cellsKeys = {}
data.forEach (d) ->
key = d.key or self.key
cellsKeys[key] = [] unless key of cellsKeys
cellsKeys[key].push d
for k of cellsKeys
cells = cellsKeys[k]
bodyRow =
key: utils.base64.encode(k)
Cell: []
for k1 of cells
cell = cells[k1]
bodyCell = {}
bodyCell.timestamp = "" + cell.timestamp if cell.timestamp
bodyCell.column = utils.base64.encode(cell.column)
bodyCell.$ = utils.base64.encode(cell.$)
bodyRow.Cell.push bodyCell
body.Row.push bodyRow
url = utils.url.encode(@table, @key or "___false-row-key___")
@client.connection.put url, body, (error, data) ->
return unless callback
callback.apply self, [error, (if error then null else true)]
###
Test if a row or a column exists
--------------------------------
```javascript
myRow.exists([column], [callback]);
```
Column is optional and corresponds to a column family optionnally followed by a column name separated with a column (":").
Callback is required and receive two arguments, an error object if any and a boolean indicating whether the column exists or not.
Example to see if a row exists:
```javascript
hbase()
.getRow('my_table','my_row')
.exists(function(error, exists){
assert.strictEqual(true, exists);
});
```
Example to see if a column exists:
```javascript
hbase()
.getRow('my_table','my_row')
.exists('my_column_family:my_column', function(error, exists){
assert.strictEqual(true, exists);
});
```
###
# myRow.exists(column, [callback])
Row::exists = (column, callback) ->
self = this
args = Array::slice.call(arguments)
column = (if typeof args[0] is "string" then args.shift() else null)
url = utils.url.encode(@table, @key, column)
@client.connection.get url, (error, exists) ->
# note:
# if row does not exists: 404
# if row exists and column family does not exists: 503
if error and (error.code is 404 or error.code is 503)
error = null
exists = false
args[0].apply self, [error, (if error then null else ((if exists is false then false else true)))]
###
Delete a row or a column
------------------------
```javascript
myRow.delete([column], [callback]);
```
Column is optional and corresponds to a column family optionnally followed by a column name separated with a column (":").
Callback is required and receive two arguments, an error object if any and a boolean indicating whether the column exists or not.
Example to delete a row:
```javascript
hbase()
.getRow('my_table','my_row')
.delete(function(error, success){
assert.strictEqual(true, success);
});
```
Example to delete a column:
```javascript
hbase()
.getRow('my_table','my_row')
.delete('my_column_family:my_column', function(error, success){
assert.strictEqual(true, success);
});
```
Delete multiple columns
-----------------------
Deleting multiple columns is achieved by providing an array of columns as the first argument.
```javascript
hbase()
.getRow('my_table','my_row')
.delete(
['my_column_family:my_column_1', 'my_column_family:my_column_2'],
function(error, success){
assert.strictEqual(true, success);
}
);
```
###
# myRow.delete([column], [callback])
Row::delete = ->
self = this
args = Array::slice.call(arguments)
columns = undefined
columns = args.shift() if typeof args[0] is "string" or (typeof args[0] is "object" and args[0] instanceof Array)
url = utils.url.encode(@table, @key, columns)
@client.connection.delete url, ((error, success) ->
args[0].apply self, [error, (if error then null else true)]
), true
module.exports = Row | 208876 | utils = require("./utils")
Table = require("./table")
###
Row operations: CRUD operation on rows and columns
==================================================
Row objects provide access and multipulation on colunns and rows. Single and multiple operations are available and are documented below.
Grab an instance of "Row"
-------------------------
```javascript
var myRow = hbase({}).getRow('my_table','my_row');
```
Or
```javascript
var myRow = hbase({}).getTable('my_table').getRow('my_row');
```
Or
```javascript
var client = new hbase.Client({});
var myRow = new hbase.Row(client, 'my_table', 'my_row');
```
###
Row = (client, table, key) ->
@client = client
@table = (if typeof table is "string" then table else table.name)
@key = key
@
###
Retrieve values from HBase
--------------------------
```javascript
myRow.get([column], [options], [callback]);
```
Column is optional and corresponds to a column family optionnally followed by a column name separated with a column (":").
An optional object of options may contains the following properties:
- start: timestamp indicating the minimal version date
- end: timestamp indicating the maximal version date
- v: maximum number of returned versions
Callback is required and receive two arguments, an error object if any and the column value.
```javascript
hbase()
.getRow('my_table','my_row')
.get('my_column_family', {from: 1285942515900}, function(error, value){
console.log(value);
});
```
Print something like
```json
[ { column: 'my_column_family:'
, timestamp: 1285942722246
, '$': 'my value 1'
}
, { column: 'my_column_family:'
, timestamp: 1285942705504
, '$': 'my value 2'
}
, { column: 'my_column_family:my_column'
, timestamp: 1285942515955
, '$': 'my value 3'
}
]
```
Attempting to retrieve a column which does not exist in HBase will return a null value and an error whose code property is set to 404.
```javascript
hbase()
.getRow('my_table','my_row')
.get('my_column_family:my_column', function(error, value){
assert.strictEqual(404, error.code);
assert.strictEqual(null, value);
});
```
Retrieve values from multiple rows
----------------------------------
Values from multiple rows is achieved by appending a suffix glob on the row key. Note the new "key" property present in the returned objects.
```javascript
hbase()
.getRow('my_table','my_key_*')
.get('my_column_family:my_column', function(error, value){
console.log(value);
});
```
Print something like
```javascript
[ { key: 'my<KEY>_key_1',
, column: 'my_column_family:my_column'
, timestamp: 1285942781739
, '$': 'my value 1'
}
, { key: 'my_<KEY>_2',
, column: 'my_column_family:my_column'
, timestamp: 12859425923984
, '$': 'my value 2'
}
]
```
###
# myRow.get([column], [callback])
Row::get = (column, callback) ->
self = this
args = Array::slice.call(arguments)
key = "/" + @table + "/" + @key
isGlob = @key.substr(-1, 1) is "*"
options = {}
columns = null
start = null
end = null
params = {}
columns = args.shift() if typeof args[0] is "string" or (typeof args[0] is "object" and args[0] instanceof Array)
options = args.shift() if typeof args[0] is "object"
start = options.start if options.start
end = options.end if options.end
params.v = options.v if options.v
url = utils.url.encode(@table, @key, columns, start, end, params)
@client.connection.get url, (error, data) ->
return args[0].apply(self, [error, null]) if error
cells = []
data.Row.forEach (row) ->
key = utils.base64.decode(row.key)
row.Cell.forEach (cell) ->
data = {}
data.key = key if isGlob
data.column = utils.base64.decode(cell.column)
data.timestamp = cell.timestamp
data.$ = utils.base64.decode(cell.$)
cells.push data
args[0].apply self, [null, cells]
###
Insert and update a column value
--------------------------------
```javascript
myRow.put(column, data, [timestamp], [callback]);
```
Column is required and corresponds to a column family optionnally followed by a column name separated with a column (":").
Callback is optional and receive two arguments, an error object if any and a boolean indicating whether the column was inserted/updated or not.
```javascript
hbase()
.getRow('my_table', 'my_row')
.put('my_column_family:my_column', 'my value', function(error, success){
assert.strictEqual(true, success);
});
```
Insert and update multiple column values
----------------------------------------
```javascript
myRow.put(columns, values, [timestamps], [callback]);
myRow.put(data, [callback]);
```
Inserting values into multiple columns is achieved the same way as for a single column but the column and data arguments must be an array of the same length.
```javascript
hbase()
.getRow('my_table', 'my_row')
.put(
['my_column_family:my_column_1', 'my_column_family:my_column_2'],
['my value 1', 'my value 2'],
function(error, success){
assert.strictEqual(true, success);
}
);
```
Alternatively, you could provide an array of cells as below:
```javascript
var cells =
[ { column: 'cf:c1', timestamp: Date.now(), $: 'my value' }
, { column: 'cf:c2', timestamp: Date.now(), $: 'my value' }
, { column: 'cf:c1', timestamp: Date.now()+1, $: 'my value' }
];
hbase()
.getRow('my_table', 'my_row')
.put(cells, function(error, success){
assert.strictEqual(true, success);
});
```
Insert and update multiple rows
-------------------------------
```javascript
myRow.put(data, [callback]);
```
HBase allows us to send multiple cells from multiple rows in batch. To achieve it, construct a new row with a null key and provide the `put` function with an array of cells. Each cell objects must include the row `key`, `column` and `$` properties while `timestamp` is optional.
```javascript
var rows =
[ { key: '<KEY>1', column: 'cf:c1', timestamp: Date.now(), $: 'my value' }
, { key: 'row_1', column: 'cf:c2', timestamp: Date.now(), $: 'my value' }
, { key: '<KEY>2', column: 'cf:c1', timestamp: Date.now()+1, $: 'my value' }
];
hbase()
.getRow('my_table', null)
.put(rows, function(error,success){
assert.strictEqual(true, success);
});
```
###
# myRow.put(column(s), value(s), [timestamp(s)], [callback])
# myRow.put(data, [callback])
Row::put = (columns, values, callback) ->
self = this
args = Array::slice.call(arguments)
url = undefined
body = undefined
bodyRow = undefined
if args.length > 2
columns = args.shift()
values = args.shift()
timestamps = undefined
timestamps = args.shift() if typeof args[0] isnt "function"
callback = args.shift()
if typeof columns is "string"
columns = [columns]
values = [values]
else throw new Error("Columns count must match values count") if columns.length isnt values.length
body = Row: []
bodyRow =
key: utils.base64.encode(self.key)
Cell: []
columns.forEach (column, i) ->
bodyCell = {}
bodyCell.timestamp = timestamps[i] if timestamps
bodyCell.column = utils.base64.encode(column)
bodyCell.$ = utils.base64.encode(values[i])
bodyRow.Cell.push bodyCell
body.Row.push bodyRow
url = utils.url.encode(@table, @key or "___false-row-key___", columns)
else
data = args.shift()
callback = args.shift()
body = Row: []
cellsKeys = {}
data.forEach (d) ->
key = d.key or self.key
cellsKeys[key] = [] unless key of cellsKeys
cellsKeys[key].push d
for k of cellsKeys
cells = cellsKeys[k]
bodyRow =
key: <KEY>(k)
Cell: []
for k1 of cells
cell = cells[k1]
bodyCell = {}
bodyCell.timestamp = "" + cell.timestamp if cell.timestamp
bodyCell.column = utils.base64.encode(cell.column)
bodyCell.$ = utils.base64.encode(cell.$)
bodyRow.Cell.push bodyCell
body.Row.push bodyRow
url = utils.url.encode(@table, @key or "___false-row-key___")
@client.connection.put url, body, (error, data) ->
return unless callback
callback.apply self, [error, (if error then null else true)]
###
Test if a row or a column exists
--------------------------------
```javascript
myRow.exists([column], [callback]);
```
Column is optional and corresponds to a column family optionnally followed by a column name separated with a column (":").
Callback is required and receive two arguments, an error object if any and a boolean indicating whether the column exists or not.
Example to see if a row exists:
```javascript
hbase()
.getRow('my_table','my_row')
.exists(function(error, exists){
assert.strictEqual(true, exists);
});
```
Example to see if a column exists:
```javascript
hbase()
.getRow('my_table','my_row')
.exists('my_column_family:my_column', function(error, exists){
assert.strictEqual(true, exists);
});
```
###
# myRow.exists(column, [callback])
Row::exists = (column, callback) ->
self = this
args = Array::slice.call(arguments)
column = (if typeof args[0] is "string" then args.shift() else null)
url = utils.url.encode(@table, @key, column)
@client.connection.get url, (error, exists) ->
# note:
# if row does not exists: 404
# if row exists and column family does not exists: 503
if error and (error.code is 404 or error.code is 503)
error = null
exists = false
args[0].apply self, [error, (if error then null else ((if exists is false then false else true)))]
###
Delete a row or a column
------------------------
```javascript
myRow.delete([column], [callback]);
```
Column is optional and corresponds to a column family optionnally followed by a column name separated with a column (":").
Callback is required and receive two arguments, an error object if any and a boolean indicating whether the column exists or not.
Example to delete a row:
```javascript
hbase()
.getRow('my_table','my_row')
.delete(function(error, success){
assert.strictEqual(true, success);
});
```
Example to delete a column:
```javascript
hbase()
.getRow('my_table','my_row')
.delete('my_column_family:my_column', function(error, success){
assert.strictEqual(true, success);
});
```
Delete multiple columns
-----------------------
Deleting multiple columns is achieved by providing an array of columns as the first argument.
```javascript
hbase()
.getRow('my_table','my_row')
.delete(
['my_column_family:my_column_1', 'my_column_family:my_column_2'],
function(error, success){
assert.strictEqual(true, success);
}
);
```
###
# myRow.delete([column], [callback])
Row::delete = ->
self = this
args = Array::slice.call(arguments)
columns = undefined
columns = args.shift() if typeof args[0] is "string" or (typeof args[0] is "object" and args[0] instanceof Array)
url = utils.url.encode(@table, @key, columns)
@client.connection.delete url, ((error, success) ->
args[0].apply self, [error, (if error then null else true)]
), true
module.exports = Row | true | utils = require("./utils")
Table = require("./table")
###
Row operations: CRUD operation on rows and columns
==================================================
Row objects provide access and multipulation on colunns and rows. Single and multiple operations are available and are documented below.
Grab an instance of "Row"
-------------------------
```javascript
var myRow = hbase({}).getRow('my_table','my_row');
```
Or
```javascript
var myRow = hbase({}).getTable('my_table').getRow('my_row');
```
Or
```javascript
var client = new hbase.Client({});
var myRow = new hbase.Row(client, 'my_table', 'my_row');
```
###
Row = (client, table, key) ->
@client = client
@table = (if typeof table is "string" then table else table.name)
@key = key
@
###
Retrieve values from HBase
--------------------------
```javascript
myRow.get([column], [options], [callback]);
```
Column is optional and corresponds to a column family optionnally followed by a column name separated with a column (":").
An optional object of options may contains the following properties:
- start: timestamp indicating the minimal version date
- end: timestamp indicating the maximal version date
- v: maximum number of returned versions
Callback is required and receive two arguments, an error object if any and the column value.
```javascript
hbase()
.getRow('my_table','my_row')
.get('my_column_family', {from: 1285942515900}, function(error, value){
console.log(value);
});
```
Print something like
```json
[ { column: 'my_column_family:'
, timestamp: 1285942722246
, '$': 'my value 1'
}
, { column: 'my_column_family:'
, timestamp: 1285942705504
, '$': 'my value 2'
}
, { column: 'my_column_family:my_column'
, timestamp: 1285942515955
, '$': 'my value 3'
}
]
```
Attempting to retrieve a column which does not exist in HBase will return a null value and an error whose code property is set to 404.
```javascript
hbase()
.getRow('my_table','my_row')
.get('my_column_family:my_column', function(error, value){
assert.strictEqual(404, error.code);
assert.strictEqual(null, value);
});
```
Retrieve values from multiple rows
----------------------------------
Values from multiple rows is achieved by appending a suffix glob on the row key. Note the new "key" property present in the returned objects.
```javascript
hbase()
.getRow('my_table','my_key_*')
.get('my_column_family:my_column', function(error, value){
console.log(value);
});
```
Print something like
```javascript
[ { key: 'myPI:KEY:<KEY>END_PI_key_1',
, column: 'my_column_family:my_column'
, timestamp: 1285942781739
, '$': 'my value 1'
}
, { key: 'my_PI:KEY:<KEY>END_PI_2',
, column: 'my_column_family:my_column'
, timestamp: 12859425923984
, '$': 'my value 2'
}
]
```
###
# myRow.get([column], [callback])
Row::get = (column, callback) ->
self = this
args = Array::slice.call(arguments)
key = "/" + @table + "/" + @key
isGlob = @key.substr(-1, 1) is "*"
options = {}
columns = null
start = null
end = null
params = {}
columns = args.shift() if typeof args[0] is "string" or (typeof args[0] is "object" and args[0] instanceof Array)
options = args.shift() if typeof args[0] is "object"
start = options.start if options.start
end = options.end if options.end
params.v = options.v if options.v
url = utils.url.encode(@table, @key, columns, start, end, params)
@client.connection.get url, (error, data) ->
return args[0].apply(self, [error, null]) if error
cells = []
data.Row.forEach (row) ->
key = utils.base64.decode(row.key)
row.Cell.forEach (cell) ->
data = {}
data.key = key if isGlob
data.column = utils.base64.decode(cell.column)
data.timestamp = cell.timestamp
data.$ = utils.base64.decode(cell.$)
cells.push data
args[0].apply self, [null, cells]
###
Insert and update a column value
--------------------------------
```javascript
myRow.put(column, data, [timestamp], [callback]);
```
Column is required and corresponds to a column family optionnally followed by a column name separated with a column (":").
Callback is optional and receive two arguments, an error object if any and a boolean indicating whether the column was inserted/updated or not.
```javascript
hbase()
.getRow('my_table', 'my_row')
.put('my_column_family:my_column', 'my value', function(error, success){
assert.strictEqual(true, success);
});
```
Insert and update multiple column values
----------------------------------------
```javascript
myRow.put(columns, values, [timestamps], [callback]);
myRow.put(data, [callback]);
```
Inserting values into multiple columns is achieved the same way as for a single column but the column and data arguments must be an array of the same length.
```javascript
hbase()
.getRow('my_table', 'my_row')
.put(
['my_column_family:my_column_1', 'my_column_family:my_column_2'],
['my value 1', 'my value 2'],
function(error, success){
assert.strictEqual(true, success);
}
);
```
Alternatively, you could provide an array of cells as below:
```javascript
var cells =
[ { column: 'cf:c1', timestamp: Date.now(), $: 'my value' }
, { column: 'cf:c2', timestamp: Date.now(), $: 'my value' }
, { column: 'cf:c1', timestamp: Date.now()+1, $: 'my value' }
];
hbase()
.getRow('my_table', 'my_row')
.put(cells, function(error, success){
assert.strictEqual(true, success);
});
```
Insert and update multiple rows
-------------------------------
```javascript
myRow.put(data, [callback]);
```
HBase allows us to send multiple cells from multiple rows in batch. To achieve it, construct a new row with a null key and provide the `put` function with an array of cells. Each cell objects must include the row `key`, `column` and `$` properties while `timestamp` is optional.
```javascript
var rows =
[ { key: 'PI:KEY:<KEY>END_PI1', column: 'cf:c1', timestamp: Date.now(), $: 'my value' }
, { key: 'row_1', column: 'cf:c2', timestamp: Date.now(), $: 'my value' }
, { key: 'PI:KEY:<KEY>END_PI2', column: 'cf:c1', timestamp: Date.now()+1, $: 'my value' }
];
hbase()
.getRow('my_table', null)
.put(rows, function(error,success){
assert.strictEqual(true, success);
});
```
###
# myRow.put(column(s), value(s), [timestamp(s)], [callback])
# myRow.put(data, [callback])
Row::put = (columns, values, callback) ->
self = this
args = Array::slice.call(arguments)
url = undefined
body = undefined
bodyRow = undefined
if args.length > 2
columns = args.shift()
values = args.shift()
timestamps = undefined
timestamps = args.shift() if typeof args[0] isnt "function"
callback = args.shift()
if typeof columns is "string"
columns = [columns]
values = [values]
else throw new Error("Columns count must match values count") if columns.length isnt values.length
body = Row: []
bodyRow =
key: utils.base64.encode(self.key)
Cell: []
columns.forEach (column, i) ->
bodyCell = {}
bodyCell.timestamp = timestamps[i] if timestamps
bodyCell.column = utils.base64.encode(column)
bodyCell.$ = utils.base64.encode(values[i])
bodyRow.Cell.push bodyCell
body.Row.push bodyRow
url = utils.url.encode(@table, @key or "___false-row-key___", columns)
else
data = args.shift()
callback = args.shift()
body = Row: []
cellsKeys = {}
data.forEach (d) ->
key = d.key or self.key
cellsKeys[key] = [] unless key of cellsKeys
cellsKeys[key].push d
for k of cellsKeys
cells = cellsKeys[k]
bodyRow =
key: PI:KEY:<KEY>END_PI(k)
Cell: []
for k1 of cells
cell = cells[k1]
bodyCell = {}
bodyCell.timestamp = "" + cell.timestamp if cell.timestamp
bodyCell.column = utils.base64.encode(cell.column)
bodyCell.$ = utils.base64.encode(cell.$)
bodyRow.Cell.push bodyCell
body.Row.push bodyRow
url = utils.url.encode(@table, @key or "___false-row-key___")
@client.connection.put url, body, (error, data) ->
return unless callback
callback.apply self, [error, (if error then null else true)]
###
Test if a row or a column exists
--------------------------------
```javascript
myRow.exists([column], [callback]);
```
Column is optional and corresponds to a column family optionnally followed by a column name separated with a column (":").
Callback is required and receive two arguments, an error object if any and a boolean indicating whether the column exists or not.
Example to see if a row exists:
```javascript
hbase()
.getRow('my_table','my_row')
.exists(function(error, exists){
assert.strictEqual(true, exists);
});
```
Example to see if a column exists:
```javascript
hbase()
.getRow('my_table','my_row')
.exists('my_column_family:my_column', function(error, exists){
assert.strictEqual(true, exists);
});
```
###
# myRow.exists(column, [callback])
Row::exists = (column, callback) ->
self = this
args = Array::slice.call(arguments)
column = (if typeof args[0] is "string" then args.shift() else null)
url = utils.url.encode(@table, @key, column)
@client.connection.get url, (error, exists) ->
# note:
# if row does not exists: 404
# if row exists and column family does not exists: 503
if error and (error.code is 404 or error.code is 503)
error = null
exists = false
args[0].apply self, [error, (if error then null else ((if exists is false then false else true)))]
###
Delete a row or a column
------------------------
```javascript
myRow.delete([column], [callback]);
```
Column is optional and corresponds to a column family optionnally followed by a column name separated with a column (":").
Callback is required and receive two arguments, an error object if any and a boolean indicating whether the column exists or not.
Example to delete a row:
```javascript
hbase()
.getRow('my_table','my_row')
.delete(function(error, success){
assert.strictEqual(true, success);
});
```
Example to delete a column:
```javascript
hbase()
.getRow('my_table','my_row')
.delete('my_column_family:my_column', function(error, success){
assert.strictEqual(true, success);
});
```
Delete multiple columns
-----------------------
Deleting multiple columns is achieved by providing an array of columns as the first argument.
```javascript
hbase()
.getRow('my_table','my_row')
.delete(
['my_column_family:my_column_1', 'my_column_family:my_column_2'],
function(error, success){
assert.strictEqual(true, success);
}
);
```
###
# myRow.delete([column], [callback])
Row::delete = ->
self = this
args = Array::slice.call(arguments)
columns = undefined
columns = args.shift() if typeof args[0] is "string" or (typeof args[0] is "object" and args[0] instanceof Array)
url = utils.url.encode(@table, @key, columns)
@client.connection.delete url, ((error, success) ->
args[0].apply self, [error, (if error then null else true)]
), true
module.exports = Row |
[
{
"context": " <%= class_name %>Controller.js\n@author Author\n@contact Contact\n\n@copyright Copyright <%= Da",
"end": 115,
"score": 0.9649048447608948,
"start": 109,
"tag": "NAME",
"value": "Author"
}
] | lib/generators/joker/js_controller/templates/model_controller.coffee | zaeznet/joker-rails | 0 | ###
@summary App.Controllers
@version 1.0.0
@file <%= class_name %>Controller.js
@author Author
@contact Contact
@copyright Copyright <%= Date.today.year %>
###
###
Callbacks object to control the
model <%= plural_table_name %>
@type {Object}
###
App.Controllers.<%= class_name %> =
###
Callback triggered when a <%= singular_table_name %> is
successfully created
@param {DOMElements} form
###
create: (form, data)->
Joker.Core.libSupport('#list-<%= plural_table_name %>').click()
new Joker.Alert
type: Joker.Alert.TYPE_SUCCESS
message: '<%= human_name %> created successfully'
###
Callback triggered when a <%= singular_table_name %> is
successfully removed
@param {DOMElements} form
###
destroy: (form, data)->
new Joker.Alert
type: Joker.Alert.TYPE_SUCCESS
message: '<%= human_name %> successfully removed'
###
Callback triggered when a <%= singular_table_name %> is
successfully updated
@param {DOMElements} form
###
update: (form, data)->
Joker.Core.libSupport('#list-<%= plural_table_name %>').click()
new Joker.Alert
type: Joker.Alert.TYPE_SUCCESS
message: '<%= human_name %> edited successfully'
| 18989 | ###
@summary App.Controllers
@version 1.0.0
@file <%= class_name %>Controller.js
@author <NAME>
@contact Contact
@copyright Copyright <%= Date.today.year %>
###
###
Callbacks object to control the
model <%= plural_table_name %>
@type {Object}
###
App.Controllers.<%= class_name %> =
###
Callback triggered when a <%= singular_table_name %> is
successfully created
@param {DOMElements} form
###
create: (form, data)->
Joker.Core.libSupport('#list-<%= plural_table_name %>').click()
new Joker.Alert
type: Joker.Alert.TYPE_SUCCESS
message: '<%= human_name %> created successfully'
###
Callback triggered when a <%= singular_table_name %> is
successfully removed
@param {DOMElements} form
###
destroy: (form, data)->
new Joker.Alert
type: Joker.Alert.TYPE_SUCCESS
message: '<%= human_name %> successfully removed'
###
Callback triggered when a <%= singular_table_name %> is
successfully updated
@param {DOMElements} form
###
update: (form, data)->
Joker.Core.libSupport('#list-<%= plural_table_name %>').click()
new Joker.Alert
type: Joker.Alert.TYPE_SUCCESS
message: '<%= human_name %> edited successfully'
| true | ###
@summary App.Controllers
@version 1.0.0
@file <%= class_name %>Controller.js
@author PI:NAME:<NAME>END_PI
@contact Contact
@copyright Copyright <%= Date.today.year %>
###
###
Callbacks object to control the
model <%= plural_table_name %>
@type {Object}
###
App.Controllers.<%= class_name %> =
###
Callback triggered when a <%= singular_table_name %> is
successfully created
@param {DOMElements} form
###
create: (form, data)->
Joker.Core.libSupport('#list-<%= plural_table_name %>').click()
new Joker.Alert
type: Joker.Alert.TYPE_SUCCESS
message: '<%= human_name %> created successfully'
###
Callback triggered when a <%= singular_table_name %> is
successfully removed
@param {DOMElements} form
###
destroy: (form, data)->
new Joker.Alert
type: Joker.Alert.TYPE_SUCCESS
message: '<%= human_name %> successfully removed'
###
Callback triggered when a <%= singular_table_name %> is
successfully updated
@param {DOMElements} form
###
update: (form, data)->
Joker.Core.libSupport('#list-<%= plural_table_name %>').click()
new Joker.Alert
type: Joker.Alert.TYPE_SUCCESS
message: '<%= human_name %> edited successfully'
|
[
{
"context": "ing\n modelKey: 'displayName'\n jsonKey: 'display_name'\n\n 'name': Attributes.String\n modelKey: '",
"end": 343,
"score": 0.899293839931488,
"start": 331,
"tag": "KEY",
"value": "display_name"
}
] | models/folder.coffee | lever/nylas-nodejs | 0 | RestfulModel = require './restful-model'
Attributes = require './attributes'
Promise = require 'bluebird'
_ = require 'underscore'
class Label extends RestfulModel
@collectionName: 'labels'
@attributes: _.extend {}, RestfulModel.attributes,
'displayName': Attributes.String
modelKey: 'displayName'
jsonKey: 'display_name'
'name': Attributes.String
modelKey: 'name'
jsonKey: 'name'
saveRequestBody: ->
json = {}
json['display_name'] = @displayName
json['name'] = @name
json
save: (params = {}, callback = null) ->
this._save(params, callback)
class Folder extends Label
@collectionName: 'folders'
module.exports.Label = Label
module.exports.Folder = Folder
| 184393 | RestfulModel = require './restful-model'
Attributes = require './attributes'
Promise = require 'bluebird'
_ = require 'underscore'
class Label extends RestfulModel
@collectionName: 'labels'
@attributes: _.extend {}, RestfulModel.attributes,
'displayName': Attributes.String
modelKey: 'displayName'
jsonKey: '<KEY>'
'name': Attributes.String
modelKey: 'name'
jsonKey: 'name'
saveRequestBody: ->
json = {}
json['display_name'] = @displayName
json['name'] = @name
json
save: (params = {}, callback = null) ->
this._save(params, callback)
class Folder extends Label
@collectionName: 'folders'
module.exports.Label = Label
module.exports.Folder = Folder
| true | RestfulModel = require './restful-model'
Attributes = require './attributes'
Promise = require 'bluebird'
_ = require 'underscore'
class Label extends RestfulModel
@collectionName: 'labels'
@attributes: _.extend {}, RestfulModel.attributes,
'displayName': Attributes.String
modelKey: 'displayName'
jsonKey: 'PI:KEY:<KEY>END_PI'
'name': Attributes.String
modelKey: 'name'
jsonKey: 'name'
saveRequestBody: ->
json = {}
json['display_name'] = @displayName
json['name'] = @name
json
save: (params = {}, callback = null) ->
this._save(params, callback)
class Folder extends Label
@collectionName: 'folders'
module.exports.Label = Label
module.exports.Folder = Folder
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998429417610168,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai... | library/nucleus/service.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
assert = require "assert"
logger = require "winston"
uuid = require "node-uuid"
crypto = require "crypto"
colors = require "colors"
async = require "async"
nconf = require "nconf"
http = require "http"
weak = require "weak"
util = require "util"
url = require "url"
_ = require "lodash"
extendz = require "./extends"
routing = require "./routing"
scoping = require "./scoping"
{format} = require "util"
{Archetype} = require "./arche"
{urlOfServer} = require "./toolkit"
{urlOfMaster} = require "./toolkit"
# This is an abstract base class for every kind of service in this
# framework and the end user application. It provides the matching
# and processing logic based on domain matches and RE match/extract
# logics, to deal with paths. Remember that this service is just a
# an internal base class, you generally should not use it directly.
# Also, all of its functionality can be overriden by any service.
module.exports.Service = class Service extends Archetype
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: configures: yes
# A hook that will be called each time when the kernel beacon
# is being fired. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
beacon: (kernel, timestamp, next) -> next()
# A hook that will be called prior to instantiating the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
instance: (kernel, service, next) -> next()
# A hook that will be called prior to registering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
register: (kernel, router, next) -> next()
# A hook that will be called prior to unregistering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
unregister: (kernel, router, next) -> next()
# A hook that will be called prior to firing up the processing
# of the service. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
ignition: (request, response, next) -> next()
# This instance method is a shortcut that internally makes use
# of the service disposition data, obtained by call underlying
# method `disposition` of the service class itself. The alias
# exists primarily for the purpose of supporting some legacy
# constructs defined well before the underlying method were.
# For the new code, you should perhaps use `disposition`.
reference: -> @constructor.disposition().reference
# This instance method is a shortcut that internally makes use
# of the service disposition data, obtained by call underlying
# method `disposition` of the service class itself. The alias
# exists primarily for the purpose of supporting some legacy
# constructs defined well before the underlying method were.
# For the new code, you should perhaps use `disposition`.
location: -> @constructor.disposition().location
# This instance method is a shortcut that internally makes use
# of the service disposition data, obtained by call underlying
# method `disposition` of the service class itself. The alias
# exists primarily for the purpose of supporting some legacy
# constructs defined well before the underlying method were.
# For the new code, you should perhaps use `disposition`.
qualified: -> @constructor.disposition().master
# This is an instance method that will be invoked by the router
# on every service, prior to actually registering it. Method is
# intended to ask the service itself if wants and deems okay to
# be registered with the current router and kernel. This sort of
# functionality can be used to disambiguate what services should
# be loaded at what environments and configuratin circumstances.
consenting: (kernel, router, consent) -> consent yes
# Every service has to have a public constructor that accepts
# the kernel instance as a parameter. You can override it as
# you see fit, but be sure to invoke the super constructor and
# it is highly advised to store the kernel instance in object.
# It is also taking care of assigning a service identification.
constructor: (@kernel) -> super; @uuid = uuid.v4()
# This is the proxy method that uses the global kernel instance
# to use for finding the instance of the current service class.
# This instance is supposed to be properly registered with the
# router in order to be found. The actual lookup implementation
# is located in the `accquire` method of `GraniteKernel` class.
# Please refer to the original implementation for the guidance.
@accquire: -> global.GRANITE_KERNEL.accquire this, yes
# An important method whose responsibility is to create a new
# instance of the service, which is later will be registered in
# the router. This is invoked by the watcher when it discovers
# new suitable services to register. This works asynchronously!
# You need to take this into account, when overriding this one.
@spawn: (kernel, callback, alloc) ->
noKernel = "no kernel supplied or given"
noFunc = "got no valid callback function"
assert _.isObject(kernel or null), noKernel
assert _.isFunction(callback or null), noFunc
alloc ?= => new this kernel, callback, alloc
assert (service = alloc()).objectOf this or 0
assert downstream = try service.downstream or 0
message = "Spawned a new instance of %s service"
firings = "Downstream spawning sequences in %s"
identify = try @identify().toString().underline
logger.debug message.grey, identify.toString()
exec = (fun) => fun kernel, service; service
assert downstream = downstream.bind service
return exec instance = downstream instance: =>
this.configure().call service, (results) =>
logger.debug firings.grey, identify
callback.call this, service, kernel
try service.emit "instance", kernel
# This method is used to obtain all the available disposition
# data of this services. Disposition data is basically the data
# related to HTTP locations (supposedly) of the service using
# the different variations. This also includes some of internal
# referential data that does not pertain to HTTP per se. Please
# refer to the method source code for the detailed information.
@disposition: (forceSsl=no) ->
securing = require "../membrane/securing"
assert hasher = try crypto.createHash "md5"
noAbsolute = "the service origin is missing"
assert absolute = this.origin?.id, noAbsolute
assert _.isString(noAbsolute), "invalid origin"
assert _.isString identify = try this.identify()
assert factor = "#{absolute}:#{identify}" or 0
onlySsl = @derives securing.OnlySsl or forceSsl
digest = try hasher.update(factor).digest "hex"
deduce = try _.head(this.resources)?.unescape()
assert not _.isEmpty(digest), "MD5 digest fail"
assert $reference = digest or this.reference?()
assert internal = "/#{$reference}/#{identify}"
$location = deduce or @location?() or internal
$location = internal unless $location or null
$server = try urlOfServer onlySsl, $location
$master = try urlOfMaster onlySsl, $location
return new Object # make and return summary
reference: $reference or null # MD5-ed
location: $location or null # relative
server: $server or null # server URL
master: $master or null # master URL
# This method should process the already matched HTTP request.
# But since this is an abstract base class, this implementation
# only extracts the domain and pathname captured groups, and
# returns them to the caller. Override it to do some real job.
# The captured groups may be used by the overrider or ditched.
process: (request, response, next) ->
gdomain = null; gresource = null # var holders
assert resources = @constructor.resources or []
assert domains = @constructor.domains or [/^.+$/]
assert pathname = url.parse(request.url).pathname
assert identify = @constructor.identify().underline
hostname = try _.head request.headers.host.split ":"
assert not _.isEmpty hostname, "missing hostname"
pdomain = (repat) -> gdomain = hostname.match repat
presource = (repat) -> gresource = pathname.match repat
xdomain = try _.find(domains, pdomain) or null # side
xresource = _.find(resources, presource) or null # side
message = "Begin service processing sequence in %s"
logger.debug message.toString().yellow, identify
assert _.isObject request.service = try weak this
assert request.domains = gdomain, "missing domain"
assert request.resources = gresource, "no resource"
@emit "process", gdomain, gresource, arguments...
return domain: gdomain, resource: gresource
# This method determines whether the supplied HTTP request
# matches this service. This is determined by examining the
# domain/host and the path, in accordance with the patterns
# that were used for configuring the class of this service.
# It is async, so be sure to call the `decide` with boolean!
matches: (request, response, decide) ->
assert resources = @constructor.resources or []
assert domains = @constructor.domains or [/^.+$/]
assert pathname = url.parse(request.url).pathname
assert identify = @constructor.identify().underline
hostname = try _.head request.headers.host.split ":"
assert not _.isEmpty hostname, "missing hostname"
pdomain = (pattern) -> try pattern.test hostname
presource = (pattern) -> try pattern.test pathname
message = "Polling %s service for a basic match"
logger.debug message.toString().yellow, identify
domainOk = try _.some(domains, pdomain) or false
resourceOk = _.some(resources, presource) or false
matches = domainOk is yes and resourceOk is yes
this.emit "matches", matches, request, response
return decide domainOk and resourceOk
# This method handles the rescuing of the request/response pair
# when some error happens during the processing of the request
# under this service. This method is able to to deliver content
# as the response if it is desirable. If not, the request will
# simply be reject with Node.js/Connect. Beware about `next`!
rescuing: (error, request, response, next) ->
assert plain = try @constructor.identify()
assert expose = "failures:exposeExceptions"
assert not _.isEmpty method = request.method
identify = @constructor.identify().underline
template = "Exception in a #{method} at %s: %s"
logger.error template.red, identify, error.stack
@emit "failure", this, error, request, response
message = "Executed error rescue handler in %s"
logger.debug message.red, identify.toString()
return next() unless nconf.get(expose) is yes
response.setHeader "Content-Type", "text/plain"
response.writeHead 500, http.STATUS_CODES[500]
render = format template, plain, error.stack
response.end render; return next undefined
# This is a very basic method that adds the specified regular
# expression pattern to the list of permitted resource patterns.
# The patterns are associated with a service class, not object.
# Supports implicit extraction of captured groups in the match.
# Use this to configure what resources should match with service.
@resource: (pattern) ->
associate = "Associating %s resource with %s"
identify = @identify().underline.toString()
r = (s) -> new RegExp "^#{RegExp.escape(s)}$"
pattern = try r pattern if _.isString pattern
inspected = try pattern.unescape()?.underline
inspected = pattern unless _.isString inspected
source = not _.isEmpty try pattern.source or null
notReg = "the #{inspected} is not a valid regexp"
assert _.isRegExp(pattern) and source or 0, notReg
assert @resources = (@resources or []).concat pattern
assert @resources = _.unique this.resources or []
logger.silly associate, inspected, identify
return this # return itself for chaining...
# This is a very basic method that adds the specified regular
# expression pattern to the list of permitted domain patterns.
# The patterns are associated with a service class, not object.
# Supports implicit extraction of captured groups in the match.
# Use this to configure what domains should match with service.
@domain: (pattern) ->
associate = "Associating %s domain with %s"
identify = @identify().underline.toString()
r = (s) -> new RegExp "^#{RegExp.escape(s)}$"
pattern = try r pattern if _.isString pattern
inspected = try pattern.unescape()?.underline
inspected = pattern unless _.isString inspected
source = not _.isEmpty try pattern.source or null
notReg = "the #{inspected} is not a valid regexp"
assert _.isRegExp(pattern) and source or 0, notReg
assert @domains = (@domains or []).concat pattern
assert @domains = _.unique this.domains or []
logger.silly associate, inspected, identify
return this # return itself for chaining...
| 226161 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
assert = require "assert"
logger = require "winston"
uuid = require "node-uuid"
crypto = require "crypto"
colors = require "colors"
async = require "async"
nconf = require "nconf"
http = require "http"
weak = require "weak"
util = require "util"
url = require "url"
_ = require "lodash"
extendz = require "./extends"
routing = require "./routing"
scoping = require "./scoping"
{format} = require "util"
{Archetype} = require "./arche"
{urlOfServer} = require "./toolkit"
{urlOfMaster} = require "./toolkit"
# This is an abstract base class for every kind of service in this
# framework and the end user application. It provides the matching
# and processing logic based on domain matches and RE match/extract
# logics, to deal with paths. Remember that this service is just a
# an internal base class, you generally should not use it directly.
# Also, all of its functionality can be overriden by any service.
module.exports.Service = class Service extends Archetype
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: configures: yes
# A hook that will be called each time when the kernel beacon
# is being fired. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
beacon: (kernel, timestamp, next) -> next()
# A hook that will be called prior to instantiating the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
instance: (kernel, service, next) -> next()
# A hook that will be called prior to registering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
register: (kernel, router, next) -> next()
# A hook that will be called prior to unregistering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
unregister: (kernel, router, next) -> next()
# A hook that will be called prior to firing up the processing
# of the service. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
ignition: (request, response, next) -> next()
# This instance method is a shortcut that internally makes use
# of the service disposition data, obtained by call underlying
# method `disposition` of the service class itself. The alias
# exists primarily for the purpose of supporting some legacy
# constructs defined well before the underlying method were.
# For the new code, you should perhaps use `disposition`.
reference: -> @constructor.disposition().reference
# This instance method is a shortcut that internally makes use
# of the service disposition data, obtained by call underlying
# method `disposition` of the service class itself. The alias
# exists primarily for the purpose of supporting some legacy
# constructs defined well before the underlying method were.
# For the new code, you should perhaps use `disposition`.
location: -> @constructor.disposition().location
# This instance method is a shortcut that internally makes use
# of the service disposition data, obtained by call underlying
# method `disposition` of the service class itself. The alias
# exists primarily for the purpose of supporting some legacy
# constructs defined well before the underlying method were.
# For the new code, you should perhaps use `disposition`.
qualified: -> @constructor.disposition().master
# This is an instance method that will be invoked by the router
# on every service, prior to actually registering it. Method is
# intended to ask the service itself if wants and deems okay to
# be registered with the current router and kernel. This sort of
# functionality can be used to disambiguate what services should
# be loaded at what environments and configuratin circumstances.
consenting: (kernel, router, consent) -> consent yes
# Every service has to have a public constructor that accepts
# the kernel instance as a parameter. You can override it as
# you see fit, but be sure to invoke the super constructor and
# it is highly advised to store the kernel instance in object.
# It is also taking care of assigning a service identification.
constructor: (@kernel) -> super; @uuid = uuid.v4()
# This is the proxy method that uses the global kernel instance
# to use for finding the instance of the current service class.
# This instance is supposed to be properly registered with the
# router in order to be found. The actual lookup implementation
# is located in the `accquire` method of `GraniteKernel` class.
# Please refer to the original implementation for the guidance.
@accquire: -> global.GRANITE_KERNEL.accquire this, yes
# An important method whose responsibility is to create a new
# instance of the service, which is later will be registered in
# the router. This is invoked by the watcher when it discovers
# new suitable services to register. This works asynchronously!
# You need to take this into account, when overriding this one.
@spawn: (kernel, callback, alloc) ->
noKernel = "no kernel supplied or given"
noFunc = "got no valid callback function"
assert _.isObject(kernel or null), noKernel
assert _.isFunction(callback or null), noFunc
alloc ?= => new this kernel, callback, alloc
assert (service = alloc()).objectOf this or 0
assert downstream = try service.downstream or 0
message = "Spawned a new instance of %s service"
firings = "Downstream spawning sequences in %s"
identify = try @identify().toString().underline
logger.debug message.grey, identify.toString()
exec = (fun) => fun kernel, service; service
assert downstream = downstream.bind service
return exec instance = downstream instance: =>
this.configure().call service, (results) =>
logger.debug firings.grey, identify
callback.call this, service, kernel
try service.emit "instance", kernel
# This method is used to obtain all the available disposition
# data of this services. Disposition data is basically the data
# related to HTTP locations (supposedly) of the service using
# the different variations. This also includes some of internal
# referential data that does not pertain to HTTP per se. Please
# refer to the method source code for the detailed information.
@disposition: (forceSsl=no) ->
securing = require "../membrane/securing"
assert hasher = try crypto.createHash "md5"
noAbsolute = "the service origin is missing"
assert absolute = this.origin?.id, noAbsolute
assert _.isString(noAbsolute), "invalid origin"
assert _.isString identify = try this.identify()
assert factor = "#{absolute}:#{identify}" or 0
onlySsl = @derives securing.OnlySsl or forceSsl
digest = try hasher.update(factor).digest "hex"
deduce = try _.head(this.resources)?.unescape()
assert not _.isEmpty(digest), "MD5 digest fail"
assert $reference = digest or this.reference?()
assert internal = "/#{$reference}/#{identify}"
$location = deduce or @location?() or internal
$location = internal unless $location or null
$server = try urlOfServer onlySsl, $location
$master = try urlOfMaster onlySsl, $location
return new Object # make and return summary
reference: $reference or null # MD5-ed
location: $location or null # relative
server: $server or null # server URL
master: $master or null # master URL
# This method should process the already matched HTTP request.
# But since this is an abstract base class, this implementation
# only extracts the domain and pathname captured groups, and
# returns them to the caller. Override it to do some real job.
# The captured groups may be used by the overrider or ditched.
process: (request, response, next) ->
gdomain = null; gresource = null # var holders
assert resources = @constructor.resources or []
assert domains = @constructor.domains or [/^.+$/]
assert pathname = url.parse(request.url).pathname
assert identify = @constructor.identify().underline
hostname = try _.head request.headers.host.split ":"
assert not _.isEmpty hostname, "missing hostname"
pdomain = (repat) -> gdomain = hostname.match repat
presource = (repat) -> gresource = pathname.match repat
xdomain = try _.find(domains, pdomain) or null # side
xresource = _.find(resources, presource) or null # side
message = "Begin service processing sequence in %s"
logger.debug message.toString().yellow, identify
assert _.isObject request.service = try weak this
assert request.domains = gdomain, "missing domain"
assert request.resources = gresource, "no resource"
@emit "process", gdomain, gresource, arguments...
return domain: gdomain, resource: gresource
# This method determines whether the supplied HTTP request
# matches this service. This is determined by examining the
# domain/host and the path, in accordance with the patterns
# that were used for configuring the class of this service.
# It is async, so be sure to call the `decide` with boolean!
matches: (request, response, decide) ->
assert resources = @constructor.resources or []
assert domains = @constructor.domains or [/^.+$/]
assert pathname = url.parse(request.url).pathname
assert identify = @constructor.identify().underline
hostname = try _.head request.headers.host.split ":"
assert not _.isEmpty hostname, "missing hostname"
pdomain = (pattern) -> try pattern.test hostname
presource = (pattern) -> try pattern.test pathname
message = "Polling %s service for a basic match"
logger.debug message.toString().yellow, identify
domainOk = try _.some(domains, pdomain) or false
resourceOk = _.some(resources, presource) or false
matches = domainOk is yes and resourceOk is yes
this.emit "matches", matches, request, response
return decide domainOk and resourceOk
# This method handles the rescuing of the request/response pair
# when some error happens during the processing of the request
# under this service. This method is able to to deliver content
# as the response if it is desirable. If not, the request will
# simply be reject with Node.js/Connect. Beware about `next`!
rescuing: (error, request, response, next) ->
assert plain = try @constructor.identify()
assert expose = "failures:exposeExceptions"
assert not _.isEmpty method = request.method
identify = @constructor.identify().underline
template = "Exception in a #{method} at %s: %s"
logger.error template.red, identify, error.stack
@emit "failure", this, error, request, response
message = "Executed error rescue handler in %s"
logger.debug message.red, identify.toString()
return next() unless nconf.get(expose) is yes
response.setHeader "Content-Type", "text/plain"
response.writeHead 500, http.STATUS_CODES[500]
render = format template, plain, error.stack
response.end render; return next undefined
# This is a very basic method that adds the specified regular
# expression pattern to the list of permitted resource patterns.
# The patterns are associated with a service class, not object.
# Supports implicit extraction of captured groups in the match.
# Use this to configure what resources should match with service.
@resource: (pattern) ->
associate = "Associating %s resource with %s"
identify = @identify().underline.toString()
r = (s) -> new RegExp "^#{RegExp.escape(s)}$"
pattern = try r pattern if _.isString pattern
inspected = try pattern.unescape()?.underline
inspected = pattern unless _.isString inspected
source = not _.isEmpty try pattern.source or null
notReg = "the #{inspected} is not a valid regexp"
assert _.isRegExp(pattern) and source or 0, notReg
assert @resources = (@resources or []).concat pattern
assert @resources = _.unique this.resources or []
logger.silly associate, inspected, identify
return this # return itself for chaining...
# This is a very basic method that adds the specified regular
# expression pattern to the list of permitted domain patterns.
# The patterns are associated with a service class, not object.
# Supports implicit extraction of captured groups in the match.
# Use this to configure what domains should match with service.
@domain: (pattern) ->
associate = "Associating %s domain with %s"
identify = @identify().underline.toString()
r = (s) -> new RegExp "^#{RegExp.escape(s)}$"
pattern = try r pattern if _.isString pattern
inspected = try pattern.unescape()?.underline
inspected = pattern unless _.isString inspected
source = not _.isEmpty try pattern.source or null
notReg = "the #{inspected} is not a valid regexp"
assert _.isRegExp(pattern) and source or 0, notReg
assert @domains = (@domains or []).concat pattern
assert @domains = _.unique this.domains or []
logger.silly associate, inspected, identify
return this # return itself for chaining...
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
assert = require "assert"
logger = require "winston"
uuid = require "node-uuid"
crypto = require "crypto"
colors = require "colors"
async = require "async"
nconf = require "nconf"
http = require "http"
weak = require "weak"
util = require "util"
url = require "url"
_ = require "lodash"
extendz = require "./extends"
routing = require "./routing"
scoping = require "./scoping"
{format} = require "util"
{Archetype} = require "./arche"
{urlOfServer} = require "./toolkit"
{urlOfMaster} = require "./toolkit"
# This is an abstract base class for every kind of service in this
# framework and the end user application. It provides the matching
# and processing logic based on domain matches and RE match/extract
# logics, to deal with paths. Remember that this service is just a
# an internal base class, you generally should not use it directly.
# Also, all of its functionality can be overriden by any service.
module.exports.Service = class Service extends Archetype
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Symbol declaration table, that states what keys, if those are
# vectors (arrays) should be exported and then merged with their
# counterparts in the destination, once the composition process
# takes place. See the `Archetype::composition` hook definition
# for more information. Keys are names, values can be anything.
@COMPOSITION_EXPORTS: configures: yes
# A hook that will be called each time when the kernel beacon
# is being fired. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
beacon: (kernel, timestamp, next) -> next()
# A hook that will be called prior to instantiating the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
instance: (kernel, service, next) -> next()
# A hook that will be called prior to registering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
register: (kernel, router, next) -> next()
# A hook that will be called prior to unregistering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
unregister: (kernel, router, next) -> next()
# A hook that will be called prior to firing up the processing
# of the service. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
ignition: (request, response, next) -> next()
# This instance method is a shortcut that internally makes use
# of the service disposition data, obtained by call underlying
# method `disposition` of the service class itself. The alias
# exists primarily for the purpose of supporting some legacy
# constructs defined well before the underlying method were.
# For the new code, you should perhaps use `disposition`.
reference: -> @constructor.disposition().reference
# This instance method is a shortcut that internally makes use
# of the service disposition data, obtained by call underlying
# method `disposition` of the service class itself. The alias
# exists primarily for the purpose of supporting some legacy
# constructs defined well before the underlying method were.
# For the new code, you should perhaps use `disposition`.
location: -> @constructor.disposition().location
# This instance method is a shortcut that internally makes use
# of the service disposition data, obtained by call underlying
# method `disposition` of the service class itself. The alias
# exists primarily for the purpose of supporting some legacy
# constructs defined well before the underlying method were.
# For the new code, you should perhaps use `disposition`.
qualified: -> @constructor.disposition().master
# This is an instance method that will be invoked by the router
# on every service, prior to actually registering it. Method is
# intended to ask the service itself if wants and deems okay to
# be registered with the current router and kernel. This sort of
# functionality can be used to disambiguate what services should
# be loaded at what environments and configuratin circumstances.
consenting: (kernel, router, consent) -> consent yes
# Every service has to have a public constructor that accepts
# the kernel instance as a parameter. You can override it as
# you see fit, but be sure to invoke the super constructor and
# it is highly advised to store the kernel instance in object.
# It is also taking care of assigning a service identification.
constructor: (@kernel) -> super; @uuid = uuid.v4()
# This is the proxy method that uses the global kernel instance
# to use for finding the instance of the current service class.
# This instance is supposed to be properly registered with the
# router in order to be found. The actual lookup implementation
# is located in the `accquire` method of `GraniteKernel` class.
# Please refer to the original implementation for the guidance.
@accquire: -> global.GRANITE_KERNEL.accquire this, yes
# An important method whose responsibility is to create a new
# instance of the service, which is later will be registered in
# the router. This is invoked by the watcher when it discovers
# new suitable services to register. This works asynchronously!
# You need to take this into account, when overriding this one.
@spawn: (kernel, callback, alloc) ->
noKernel = "no kernel supplied or given"
noFunc = "got no valid callback function"
assert _.isObject(kernel or null), noKernel
assert _.isFunction(callback or null), noFunc
alloc ?= => new this kernel, callback, alloc
assert (service = alloc()).objectOf this or 0
assert downstream = try service.downstream or 0
message = "Spawned a new instance of %s service"
firings = "Downstream spawning sequences in %s"
identify = try @identify().toString().underline
logger.debug message.grey, identify.toString()
exec = (fun) => fun kernel, service; service
assert downstream = downstream.bind service
return exec instance = downstream instance: =>
this.configure().call service, (results) =>
logger.debug firings.grey, identify
callback.call this, service, kernel
try service.emit "instance", kernel
# This method is used to obtain all the available disposition
# data of this services. Disposition data is basically the data
# related to HTTP locations (supposedly) of the service using
# the different variations. This also includes some of internal
# referential data that does not pertain to HTTP per se. Please
# refer to the method source code for the detailed information.
@disposition: (forceSsl=no) ->
securing = require "../membrane/securing"
assert hasher = try crypto.createHash "md5"
noAbsolute = "the service origin is missing"
assert absolute = this.origin?.id, noAbsolute
assert _.isString(noAbsolute), "invalid origin"
assert _.isString identify = try this.identify()
assert factor = "#{absolute}:#{identify}" or 0
onlySsl = @derives securing.OnlySsl or forceSsl
digest = try hasher.update(factor).digest "hex"
deduce = try _.head(this.resources)?.unescape()
assert not _.isEmpty(digest), "MD5 digest fail"
assert $reference = digest or this.reference?()
assert internal = "/#{$reference}/#{identify}"
$location = deduce or @location?() or internal
$location = internal unless $location or null
$server = try urlOfServer onlySsl, $location
$master = try urlOfMaster onlySsl, $location
return new Object # make and return summary
reference: $reference or null # MD5-ed
location: $location or null # relative
server: $server or null # server URL
master: $master or null # master URL
# This method should process the already matched HTTP request.
# But since this is an abstract base class, this implementation
# only extracts the domain and pathname captured groups, and
# returns them to the caller. Override it to do some real job.
# The captured groups may be used by the overrider or ditched.
process: (request, response, next) ->
gdomain = null; gresource = null # var holders
assert resources = @constructor.resources or []
assert domains = @constructor.domains or [/^.+$/]
assert pathname = url.parse(request.url).pathname
assert identify = @constructor.identify().underline
hostname = try _.head request.headers.host.split ":"
assert not _.isEmpty hostname, "missing hostname"
pdomain = (repat) -> gdomain = hostname.match repat
presource = (repat) -> gresource = pathname.match repat
xdomain = try _.find(domains, pdomain) or null # side
xresource = _.find(resources, presource) or null # side
message = "Begin service processing sequence in %s"
logger.debug message.toString().yellow, identify
assert _.isObject request.service = try weak this
assert request.domains = gdomain, "missing domain"
assert request.resources = gresource, "no resource"
@emit "process", gdomain, gresource, arguments...
return domain: gdomain, resource: gresource
# This method determines whether the supplied HTTP request
# matches this service. This is determined by examining the
# domain/host and the path, in accordance with the patterns
# that were used for configuring the class of this service.
# It is async, so be sure to call the `decide` with boolean!
matches: (request, response, decide) ->
assert resources = @constructor.resources or []
assert domains = @constructor.domains or [/^.+$/]
assert pathname = url.parse(request.url).pathname
assert identify = @constructor.identify().underline
hostname = try _.head request.headers.host.split ":"
assert not _.isEmpty hostname, "missing hostname"
pdomain = (pattern) -> try pattern.test hostname
presource = (pattern) -> try pattern.test pathname
message = "Polling %s service for a basic match"
logger.debug message.toString().yellow, identify
domainOk = try _.some(domains, pdomain) or false
resourceOk = _.some(resources, presource) or false
matches = domainOk is yes and resourceOk is yes
this.emit "matches", matches, request, response
return decide domainOk and resourceOk
# This method handles the rescuing of the request/response pair
# when some error happens during the processing of the request
# under this service. This method is able to to deliver content
# as the response if it is desirable. If not, the request will
# simply be reject with Node.js/Connect. Beware about `next`!
rescuing: (error, request, response, next) ->
assert plain = try @constructor.identify()
assert expose = "failures:exposeExceptions"
assert not _.isEmpty method = request.method
identify = @constructor.identify().underline
template = "Exception in a #{method} at %s: %s"
logger.error template.red, identify, error.stack
@emit "failure", this, error, request, response
message = "Executed error rescue handler in %s"
logger.debug message.red, identify.toString()
return next() unless nconf.get(expose) is yes
response.setHeader "Content-Type", "text/plain"
response.writeHead 500, http.STATUS_CODES[500]
render = format template, plain, error.stack
response.end render; return next undefined
# This is a very basic method that adds the specified regular
# expression pattern to the list of permitted resource patterns.
# The patterns are associated with a service class, not object.
# Supports implicit extraction of captured groups in the match.
# Use this to configure what resources should match with service.
@resource: (pattern) ->
associate = "Associating %s resource with %s"
identify = @identify().underline.toString()
r = (s) -> new RegExp "^#{RegExp.escape(s)}$"
pattern = try r pattern if _.isString pattern
inspected = try pattern.unescape()?.underline
inspected = pattern unless _.isString inspected
source = not _.isEmpty try pattern.source or null
notReg = "the #{inspected} is not a valid regexp"
assert _.isRegExp(pattern) and source or 0, notReg
assert @resources = (@resources or []).concat pattern
assert @resources = _.unique this.resources or []
logger.silly associate, inspected, identify
return this # return itself for chaining...
# This is a very basic method that adds the specified regular
# expression pattern to the list of permitted domain patterns.
# The patterns are associated with a service class, not object.
# Supports implicit extraction of captured groups in the match.
# Use this to configure what domains should match with service.
@domain: (pattern) ->
associate = "Associating %s domain with %s"
identify = @identify().underline.toString()
r = (s) -> new RegExp "^#{RegExp.escape(s)}$"
pattern = try r pattern if _.isString pattern
inspected = try pattern.unescape()?.underline
inspected = pattern unless _.isString inspected
source = not _.isEmpty try pattern.source or null
notReg = "the #{inspected} is not a valid regexp"
assert _.isRegExp(pattern) and source or 0, notReg
assert @domains = (@domains or []).concat pattern
assert @domains = _.unique this.domains or []
logger.silly associate, inspected, identify
return this # return itself for chaining...
|
[
{
"context": "'use strict'\n\n\n# Key\n#\n# @copyright Andrew Lawson 2012\n# @see http://github.com/adlawson/key\n# @see",
"end": 49,
"score": 0.9998787045478821,
"start": 36,
"tag": "NAME",
"value": "Andrew Lawson"
},
{
"context": "right Andrew Lawson 2012\n# @see http://github.com/... | src/code/special.coffee | adlawson/coffee-key | 1 | 'use strict'
# Key
#
# @copyright Andrew Lawson 2012
# @see http://github.com/adlawson/key
# @see http://npmjs.org/package/key
# @see http://opensource.org/licenses/mit-license.php MIT License
# Dependencies
{ref} = require '../ref'
# Definitions
special = {
backspace: ref 'Backspace', 8
tab: ref 'Tab', 9
enter: ref 'Enter', 13
shift: ref 'Shift', 16
ctrl: ref 'Ctrl', 17
alt: ref 'Alt', 18
caps: ref 'Caps Lock', 20
esc: ref 'Escape', 27
space: ref 'Space', 32
num: ref 'Num Lock', 144
}
# Exports
module.exports = special
| 142202 | 'use strict'
# Key
#
# @copyright <NAME> 2012
# @see http://github.com/adlawson/key
# @see http://npmjs.org/package/key
# @see http://opensource.org/licenses/mit-license.php MIT License
# Dependencies
{ref} = require '../ref'
# Definitions
special = {
backspace: ref 'Backspace', 8
tab: ref 'Tab', 9
enter: ref 'Enter', 13
shift: ref 'Shift', 16
ctrl: ref 'Ctrl', 17
alt: ref 'Alt', 18
caps: ref 'Caps Lock', 20
esc: ref 'Escape', 27
space: ref 'Space', 32
num: ref 'Num Lock', 144
}
# Exports
module.exports = special
| true | 'use strict'
# Key
#
# @copyright PI:NAME:<NAME>END_PI 2012
# @see http://github.com/adlawson/key
# @see http://npmjs.org/package/key
# @see http://opensource.org/licenses/mit-license.php MIT License
# Dependencies
{ref} = require '../ref'
# Definitions
special = {
backspace: ref 'Backspace', 8
tab: ref 'Tab', 9
enter: ref 'Enter', 13
shift: ref 'Shift', 16
ctrl: ref 'Ctrl', 17
alt: ref 'Alt', 18
caps: ref 'Caps Lock', 20
esc: ref 'Escape', 27
space: ref 'Space', 32
num: ref 'Num Lock', 144
}
# Exports
module.exports = special
|
[
{
"context": "e(this).attach($scope)\n vm = this\n vm.password = ''\n vm.error = ''\n\n vm.set = ->\n Accounts.reset",
"end": 160,
"score": 0.9845103621482849,
"start": 160,
"tag": "PASSWORD",
"value": ""
}
] | client/user/auth/controllers/activateCtrl.ng.coffee | redhead-web/meteor-foodcoop | 11 | angular.module('food-coop').controller 'ActivateCtrl',
($state, $scope, $stateParams, $reactive) ->
$reactive(this).attach($scope)
vm = this
vm.password = ''
vm.error = ''
vm.set = ->
Accounts.resetPassword $stateParams.token, vm.password, vm.$bindToContext (err) ->
if err
vm.error = 'Error reset password - ' + err
console.error err
else
$state.go 'store'
return
return
return
# ---
# generated by js2coffee 2.1.0
| 187179 | angular.module('food-coop').controller 'ActivateCtrl',
($state, $scope, $stateParams, $reactive) ->
$reactive(this).attach($scope)
vm = this
vm.password =<PASSWORD> ''
vm.error = ''
vm.set = ->
Accounts.resetPassword $stateParams.token, vm.password, vm.$bindToContext (err) ->
if err
vm.error = 'Error reset password - ' + err
console.error err
else
$state.go 'store'
return
return
return
# ---
# generated by js2coffee 2.1.0
| true | angular.module('food-coop').controller 'ActivateCtrl',
($state, $scope, $stateParams, $reactive) ->
$reactive(this).attach($scope)
vm = this
vm.password =PI:PASSWORD:<PASSWORD>END_PI ''
vm.error = ''
vm.set = ->
Accounts.resetPassword $stateParams.token, vm.password, vm.$bindToContext (err) ->
if err
vm.error = 'Error reset password - ' + err
console.error err
else
$state.go 'store'
return
return
return
# ---
# generated by js2coffee 2.1.0
|
[
{
"context": " {0}! Let me quickly introduce myself.\\nMy name is Oskar, and the team has drafted me in to be their new h",
"end": 434,
"score": 0.9998564720153809,
"start": 429,
"tag": "NAME",
"value": "Oskar"
}
] | src/content/oskarTexts.coffee | wearehanno/oskar | 155 | # needed in order to do string replacement
String.prototype.format = ->
args = arguments
return this.replace /{(\d+)}/g, (match, number) ->
return if typeof args[number] isnt 'undefined' then args[number] else match
OskarTexts =
statusText:
'1': 'pretty bad'
'2': 'a bit down'
'3': 'alright'
'4': 'really good'
'5': 'awesome'
introduction: "Hey {0}! Let me quickly introduce myself.\nMy name is Oskar, and the team has drafted me in to be their new happiness coach on Slack. I'm not going to bother you a lot, but every once in a while (usually twice a day), I'm gonna ask how you feel. Ready? *Just reply to this message and we'll give is a try* :smile:"
firstMessage: "Alright! From now on, I'll check in once in a while to ask how you're feeling?'\n\nYou can reply to me with a number between 1 and 5, and I'll keep track of your answers over time and share them with your team.\n\nOK? Let's give it a try: *How do you feel right now?*\n
(5) :heart_eyes_cat: Awesome\n
(4) :smile: Really good\n
(3) :neutral_face: Alright\n
(2) :pensive: A bit down\n
(1) :tired_face: Pretty bad\n"
firstMessageSuccess: "That was easy, wasn't it? :smile: I'm gonna disappear for a few hours now, but I'll check in on you in a couple of hours, or tomorrow, if I miss you." # todo: is now afternoon or next day"
firstMessageFailure: "Whoops, it looks like you're trying to tell me how you feel, but unfortunately I only understand numbers between 1 and 5. Can you give it another go?"
requestFeedback:
random: [
"Hey {0}, How are you feeling right now? Hit me with a number and I'll share it with the rest of our team.\n",
"Hello, me again! Just checking in to see how you're feeling. Want to share?\n",
"Nice to see you, {0}, Wanna tell me how you feel? A number between 1 and 5 is all I need.\n"
]
selection: "(5) :heart_eyes_cat: Awesome\n
(4) :smile: Really good\n
(3) :neutral_face: Alright\n
(2) :pensive: A bit down\n
(1) :tired_face: Pretty bad\n"
options: [
"Perhaps you missed my last message... I'd really love to hear how you're doing. Would you mind letting me know?"
"Hey, looks like you missed me last time, but if you can give me a number between 1-5 to let me know how you feel, I'll be on my way :smile:"
]
faq: "Looks like you need a little help. Here's the link to the <http://oskar.herokuapp.com/faq|Oskar FAQ>"
revealChannelStatus:
error: "*{0}* hasn\'t submitted a status yet."
status: "*{0}* is feeling *{1}/5*"
message: "\n>\"{0}\""
revealUserStatus:
error: "Oh, it looks like I haven\'t heard from {0} for a while. Sorry!"
status: "*{0}* is feeling *{1}/5*"
message: "\n>\"{0}\""
newUserFeedback: "*{0}* is feeling *{1}/5*\n>\"{2}\""
alreadySubmitted: [
"Oops, looks like you've already told me how you feel in the last couple of hours. Let's check in again later.",
"Oh, hey there! I actually have some feedback from you already, in the last 4 hours. Let's leave it a little longer before we catch up :smile:",
"Easy, tiger! I know you love our number games, but let\'s wait a bit before we play again! I'll ping you in a few hours to see how you're doing."
]
invalidInput: [
"Oh! I'm not sure what you meant, there: I only understand numbers between 1 and 5. Do you mind phrasing that a little differently?",
"Oh! I'm not sure what you meant, there: I only understand numbers between 1 and 5. Do you mind phrasing that a little differently?",
"I\'d really love to understand what you\'re saying, but until I become a little more educated, I'll need you to stick to using numbers between 1 and 5 to tell me how you feel."
]
lowFeedback: [
"That sucks. I was really hoping you'd be feeling a little better than that. *Is there anything I should know?*",
"Oh dear :worried: I'm having a rough day over here too... :tired_face: *Wanna tell me a little more?* Perhaps one of our teammates will be able to help out.",
"Ah, man :disappointed: I really hate to hear when a friend is having a rough time. *Wanna explain a little more?* "
]
averageFeedback: [
"Alright! Go get em :tiger: *If you've got something you want to share, feel free. If not, have a grrreat day!*",
"Good luck with powering through things. *If you've got something you want to share, feel free.*",
"That's alright. We can't all be having crazy highs and killer lows. *If you feel like telling me more, feel free!*"
]
highFeedback: [
":trophy: Winning! It's so great to hear that. *Why not type a message to let your team know why things are going so well?*",
":thumbsup: looks like you're on :fire: today. *Is there anything you'd like to share with the team?*",
"There's nothing I like more than great feedback! :clap::skin-tone-4: *What's made you feel so awesome today?*"
]
# feedback already received
feedbackReceived: [
"Thanks a lot, buddy! Keep up the good work!",
"You\'re a champion. Thanks for the input and have a great day!",
"That\'s really helpful. I wish you good luck with everything today!"
]
# feedback received
feedbackMessageReceived: [
"Thanks for sharing with me, my friend. Let's catch up again soon.",
"Thanks for being so open! Let's catch up in a few hours.",
"Gotcha. I've pinged that message to the rest of the team."
]
module.exports = OskarTexts
| 66354 | # needed in order to do string replacement
String.prototype.format = ->
args = arguments
return this.replace /{(\d+)}/g, (match, number) ->
return if typeof args[number] isnt 'undefined' then args[number] else match
OskarTexts =
statusText:
'1': 'pretty bad'
'2': 'a bit down'
'3': 'alright'
'4': 'really good'
'5': 'awesome'
introduction: "Hey {0}! Let me quickly introduce myself.\nMy name is <NAME>, and the team has drafted me in to be their new happiness coach on Slack. I'm not going to bother you a lot, but every once in a while (usually twice a day), I'm gonna ask how you feel. Ready? *Just reply to this message and we'll give is a try* :smile:"
firstMessage: "Alright! From now on, I'll check in once in a while to ask how you're feeling?'\n\nYou can reply to me with a number between 1 and 5, and I'll keep track of your answers over time and share them with your team.\n\nOK? Let's give it a try: *How do you feel right now?*\n
(5) :heart_eyes_cat: Awesome\n
(4) :smile: Really good\n
(3) :neutral_face: Alright\n
(2) :pensive: A bit down\n
(1) :tired_face: Pretty bad\n"
firstMessageSuccess: "That was easy, wasn't it? :smile: I'm gonna disappear for a few hours now, but I'll check in on you in a couple of hours, or tomorrow, if I miss you." # todo: is now afternoon or next day"
firstMessageFailure: "Whoops, it looks like you're trying to tell me how you feel, but unfortunately I only understand numbers between 1 and 5. Can you give it another go?"
requestFeedback:
random: [
"Hey {0}, How are you feeling right now? Hit me with a number and I'll share it with the rest of our team.\n",
"Hello, me again! Just checking in to see how you're feeling. Want to share?\n",
"Nice to see you, {0}, Wanna tell me how you feel? A number between 1 and 5 is all I need.\n"
]
selection: "(5) :heart_eyes_cat: Awesome\n
(4) :smile: Really good\n
(3) :neutral_face: Alright\n
(2) :pensive: A bit down\n
(1) :tired_face: Pretty bad\n"
options: [
"Perhaps you missed my last message... I'd really love to hear how you're doing. Would you mind letting me know?"
"Hey, looks like you missed me last time, but if you can give me a number between 1-5 to let me know how you feel, I'll be on my way :smile:"
]
faq: "Looks like you need a little help. Here's the link to the <http://oskar.herokuapp.com/faq|Oskar FAQ>"
revealChannelStatus:
error: "*{0}* hasn\'t submitted a status yet."
status: "*{0}* is feeling *{1}/5*"
message: "\n>\"{0}\""
revealUserStatus:
error: "Oh, it looks like I haven\'t heard from {0} for a while. Sorry!"
status: "*{0}* is feeling *{1}/5*"
message: "\n>\"{0}\""
newUserFeedback: "*{0}* is feeling *{1}/5*\n>\"{2}\""
alreadySubmitted: [
"Oops, looks like you've already told me how you feel in the last couple of hours. Let's check in again later.",
"Oh, hey there! I actually have some feedback from you already, in the last 4 hours. Let's leave it a little longer before we catch up :smile:",
"Easy, tiger! I know you love our number games, but let\'s wait a bit before we play again! I'll ping you in a few hours to see how you're doing."
]
invalidInput: [
"Oh! I'm not sure what you meant, there: I only understand numbers between 1 and 5. Do you mind phrasing that a little differently?",
"Oh! I'm not sure what you meant, there: I only understand numbers between 1 and 5. Do you mind phrasing that a little differently?",
"I\'d really love to understand what you\'re saying, but until I become a little more educated, I'll need you to stick to using numbers between 1 and 5 to tell me how you feel."
]
lowFeedback: [
"That sucks. I was really hoping you'd be feeling a little better than that. *Is there anything I should know?*",
"Oh dear :worried: I'm having a rough day over here too... :tired_face: *Wanna tell me a little more?* Perhaps one of our teammates will be able to help out.",
"Ah, man :disappointed: I really hate to hear when a friend is having a rough time. *Wanna explain a little more?* "
]
averageFeedback: [
"Alright! Go get em :tiger: *If you've got something you want to share, feel free. If not, have a grrreat day!*",
"Good luck with powering through things. *If you've got something you want to share, feel free.*",
"That's alright. We can't all be having crazy highs and killer lows. *If you feel like telling me more, feel free!*"
]
highFeedback: [
":trophy: Winning! It's so great to hear that. *Why not type a message to let your team know why things are going so well?*",
":thumbsup: looks like you're on :fire: today. *Is there anything you'd like to share with the team?*",
"There's nothing I like more than great feedback! :clap::skin-tone-4: *What's made you feel so awesome today?*"
]
# feedback already received
feedbackReceived: [
"Thanks a lot, buddy! Keep up the good work!",
"You\'re a champion. Thanks for the input and have a great day!",
"That\'s really helpful. I wish you good luck with everything today!"
]
# feedback received
feedbackMessageReceived: [
"Thanks for sharing with me, my friend. Let's catch up again soon.",
"Thanks for being so open! Let's catch up in a few hours.",
"Gotcha. I've pinged that message to the rest of the team."
]
module.exports = OskarTexts
| true | # needed in order to do string replacement
String.prototype.format = ->
args = arguments
return this.replace /{(\d+)}/g, (match, number) ->
return if typeof args[number] isnt 'undefined' then args[number] else match
OskarTexts =
statusText:
'1': 'pretty bad'
'2': 'a bit down'
'3': 'alright'
'4': 'really good'
'5': 'awesome'
introduction: "Hey {0}! Let me quickly introduce myself.\nMy name is PI:NAME:<NAME>END_PI, and the team has drafted me in to be their new happiness coach on Slack. I'm not going to bother you a lot, but every once in a while (usually twice a day), I'm gonna ask how you feel. Ready? *Just reply to this message and we'll give is a try* :smile:"
firstMessage: "Alright! From now on, I'll check in once in a while to ask how you're feeling?'\n\nYou can reply to me with a number between 1 and 5, and I'll keep track of your answers over time and share them with your team.\n\nOK? Let's give it a try: *How do you feel right now?*\n
(5) :heart_eyes_cat: Awesome\n
(4) :smile: Really good\n
(3) :neutral_face: Alright\n
(2) :pensive: A bit down\n
(1) :tired_face: Pretty bad\n"
firstMessageSuccess: "That was easy, wasn't it? :smile: I'm gonna disappear for a few hours now, but I'll check in on you in a couple of hours, or tomorrow, if I miss you." # todo: is now afternoon or next day"
firstMessageFailure: "Whoops, it looks like you're trying to tell me how you feel, but unfortunately I only understand numbers between 1 and 5. Can you give it another go?"
requestFeedback:
random: [
"Hey {0}, How are you feeling right now? Hit me with a number and I'll share it with the rest of our team.\n",
"Hello, me again! Just checking in to see how you're feeling. Want to share?\n",
"Nice to see you, {0}, Wanna tell me how you feel? A number between 1 and 5 is all I need.\n"
]
selection: "(5) :heart_eyes_cat: Awesome\n
(4) :smile: Really good\n
(3) :neutral_face: Alright\n
(2) :pensive: A bit down\n
(1) :tired_face: Pretty bad\n"
options: [
"Perhaps you missed my last message... I'd really love to hear how you're doing. Would you mind letting me know?"
"Hey, looks like you missed me last time, but if you can give me a number between 1-5 to let me know how you feel, I'll be on my way :smile:"
]
faq: "Looks like you need a little help. Here's the link to the <http://oskar.herokuapp.com/faq|Oskar FAQ>"
revealChannelStatus:
error: "*{0}* hasn\'t submitted a status yet."
status: "*{0}* is feeling *{1}/5*"
message: "\n>\"{0}\""
revealUserStatus:
error: "Oh, it looks like I haven\'t heard from {0} for a while. Sorry!"
status: "*{0}* is feeling *{1}/5*"
message: "\n>\"{0}\""
newUserFeedback: "*{0}* is feeling *{1}/5*\n>\"{2}\""
alreadySubmitted: [
"Oops, looks like you've already told me how you feel in the last couple of hours. Let's check in again later.",
"Oh, hey there! I actually have some feedback from you already, in the last 4 hours. Let's leave it a little longer before we catch up :smile:",
"Easy, tiger! I know you love our number games, but let\'s wait a bit before we play again! I'll ping you in a few hours to see how you're doing."
]
invalidInput: [
"Oh! I'm not sure what you meant, there: I only understand numbers between 1 and 5. Do you mind phrasing that a little differently?",
"Oh! I'm not sure what you meant, there: I only understand numbers between 1 and 5. Do you mind phrasing that a little differently?",
"I\'d really love to understand what you\'re saying, but until I become a little more educated, I'll need you to stick to using numbers between 1 and 5 to tell me how you feel."
]
lowFeedback: [
"That sucks. I was really hoping you'd be feeling a little better than that. *Is there anything I should know?*",
"Oh dear :worried: I'm having a rough day over here too... :tired_face: *Wanna tell me a little more?* Perhaps one of our teammates will be able to help out.",
"Ah, man :disappointed: I really hate to hear when a friend is having a rough time. *Wanna explain a little more?* "
]
averageFeedback: [
"Alright! Go get em :tiger: *If you've got something you want to share, feel free. If not, have a grrreat day!*",
"Good luck with powering through things. *If you've got something you want to share, feel free.*",
"That's alright. We can't all be having crazy highs and killer lows. *If you feel like telling me more, feel free!*"
]
highFeedback: [
":trophy: Winning! It's so great to hear that. *Why not type a message to let your team know why things are going so well?*",
":thumbsup: looks like you're on :fire: today. *Is there anything you'd like to share with the team?*",
"There's nothing I like more than great feedback! :clap::skin-tone-4: *What's made you feel so awesome today?*"
]
# feedback already received
feedbackReceived: [
"Thanks a lot, buddy! Keep up the good work!",
"You\'re a champion. Thanks for the input and have a great day!",
"That\'s really helpful. I wish you good luck with everything today!"
]
# feedback received
feedbackMessageReceived: [
"Thanks for sharing with me, my friend. Let's catch up again soon.",
"Thanks for being so open! Let's catch up in a few hours.",
"Gotcha. I've pinged that message to the rest of the team."
]
module.exports = OskarTexts
|
[
{
"context": "ne()\n\n beforeEach ->\n auth =\n username: 'ai-turns-hostile'\n password: 'team-token'\n\n @options =\n ",
"end": 910,
"score": 0.999643862247467,
"start": 894,
"tag": "USERNAME",
"value": "ai-turns-hostile"
},
{
"context": " username: 'ai-turns-h... | test/integration/flow-contains-triggers-spec.coffee | octoblu/triggers-service | 5 | _ = require 'lodash'
http = require 'http'
request = require 'request'
shmock = require 'shmock'
Server = require '../../src/server'
fakeFlow = require './fake-flow.json'
enableDestroy = require 'server-destroy'
describe 'GET /all-triggers?flowContains=device:generic', ->
beforeEach (done) ->
@meshblu = shmock done
enableDestroy @meshblu
afterEach (done) ->
@meshblu.destroy done
beforeEach (done) ->
meshbluConfig =
hostname: 'localhost'
port: @meshblu.address().port
protocol: 'http'
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig: meshbluConfig
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop => done()
beforeEach ->
auth =
username: 'ai-turns-hostile'
password: 'team-token'
@options =
auth: auth
json: true
@meshblu.post('/authenticate')
.reply 200, uuid: 'ai-turns-hostile', token: 'team-token'
@getHandler = @meshblu.get('/v2/devices')
.query(type:'octoblu:flow', online: 'true')
.reply 200, [fakeFlow]
context 'when the device does not exist', ->
beforeEach (done) ->
request.get "http://localhost:#{@serverPort}/all-triggers?flowContains=device:no-way", @options, (error, @response, @body) =>
done error
it 'should not return triggers', ->
expect(@response.statusCode).to.equal 200
expect(@getHandler.isDone).to.be.true
expect(@body).to.deep.equal []
context 'when the device exists', ->
beforeEach (done) ->
request.get "http://localhost:#{@serverPort}/all-triggers?flowContains=device:generic", @options, (error, @response, @body) =>
done error
it 'should return triggers', ->
expect(@response.statusCode).to.equal 200
expect(@getHandler.isDone).to.be.true
expect(@body).not.to.deep.equal []
context 'when multiple device exists', ->
beforeEach (done) ->
request.get "http://localhost:#{@serverPort}/all-triggers?flowContains=device:generic&flowContains=device:twitter", @options, (error, @response, @body) =>
done error
it 'should return triggers', ->
expect(@response.statusCode).to.equal 200
expect(@getHandler.isDone).to.be.true
expect(@body).not.to.deep.equal []
| 28805 | _ = require 'lodash'
http = require 'http'
request = require 'request'
shmock = require 'shmock'
Server = require '../../src/server'
fakeFlow = require './fake-flow.json'
enableDestroy = require 'server-destroy'
describe 'GET /all-triggers?flowContains=device:generic', ->
beforeEach (done) ->
@meshblu = shmock done
enableDestroy @meshblu
afterEach (done) ->
@meshblu.destroy done
beforeEach (done) ->
meshbluConfig =
hostname: 'localhost'
port: @meshblu.address().port
protocol: 'http'
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig: meshbluConfig
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop => done()
beforeEach ->
auth =
username: 'ai-turns-hostile'
password: '<PASSWORD>'
@options =
auth: auth
json: true
@meshblu.post('/authenticate')
.reply 200, uuid: 'ai-turns-hostile', token: 'team-token'
@getHandler = @meshblu.get('/v2/devices')
.query(type:'octoblu:flow', online: 'true')
.reply 200, [fakeFlow]
context 'when the device does not exist', ->
beforeEach (done) ->
request.get "http://localhost:#{@serverPort}/all-triggers?flowContains=device:no-way", @options, (error, @response, @body) =>
done error
it 'should not return triggers', ->
expect(@response.statusCode).to.equal 200
expect(@getHandler.isDone).to.be.true
expect(@body).to.deep.equal []
context 'when the device exists', ->
beforeEach (done) ->
request.get "http://localhost:#{@serverPort}/all-triggers?flowContains=device:generic", @options, (error, @response, @body) =>
done error
it 'should return triggers', ->
expect(@response.statusCode).to.equal 200
expect(@getHandler.isDone).to.be.true
expect(@body).not.to.deep.equal []
context 'when multiple device exists', ->
beforeEach (done) ->
request.get "http://localhost:#{@serverPort}/all-triggers?flowContains=device:generic&flowContains=device:twitter", @options, (error, @response, @body) =>
done error
it 'should return triggers', ->
expect(@response.statusCode).to.equal 200
expect(@getHandler.isDone).to.be.true
expect(@body).not.to.deep.equal []
| true | _ = require 'lodash'
http = require 'http'
request = require 'request'
shmock = require 'shmock'
Server = require '../../src/server'
fakeFlow = require './fake-flow.json'
enableDestroy = require 'server-destroy'
describe 'GET /all-triggers?flowContains=device:generic', ->
beforeEach (done) ->
@meshblu = shmock done
enableDestroy @meshblu
afterEach (done) ->
@meshblu.destroy done
beforeEach (done) ->
meshbluConfig =
hostname: 'localhost'
port: @meshblu.address().port
protocol: 'http'
serverOptions =
port: undefined,
disableLogging: true
meshbluConfig: meshbluConfig
@server = new Server serverOptions
@server.run =>
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop => done()
beforeEach ->
auth =
username: 'ai-turns-hostile'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
@options =
auth: auth
json: true
@meshblu.post('/authenticate')
.reply 200, uuid: 'ai-turns-hostile', token: 'team-token'
@getHandler = @meshblu.get('/v2/devices')
.query(type:'octoblu:flow', online: 'true')
.reply 200, [fakeFlow]
context 'when the device does not exist', ->
beforeEach (done) ->
request.get "http://localhost:#{@serverPort}/all-triggers?flowContains=device:no-way", @options, (error, @response, @body) =>
done error
it 'should not return triggers', ->
expect(@response.statusCode).to.equal 200
expect(@getHandler.isDone).to.be.true
expect(@body).to.deep.equal []
context 'when the device exists', ->
beforeEach (done) ->
request.get "http://localhost:#{@serverPort}/all-triggers?flowContains=device:generic", @options, (error, @response, @body) =>
done error
it 'should return triggers', ->
expect(@response.statusCode).to.equal 200
expect(@getHandler.isDone).to.be.true
expect(@body).not.to.deep.equal []
context 'when multiple device exists', ->
beforeEach (done) ->
request.get "http://localhost:#{@serverPort}/all-triggers?flowContains=device:generic&flowContains=device:twitter", @options, (error, @response, @body) =>
done error
it 'should return triggers', ->
expect(@response.statusCode).to.equal 200
expect(@getHandler.isDone).to.be.true
expect(@body).not.to.deep.equal []
|
[
{
"context": "me] = -> x)()\n\nmemox = (klass, name, f) ->\n key = \"#{name}__\"\n klass::[name] = (args...) ->\n val = (@[key]",
"end": 927,
"score": 0.998965322971344,
"start": 917,
"tag": "KEY",
"value": "\"#{name}__"
}
] | lib/dsymbol.coffee | odf/gavrog.js | 1 | if typeof(require) != 'undefined'
# for now we assume that pazy.js lives next to gavrog.js
require.paths.unshift("#{__dirname}/../../pazy.js/lib")
{ bounce } = require('functional')
{ seq } = require('sequence')
{ IntSet, IntMap, HashSet, HashMap } = require('indexed')
{ Stack } = require('stack')
{ Queue } = require('queue')
{ Partition } = require('partition')
{ num } = require('number')
require 'sequence_extras'
else
{
bounce, seq, IntSet, IntMap, HashSet, HashMap, Stack, Queue, Partition, num
} = this.pazy
# ----
# To be used in class bodies in order to create methods with memoized results.
memo = (klass, name, f) ->
klass::[name] = -> x = f.call(this); (@[name] = -> x)()
memox = (klass, name, f) ->
key = "#{name}__"
klass::[name] = (args...) ->
val = (@[key] ||= new HashMap()).get(args)
if val?
val
else
v = f.apply(this, args)
@[key] = @[key].plus [args, v]
v
# ----
# Other helper methods
zip = (s,t) -> seq.zip(s, t).map (x) -> x.into []
zap = (s,t) -> zip(s,t)?.takeWhile ([a,b]) -> (a? and b?)
# ----
# The base class for Delaney symbols. All child classes need to
# implement the following four methods (see class DSymbol below for
# details):
#
# indexSet
# elementSet
# s
# m
#
# The first two methods must return an object that recognizes these methods:
#
# toSeq
# size
# contains
class Delaney
isDelaney: -> true
indices: -> @indexSet().toSeq()
dimension: -> @indexSet().size() - 1
hasIndex: (i) -> @indexSet().contains i
elements: -> @elementSet().toSeq()
size: -> @elementSet().size()
hasElement: (D) -> @elementSet().contains D
flat: -> DSymbol.flat this
assertValidity: ->
report = (msgs) ->
if msgs?.find((x) -> x?)
throw new Error(msgs?.select((x) -> x?)?.into([]).join("\n"))
report @indices()?.flatMap (i) =>
@elements()?.map (D) =>
Di = @s(i)(D)
if not @hasElement Di
"not an element: s(#{i}) #{D} = #{Di}"
else if Di > 0 and @s(i)(Di) != D
"inconsistent: s(#{i}) s(#{i}) #{D} = #{s(i) s(i) D}"
report @indices()?.flatMap (i) =>
@indices()?.flatMap (j) =>
@elements()?.map (D) =>
if @m(i, j)(D) < 0
"illegal: m(#{i}, #{j}) #{D} = #{m(i, j) D}"
else if @m(i, j)(D) != @m(i, j) @s(i) D
"inconsistent: m(#{i}, #{j}) #{D} = #{@m(i, j) D}, " +
"but m(#{i}, #{j}) s(#{i}) #{D} = #{@m(i, j) @s(i) D}"
report @indices()?.flatMap (i) =>
@indices()?.flatMap (j) =>
@orbitFirsts(i, j)?.map (D) =>
complete = @orbit(i, j)(D)?.forall (E) => @s(i)(E)? and @s(j)(E)?
m = @m(i,j)(D)
r = @r(i,j)(D)
if m % r > 0 and complete
"inconsistent: m(#{i}, #{j})(#{D}) = #{m} " +
"should be a multiple of #{r}"
else if m < r
"inconsistent: m(#{i}, #{j})(#{D}) = #{m} should be at least #{r}"
r: (i, j) -> (D) =>
step = (n, E0) =>
E1 = @s(i)(E0) or E0
E2 = @s(j)(E1) or E1
if E2 == D then n + 1 else -> step n + 1, E2
bounce step 0, D
v: (i, j) -> (D) => @m(i, j)(D) / @r(i, j)(D)
drop = (s, f) ->
if s.first()? and f s.first() then -> drop s.rest(), f else s
traversal: (idcs, seed_elms) ->
collect = (seeds_left, next, seen) =>
tmp = next.map ([k, d]) -> [k, bounce drop d, (x) -> seen.contains [x, k]]
if r = tmp.find(([k, x]) -> x.first()?)
[i, d] = r
[D, s] = [d.first(), d.rest()]
newNext = tmp.map ([k, x]) => [k, if k == i then s else x.push @s(k)(D)]
newSeen = seen.plus [D], [D, i], [@s(i)(D), i]
seq.conj [D, i], -> collect seeds_left, newNext, newSeen
else if D = seeds_left?.find((x) -> not seen.contains [x])
newNext = tmp.map ([k, x]) => [k, x.push @s(k)(D)]
newSeen = seen.plus [D]
seq.conj [D], -> collect seeds_left.rest(), newNext, newSeen
else
null
indices = seq(idcs) or @indices()
seeds = seq(seed_elms) or @elements()
stacks = seq.take(indices, 2)?.map (i) -> [i, new Stack()]
queues = seq.drop(indices, 2)?.map (i) -> [i, new Queue()]
initialNext = seq.concat(stacks, queues).forced()
collect seeds, initialNext, new HashSet()
orbit: (indices...) -> (D) =>
@traversal(indices, [D])?.map(([E, k]) -> E)?.uniq()
orbitFirsts: (indices...) ->
@traversal(indices)?.select(([D, k]) -> not k?)?.map ([D]) -> D
orbits: (indices...) ->
@orbitFirsts(indices...).map @orbit(indices...)
memo @, 'isComplete', ->
@elements()?.forall (D) =>
@indices()?.forall (i) => @s(i)(D)? and
@indices()?.forall (j) => @m(i, j)(D)?
memo @,'isConnected', -> not @orbitFirsts()?.rest()
traversalPartialOrientation: (traversal) ->
seq.reduce traversal, new HashMap(), (hash, [D,i]) =>
hash.plus [D, if i? then -hash.get(@s(i)(D)) else 1]
orbitPartialOrientation: (idcs, seeds) ->
@traversalPartialOrientation @traversal idcs, seeds
orbitIsLoopless: (idcs, seeds) ->
not @traversal(idcs, seeds)?.find ([D, i]) => i? and @s(i)(D) == D
orbitIsOriented: (idcs, seeds) ->
traversal = @traversal idcs, seeds
ori = @traversalPartialOrientation traversal
not traversal?.find ([D, i]) => i? and ori.get(@s(i)(D)) == ori.get(D)
orbitIsWeaklyOriented: (idcs, seeds) ->
traversal = @traversal idcs, seeds
ori = @traversalPartialOrientation traversal
not traversal?.find ([D, i]) =>
i? and @s(i)(D) != D and ori.get(@s(i)(D)) == ori.get(D)
memo @,'isLoopless', -> @orbitIsLoopless()
memo @,'isOriented', -> @orbitIsOriented()
memo @,'isWeaklyOriented', -> @orbitIsWeaklyOriented()
memo @,'partialOrientation', -> @orbitPartialOrientation()
protocol: (indices, traversal) ->
imap = new HashMap().plusAll zap indices, seq.from 0
indexPairs = zap indices, indices.drop 1
tmp = traversal?.accumulate [new HashMap(), 1], ([hash, n, s], [D,i]) =>
[E, isNew] = if hash.get(D)? then [hash.get(D), false] else [n, true]
head = if i? then [imap.get(i), hash.get(@s(i)(D)), E] else [-1, E]
if isNew
[hash.plus([D,n]), n+1,
seq.concat head, indexPairs?.map ([i,j]) => @m(i,j)(D)]
else
[hash, n, head]
[tmp?.flatMap(([h, n, s]) -> s), tmp?.map ([h, n, s]) -> h]
lesser = (s1, s2) ->
if not s1? or s1[0].sub(s2[0]).find((a) -> a) > 0 then s2 else s1
memo @,'invariant', ->
unless @isConnected()
throw new Error "Not yet implemented for non-connected symbols"
tmp = @elements().reduce null, (best, D) =>
lesser best, @protocol @indices(), @traversal null, [D]
[tmp[0].forced(), tmp[1].last()] if tmp?
memo @,'hashCode', ->
seq.reduce @invariant(), 0, (code, n) -> (code * 37 + n) & 0xffffffff
equals: (other) ->
other.isDelaney and this.invariant()[0].equals other.invariant()[0]
memox @, 'type', (D) ->
(@indices()?.flatMap (i) =>
@indices()?.select((j) -> j > i)?.map (j) =>
@m(i, j)(D)
).forced()
typePartition: ->
unless @isConnected()
throw new Error "Not yet implemented for non-connected symbols"
step = (p, q) =>
if not q?.first()?
p
else
[[D, E], qn] = [q.first(), q.rest()]
if p.find(D) == p.find(E)
-> step p, qn
else if @type(D).equals(@type(E))
pn = p.union(D, E)
qx = seq.reduce @indices(), qn, (t, i) =>
t.push [@s(i)(D), @s(i)(E)]
-> step pn, qx
D0 = @elements().first()
seq.reduce @elements(), new Partition(), (p, D) ->
pn = bounce step p, (new Queue()).push [D0, D]
if pn? then pn else p
memo @,'isMinimal', ->
p = @typePartition()
seq.forall @elements(), (D) -> p.find(D) == D
memo @,'curvature2D', ->
throw new Error "Symbol must be two-dimensional" unless @dimension() == 2
inv = (x) -> num.div 1, x
term = (i, j) => @elements().map(@m(i, j)).map(inv).fold (a, b) -> a.plus b
[i, j, k] = @indices().into []
term(i, j).plus(term(i, k)).plus(term(j, k)).minus @size()
memo @,'isSpherical2D', ->
throw new Error "Symbol must be two-dimensional" unless @dimension() == 2
throw new Error "Symbol must be connected" unless @isConnected()
if @curvature2D().cmp(0) > 0
sym = @flat().orientedCover()
[r, s, t] = sym.indices().into []
deg = seq.flatMap [[r, s], [r, t], [s, t]], ([i, j]) ->
sym.orbitFirsts(i, j).map(sym.v(i, j)).select (v) -> v > 1
not (deg?.size() == 1 or (deg?.size() == 2 and deg.get(0) != deg.get(1)))
else
false
memo @,'sphericalGroupSize2D', ->
if @isSpherical2D()
@curvature2D().div(4).inv().toNative()
else
throw new Error "Symbol must be spherical"
memo @,'isLocallyEuclidean3D', ->
throw new Error "Symbol must be three-dimensional" unless @dimension() == 3
seq.forall @indices(), (i) =>
idcs = seq.select(@indices(), (j) -> j != i).into []
seq.forall @orbitFirsts(idcs...), (D) =>
new Subsymbol(this, idcs, D).isSpherical2D()
memo @,'orbifoldSymbol2D', ->
throw new Error "Symbol must be two-dimensional" unless @dimension() == 2
throw new Error "Symbol must be connected" unless @isConnected()
[r, s, t] = @indices().into []
tmp = seq.flatMap [[r, s], [r, t], [s, t]], ([i, j]) =>
@orbitFirsts(i, j).map((D) => [@v(i, j)(D), @orbitIsLoopless([i, j], [D])])
cones = tmp.select(([v, b]) -> b and v > 1)?.map(([v, b]) -> v)
crnrs = tmp.select(([v, b]) -> not b and v > 1)?.map(([v, b]) -> v)
c0 = @curvature2D().div(2)
c1 = seq.reduce cones, c0, (s, v) -> s.plus num.div v-1, v
c2 = seq.reduce crnrs, c1, (s, v) -> s.plus num.div v-1, 2*v
c3 = if @isLoopless() then c2 else c2.plus 1
c = 2 - c3.toNative()
series = (n, c) -> seq.join seq.constant(c).take(n), ''
tmp = seq.into(cones, []).sort().join('') +
(if @isLoopless() then '' else '*') +
seq.into(crnrs, []).sort().join('') +
if @isWeaklyOriented() then series(c / 2, 'o') else series(c, 'x')
if tmp.length > 0 then tmp else '1'
class DSymbol extends Delaney
# -- the constructor receives the dimension and an initial set of elements
constructor: (dimension, elms) ->
@dim__ = dimension
@elms__ = new IntSet().plus elms...
@ops__ = new IntMap().plus ([i, new IntMap()] for i in [0..dimension])...
@degs__ = new IntMap().plus ([i, new IntMap()] for i in [0...dimension])...
# -- the following four methods implement the common interface for
# all Delaney symbol classes.
memo @, 'indexSet', -> new IntSet().plusAll seq.range 0, @dim__
elementSet: -> @elms__
s: (i) -> (D) => @ops__.get(i).get(D)
m: (i, j) ->
if j?
switch j
when i + 1 then (D) => @degs__.get(i).get(D)
when i - 1 then (D) => @degs__.get(j).get(D)
when i then (D) -> 1
else (D) -> 2
else
(D) -> 1
# -- some private helper methods
create = (dimension, elements, operations, degrees) ->
ds = new DSymbol(dimension)
ds.elms__ = elements
ds.ops__ = operations
ds.degs__ = degrees
ds
# -- the following methods manipulate and incrementally build DSymbols
withElements: (args...) ->
create(@dim__, @elms__.plus(args...), @ops__, @degs__)
withoutElements: ->
args = seq arguments
elms = @elms__.minusAll args
ops = @ops__.map ([i, a]) => [i, a.minusAll(args).minusAll args.map @s(i)]
degs = @degs__.map ([i, d]) => [i, d.minusAll(args)]
create @dim__, elms, ops, degs
withGluings: (i) ->
(args...) =>
elms = @elms__.plusAll seq.flatten args
op = @ops__.get(i).plusAll seq.flatMap args, ([D, E]) ->
if E? then [[D, E], [E, D]] else [[D, D]]
create @dim__, elms, @ops__.plus([i, op]), @degs__
withoutGluings: (i) ->
(args...) =>
op = @ops__.get(i).minusAll seq.flatMap args, (D) => [D, @s(i)(D)]
create @dim__, @elms__, @ops__.plus([i, op]), @degs__
withDegrees: (i) ->
(args...) =>
m = @degs__.get(i).plusAll seq.flatMap args, ([D, val]) =>
@orbit(i, i + 1)(D).map (E) -> [E, val]
create @dim__, @elms__, @ops__, @degs__.plus [i, m]
withoutDegrees: (i) ->
(args...) =>
m = @degs__.get(i).minusAll seq.flatMap args, @orbit(i, i + 1)
create @dim__, @elms__, @ops__, @degs__.plus [i, m]
dual: ->
dim = @dim__
ops = @ops__.map ([i, m]) -> [dim-i, m]
degs = @degs__.map ([i, m]) -> [dim-1-i, m]
create(dim, @elms__, ops, degs)
filledIn: ->
elms = new IntSet().plusAll seq.range 1, seq.max @elms__
create(@dim__, elms, @ops__, @degs__)
renumbered: (f) ->
elms = @elms__.map f
ops = @ops__.map ([i, a]) -> [i, a.map ([D, E]) -> [f(D), f(E)]]
degs = @degs__.map ([i, a]) -> [i, a.map ([D, m]) -> [f(D), m]]
create @dim__, elms, ops, degs
concat: (sym) ->
offset = seq.max @elms__
tmp = sym.renumbered (D) -> D + offset
elms = @elms__.plusAll tmp.elms__
ops = @ops__.map ([i, a]) -> [i, a.plusAll tmp.ops__.get(i)]
degs = @degs__.map ([i, a]) -> [i, a.plusAll tmp.degs__.get(i)]
create @dim__, elms, ops, degs
collapsed: (connector, args...) ->
trash = new IntSet().plus args...
unless seq.forall(trash, (D) => trash.contains @s(connector)(D))
throw new Error "removed set must be invariant under s(#{connector})"
end = (E, i) =>
if trash.contains(E)
edge = @traversal([connector, i], [E]).find ([E1, k]) ->
k == i and not trash.contains E1
edge[0]
else
E
elms = @elms__.minus args...
ops = @ops__.map ([i, a]) =>
kept = seq.select a, ([D, E]) => not trash.contains D
[i, new IntMap().plusAll kept.map ([D, E]) => [D, end E, i]]
tmp = create @dim__, elms, ops, @degs__
degs = @degs__.map ([i, a]) =>
[i, a.map ([D, m]) => [D, if m? then @v(i, i+1)(D) * tmp.r(i, i+1)(D)]]
create @dim__, elms, ops, degs
memo @,'canonical', ->
map = @invariant()[1]
@renumbered (D) -> map.get(D)
memo @,'minimal', ->
p = @typePartition()
reps = seq.select @elements(), (D) -> p.find(D) == D
if reps.equals @elements()
this
else
n = reps.size()
map = new HashMap().plusAll zap reps, seq.from 1
ops = new IntMap().plusAll seq.range(0, @dimension()).map (i) =>
pairs = reps.map (D) => [map.get(D), map.get p.find @s(i)(D)]
[i, new IntMap().plusAll pairs]
degs = new IntMap().plusAll seq.range(0, @dimension()-1).map (i) =>
pairs = reps.map (D) => [map.get(D), @m(i, i+1)(D)]
[i, new IntMap().plusAll pairs]
create @dimension(), new IntSet().plus([1..n]...), ops, degs
orientedCover: ->
if @isOriented()
this
else
ori = @partialOrientation()
dim = @dimension()
n = @size()
ops = new IntMap().plusAll seq.range(0, dim).map (i) =>
pairs = @elements().flatMap (D) =>
E = @s(i)(D)
if E == D
[ [D , D + n], [D + n, D ] ]
else if ori.get(D) == ori.get(E)
[ [D , E + n], [D + n, E ], [E , D + n], [E + n, D ] ]
else
[ [D , E ], [D + n, E + n], [E , D ], [E + n, D + n] ]
[i, new IntMap().plusAll pairs]
degs = new IntMap().plusAll seq.range(0, dim-1).map (i) =>
pairs = @elements().flatMap (D) =>
m = @m(i, i+1)(D)
[[D, m], [D+n, m]]
[i, new IntMap().plusAll pairs]
create dim, new IntSet().plus([1..(2 * n)]...), ops, degs
# -- other methods specific to this class
toString: ->
join = (sep, s) -> seq.join s, sep
sym = @filledIn()
ops = join ",", sym.indices().map (i) ->
join " ", sym.orbitFirsts(i, i).map (D) -> sym.s(i)(D) or 0
degs = join ",", sym.indices().take(sym.dimension()).map (i) ->
join " ", sym.orbitFirsts(i, i+1).map (D) -> sym.m(i,i+1)(D) or 0
"<1.1:#{sym.size()} #{sym.dimension()}:#{ops}:#{degs}>"
DSymbol.flat = (sym) ->
raise new Error "must have a definite size" unless sym.size()?
dim = sym.dimension()
elms = seq.range 1, sym.size()
ds = new DSymbol dim
ds.elms__ = new HashSet().plusAll elms
emap = new HashMap().plusAll zip sym.elements(), elms
irev = new IntMap().plusAll zip seq.range(0, dim), sym.indices()
ds.ops__ = new IntMap().plusAll seq.range(0, dim).map (i) =>
j = irev.get i
pairs = sym.elements().map (D) => [emap.get(D), emap.get sym.s(j)(D)]
[i, new IntMap().plusAll pairs]
ds.degs__ = new IntMap().plusAll seq.range(0, dim-1).map (i) =>
[j, k] = [irev.get(i), irev.get(i+1)]
pairs = sym.elements().map (D) => [emap.get(D), sym.m(j, k)(D)]
[i, new IntMap().plusAll pairs]
ds
DSymbol.fromString = (code) ->
extract = (sym, str, fun) -> (
seq.map(str.trim().split(/\s+/), parseInt).
reduce [seq(), new IntSet().plusAll sym.elements()],
([acc, todo], val) ->
D = todo.toSeq()?.first()
[seq.concat(acc, [[D, val]]), todo.minusAll fun(D, val)]
)[0]
parts = code.trim().replace(/^</, '').replace(/>$/, '').split(":")
data = if parts[0].trim().match(/\d+\.\d+/) then parts[1..3] else parts[0..2]
[size, dim] = seq.map(data[0].trim().split(/\s+/), parseInt).into []
dimension = if dim? then dim else 2
throw new Error "the dimension is negative" if dimension < 0
throw new Error "the size is negative" if size < 0
gluings = data[1].trim().split(/,/)
degrees = data[2].trim().split(/,/)
ds0 = new DSymbol(dimension, [1..size])
ds1 = seq.range(0, dimension).reduce ds0, (sym, i) ->
pairs = extract sym, gluings[i], (D, E) -> seq([D, E])
pairs.reduce new IntMap(), (seen, [D, E]) ->
if seen.get(E)
throw new Error "s(#{i})(#{E}) was already set to #{seen.get(E)}"
seen.plus [D, E], [E, D]
sym.withGluings(i) pairs.into([])...
ds2 = seq.range(0, dimension-1).reduce ds1, (sym, i) ->
pairs = extract sym, degrees[i], (D, m) -> sym.orbit(i, i+1)(D)
sym.withDegrees(i) pairs.into([])...
ds2.assertValidity()
ds2
class Subsymbol extends Delaney
constructor: (@base, @idcs, @seed) ->
# -- the following eight methods implement the common interface for
# all Delaney symbol classes.
memo @,'indexSet', -> new IntSet().plusAll seq @idcs
memo @,'elementSet', ->
elms = @base.traversal(@idcs, [@seed])?.map(([E, k]) -> E)?.uniq()
new HashSet().plusAll elms
s: (i) ->
if @hasIndex(i)
(D) => @base.s(i)(D) if @hasElement(D)
else
(D) ->
m: (i, j) ->
if @hasIndex(i) and not j? or @hasIndex(j)
(D) => @base.m(i,j)(D) if @hasElement(D)
else
(D) ->
# --------------------------------------------------------------------
# Exporting.
# --------------------------------------------------------------------
exports ?= this.pazy ?= {}
exports.Delaney = Delaney
exports.DSymbol = DSymbol
exports.Subsymbol = Subsymbol
# --------------------------------------------------------------------
# Test code --
# --------------------------------------------------------------------
test = ->
{ show } = require 'testing'
puts = console.log
ds = new DSymbol(2, [1..3]).
withGluings(0)([1], [2], [3]).
withGluings(1)([1,2], [3]).
withGluings(2)([1], [2,3]).
withDegrees(0)([1,8], [3,4]).
withDegrees(1)([1,3])
show -> ds
show -> ds.size()
show -> ds.dimension()
show -> ds.elements()
show -> ds.indices()
show -> ds.s(1)(1)
show -> ds.m(0,1)(2)
puts ""
show -> ds.withoutDegrees(0)(1).withoutGluings(1)(1).withoutElements(3)
puts ""
show -> ds = DSymbol.fromString "<1.1:3:1 2 3,2 3,1 3:8 4,3>"
show -> ds.dual()
puts ""
puts "The following should throw an error:"
show -> DSymbol.fromString "<1.1:3:1 2 3,2 3,1 3:7 4,3>"
puts ""
show -> ds.withoutDegrees(1)(1).collapsed 0, 3
puts ""
show -> ds.traversal()
show -> ds.protocol(ds.indices(), ds.traversal(ds.indices(), [1]))[0].into []
puts ""
show -> ds.invariant()[0].into []
show -> ds.invariant()[1].toSeq()
show -> ds.canonical()
puts ""
p = null
show -> p = ds.typePartition()
show -> p.find 1
puts ""
show -> ds.minimal()
show -> DSymbol.fromString('<1.1:8:2 4 6 8,8 3 5 7,6 5 8 7:4,4>').minimal()
puts ""
show -> DSymbol.fromString('<1.1:4:2 4,4 3,4 3:2,5 5>').isSpherical2D()
show (-> DSymbol.fromString('<1.1:6:2 4 6,6 3 5,1 2 3 4 5 6:3,4 6 10>')
.orbifoldSymbol2D()), false
show -> DSymbol.fromString('<1.1:3 3:1 2 3,1 2 3,1 3,2 3:3 3 4,4 4,3>')
.isLocallyEuclidean3D()
if module? and not module.parent
args = seq.map(process.argv[2..], parseInt)?.into []
test args...
# -- End of test code --
| 1328 | if typeof(require) != 'undefined'
# for now we assume that pazy.js lives next to gavrog.js
require.paths.unshift("#{__dirname}/../../pazy.js/lib")
{ bounce } = require('functional')
{ seq } = require('sequence')
{ IntSet, IntMap, HashSet, HashMap } = require('indexed')
{ Stack } = require('stack')
{ Queue } = require('queue')
{ Partition } = require('partition')
{ num } = require('number')
require 'sequence_extras'
else
{
bounce, seq, IntSet, IntMap, HashSet, HashMap, Stack, Queue, Partition, num
} = this.pazy
# ----
# To be used in class bodies in order to create methods with memoized results.
memo = (klass, name, f) ->
klass::[name] = -> x = f.call(this); (@[name] = -> x)()
memox = (klass, name, f) ->
key = <KEY>"
klass::[name] = (args...) ->
val = (@[key] ||= new HashMap()).get(args)
if val?
val
else
v = f.apply(this, args)
@[key] = @[key].plus [args, v]
v
# ----
# Other helper methods
zip = (s,t) -> seq.zip(s, t).map (x) -> x.into []
zap = (s,t) -> zip(s,t)?.takeWhile ([a,b]) -> (a? and b?)
# ----
# The base class for Delaney symbols. All child classes need to
# implement the following four methods (see class DSymbol below for
# details):
#
# indexSet
# elementSet
# s
# m
#
# The first two methods must return an object that recognizes these methods:
#
# toSeq
# size
# contains
class Delaney
isDelaney: -> true
indices: -> @indexSet().toSeq()
dimension: -> @indexSet().size() - 1
hasIndex: (i) -> @indexSet().contains i
elements: -> @elementSet().toSeq()
size: -> @elementSet().size()
hasElement: (D) -> @elementSet().contains D
flat: -> DSymbol.flat this
assertValidity: ->
report = (msgs) ->
if msgs?.find((x) -> x?)
throw new Error(msgs?.select((x) -> x?)?.into([]).join("\n"))
report @indices()?.flatMap (i) =>
@elements()?.map (D) =>
Di = @s(i)(D)
if not @hasElement Di
"not an element: s(#{i}) #{D} = #{Di}"
else if Di > 0 and @s(i)(Di) != D
"inconsistent: s(#{i}) s(#{i}) #{D} = #{s(i) s(i) D}"
report @indices()?.flatMap (i) =>
@indices()?.flatMap (j) =>
@elements()?.map (D) =>
if @m(i, j)(D) < 0
"illegal: m(#{i}, #{j}) #{D} = #{m(i, j) D}"
else if @m(i, j)(D) != @m(i, j) @s(i) D
"inconsistent: m(#{i}, #{j}) #{D} = #{@m(i, j) D}, " +
"but m(#{i}, #{j}) s(#{i}) #{D} = #{@m(i, j) @s(i) D}"
report @indices()?.flatMap (i) =>
@indices()?.flatMap (j) =>
@orbitFirsts(i, j)?.map (D) =>
complete = @orbit(i, j)(D)?.forall (E) => @s(i)(E)? and @s(j)(E)?
m = @m(i,j)(D)
r = @r(i,j)(D)
if m % r > 0 and complete
"inconsistent: m(#{i}, #{j})(#{D}) = #{m} " +
"should be a multiple of #{r}"
else if m < r
"inconsistent: m(#{i}, #{j})(#{D}) = #{m} should be at least #{r}"
r: (i, j) -> (D) =>
step = (n, E0) =>
E1 = @s(i)(E0) or E0
E2 = @s(j)(E1) or E1
if E2 == D then n + 1 else -> step n + 1, E2
bounce step 0, D
v: (i, j) -> (D) => @m(i, j)(D) / @r(i, j)(D)
drop = (s, f) ->
if s.first()? and f s.first() then -> drop s.rest(), f else s
traversal: (idcs, seed_elms) ->
collect = (seeds_left, next, seen) =>
tmp = next.map ([k, d]) -> [k, bounce drop d, (x) -> seen.contains [x, k]]
if r = tmp.find(([k, x]) -> x.first()?)
[i, d] = r
[D, s] = [d.first(), d.rest()]
newNext = tmp.map ([k, x]) => [k, if k == i then s else x.push @s(k)(D)]
newSeen = seen.plus [D], [D, i], [@s(i)(D), i]
seq.conj [D, i], -> collect seeds_left, newNext, newSeen
else if D = seeds_left?.find((x) -> not seen.contains [x])
newNext = tmp.map ([k, x]) => [k, x.push @s(k)(D)]
newSeen = seen.plus [D]
seq.conj [D], -> collect seeds_left.rest(), newNext, newSeen
else
null
indices = seq(idcs) or @indices()
seeds = seq(seed_elms) or @elements()
stacks = seq.take(indices, 2)?.map (i) -> [i, new Stack()]
queues = seq.drop(indices, 2)?.map (i) -> [i, new Queue()]
initialNext = seq.concat(stacks, queues).forced()
collect seeds, initialNext, new HashSet()
orbit: (indices...) -> (D) =>
@traversal(indices, [D])?.map(([E, k]) -> E)?.uniq()
orbitFirsts: (indices...) ->
@traversal(indices)?.select(([D, k]) -> not k?)?.map ([D]) -> D
orbits: (indices...) ->
@orbitFirsts(indices...).map @orbit(indices...)
memo @, 'isComplete', ->
@elements()?.forall (D) =>
@indices()?.forall (i) => @s(i)(D)? and
@indices()?.forall (j) => @m(i, j)(D)?
memo @,'isConnected', -> not @orbitFirsts()?.rest()
traversalPartialOrientation: (traversal) ->
seq.reduce traversal, new HashMap(), (hash, [D,i]) =>
hash.plus [D, if i? then -hash.get(@s(i)(D)) else 1]
orbitPartialOrientation: (idcs, seeds) ->
@traversalPartialOrientation @traversal idcs, seeds
orbitIsLoopless: (idcs, seeds) ->
not @traversal(idcs, seeds)?.find ([D, i]) => i? and @s(i)(D) == D
orbitIsOriented: (idcs, seeds) ->
traversal = @traversal idcs, seeds
ori = @traversalPartialOrientation traversal
not traversal?.find ([D, i]) => i? and ori.get(@s(i)(D)) == ori.get(D)
orbitIsWeaklyOriented: (idcs, seeds) ->
traversal = @traversal idcs, seeds
ori = @traversalPartialOrientation traversal
not traversal?.find ([D, i]) =>
i? and @s(i)(D) != D and ori.get(@s(i)(D)) == ori.get(D)
memo @,'isLoopless', -> @orbitIsLoopless()
memo @,'isOriented', -> @orbitIsOriented()
memo @,'isWeaklyOriented', -> @orbitIsWeaklyOriented()
memo @,'partialOrientation', -> @orbitPartialOrientation()
protocol: (indices, traversal) ->
imap = new HashMap().plusAll zap indices, seq.from 0
indexPairs = zap indices, indices.drop 1
tmp = traversal?.accumulate [new HashMap(), 1], ([hash, n, s], [D,i]) =>
[E, isNew] = if hash.get(D)? then [hash.get(D), false] else [n, true]
head = if i? then [imap.get(i), hash.get(@s(i)(D)), E] else [-1, E]
if isNew
[hash.plus([D,n]), n+1,
seq.concat head, indexPairs?.map ([i,j]) => @m(i,j)(D)]
else
[hash, n, head]
[tmp?.flatMap(([h, n, s]) -> s), tmp?.map ([h, n, s]) -> h]
lesser = (s1, s2) ->
if not s1? or s1[0].sub(s2[0]).find((a) -> a) > 0 then s2 else s1
memo @,'invariant', ->
unless @isConnected()
throw new Error "Not yet implemented for non-connected symbols"
tmp = @elements().reduce null, (best, D) =>
lesser best, @protocol @indices(), @traversal null, [D]
[tmp[0].forced(), tmp[1].last()] if tmp?
memo @,'hashCode', ->
seq.reduce @invariant(), 0, (code, n) -> (code * 37 + n) & 0xffffffff
equals: (other) ->
other.isDelaney and this.invariant()[0].equals other.invariant()[0]
memox @, 'type', (D) ->
(@indices()?.flatMap (i) =>
@indices()?.select((j) -> j > i)?.map (j) =>
@m(i, j)(D)
).forced()
typePartition: ->
unless @isConnected()
throw new Error "Not yet implemented for non-connected symbols"
step = (p, q) =>
if not q?.first()?
p
else
[[D, E], qn] = [q.first(), q.rest()]
if p.find(D) == p.find(E)
-> step p, qn
else if @type(D).equals(@type(E))
pn = p.union(D, E)
qx = seq.reduce @indices(), qn, (t, i) =>
t.push [@s(i)(D), @s(i)(E)]
-> step pn, qx
D0 = @elements().first()
seq.reduce @elements(), new Partition(), (p, D) ->
pn = bounce step p, (new Queue()).push [D0, D]
if pn? then pn else p
memo @,'isMinimal', ->
p = @typePartition()
seq.forall @elements(), (D) -> p.find(D) == D
memo @,'curvature2D', ->
throw new Error "Symbol must be two-dimensional" unless @dimension() == 2
inv = (x) -> num.div 1, x
term = (i, j) => @elements().map(@m(i, j)).map(inv).fold (a, b) -> a.plus b
[i, j, k] = @indices().into []
term(i, j).plus(term(i, k)).plus(term(j, k)).minus @size()
memo @,'isSpherical2D', ->
throw new Error "Symbol must be two-dimensional" unless @dimension() == 2
throw new Error "Symbol must be connected" unless @isConnected()
if @curvature2D().cmp(0) > 0
sym = @flat().orientedCover()
[r, s, t] = sym.indices().into []
deg = seq.flatMap [[r, s], [r, t], [s, t]], ([i, j]) ->
sym.orbitFirsts(i, j).map(sym.v(i, j)).select (v) -> v > 1
not (deg?.size() == 1 or (deg?.size() == 2 and deg.get(0) != deg.get(1)))
else
false
memo @,'sphericalGroupSize2D', ->
if @isSpherical2D()
@curvature2D().div(4).inv().toNative()
else
throw new Error "Symbol must be spherical"
memo @,'isLocallyEuclidean3D', ->
throw new Error "Symbol must be three-dimensional" unless @dimension() == 3
seq.forall @indices(), (i) =>
idcs = seq.select(@indices(), (j) -> j != i).into []
seq.forall @orbitFirsts(idcs...), (D) =>
new Subsymbol(this, idcs, D).isSpherical2D()
memo @,'orbifoldSymbol2D', ->
throw new Error "Symbol must be two-dimensional" unless @dimension() == 2
throw new Error "Symbol must be connected" unless @isConnected()
[r, s, t] = @indices().into []
tmp = seq.flatMap [[r, s], [r, t], [s, t]], ([i, j]) =>
@orbitFirsts(i, j).map((D) => [@v(i, j)(D), @orbitIsLoopless([i, j], [D])])
cones = tmp.select(([v, b]) -> b and v > 1)?.map(([v, b]) -> v)
crnrs = tmp.select(([v, b]) -> not b and v > 1)?.map(([v, b]) -> v)
c0 = @curvature2D().div(2)
c1 = seq.reduce cones, c0, (s, v) -> s.plus num.div v-1, v
c2 = seq.reduce crnrs, c1, (s, v) -> s.plus num.div v-1, 2*v
c3 = if @isLoopless() then c2 else c2.plus 1
c = 2 - c3.toNative()
series = (n, c) -> seq.join seq.constant(c).take(n), ''
tmp = seq.into(cones, []).sort().join('') +
(if @isLoopless() then '' else '*') +
seq.into(crnrs, []).sort().join('') +
if @isWeaklyOriented() then series(c / 2, 'o') else series(c, 'x')
if tmp.length > 0 then tmp else '1'
class DSymbol extends Delaney
# -- the constructor receives the dimension and an initial set of elements
constructor: (dimension, elms) ->
@dim__ = dimension
@elms__ = new IntSet().plus elms...
@ops__ = new IntMap().plus ([i, new IntMap()] for i in [0..dimension])...
@degs__ = new IntMap().plus ([i, new IntMap()] for i in [0...dimension])...
# -- the following four methods implement the common interface for
# all Delaney symbol classes.
memo @, 'indexSet', -> new IntSet().plusAll seq.range 0, @dim__
elementSet: -> @elms__
s: (i) -> (D) => @ops__.get(i).get(D)
m: (i, j) ->
if j?
switch j
when i + 1 then (D) => @degs__.get(i).get(D)
when i - 1 then (D) => @degs__.get(j).get(D)
when i then (D) -> 1
else (D) -> 2
else
(D) -> 1
# -- some private helper methods
create = (dimension, elements, operations, degrees) ->
ds = new DSymbol(dimension)
ds.elms__ = elements
ds.ops__ = operations
ds.degs__ = degrees
ds
# -- the following methods manipulate and incrementally build DSymbols
withElements: (args...) ->
create(@dim__, @elms__.plus(args...), @ops__, @degs__)
withoutElements: ->
args = seq arguments
elms = @elms__.minusAll args
ops = @ops__.map ([i, a]) => [i, a.minusAll(args).minusAll args.map @s(i)]
degs = @degs__.map ([i, d]) => [i, d.minusAll(args)]
create @dim__, elms, ops, degs
withGluings: (i) ->
(args...) =>
elms = @elms__.plusAll seq.flatten args
op = @ops__.get(i).plusAll seq.flatMap args, ([D, E]) ->
if E? then [[D, E], [E, D]] else [[D, D]]
create @dim__, elms, @ops__.plus([i, op]), @degs__
withoutGluings: (i) ->
(args...) =>
op = @ops__.get(i).minusAll seq.flatMap args, (D) => [D, @s(i)(D)]
create @dim__, @elms__, @ops__.plus([i, op]), @degs__
withDegrees: (i) ->
(args...) =>
m = @degs__.get(i).plusAll seq.flatMap args, ([D, val]) =>
@orbit(i, i + 1)(D).map (E) -> [E, val]
create @dim__, @elms__, @ops__, @degs__.plus [i, m]
withoutDegrees: (i) ->
(args...) =>
m = @degs__.get(i).minusAll seq.flatMap args, @orbit(i, i + 1)
create @dim__, @elms__, @ops__, @degs__.plus [i, m]
dual: ->
dim = @dim__
ops = @ops__.map ([i, m]) -> [dim-i, m]
degs = @degs__.map ([i, m]) -> [dim-1-i, m]
create(dim, @elms__, ops, degs)
filledIn: ->
elms = new IntSet().plusAll seq.range 1, seq.max @elms__
create(@dim__, elms, @ops__, @degs__)
renumbered: (f) ->
elms = @elms__.map f
ops = @ops__.map ([i, a]) -> [i, a.map ([D, E]) -> [f(D), f(E)]]
degs = @degs__.map ([i, a]) -> [i, a.map ([D, m]) -> [f(D), m]]
create @dim__, elms, ops, degs
concat: (sym) ->
offset = seq.max @elms__
tmp = sym.renumbered (D) -> D + offset
elms = @elms__.plusAll tmp.elms__
ops = @ops__.map ([i, a]) -> [i, a.plusAll tmp.ops__.get(i)]
degs = @degs__.map ([i, a]) -> [i, a.plusAll tmp.degs__.get(i)]
create @dim__, elms, ops, degs
collapsed: (connector, args...) ->
trash = new IntSet().plus args...
unless seq.forall(trash, (D) => trash.contains @s(connector)(D))
throw new Error "removed set must be invariant under s(#{connector})"
end = (E, i) =>
if trash.contains(E)
edge = @traversal([connector, i], [E]).find ([E1, k]) ->
k == i and not trash.contains E1
edge[0]
else
E
elms = @elms__.minus args...
ops = @ops__.map ([i, a]) =>
kept = seq.select a, ([D, E]) => not trash.contains D
[i, new IntMap().plusAll kept.map ([D, E]) => [D, end E, i]]
tmp = create @dim__, elms, ops, @degs__
degs = @degs__.map ([i, a]) =>
[i, a.map ([D, m]) => [D, if m? then @v(i, i+1)(D) * tmp.r(i, i+1)(D)]]
create @dim__, elms, ops, degs
memo @,'canonical', ->
map = @invariant()[1]
@renumbered (D) -> map.get(D)
memo @,'minimal', ->
p = @typePartition()
reps = seq.select @elements(), (D) -> p.find(D) == D
if reps.equals @elements()
this
else
n = reps.size()
map = new HashMap().plusAll zap reps, seq.from 1
ops = new IntMap().plusAll seq.range(0, @dimension()).map (i) =>
pairs = reps.map (D) => [map.get(D), map.get p.find @s(i)(D)]
[i, new IntMap().plusAll pairs]
degs = new IntMap().plusAll seq.range(0, @dimension()-1).map (i) =>
pairs = reps.map (D) => [map.get(D), @m(i, i+1)(D)]
[i, new IntMap().plusAll pairs]
create @dimension(), new IntSet().plus([1..n]...), ops, degs
orientedCover: ->
if @isOriented()
this
else
ori = @partialOrientation()
dim = @dimension()
n = @size()
ops = new IntMap().plusAll seq.range(0, dim).map (i) =>
pairs = @elements().flatMap (D) =>
E = @s(i)(D)
if E == D
[ [D , D + n], [D + n, D ] ]
else if ori.get(D) == ori.get(E)
[ [D , E + n], [D + n, E ], [E , D + n], [E + n, D ] ]
else
[ [D , E ], [D + n, E + n], [E , D ], [E + n, D + n] ]
[i, new IntMap().plusAll pairs]
degs = new IntMap().plusAll seq.range(0, dim-1).map (i) =>
pairs = @elements().flatMap (D) =>
m = @m(i, i+1)(D)
[[D, m], [D+n, m]]
[i, new IntMap().plusAll pairs]
create dim, new IntSet().plus([1..(2 * n)]...), ops, degs
# -- other methods specific to this class
toString: ->
join = (sep, s) -> seq.join s, sep
sym = @filledIn()
ops = join ",", sym.indices().map (i) ->
join " ", sym.orbitFirsts(i, i).map (D) -> sym.s(i)(D) or 0
degs = join ",", sym.indices().take(sym.dimension()).map (i) ->
join " ", sym.orbitFirsts(i, i+1).map (D) -> sym.m(i,i+1)(D) or 0
"<1.1:#{sym.size()} #{sym.dimension()}:#{ops}:#{degs}>"
DSymbol.flat = (sym) ->
raise new Error "must have a definite size" unless sym.size()?
dim = sym.dimension()
elms = seq.range 1, sym.size()
ds = new DSymbol dim
ds.elms__ = new HashSet().plusAll elms
emap = new HashMap().plusAll zip sym.elements(), elms
irev = new IntMap().plusAll zip seq.range(0, dim), sym.indices()
ds.ops__ = new IntMap().plusAll seq.range(0, dim).map (i) =>
j = irev.get i
pairs = sym.elements().map (D) => [emap.get(D), emap.get sym.s(j)(D)]
[i, new IntMap().plusAll pairs]
ds.degs__ = new IntMap().plusAll seq.range(0, dim-1).map (i) =>
[j, k] = [irev.get(i), irev.get(i+1)]
pairs = sym.elements().map (D) => [emap.get(D), sym.m(j, k)(D)]
[i, new IntMap().plusAll pairs]
ds
DSymbol.fromString = (code) ->
extract = (sym, str, fun) -> (
seq.map(str.trim().split(/\s+/), parseInt).
reduce [seq(), new IntSet().plusAll sym.elements()],
([acc, todo], val) ->
D = todo.toSeq()?.first()
[seq.concat(acc, [[D, val]]), todo.minusAll fun(D, val)]
)[0]
parts = code.trim().replace(/^</, '').replace(/>$/, '').split(":")
data = if parts[0].trim().match(/\d+\.\d+/) then parts[1..3] else parts[0..2]
[size, dim] = seq.map(data[0].trim().split(/\s+/), parseInt).into []
dimension = if dim? then dim else 2
throw new Error "the dimension is negative" if dimension < 0
throw new Error "the size is negative" if size < 0
gluings = data[1].trim().split(/,/)
degrees = data[2].trim().split(/,/)
ds0 = new DSymbol(dimension, [1..size])
ds1 = seq.range(0, dimension).reduce ds0, (sym, i) ->
pairs = extract sym, gluings[i], (D, E) -> seq([D, E])
pairs.reduce new IntMap(), (seen, [D, E]) ->
if seen.get(E)
throw new Error "s(#{i})(#{E}) was already set to #{seen.get(E)}"
seen.plus [D, E], [E, D]
sym.withGluings(i) pairs.into([])...
ds2 = seq.range(0, dimension-1).reduce ds1, (sym, i) ->
pairs = extract sym, degrees[i], (D, m) -> sym.orbit(i, i+1)(D)
sym.withDegrees(i) pairs.into([])...
ds2.assertValidity()
ds2
class Subsymbol extends Delaney
constructor: (@base, @idcs, @seed) ->
# -- the following eight methods implement the common interface for
# all Delaney symbol classes.
memo @,'indexSet', -> new IntSet().plusAll seq @idcs
memo @,'elementSet', ->
elms = @base.traversal(@idcs, [@seed])?.map(([E, k]) -> E)?.uniq()
new HashSet().plusAll elms
s: (i) ->
if @hasIndex(i)
(D) => @base.s(i)(D) if @hasElement(D)
else
(D) ->
m: (i, j) ->
if @hasIndex(i) and not j? or @hasIndex(j)
(D) => @base.m(i,j)(D) if @hasElement(D)
else
(D) ->
# --------------------------------------------------------------------
# Exporting.
# --------------------------------------------------------------------
exports ?= this.pazy ?= {}
exports.Delaney = Delaney
exports.DSymbol = DSymbol
exports.Subsymbol = Subsymbol
# --------------------------------------------------------------------
# Test code --
# --------------------------------------------------------------------
test = ->
{ show } = require 'testing'
puts = console.log
ds = new DSymbol(2, [1..3]).
withGluings(0)([1], [2], [3]).
withGluings(1)([1,2], [3]).
withGluings(2)([1], [2,3]).
withDegrees(0)([1,8], [3,4]).
withDegrees(1)([1,3])
show -> ds
show -> ds.size()
show -> ds.dimension()
show -> ds.elements()
show -> ds.indices()
show -> ds.s(1)(1)
show -> ds.m(0,1)(2)
puts ""
show -> ds.withoutDegrees(0)(1).withoutGluings(1)(1).withoutElements(3)
puts ""
show -> ds = DSymbol.fromString "<1.1:3:1 2 3,2 3,1 3:8 4,3>"
show -> ds.dual()
puts ""
puts "The following should throw an error:"
show -> DSymbol.fromString "<1.1:3:1 2 3,2 3,1 3:7 4,3>"
puts ""
show -> ds.withoutDegrees(1)(1).collapsed 0, 3
puts ""
show -> ds.traversal()
show -> ds.protocol(ds.indices(), ds.traversal(ds.indices(), [1]))[0].into []
puts ""
show -> ds.invariant()[0].into []
show -> ds.invariant()[1].toSeq()
show -> ds.canonical()
puts ""
p = null
show -> p = ds.typePartition()
show -> p.find 1
puts ""
show -> ds.minimal()
show -> DSymbol.fromString('<1.1:8:2 4 6 8,8 3 5 7,6 5 8 7:4,4>').minimal()
puts ""
show -> DSymbol.fromString('<1.1:4:2 4,4 3,4 3:2,5 5>').isSpherical2D()
show (-> DSymbol.fromString('<1.1:6:2 4 6,6 3 5,1 2 3 4 5 6:3,4 6 10>')
.orbifoldSymbol2D()), false
show -> DSymbol.fromString('<1.1:3 3:1 2 3,1 2 3,1 3,2 3:3 3 4,4 4,3>')
.isLocallyEuclidean3D()
if module? and not module.parent
args = seq.map(process.argv[2..], parseInt)?.into []
test args...
# -- End of test code --
| true | if typeof(require) != 'undefined'
# for now we assume that pazy.js lives next to gavrog.js
require.paths.unshift("#{__dirname}/../../pazy.js/lib")
{ bounce } = require('functional')
{ seq } = require('sequence')
{ IntSet, IntMap, HashSet, HashMap } = require('indexed')
{ Stack } = require('stack')
{ Queue } = require('queue')
{ Partition } = require('partition')
{ num } = require('number')
require 'sequence_extras'
else
{
bounce, seq, IntSet, IntMap, HashSet, HashMap, Stack, Queue, Partition, num
} = this.pazy
# ----
# To be used in class bodies in order to create methods with memoized results.
memo = (klass, name, f) ->
klass::[name] = -> x = f.call(this); (@[name] = -> x)()
memox = (klass, name, f) ->
key = PI:KEY:<KEY>END_PI"
klass::[name] = (args...) ->
val = (@[key] ||= new HashMap()).get(args)
if val?
val
else
v = f.apply(this, args)
@[key] = @[key].plus [args, v]
v
# ----
# Other helper methods
zip = (s,t) -> seq.zip(s, t).map (x) -> x.into []
zap = (s,t) -> zip(s,t)?.takeWhile ([a,b]) -> (a? and b?)
# ----
# The base class for Delaney symbols. All child classes need to
# implement the following four methods (see class DSymbol below for
# details):
#
# indexSet
# elementSet
# s
# m
#
# The first two methods must return an object that recognizes these methods:
#
# toSeq
# size
# contains
class Delaney
isDelaney: -> true
indices: -> @indexSet().toSeq()
dimension: -> @indexSet().size() - 1
hasIndex: (i) -> @indexSet().contains i
elements: -> @elementSet().toSeq()
size: -> @elementSet().size()
hasElement: (D) -> @elementSet().contains D
flat: -> DSymbol.flat this
assertValidity: ->
report = (msgs) ->
if msgs?.find((x) -> x?)
throw new Error(msgs?.select((x) -> x?)?.into([]).join("\n"))
report @indices()?.flatMap (i) =>
@elements()?.map (D) =>
Di = @s(i)(D)
if not @hasElement Di
"not an element: s(#{i}) #{D} = #{Di}"
else if Di > 0 and @s(i)(Di) != D
"inconsistent: s(#{i}) s(#{i}) #{D} = #{s(i) s(i) D}"
report @indices()?.flatMap (i) =>
@indices()?.flatMap (j) =>
@elements()?.map (D) =>
if @m(i, j)(D) < 0
"illegal: m(#{i}, #{j}) #{D} = #{m(i, j) D}"
else if @m(i, j)(D) != @m(i, j) @s(i) D
"inconsistent: m(#{i}, #{j}) #{D} = #{@m(i, j) D}, " +
"but m(#{i}, #{j}) s(#{i}) #{D} = #{@m(i, j) @s(i) D}"
report @indices()?.flatMap (i) =>
@indices()?.flatMap (j) =>
@orbitFirsts(i, j)?.map (D) =>
complete = @orbit(i, j)(D)?.forall (E) => @s(i)(E)? and @s(j)(E)?
m = @m(i,j)(D)
r = @r(i,j)(D)
if m % r > 0 and complete
"inconsistent: m(#{i}, #{j})(#{D}) = #{m} " +
"should be a multiple of #{r}"
else if m < r
"inconsistent: m(#{i}, #{j})(#{D}) = #{m} should be at least #{r}"
r: (i, j) -> (D) =>
step = (n, E0) =>
E1 = @s(i)(E0) or E0
E2 = @s(j)(E1) or E1
if E2 == D then n + 1 else -> step n + 1, E2
bounce step 0, D
v: (i, j) -> (D) => @m(i, j)(D) / @r(i, j)(D)
drop = (s, f) ->
if s.first()? and f s.first() then -> drop s.rest(), f else s
traversal: (idcs, seed_elms) ->
collect = (seeds_left, next, seen) =>
tmp = next.map ([k, d]) -> [k, bounce drop d, (x) -> seen.contains [x, k]]
if r = tmp.find(([k, x]) -> x.first()?)
[i, d] = r
[D, s] = [d.first(), d.rest()]
newNext = tmp.map ([k, x]) => [k, if k == i then s else x.push @s(k)(D)]
newSeen = seen.plus [D], [D, i], [@s(i)(D), i]
seq.conj [D, i], -> collect seeds_left, newNext, newSeen
else if D = seeds_left?.find((x) -> not seen.contains [x])
newNext = tmp.map ([k, x]) => [k, x.push @s(k)(D)]
newSeen = seen.plus [D]
seq.conj [D], -> collect seeds_left.rest(), newNext, newSeen
else
null
indices = seq(idcs) or @indices()
seeds = seq(seed_elms) or @elements()
stacks = seq.take(indices, 2)?.map (i) -> [i, new Stack()]
queues = seq.drop(indices, 2)?.map (i) -> [i, new Queue()]
initialNext = seq.concat(stacks, queues).forced()
collect seeds, initialNext, new HashSet()
orbit: (indices...) -> (D) =>
@traversal(indices, [D])?.map(([E, k]) -> E)?.uniq()
orbitFirsts: (indices...) ->
@traversal(indices)?.select(([D, k]) -> not k?)?.map ([D]) -> D
orbits: (indices...) ->
@orbitFirsts(indices...).map @orbit(indices...)
memo @, 'isComplete', ->
@elements()?.forall (D) =>
@indices()?.forall (i) => @s(i)(D)? and
@indices()?.forall (j) => @m(i, j)(D)?
memo @,'isConnected', -> not @orbitFirsts()?.rest()
traversalPartialOrientation: (traversal) ->
seq.reduce traversal, new HashMap(), (hash, [D,i]) =>
hash.plus [D, if i? then -hash.get(@s(i)(D)) else 1]
orbitPartialOrientation: (idcs, seeds) ->
@traversalPartialOrientation @traversal idcs, seeds
orbitIsLoopless: (idcs, seeds) ->
not @traversal(idcs, seeds)?.find ([D, i]) => i? and @s(i)(D) == D
orbitIsOriented: (idcs, seeds) ->
traversal = @traversal idcs, seeds
ori = @traversalPartialOrientation traversal
not traversal?.find ([D, i]) => i? and ori.get(@s(i)(D)) == ori.get(D)
orbitIsWeaklyOriented: (idcs, seeds) ->
traversal = @traversal idcs, seeds
ori = @traversalPartialOrientation traversal
not traversal?.find ([D, i]) =>
i? and @s(i)(D) != D and ori.get(@s(i)(D)) == ori.get(D)
memo @,'isLoopless', -> @orbitIsLoopless()
memo @,'isOriented', -> @orbitIsOriented()
memo @,'isWeaklyOriented', -> @orbitIsWeaklyOriented()
memo @,'partialOrientation', -> @orbitPartialOrientation()
protocol: (indices, traversal) ->
imap = new HashMap().plusAll zap indices, seq.from 0
indexPairs = zap indices, indices.drop 1
tmp = traversal?.accumulate [new HashMap(), 1], ([hash, n, s], [D,i]) =>
[E, isNew] = if hash.get(D)? then [hash.get(D), false] else [n, true]
head = if i? then [imap.get(i), hash.get(@s(i)(D)), E] else [-1, E]
if isNew
[hash.plus([D,n]), n+1,
seq.concat head, indexPairs?.map ([i,j]) => @m(i,j)(D)]
else
[hash, n, head]
[tmp?.flatMap(([h, n, s]) -> s), tmp?.map ([h, n, s]) -> h]
lesser = (s1, s2) ->
if not s1? or s1[0].sub(s2[0]).find((a) -> a) > 0 then s2 else s1
memo @,'invariant', ->
unless @isConnected()
throw new Error "Not yet implemented for non-connected symbols"
tmp = @elements().reduce null, (best, D) =>
lesser best, @protocol @indices(), @traversal null, [D]
[tmp[0].forced(), tmp[1].last()] if tmp?
memo @,'hashCode', ->
seq.reduce @invariant(), 0, (code, n) -> (code * 37 + n) & 0xffffffff
equals: (other) ->
other.isDelaney and this.invariant()[0].equals other.invariant()[0]
memox @, 'type', (D) ->
(@indices()?.flatMap (i) =>
@indices()?.select((j) -> j > i)?.map (j) =>
@m(i, j)(D)
).forced()
typePartition: ->
unless @isConnected()
throw new Error "Not yet implemented for non-connected symbols"
step = (p, q) =>
if not q?.first()?
p
else
[[D, E], qn] = [q.first(), q.rest()]
if p.find(D) == p.find(E)
-> step p, qn
else if @type(D).equals(@type(E))
pn = p.union(D, E)
qx = seq.reduce @indices(), qn, (t, i) =>
t.push [@s(i)(D), @s(i)(E)]
-> step pn, qx
D0 = @elements().first()
seq.reduce @elements(), new Partition(), (p, D) ->
pn = bounce step p, (new Queue()).push [D0, D]
if pn? then pn else p
memo @,'isMinimal', ->
p = @typePartition()
seq.forall @elements(), (D) -> p.find(D) == D
memo @,'curvature2D', ->
throw new Error "Symbol must be two-dimensional" unless @dimension() == 2
inv = (x) -> num.div 1, x
term = (i, j) => @elements().map(@m(i, j)).map(inv).fold (a, b) -> a.plus b
[i, j, k] = @indices().into []
term(i, j).plus(term(i, k)).plus(term(j, k)).minus @size()
memo @,'isSpherical2D', ->
throw new Error "Symbol must be two-dimensional" unless @dimension() == 2
throw new Error "Symbol must be connected" unless @isConnected()
if @curvature2D().cmp(0) > 0
sym = @flat().orientedCover()
[r, s, t] = sym.indices().into []
deg = seq.flatMap [[r, s], [r, t], [s, t]], ([i, j]) ->
sym.orbitFirsts(i, j).map(sym.v(i, j)).select (v) -> v > 1
not (deg?.size() == 1 or (deg?.size() == 2 and deg.get(0) != deg.get(1)))
else
false
memo @,'sphericalGroupSize2D', ->
if @isSpherical2D()
@curvature2D().div(4).inv().toNative()
else
throw new Error "Symbol must be spherical"
memo @,'isLocallyEuclidean3D', ->
throw new Error "Symbol must be three-dimensional" unless @dimension() == 3
seq.forall @indices(), (i) =>
idcs = seq.select(@indices(), (j) -> j != i).into []
seq.forall @orbitFirsts(idcs...), (D) =>
new Subsymbol(this, idcs, D).isSpherical2D()
memo @,'orbifoldSymbol2D', ->
throw new Error "Symbol must be two-dimensional" unless @dimension() == 2
throw new Error "Symbol must be connected" unless @isConnected()
[r, s, t] = @indices().into []
tmp = seq.flatMap [[r, s], [r, t], [s, t]], ([i, j]) =>
@orbitFirsts(i, j).map((D) => [@v(i, j)(D), @orbitIsLoopless([i, j], [D])])
cones = tmp.select(([v, b]) -> b and v > 1)?.map(([v, b]) -> v)
crnrs = tmp.select(([v, b]) -> not b and v > 1)?.map(([v, b]) -> v)
c0 = @curvature2D().div(2)
c1 = seq.reduce cones, c0, (s, v) -> s.plus num.div v-1, v
c2 = seq.reduce crnrs, c1, (s, v) -> s.plus num.div v-1, 2*v
c3 = if @isLoopless() then c2 else c2.plus 1
c = 2 - c3.toNative()
series = (n, c) -> seq.join seq.constant(c).take(n), ''
tmp = seq.into(cones, []).sort().join('') +
(if @isLoopless() then '' else '*') +
seq.into(crnrs, []).sort().join('') +
if @isWeaklyOriented() then series(c / 2, 'o') else series(c, 'x')
if tmp.length > 0 then tmp else '1'
class DSymbol extends Delaney
# -- the constructor receives the dimension and an initial set of elements
constructor: (dimension, elms) ->
@dim__ = dimension
@elms__ = new IntSet().plus elms...
@ops__ = new IntMap().plus ([i, new IntMap()] for i in [0..dimension])...
@degs__ = new IntMap().plus ([i, new IntMap()] for i in [0...dimension])...
# -- the following four methods implement the common interface for
# all Delaney symbol classes.
memo @, 'indexSet', -> new IntSet().plusAll seq.range 0, @dim__
elementSet: -> @elms__
s: (i) -> (D) => @ops__.get(i).get(D)
m: (i, j) ->
if j?
switch j
when i + 1 then (D) => @degs__.get(i).get(D)
when i - 1 then (D) => @degs__.get(j).get(D)
when i then (D) -> 1
else (D) -> 2
else
(D) -> 1
# -- some private helper methods
create = (dimension, elements, operations, degrees) ->
ds = new DSymbol(dimension)
ds.elms__ = elements
ds.ops__ = operations
ds.degs__ = degrees
ds
# -- the following methods manipulate and incrementally build DSymbols
withElements: (args...) ->
create(@dim__, @elms__.plus(args...), @ops__, @degs__)
withoutElements: ->
args = seq arguments
elms = @elms__.minusAll args
ops = @ops__.map ([i, a]) => [i, a.minusAll(args).minusAll args.map @s(i)]
degs = @degs__.map ([i, d]) => [i, d.minusAll(args)]
create @dim__, elms, ops, degs
withGluings: (i) ->
(args...) =>
elms = @elms__.plusAll seq.flatten args
op = @ops__.get(i).plusAll seq.flatMap args, ([D, E]) ->
if E? then [[D, E], [E, D]] else [[D, D]]
create @dim__, elms, @ops__.plus([i, op]), @degs__
withoutGluings: (i) ->
(args...) =>
op = @ops__.get(i).minusAll seq.flatMap args, (D) => [D, @s(i)(D)]
create @dim__, @elms__, @ops__.plus([i, op]), @degs__
withDegrees: (i) ->
(args...) =>
m = @degs__.get(i).plusAll seq.flatMap args, ([D, val]) =>
@orbit(i, i + 1)(D).map (E) -> [E, val]
create @dim__, @elms__, @ops__, @degs__.plus [i, m]
withoutDegrees: (i) ->
(args...) =>
m = @degs__.get(i).minusAll seq.flatMap args, @orbit(i, i + 1)
create @dim__, @elms__, @ops__, @degs__.plus [i, m]
dual: ->
dim = @dim__
ops = @ops__.map ([i, m]) -> [dim-i, m]
degs = @degs__.map ([i, m]) -> [dim-1-i, m]
create(dim, @elms__, ops, degs)
filledIn: ->
elms = new IntSet().plusAll seq.range 1, seq.max @elms__
create(@dim__, elms, @ops__, @degs__)
renumbered: (f) ->
elms = @elms__.map f
ops = @ops__.map ([i, a]) -> [i, a.map ([D, E]) -> [f(D), f(E)]]
degs = @degs__.map ([i, a]) -> [i, a.map ([D, m]) -> [f(D), m]]
create @dim__, elms, ops, degs
concat: (sym) ->
offset = seq.max @elms__
tmp = sym.renumbered (D) -> D + offset
elms = @elms__.plusAll tmp.elms__
ops = @ops__.map ([i, a]) -> [i, a.plusAll tmp.ops__.get(i)]
degs = @degs__.map ([i, a]) -> [i, a.plusAll tmp.degs__.get(i)]
create @dim__, elms, ops, degs
collapsed: (connector, args...) ->
trash = new IntSet().plus args...
unless seq.forall(trash, (D) => trash.contains @s(connector)(D))
throw new Error "removed set must be invariant under s(#{connector})"
end = (E, i) =>
if trash.contains(E)
edge = @traversal([connector, i], [E]).find ([E1, k]) ->
k == i and not trash.contains E1
edge[0]
else
E
elms = @elms__.minus args...
ops = @ops__.map ([i, a]) =>
kept = seq.select a, ([D, E]) => not trash.contains D
[i, new IntMap().plusAll kept.map ([D, E]) => [D, end E, i]]
tmp = create @dim__, elms, ops, @degs__
degs = @degs__.map ([i, a]) =>
[i, a.map ([D, m]) => [D, if m? then @v(i, i+1)(D) * tmp.r(i, i+1)(D)]]
create @dim__, elms, ops, degs
memo @,'canonical', ->
map = @invariant()[1]
@renumbered (D) -> map.get(D)
memo @,'minimal', ->
p = @typePartition()
reps = seq.select @elements(), (D) -> p.find(D) == D
if reps.equals @elements()
this
else
n = reps.size()
map = new HashMap().plusAll zap reps, seq.from 1
ops = new IntMap().plusAll seq.range(0, @dimension()).map (i) =>
pairs = reps.map (D) => [map.get(D), map.get p.find @s(i)(D)]
[i, new IntMap().plusAll pairs]
degs = new IntMap().plusAll seq.range(0, @dimension()-1).map (i) =>
pairs = reps.map (D) => [map.get(D), @m(i, i+1)(D)]
[i, new IntMap().plusAll pairs]
create @dimension(), new IntSet().plus([1..n]...), ops, degs
orientedCover: ->
if @isOriented()
this
else
ori = @partialOrientation()
dim = @dimension()
n = @size()
ops = new IntMap().plusAll seq.range(0, dim).map (i) =>
pairs = @elements().flatMap (D) =>
E = @s(i)(D)
if E == D
[ [D , D + n], [D + n, D ] ]
else if ori.get(D) == ori.get(E)
[ [D , E + n], [D + n, E ], [E , D + n], [E + n, D ] ]
else
[ [D , E ], [D + n, E + n], [E , D ], [E + n, D + n] ]
[i, new IntMap().plusAll pairs]
degs = new IntMap().plusAll seq.range(0, dim-1).map (i) =>
pairs = @elements().flatMap (D) =>
m = @m(i, i+1)(D)
[[D, m], [D+n, m]]
[i, new IntMap().plusAll pairs]
create dim, new IntSet().plus([1..(2 * n)]...), ops, degs
# -- other methods specific to this class
toString: ->
join = (sep, s) -> seq.join s, sep
sym = @filledIn()
ops = join ",", sym.indices().map (i) ->
join " ", sym.orbitFirsts(i, i).map (D) -> sym.s(i)(D) or 0
degs = join ",", sym.indices().take(sym.dimension()).map (i) ->
join " ", sym.orbitFirsts(i, i+1).map (D) -> sym.m(i,i+1)(D) or 0
"<1.1:#{sym.size()} #{sym.dimension()}:#{ops}:#{degs}>"
DSymbol.flat = (sym) ->
raise new Error "must have a definite size" unless sym.size()?
dim = sym.dimension()
elms = seq.range 1, sym.size()
ds = new DSymbol dim
ds.elms__ = new HashSet().plusAll elms
emap = new HashMap().plusAll zip sym.elements(), elms
irev = new IntMap().plusAll zip seq.range(0, dim), sym.indices()
ds.ops__ = new IntMap().plusAll seq.range(0, dim).map (i) =>
j = irev.get i
pairs = sym.elements().map (D) => [emap.get(D), emap.get sym.s(j)(D)]
[i, new IntMap().plusAll pairs]
ds.degs__ = new IntMap().plusAll seq.range(0, dim-1).map (i) =>
[j, k] = [irev.get(i), irev.get(i+1)]
pairs = sym.elements().map (D) => [emap.get(D), sym.m(j, k)(D)]
[i, new IntMap().plusAll pairs]
ds
DSymbol.fromString = (code) ->
extract = (sym, str, fun) -> (
seq.map(str.trim().split(/\s+/), parseInt).
reduce [seq(), new IntSet().plusAll sym.elements()],
([acc, todo], val) ->
D = todo.toSeq()?.first()
[seq.concat(acc, [[D, val]]), todo.minusAll fun(D, val)]
)[0]
parts = code.trim().replace(/^</, '').replace(/>$/, '').split(":")
data = if parts[0].trim().match(/\d+\.\d+/) then parts[1..3] else parts[0..2]
[size, dim] = seq.map(data[0].trim().split(/\s+/), parseInt).into []
dimension = if dim? then dim else 2
throw new Error "the dimension is negative" if dimension < 0
throw new Error "the size is negative" if size < 0
gluings = data[1].trim().split(/,/)
degrees = data[2].trim().split(/,/)
ds0 = new DSymbol(dimension, [1..size])
ds1 = seq.range(0, dimension).reduce ds0, (sym, i) ->
pairs = extract sym, gluings[i], (D, E) -> seq([D, E])
pairs.reduce new IntMap(), (seen, [D, E]) ->
if seen.get(E)
throw new Error "s(#{i})(#{E}) was already set to #{seen.get(E)}"
seen.plus [D, E], [E, D]
sym.withGluings(i) pairs.into([])...
ds2 = seq.range(0, dimension-1).reduce ds1, (sym, i) ->
pairs = extract sym, degrees[i], (D, m) -> sym.orbit(i, i+1)(D)
sym.withDegrees(i) pairs.into([])...
ds2.assertValidity()
ds2
class Subsymbol extends Delaney
constructor: (@base, @idcs, @seed) ->
# -- the following eight methods implement the common interface for
# all Delaney symbol classes.
memo @,'indexSet', -> new IntSet().plusAll seq @idcs
memo @,'elementSet', ->
elms = @base.traversal(@idcs, [@seed])?.map(([E, k]) -> E)?.uniq()
new HashSet().plusAll elms
s: (i) ->
if @hasIndex(i)
(D) => @base.s(i)(D) if @hasElement(D)
else
(D) ->
m: (i, j) ->
if @hasIndex(i) and not j? or @hasIndex(j)
(D) => @base.m(i,j)(D) if @hasElement(D)
else
(D) ->
# --------------------------------------------------------------------
# Exporting.
# --------------------------------------------------------------------
exports ?= this.pazy ?= {}
exports.Delaney = Delaney
exports.DSymbol = DSymbol
exports.Subsymbol = Subsymbol
# --------------------------------------------------------------------
# Test code --
# --------------------------------------------------------------------
test = ->
{ show } = require 'testing'
puts = console.log
ds = new DSymbol(2, [1..3]).
withGluings(0)([1], [2], [3]).
withGluings(1)([1,2], [3]).
withGluings(2)([1], [2,3]).
withDegrees(0)([1,8], [3,4]).
withDegrees(1)([1,3])
show -> ds
show -> ds.size()
show -> ds.dimension()
show -> ds.elements()
show -> ds.indices()
show -> ds.s(1)(1)
show -> ds.m(0,1)(2)
puts ""
show -> ds.withoutDegrees(0)(1).withoutGluings(1)(1).withoutElements(3)
puts ""
show -> ds = DSymbol.fromString "<1.1:3:1 2 3,2 3,1 3:8 4,3>"
show -> ds.dual()
puts ""
puts "The following should throw an error:"
show -> DSymbol.fromString "<1.1:3:1 2 3,2 3,1 3:7 4,3>"
puts ""
show -> ds.withoutDegrees(1)(1).collapsed 0, 3
puts ""
show -> ds.traversal()
show -> ds.protocol(ds.indices(), ds.traversal(ds.indices(), [1]))[0].into []
puts ""
show -> ds.invariant()[0].into []
show -> ds.invariant()[1].toSeq()
show -> ds.canonical()
puts ""
p = null
show -> p = ds.typePartition()
show -> p.find 1
puts ""
show -> ds.minimal()
show -> DSymbol.fromString('<1.1:8:2 4 6 8,8 3 5 7,6 5 8 7:4,4>').minimal()
puts ""
show -> DSymbol.fromString('<1.1:4:2 4,4 3,4 3:2,5 5>').isSpherical2D()
show (-> DSymbol.fromString('<1.1:6:2 4 6,6 3 5,1 2 3 4 5 6:3,4 6 10>')
.orbifoldSymbol2D()), false
show -> DSymbol.fromString('<1.1:3 3:1 2 3,1 2 3,1 3,2 3:3 3 4,4 4,3>')
.isLocallyEuclidean3D()
if module? and not module.parent
args = seq.map(process.argv[2..], parseInt)?.into []
test args...
# -- End of test code --
|
[
{
"context": "##\n#\n# author: Nicholas McCready\n# directive to invoke google-maps-tools keydragzo",
"end": 32,
"score": 0.9998731017112732,
"start": 15,
"tag": "NAME",
"value": "Nicholas McCready"
}
] | public/bower_components/angular-google-maps/src/coffee/directives/api/drag-zoom.coffee | arslannaseem/notasoft | 1 | ##
#
# author: Nicholas McCready
# directive to invoke google-maps-tools keydragzoom
#
# details: http://google-maps-utility-library-v3.googlecode.com/svn/tags/keydragzoom/2.0.9/docs/examples.html
# options: can set styles and keys
#
##
angular.module('uiGmapgoogle-maps.directives.api').service 'uiGmapDragZoom', [
'uiGmapCtrlHandle', 'uiGmapPropertyAction', (CtrlHandle, PropertyAction) ->
restrict: 'EMA'
transclude: true
template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>'
require: '^' + 'uiGmapGoogleMap'
scope:
keyboardkey: '='
options: '='
spec: '=' #callback hack for testing, I can't seem to intercept DragZoom creation on map::enableKeyDragZoom
controller: ['$scope', '$element', ($scope, $element) ->
$scope.ctrlType = 'uiGmapDragZoom'
_.extend @, CtrlHandle.handle($scope, $element)
]
link: (scope, element, attrs, ctrl) ->
CtrlHandle.mapPromise(scope, ctrl).then (map) ->
enableKeyDragZoom = (opts) ->
map.enableKeyDragZoom(opts)
scope.spec.enableKeyDragZoom(opts) if scope.spec
setKeyAction = new PropertyAction (key, newVal) ->
if newVal
enableKeyDragZoom key: newVal
else
enableKeyDragZoom()
setOptionsAction = new PropertyAction (key, newVal) ->
enableKeyDragZoom newVal if newVal
scope.$watch 'keyboardkey', setKeyAction.sic
setKeyAction.sic scope.keyboardkey
scope.$watch 'options', setOptionsAction.sic
setOptionsAction.sic scope.options
]
| 94147 | ##
#
# author: <NAME>
# directive to invoke google-maps-tools keydragzoom
#
# details: http://google-maps-utility-library-v3.googlecode.com/svn/tags/keydragzoom/2.0.9/docs/examples.html
# options: can set styles and keys
#
##
angular.module('uiGmapgoogle-maps.directives.api').service 'uiGmapDragZoom', [
'uiGmapCtrlHandle', 'uiGmapPropertyAction', (CtrlHandle, PropertyAction) ->
restrict: 'EMA'
transclude: true
template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>'
require: '^' + 'uiGmapGoogleMap'
scope:
keyboardkey: '='
options: '='
spec: '=' #callback hack for testing, I can't seem to intercept DragZoom creation on map::enableKeyDragZoom
controller: ['$scope', '$element', ($scope, $element) ->
$scope.ctrlType = 'uiGmapDragZoom'
_.extend @, CtrlHandle.handle($scope, $element)
]
link: (scope, element, attrs, ctrl) ->
CtrlHandle.mapPromise(scope, ctrl).then (map) ->
enableKeyDragZoom = (opts) ->
map.enableKeyDragZoom(opts)
scope.spec.enableKeyDragZoom(opts) if scope.spec
setKeyAction = new PropertyAction (key, newVal) ->
if newVal
enableKeyDragZoom key: newVal
else
enableKeyDragZoom()
setOptionsAction = new PropertyAction (key, newVal) ->
enableKeyDragZoom newVal if newVal
scope.$watch 'keyboardkey', setKeyAction.sic
setKeyAction.sic scope.keyboardkey
scope.$watch 'options', setOptionsAction.sic
setOptionsAction.sic scope.options
]
| true | ##
#
# author: PI:NAME:<NAME>END_PI
# directive to invoke google-maps-tools keydragzoom
#
# details: http://google-maps-utility-library-v3.googlecode.com/svn/tags/keydragzoom/2.0.9/docs/examples.html
# options: can set styles and keys
#
##
angular.module('uiGmapgoogle-maps.directives.api').service 'uiGmapDragZoom', [
'uiGmapCtrlHandle', 'uiGmapPropertyAction', (CtrlHandle, PropertyAction) ->
restrict: 'EMA'
transclude: true
template: '<div class="angular-google-map-dragzoom" ng-transclude style="display: none"></div>'
require: '^' + 'uiGmapGoogleMap'
scope:
keyboardkey: '='
options: '='
spec: '=' #callback hack for testing, I can't seem to intercept DragZoom creation on map::enableKeyDragZoom
controller: ['$scope', '$element', ($scope, $element) ->
$scope.ctrlType = 'uiGmapDragZoom'
_.extend @, CtrlHandle.handle($scope, $element)
]
link: (scope, element, attrs, ctrl) ->
CtrlHandle.mapPromise(scope, ctrl).then (map) ->
enableKeyDragZoom = (opts) ->
map.enableKeyDragZoom(opts)
scope.spec.enableKeyDragZoom(opts) if scope.spec
setKeyAction = new PropertyAction (key, newVal) ->
if newVal
enableKeyDragZoom key: newVal
else
enableKeyDragZoom()
setOptionsAction = new PropertyAction (key, newVal) ->
enableKeyDragZoom newVal if newVal
scope.$watch 'keyboardkey', setKeyAction.sic
setKeyAction.sic scope.keyboardkey
scope.$watch 'options', setOptionsAction.sic
setOptionsAction.sic scope.options
]
|
[
{
"context": "ee here for more details:\n#\n# https://github.com/openpgpjs/openpgpjs/wiki/Cure53-security-audit\n#\n\n{do_messa",
"end": 65,
"score": 0.9871965050697327,
"start": 56,
"tag": "USERNAME",
"value": "openpgpjs"
},
{
"context": "(Darwin)\nComment: GPGTools - https://gpgto... | test/files/openpgp_js_cure53_audit.iced | samkenxstream/kbpgp | 464 |
#
# See here for more details:
#
# https://github.com/openpgpjs/openpgpjs/wiki/Cure53-security-audit
#
{do_message,Message} = require '../../lib/openpgp/processor'
{PgpKeyRing} = require '../../lib/keyring'
{KeyManager} = require '../../'
{decode} = require('pgp-utils').armor
testing_unixtime = Math.floor(new Date(2014, 4, 10)/1000)
#===============================================================================
key = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
mQENBFM9bqwBCADPDhFyVqlMDoIP34Tk1xEqcu3EpM36Q2ls4Rv0wlwsdCcmhh3x
OIjlP+jzR6cnQm3f+b46bXGgrl3Gis8CjceHmmcp4NAyRxsMYfSWNl6w46vKbjFZ
UbpmXJY4L80EJ3kUnnIf2U8DdpHGy+sXPeBoNT/S3zuFmYw0EEYl3EkiRwqrL2PA
iTEH2zqJKctFuja4NE01GLXU9XPl9EiAzmPQOgjRbJk1cz8eReTjDwnafLYamZfr
5xzUeAKyASA/784wbocmteRyu3ph7rJMFpv3/VBy/PgaCB4JmdtdqimofPFv+bPo
S5LQw4z/9FETFyxF7mcffd+TTodsYojYxvHxABEBAAG0Hk1heCAzMDkgPHRoZW1h
eCszMDlAZ21haWwuY29tPokBPQQTAQoAJwUCUz1urAIbAwUJEswDAAULCQgHAwUV
CgkICwUWAgMBAAIeAQIXgAAKCRDXB+6Ch7YlFCvnB/94453NRlRMfcXGN/goIzGs
rsP6YNDGLErftxPCUd3ve4qUIw+2vniokIcAWYQLgUlGmasp5B64h+6woMZBfP9G
Klz0R7LRu0bBnlRvq2DkRItPIZBF79bE6HUfsRfJloyshexPYiOWkmSGKbeBT+R2
5hCzab8KLpAsM1tAaOqNX02NclMtKlzHt2XWoIpKbB/n+JXaj6+S3m6l+SFAYQz1
jn5bV3xbNPLHMgz+5spKuQBrS2tsZQYYzFQhL9vSnw00uvmOApWahizx/eZc7sxb
aFcRwknx7zkUAMnEXWdkKmCCRljMSVuaqZhSb8cEMPl7mtqxhKG3svYbVBJXNHq/
uQENBFM9bqwBCACzl2QZcxs0/Hf21Y/N4G7IucUQTBuxrOXvQyL0ra1OAEsgoVox
YWS5j0HKGmEH7lVxDz+8j3HdW0B+0n/6tErDfIPUAfd/fiJ5WHiFbD1b5La98ahk
sDSiyxPnoT1mlpE2+9/XHtid0JKluWlzp9Nsr6sXXkUIp2CMUKMPAbwpgNvveoaQ
5l8+4j5eqgzU2TOuLJOhjU9PpNx05EtMz2ZUCSYokcEd9jIC5LuqbXnptQ8COsdt
r+BARE++TO8FT6JtvJAF+ya/d6NABxLREIC1Xc/bC/clCufG1gu6rxizAvbFn0RI
XpuhYyYNycOHCN0W+dTkSDQZdTAVVQaNhppvABEBAAGJASUEGAEKAA8FAlM9bqwC
GwwFCRLMAwAACgkQ1wfugoe2JRQHGgf+L2KfPWleZ2YF19t5fvkr/WoTf8vHeGSt
rhcXuOEZ6958KDDc9YRL9FiRJif+vzjy/KBobb2f/7dJYoLWV/3wip8YOhwMUMAQ
XFfDUFVrfiK2yYZ/gOHROhl5CdJ4qihT5AH5yyqMNpiTlGxzPkVnVaO7oufX330w
9g82evapQ+VidksCWG6TSQVYUh9QnBIwlO+Nx2Fn4mnyXb4eeRFF5OfFfFPhB7Nm
iSFt2y3redHUHU/rqiss2b8+99d0Qjur6Mpn9aofzl4M81Ehcofxo3++B8QbxKag
EbI/F53ALAWVs1gB85WnO6CBxHHkzZ89O7QwB0ue6KdHkGF0O2F7RA==
=pwsn
-----END PGP PUBLIC KEY BLOCK-----
"""
ring = new PgpKeyRing()
#================================================================================
exports.init = (T,cb) ->
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : key, opts }, defer err, km
T.no_error err
ring = new PgpKeyRing()
ring.add_key_manager km
cb()
#===============================================================================
exports.op_01_019 = (T,cb) ->
lines = [
'-----BEGIN PGP SIGNED MESSAGE\u2010\u2010\u2010\u2010\u2010\nHash:SHA1\n\nIs this properly-----',
'',
'sign this',
'-----BEGIN PGP SIGNATURE-----',
'Version: GnuPG v2.0.22 (GNU/Linux)',
'',
'iJwEAQECAAYFAlMrPj0ACgkQ4IT3RGwgLJfYkQQAgHMQieazCVdfGAfzQM69Egm5',
'HhcQszODD898wpoGCHgiNdNo1+5nujQAtXnkcxM+Vf7onfbTvUqut/siyO3fzqhK',
'LQ9DiQUwJMBE8nOwVR7Mpc4kLNngMTNaHAjZaVaDpTCrklPY+TPHIZnu0B6Ur+6t',
'skTzzVXIxMYw8ihbHfk=',
'=e/eA',
'-----END PGP SIGNATURE-----' ]
msg = lines.join '\n'
await do_message { keyfetch : ring, armored : msg, now : testing_unixtime }, defer err, outmsg
T.assert err?, "Got an error on malformed header"
cb()
#===============================================================================
exports.op_01_009 = (T,cb) ->
get_msg = (headers) ->
body = """
sign this
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
iQEcBAEBCgAGBQJTQprhAAoJENcH7oKHtiUUs6EH+wf2TM9dhVnwwp5PgOsmCO+W
91pudWHCiSWzPdk32ck8N2bdTviuav2nZKYb6TNu8JRwsDesJHxMIs9pBop92k7B
Mx22O6DMQ8irnBJBvQqP76hwJ7hkcaiy1QbYZQZZUtDDPWljV2YTtLhCc4KRZFGz
OSUWScDGUtkHvJCUIqWNioZbnHv1y2LpeonbS1pWy4M5rSTwhhPnJkkzpJa3tRgN
s3fYMkuJh5u2lQlvrr5EO1E7Nj4ab3PYh0DFZ8jjPteag+cj3WZ9iB4LtVPnV2Bq
7r0rnEyv0zndZXoeqs9a2bJyG9DfAWKACcWpHaHCxqtNWBESHtOThgUQwUiP8dE=
=jYzT
-----END PGP SIGNATURE-----
"""
return [ '-----BEGIN PGP SIGNED MESSAGE-----'].concat(headers).concat(body).join("\n")
#----------
now = testing_unixtime
x = get_msg "Hash: SHA512"
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.no_error err, "Simple clearsign verification worked"
T.assert outmsg[0].to_literal()?.get_data_signer()?, "was a signed literal"
T.waypoint "success 1"
#----------
x = get_msg("Hash: SHA256")
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a hash mismatch error"
T.assert (err.message.indexOf("missing ASN header for SHA256") >= 0), "didn't try to run SHA256"
T.waypoint "fail 1"
#----------
x = get_msg()
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a hash mismatch error"
T.assert (err.message.indexOf("missing ASN header for MD5") >= 0), "didn't try to run MD5"
T.waypoint "fail 2"
#----------
x = get_msg("Hash: LAV750")
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.indexOf("Unknown hash algorithm: LAV750") >= 0), "didn't find LAV750"
T.waypoint "fail 3"
#----------
# For now, don't support multiple hash values
x = get_msg("Hash: SHA1, SHA512")
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.indexOf("Unknown hash algorithm: SHA1, SHA512") >= 0), "didn't find SHA1,SHA512"
T.waypoint "fail 4"
#----------
# For now, don't support multiple hash values, just use the first
x = get_msg(["Hash: SHA1", "Hash: SHA512"])
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.no_error err, "last hash wins"
T.waypoint "success 2"
#----------
# For now, don't support multiple hash values, just use the first
x = get_msg(["Hash: SHA512", "Comment: No comments allowed!"])
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "no comments allowed"
T.assert err.message.indexOf("Unallowed header: comment") >= 0, "found an header not allowed"
T.waypoint "fail 5"
#----------
# Wrong guy in last is a problem
x = get_msg(["Hash: SHA512", "Hash: SHA1"])
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.indexOf("missing ASN header for SHA1") >= 0), "multiple order matters"
T.waypoint "fail 6"
#----------
x = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
\u000b\u00a0
sign this
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
iQEcBAEBCgAGBQJTQprhAAoJENcH7oKHtiUUs6EH+wf2TM9dhVnwwp5PgOsmCO+W
91pudWHCiSWzPdk32ck8N2bdTviuav2nZKYb6TNu8JRwsDesJHxMIs9pBop92k7B
Mx22O6DMQ8irnBJBvQqP76hwJ7hkcaiy1QbYZQZZUtDDPWljV2YTtLhCc4KRZFGz
OSUWScDGUtkHvJCUIqWNioZbnHv1y2LpeonbS1pWy4M5rSTwhhPnJkkzpJa3tRgN
s3fYMkuJh5u2lQlvrr5EO1E7Nj4ab3PYh0DFZ8jjPteag+cj3WZ9iB4LtVPnV2Bq
7r0rnEyv0zndZXoeqs9a2bJyG9DfAWKACcWpHaHCxqtNWBESHtOThgUQwUiP8dE=
=jYzT
-----END PGP SIGNATURE-----
"""
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert not err?, "control characters should be allowed in armor if the message is clearsigned"
T.waypoint "success 3"
#----------
for h in [ 'Hash:SHA512', '<script>: SHA256', 'Hash SHA512' ]
x = get_msg h
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.match /Bad line in clearsign header|Unallowed header/), "bad line"
T.waypoint "fail #{h}"
#----------
cb()
#===============================================================================
| 24635 |
#
# See here for more details:
#
# https://github.com/openpgpjs/openpgpjs/wiki/Cure53-security-audit
#
{do_message,Message} = require '../../lib/openpgp/processor'
{PgpKeyRing} = require '../../lib/keyring'
{KeyManager} = require '../../'
{decode} = require('pgp-utils').armor
testing_unixtime = Math.floor(new Date(2014, 4, 10)/1000)
#===============================================================================
key = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
-----END PGP PUBLIC KEY BLOCK-----
"""
ring = new PgpKeyRing()
#================================================================================
exports.init = (T,cb) ->
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : key, opts }, defer err, km
T.no_error err
ring = new PgpKeyRing()
ring.add_key_manager km
cb()
#===============================================================================
exports.op_01_019 = (T,cb) ->
lines = [
'-----BEGIN PGP SIGNED MESSAGE\u2010\u2010\u2010\u2010\u2010\nHash:SHA1\n\nIs this properly-----',
'',
'sign this',
'-----BEGIN PGP SIGNATURE-----',
'Version: GnuPG v2.0.22 (GNU/Linux)',
'',
'iJwEAQECAAYFAlMrPj0ACgkQ4IT3RGwgLJfYkQQAgHMQieazCVdfGAfzQM69Egm5',
'HhcQszODD898wpoGCHgiNdNo1+5nujQAtXnkcxM+Vf7onfbTvUqut/siyO3fzqhK',
'LQ9DiQUwJMBE8nOwVR7Mpc4kLNngMTNaHAjZaVaDpTCrklPY+TPHIZnu0B6Ur+6t',
'skTzzVXIxMYw8ihbHfk=',
'=e/eA',
'-----END PGP SIGNATURE-----' ]
msg = lines.join '\n'
await do_message { keyfetch : ring, armored : msg, now : testing_unixtime }, defer err, outmsg
T.assert err?, "Got an error on malformed header"
cb()
#===============================================================================
exports.op_01_009 = (T,cb) ->
get_msg = (headers) ->
body = """
sign this
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
7r0rnEyv0zndZXoeqs9a2bJyG9DfAWKACcWpHaHCxqtNWBESHtOThgUQwUiP8dE=
=jYzT
-----END PGP SIGNATURE-----
"""
return [ '-----BEGIN PGP SIGNED MESSAGE-----'].concat(headers).concat(body).join("\n")
#----------
now = testing_unixtime
x = get_msg "Hash: SHA512"
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.no_error err, "Simple clearsign verification worked"
T.assert outmsg[0].to_literal()?.get_data_signer()?, "was a signed literal"
T.waypoint "success 1"
#----------
x = get_msg("Hash: SHA256")
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a hash mismatch error"
T.assert (err.message.indexOf("missing ASN header for SHA256") >= 0), "didn't try to run SHA256"
T.waypoint "fail 1"
#----------
x = get_msg()
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a hash mismatch error"
T.assert (err.message.indexOf("missing ASN header for MD5") >= 0), "didn't try to run MD5"
T.waypoint "fail 2"
#----------
x = get_msg("Hash: LAV750")
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.indexOf("Unknown hash algorithm: LAV750") >= 0), "didn't find LAV750"
T.waypoint "fail 3"
#----------
# For now, don't support multiple hash values
x = get_msg("Hash: SHA1, SHA512")
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.indexOf("Unknown hash algorithm: SHA1, SHA512") >= 0), "didn't find SHA1,SHA512"
T.waypoint "fail 4"
#----------
# For now, don't support multiple hash values, just use the first
x = get_msg(["Hash: SHA1", "Hash: SHA512"])
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.no_error err, "last hash wins"
T.waypoint "success 2"
#----------
# For now, don't support multiple hash values, just use the first
x = get_msg(["Hash: SHA512", "Comment: No comments allowed!"])
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "no comments allowed"
T.assert err.message.indexOf("Unallowed header: comment") >= 0, "found an header not allowed"
T.waypoint "fail 5"
#----------
# Wrong guy in last is a problem
x = get_msg(["Hash: SHA512", "Hash: SHA1"])
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.indexOf("missing ASN header for SHA1") >= 0), "multiple order matters"
T.waypoint "fail 6"
#----------
x = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
\u000b\u00a0
sign this
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
iQEcBAEBCgAGBQJTQprhAAoJENcH7oKHtiUUs6EH+wf2TM9dhVnwwp5PgOsmCO+W
91pudWHCiSWzPdk32<KEY>
-----END PGP SIGNATURE-----
"""
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert not err?, "control characters should be allowed in armor if the message is clearsigned"
T.waypoint "success 3"
#----------
for h in [ 'Hash:SHA512', '<script>: SHA256', 'Hash SHA512' ]
x = get_msg h
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.match /Bad line in clearsign header|Unallowed header/), "bad line"
T.waypoint "fail #{h}"
#----------
cb()
#===============================================================================
| true |
#
# See here for more details:
#
# https://github.com/openpgpjs/openpgpjs/wiki/Cure53-security-audit
#
{do_message,Message} = require '../../lib/openpgp/processor'
{PgpKeyRing} = require '../../lib/keyring'
{KeyManager} = require '../../'
{decode} = require('pgp-utils').armor
testing_unixtime = Math.floor(new Date(2014, 4, 10)/1000)
#===============================================================================
key = """
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----
"""
ring = new PgpKeyRing()
#================================================================================
exports.init = (T,cb) ->
opts = now : testing_unixtime
await KeyManager.import_from_armored_pgp { raw : key, opts }, defer err, km
T.no_error err
ring = new PgpKeyRing()
ring.add_key_manager km
cb()
#===============================================================================
exports.op_01_019 = (T,cb) ->
lines = [
'-----BEGIN PGP SIGNED MESSAGE\u2010\u2010\u2010\u2010\u2010\nHash:SHA1\n\nIs this properly-----',
'',
'sign this',
'-----BEGIN PGP SIGNATURE-----',
'Version: GnuPG v2.0.22 (GNU/Linux)',
'',
'iJwEAQECAAYFAlMrPj0ACgkQ4IT3RGwgLJfYkQQAgHMQieazCVdfGAfzQM69Egm5',
'HhcQszODD898wpoGCHgiNdNo1+5nujQAtXnkcxM+Vf7onfbTvUqut/siyO3fzqhK',
'LQ9DiQUwJMBE8nOwVR7Mpc4kLNngMTNaHAjZaVaDpTCrklPY+TPHIZnu0B6Ur+6t',
'skTzzVXIxMYw8ihbHfk=',
'=e/eA',
'-----END PGP SIGNATURE-----' ]
msg = lines.join '\n'
await do_message { keyfetch : ring, armored : msg, now : testing_unixtime }, defer err, outmsg
T.assert err?, "Got an error on malformed header"
cb()
#===============================================================================
exports.op_01_009 = (T,cb) ->
get_msg = (headers) ->
body = """
sign this
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
7r0rnEyv0zndZXoeqs9a2bJyG9DfAWKACcWpHaHCxqtNWBESHtOThgUQwUiP8dE=
=jYzT
-----END PGP SIGNATURE-----
"""
return [ '-----BEGIN PGP SIGNED MESSAGE-----'].concat(headers).concat(body).join("\n")
#----------
now = testing_unixtime
x = get_msg "Hash: SHA512"
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.no_error err, "Simple clearsign verification worked"
T.assert outmsg[0].to_literal()?.get_data_signer()?, "was a signed literal"
T.waypoint "success 1"
#----------
x = get_msg("Hash: SHA256")
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a hash mismatch error"
T.assert (err.message.indexOf("missing ASN header for SHA256") >= 0), "didn't try to run SHA256"
T.waypoint "fail 1"
#----------
x = get_msg()
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a hash mismatch error"
T.assert (err.message.indexOf("missing ASN header for MD5") >= 0), "didn't try to run MD5"
T.waypoint "fail 2"
#----------
x = get_msg("Hash: LAV750")
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.indexOf("Unknown hash algorithm: LAV750") >= 0), "didn't find LAV750"
T.waypoint "fail 3"
#----------
# For now, don't support multiple hash values
x = get_msg("Hash: SHA1, SHA512")
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.indexOf("Unknown hash algorithm: SHA1, SHA512") >= 0), "didn't find SHA1,SHA512"
T.waypoint "fail 4"
#----------
# For now, don't support multiple hash values, just use the first
x = get_msg(["Hash: SHA1", "Hash: SHA512"])
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.no_error err, "last hash wins"
T.waypoint "success 2"
#----------
# For now, don't support multiple hash values, just use the first
x = get_msg(["Hash: SHA512", "Comment: No comments allowed!"])
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "no comments allowed"
T.assert err.message.indexOf("Unallowed header: comment") >= 0, "found an header not allowed"
T.waypoint "fail 5"
#----------
# Wrong guy in last is a problem
x = get_msg(["Hash: SHA512", "Hash: SHA1"])
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.indexOf("missing ASN header for SHA1") >= 0), "multiple order matters"
T.waypoint "fail 6"
#----------
x = """
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512
\u000b\u00a0
sign this
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
iQEcBAEBCgAGBQJTQprhAAoJENcH7oKHtiUUs6EH+wf2TM9dhVnwwp5PgOsmCO+W
91pudWHCiSWzPdk32PI:KEY:<KEY>END_PI
-----END PGP SIGNATURE-----
"""
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert not err?, "control characters should be allowed in armor if the message is clearsigned"
T.waypoint "success 3"
#----------
for h in [ 'Hash:SHA512', '<script>: SHA256', 'Hash SHA512' ]
x = get_msg h
await do_message { keyfetch : ring, armored : x, now }, defer err, outmsg
T.assert err?, "Got a failure"
T.assert (err.message.match /Bad line in clearsign header|Unallowed header/), "bad line"
T.waypoint "fail #{h}"
#----------
cb()
#===============================================================================
|
[
{
"context": "(req, res) ->\n res.json {\n access_token: 'super_save_token',\n id: 1,\n first_name: 'Just',\n la",
"end": 775,
"score": 0.7667775750160217,
"start": 759,
"tag": "PASSWORD",
"value": "super_save_token"
},
{
"context": "uper_save_token',\n id... | frontend/config/server.coffee | degzcs/rails-angular-lineman-example | 0 | ### Define custom server-side HTTP routes for lineman's development server
# These might be as simple as stubbing a little JSON to
# facilitate development of code that interacts with an HTTP service
# (presumably, mirroring one that will be reachable in a live environment).
#
# It's important to remember that any custom endpoints defined here
# will only be available in development, as lineman only builds
# static assets, it can't run server-side code.
#
# This file can be very useful for rapid prototyping or even organically
# defining a spec based on the needs of the client code that emerge.
#
###
module.exports = drawRoutes: (app) ->
#
# Auth
#
app.post '/api/v1/auth/login', (req, res) ->
res.json {
access_token: 'super_save_token',
id: 1,
first_name: 'Just',
last_name: 'Incase',
email: 'just.incase@fake.com',
}
app.post '/logout', (req, res) ->
res.json message: 'logging out!'
#
# Inventory
#
# GET
# it is a possible route for the inventory (it is inventory or inventories ?)
app.get '/api/v1/inventory', (req, res) ->
list = []
i = 0
while i < 10
inventory_item =
date: ''
hour: ''
quien: '' # NOTE: is this the person that created a inventory?
cuantos: '' # ?
law: ''
value: ''
inventory_item.selected = false
inventory_item.date = '10/20/2014' + i
inventory_item.hour = '10:20' + i
inventory_item.quien = 'Carlos R' + i # TODO: change name
inventory_item.cuantos = i # TODO: change name
inventory_item.law = '100' + i
inventory_item.value = '100' + i
list.push inventory_item
i++
console.log 'inventory list from the fake server ...'
res.json {
list: list,
access_token: 'super_save_token'
}
#
# Transporter
#
# POST
# Create a transoporter
app.post '/api/v1/transporter', (req, res) ->
console.log('trasporter created... yay!!!')
console.log('parameters: >> ' + req.params)
res.json {
name: 'Pepito',
document_number: '123456789',
phone: '+57300214587',
address: 'calle falsa # 12 -3',
email: 'pepito@fake.com',
access_token: 'super_save_token'
}
# I know the following declaration may not be a good practice... but it's just temporal
providerList = [
{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: 'Diego Caicedo',
id: '9800000-1',
mineral: 'Oro',
id_rucom: 'RUCOM-201502204885',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226977293',
prov_type: 2,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'diego.caicedo@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-wx3BmJUhhpE/AAAAAAAAAAI/AAAAAAAAACM/R6R-aAQB62E/photo.jpg',
name: 'Andres Maya',
id: '9800000-2',
mineral: 'Oro',
id_rucom: 'RUCOM-201503014886',
rucom_status: 'Certificado',
last_transaction_date: '1427226977300',
prov_type: 3,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'andres.maya@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-MPs16CJ6ZBI/AAAAAAAAAAI/AAAAAAAAAfw/qZNidz7KVvo/photo.jpg',
name: 'Carlos Mejía',
id: '9800000-3',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014887',
rucom_status: 'Certificado',
last_transaction_date: '1427226978293',
prov_type: 4,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'carlos.mejia@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh3.googleusercontent.com/-7qT3MgVr0rk/AAAAAAAAAAI/AAAAAAAAAJE/i1Yc_rFyVz8/photo.jpg',
name: 'Camilo Pedraza',
id: '9800000-4',
mineral: 'Oro',
id_rucom: 'RUCOM-201303014890',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226977493',
prov_type: 5,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'camilo.pedraza@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh3.googleusercontent.com/-xUqWqzQQaZc/AAAAAAAAAAI/AAAAAAAAA88/M5EhGqXSItk/photo.jpg',
name: 'Jesus Muñoz',
id: '9800000-5',
mineral: 'Oro',
id_rucom: 'RUCOM-201503014892',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226977600',
prov_type: 6,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'jesus.munoz@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh6.googleusercontent.com/-KAhFBi4grKU/AAAAAAAAAAI/AAAAAAAABLM/hnWGNvV7D2k/photo.jpg',
name: 'Esteban Cerón',
id: '9800000-6',
mineral: 'Oro',
id_rucom: 'RUCOM-201203014810',
rucom_status: 'Certificado',
last_transaction_date: '1427226977550',
prov_type: 7,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'esteban.ceron@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://plus.google.com/u/0/_/focus/photos/public/AIbEiAIAAABECOnz4JakhaOK_gEiC3ZjYXJkX3Bob3RvKihiMWQyMWNkZmRiYzIzM2EzODUyZDQyMjU3ZWVlZTU4MzU0MWE3ZjY3MAFLUhAwq57N0mPOSXuYPdiOmJZ9KQ?sz=48',
name: 'Juan Cerón',
id: '9800000-7',
mineral: 'Oro',
id_rucom: 'RUCOM-201303014800',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226978293',
prov_type: 1,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'juan.ceron@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh3.googleusercontent.com/-q9i8c2WHh9I/AAAAAAAAAAI/AAAAAAAAAK0/p9wFW0PJ_oo/photo.jpg',
name: 'Diego Gómez',
id: '9800000-8',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014802',
rucom_status: 'Certificado',
last_transaction_date: '1427226977893',
prov_type: 2,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'diego.gomez@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-kzZKDrB6wb4/AAAAAAAAAAI/AAAAAAAAAzU/CnnUA5Ygbjs/photo.jpg',
name: 'Javier Suarez',
id: '9800000-9',
mineral: 'Oro',
id_rucom: 'RUCOM-201303014201',
rucom_status: 'Certificado',
last_transaction_date: '1427226979293',
prov_type: 3,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'javier.suarez@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh5.googleusercontent.com/-K1ZinAJG6D0/AAAAAAAAAAI/AAAAAAAAAGk/vFy0NwAptgI/photo.jpg',
name: 'Luis Rojas',
id: '9800001-0',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014833',
rucom_status: 'Certificado',
last_transaction_date: '1427226977777',
prov_type: 4,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'luis.rojas@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-9pJ7LbpZ_nA/AAAAAAAAAAI/AAAAAAAAFuc/VxoI6yvIzlE/photo.jpg',
name: 'Leandro Ordóñez',
id: '1023939222',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014943',
rucom_status: 'Certificado',
last_transaction_date: '1427227113631',
prov_type: 5,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'leandro.ordonez.ante@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: 'Conrado Franco',
id: '9800001-2',
mineral: 'Oro',
id_rucom: 'RUCOM-201503204884',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427227123631',
prov_type: 6,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'conrado.franco@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: 'José Valdovino',
id: '9800001-3',
mineral: 'Oro',
id_rucom: 'RUCOM-201503204883',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427227133631',
prov_type: 7,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'jose.valdovino@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: 'Sandis Martinez',
id: '9800001-4',
mineral: 'Oro',
id_rucom: 'RUCOM-201503194882',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427227113731',
prov_type: 1,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'sandis.martinez@gmail.com',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
}
];
#
# provider
#
# GET
# it is a possible route for the provider
app.get '/api/v1/provider', (req, res) ->
console.log 'provider list from the fake server ...'
res.json {
list: providerList,
access_token: 'super_save_token'
}
# GET
# endpoint for retrieving providers by ID
app.get '/api/v1/provider/:providerId', (req, res) ->
console.log 'retrieving provider ' + req.params.providerId + ' from the fake server ...'
provider = {}
for p of providerList
if providerList[p].id == req.params.providerId
provider = providerList[p]
break
res.json {
provider: provider,
access_token: 'super_save_token'
}
| 219713 | ### Define custom server-side HTTP routes for lineman's development server
# These might be as simple as stubbing a little JSON to
# facilitate development of code that interacts with an HTTP service
# (presumably, mirroring one that will be reachable in a live environment).
#
# It's important to remember that any custom endpoints defined here
# will only be available in development, as lineman only builds
# static assets, it can't run server-side code.
#
# This file can be very useful for rapid prototyping or even organically
# defining a spec based on the needs of the client code that emerge.
#
###
module.exports = drawRoutes: (app) ->
#
# Auth
#
app.post '/api/v1/auth/login', (req, res) ->
res.json {
access_token: '<PASSWORD>',
id: 1,
first_name: '<NAME>',
last_name: '<NAME>',
email: '<EMAIL>',
}
app.post '/logout', (req, res) ->
res.json message: 'logging out!'
#
# Inventory
#
# GET
# it is a possible route for the inventory (it is inventory or inventories ?)
app.get '/api/v1/inventory', (req, res) ->
list = []
i = 0
while i < 10
inventory_item =
date: ''
hour: ''
quien: '' # NOTE: is this the person that created a inventory?
cuantos: '' # ?
law: ''
value: ''
inventory_item.selected = false
inventory_item.date = '10/20/2014' + i
inventory_item.hour = '10:20' + i
inventory_item.quien = '<NAME>' + i # TODO: change name
inventory_item.cuantos = i # TODO: change name
inventory_item.law = '100' + i
inventory_item.value = '100' + i
list.push inventory_item
i++
console.log 'inventory list from the fake server ...'
res.json {
list: list,
access_token: '<PASSWORD>'
}
#
# Transporter
#
# POST
# Create a transoporter
app.post '/api/v1/transporter', (req, res) ->
console.log('trasporter created... yay!!!')
console.log('parameters: >> ' + req.params)
res.json {
name: '<NAME>',
document_number: '123456789',
phone: '+57300214587',
address: 'calle falsa # 12 -3',
email: '<EMAIL>',
access_token: '<PASSWORD>'
}
# I know the following declaration may not be a good practice... but it's just temporal
providerList = [
{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: '<NAME>',
id: '9800000-1',
mineral: 'Oro',
id_rucom: 'RUCOM-201502204885',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226977293',
prov_type: 2,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-wx3BmJUhhpE/AAAAAAAAAAI/AAAAAAAAACM/R6R-aAQB62E/photo.jpg',
name: '<NAME>',
id: '9800000-2',
mineral: 'Oro',
id_rucom: 'RUCOM-201503014886',
rucom_status: 'Certificado',
last_transaction_date: '1427226977300',
prov_type: 3,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-MPs16CJ6ZBI/AAAAAAAAAAI/AAAAAAAAAfw/qZNidz7KVvo/photo.jpg',
name: '<NAME>',
id: '9800000-3',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014887',
rucom_status: 'Certificado',
last_transaction_date: '1427226978293',
prov_type: 4,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh3.googleusercontent.com/-7qT3MgVr0rk/AAAAAAAAAAI/AAAAAAAAAJE/i1Yc_rFyVz8/photo.jpg',
name: '<NAME>',
id: '9800000-4',
mineral: 'Oro',
id_rucom: 'RUCOM-201303014890',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226977493',
prov_type: 5,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh3.googleusercontent.com/-xUqWqzQQaZc/AAAAAAAAAAI/AAAAAAAAA88/M5EhGqXSItk/photo.jpg',
name: '<NAME>',
id: '9800000-5',
mineral: 'Oro',
id_rucom: 'RUCOM-201503014892',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226977600',
prov_type: 6,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh6.googleusercontent.com/-KAhFBi4grKU/AAAAAAAAAAI/AAAAAAAABLM/hnWGNvV7D2k/photo.jpg',
name: '<NAME>',
id: '9800000-6',
mineral: 'Oro',
id_rucom: 'RUCOM-201203014810',
rucom_status: 'Certificado',
last_transaction_date: '1427226977550',
prov_type: 7,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://plus.google.com/u/0/_/focus/photos/public/AIbEiAIAAABECOnz4JakhaOK_gEiC3ZjYXJkX3Bob3RvKihiMWQyMWNkZmRiYzIzM2EzODUyZDQyMjU3ZWVlZTU4MzU0MWE3ZjY3MAFLUhAwq57N0mPOSXuYPdiOmJZ9KQ?sz=48',
name: '<NAME>',
id: '9800000-7',
mineral: 'Oro',
id_rucom: 'RUCOM-201303014800',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226978293',
prov_type: 1,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh3.googleusercontent.com/-q9i8c2WHh9I/AAAAAAAAAAI/AAAAAAAAAK0/p9wFW0PJ_oo/photo.jpg',
name: '<NAME>',
id: '9800000-8',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014802',
rucom_status: 'Certificado',
last_transaction_date: '1427226977893',
prov_type: 2,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-kzZKDrB6wb4/AAAAAAAAAAI/AAAAAAAAAzU/CnnUA5Ygbjs/photo.jpg',
name: '<NAME>',
id: '9800000-9',
mineral: 'Oro',
id_rucom: 'RUCOM-201303014201',
rucom_status: 'Certificado',
last_transaction_date: '1427226979293',
prov_type: 3,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh5.googleusercontent.com/-K1ZinAJG6D0/AAAAAAAAAAI/AAAAAAAAAGk/vFy0NwAptgI/photo.jpg',
name: '<NAME>',
id: '9800001-0',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014833',
rucom_status: 'Certificado',
last_transaction_date: '1427226977777',
prov_type: 4,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-9pJ7LbpZ_nA/AAAAAAAAAAI/AAAAAAAAFuc/VxoI6yvIzlE/photo.jpg',
name: '<NAME>',
id: '1023939222',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014943',
rucom_status: 'Certificado',
last_transaction_date: '1427227113631',
prov_type: 5,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: '<NAME>',
id: '9800001-2',
mineral: 'Oro',
id_rucom: 'RUCOM-201503204884',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427227123631',
prov_type: 6,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: '<NAME>',
id: '9800001-3',
mineral: 'Oro',
id_rucom: 'RUCOM-201503204883',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427227133631',
prov_type: 7,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: '<NAME>',
id: '9800001-4',
mineral: 'Oro',
id_rucom: 'RUCOM-201503194882',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427227113731',
prov_type: 1,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: '<EMAIL>',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
}
];
#
# provider
#
# GET
# it is a possible route for the provider
app.get '/api/v1/provider', (req, res) ->
console.log 'provider list from the fake server ...'
res.json {
list: providerList,
access_token: '<PASSWORD>'
}
# GET
# endpoint for retrieving providers by ID
app.get '/api/v1/provider/:providerId', (req, res) ->
console.log 'retrieving provider ' + req.params.providerId + ' from the fake server ...'
provider = {}
for p of providerList
if providerList[p].id == req.params.providerId
provider = providerList[p]
break
res.json {
provider: provider,
access_token: '<PASSWORD>'
}
| true | ### Define custom server-side HTTP routes for lineman's development server
# These might be as simple as stubbing a little JSON to
# facilitate development of code that interacts with an HTTP service
# (presumably, mirroring one that will be reachable in a live environment).
#
# It's important to remember that any custom endpoints defined here
# will only be available in development, as lineman only builds
# static assets, it can't run server-side code.
#
# This file can be very useful for rapid prototyping or even organically
# defining a spec based on the needs of the client code that emerge.
#
###
module.exports = drawRoutes: (app) ->
#
# Auth
#
app.post '/api/v1/auth/login', (req, res) ->
res.json {
access_token: 'PI:PASSWORD:<PASSWORD>END_PI',
id: 1,
first_name: 'PI:NAME:<NAME>END_PI',
last_name: 'PI:NAME:<NAME>END_PI',
email: 'PI:EMAIL:<EMAIL>END_PI',
}
app.post '/logout', (req, res) ->
res.json message: 'logging out!'
#
# Inventory
#
# GET
# it is a possible route for the inventory (it is inventory or inventories ?)
app.get '/api/v1/inventory', (req, res) ->
list = []
i = 0
while i < 10
inventory_item =
date: ''
hour: ''
quien: '' # NOTE: is this the person that created a inventory?
cuantos: '' # ?
law: ''
value: ''
inventory_item.selected = false
inventory_item.date = '10/20/2014' + i
inventory_item.hour = '10:20' + i
inventory_item.quien = 'PI:NAME:<NAME>END_PI' + i # TODO: change name
inventory_item.cuantos = i # TODO: change name
inventory_item.law = '100' + i
inventory_item.value = '100' + i
list.push inventory_item
i++
console.log 'inventory list from the fake server ...'
res.json {
list: list,
access_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
#
# Transporter
#
# POST
# Create a transoporter
app.post '/api/v1/transporter', (req, res) ->
console.log('trasporter created... yay!!!')
console.log('parameters: >> ' + req.params)
res.json {
name: 'PI:NAME:<NAME>END_PI',
document_number: '123456789',
phone: '+57300214587',
address: 'calle falsa # 12 -3',
email: 'PI:EMAIL:<EMAIL>END_PI',
access_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
# I know the following declaration may not be a good practice... but it's just temporal
providerList = [
{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: 'PI:NAME:<NAME>END_PI',
id: '9800000-1',
mineral: 'Oro',
id_rucom: 'RUCOM-201502204885',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226977293',
prov_type: 2,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-wx3BmJUhhpE/AAAAAAAAAAI/AAAAAAAAACM/R6R-aAQB62E/photo.jpg',
name: 'PI:NAME:<NAME>END_PI',
id: '9800000-2',
mineral: 'Oro',
id_rucom: 'RUCOM-201503014886',
rucom_status: 'Certificado',
last_transaction_date: '1427226977300',
prov_type: 3,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-MPs16CJ6ZBI/AAAAAAAAAAI/AAAAAAAAAfw/qZNidz7KVvo/photo.jpg',
name: 'PI:NAME:<NAME>END_PI',
id: '9800000-3',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014887',
rucom_status: 'Certificado',
last_transaction_date: '1427226978293',
prov_type: 4,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh3.googleusercontent.com/-7qT3MgVr0rk/AAAAAAAAAAI/AAAAAAAAAJE/i1Yc_rFyVz8/photo.jpg',
name: 'PI:NAME:<NAME>END_PI',
id: '9800000-4',
mineral: 'Oro',
id_rucom: 'RUCOM-201303014890',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226977493',
prov_type: 5,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh3.googleusercontent.com/-xUqWqzQQaZc/AAAAAAAAAAI/AAAAAAAAA88/M5EhGqXSItk/photo.jpg',
name: 'PI:NAME:<NAME>END_PI',
id: '9800000-5',
mineral: 'Oro',
id_rucom: 'RUCOM-201503014892',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226977600',
prov_type: 6,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh6.googleusercontent.com/-KAhFBi4grKU/AAAAAAAAAAI/AAAAAAAABLM/hnWGNvV7D2k/photo.jpg',
name: 'PI:NAME:<NAME>END_PI',
id: '9800000-6',
mineral: 'Oro',
id_rucom: 'RUCOM-201203014810',
rucom_status: 'Certificado',
last_transaction_date: '1427226977550',
prov_type: 7,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://plus.google.com/u/0/_/focus/photos/public/AIbEiAIAAABECOnz4JakhaOK_gEiC3ZjYXJkX3Bob3RvKihiMWQyMWNkZmRiYzIzM2EzODUyZDQyMjU3ZWVlZTU4MzU0MWE3ZjY3MAFLUhAwq57N0mPOSXuYPdiOmJZ9KQ?sz=48',
name: 'PI:NAME:<NAME>END_PI',
id: '9800000-7',
mineral: 'Oro',
id_rucom: 'RUCOM-201303014800',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427226978293',
prov_type: 1,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh3.googleusercontent.com/-q9i8c2WHh9I/AAAAAAAAAAI/AAAAAAAAAK0/p9wFW0PJ_oo/photo.jpg',
name: 'PI:NAME:<NAME>END_PI',
id: '9800000-8',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014802',
rucom_status: 'Certificado',
last_transaction_date: '1427226977893',
prov_type: 2,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-kzZKDrB6wb4/AAAAAAAAAAI/AAAAAAAAAzU/CnnUA5Ygbjs/photo.jpg',
name: 'PI:NAME:<NAME>END_PI',
id: '9800000-9',
mineral: 'Oro',
id_rucom: 'RUCOM-201303014201',
rucom_status: 'Certificado',
last_transaction_date: '1427226979293',
prov_type: 3,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh5.googleusercontent.com/-K1ZinAJG6D0/AAAAAAAAAAI/AAAAAAAAAGk/vFy0NwAptgI/photo.jpg',
name: 'PI:NAME:<NAME>END_PI',
id: '9800001-0',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014833',
rucom_status: 'Certificado',
last_transaction_date: '1427226977777',
prov_type: 4,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://lh4.googleusercontent.com/-9pJ7LbpZ_nA/AAAAAAAAAAI/AAAAAAAAFuc/VxoI6yvIzlE/photo.jpg',
name: 'PI:NAME:<NAME>END_PI',
id: '1023939222',
mineral: 'Oro',
id_rucom: 'RUCOM-201403014943',
rucom_status: 'Certificado',
last_transaction_date: '1427227113631',
prov_type: 5,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: 'PI:NAME:<NAME>END_PI',
id: '9800001-2',
mineral: 'Oro',
id_rucom: 'RUCOM-201503204884',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427227123631',
prov_type: 6,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: 'PI:NAME:<NAME>END_PI',
id: '9800001-3',
mineral: 'Oro',
id_rucom: 'RUCOM-201503204883',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427227133631',
prov_type: 7,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
},{
thumb:'https://ssl.gstatic.com/s2/profiles/images/silhouette48.png',
name: 'PI:NAME:<NAME>END_PI',
id: '9800001-4',
mineral: 'Oro',
id_rucom: 'RUCOM-201503194882',
rucom_status: 'En trámite, pendiente de evaluación',
last_transaction_date: '1427227113731',
prov_type: 1,
type: 'Persona Natural',
phone_nb: '314 757 9454',
address: 'Cra 1 # 2N - 3, Urbanizacion A, Popayan, Colombia',
email: 'PI:EMAIL:<EMAIL>END_PI',
city: 'Popayán',
state: 'CAUCA',
postalCode : '94043'
}
];
#
# provider
#
# GET
# it is a possible route for the provider
app.get '/api/v1/provider', (req, res) ->
console.log 'provider list from the fake server ...'
res.json {
list: providerList,
access_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
# GET
# endpoint for retrieving providers by ID
app.get '/api/v1/provider/:providerId', (req, res) ->
console.log 'retrieving provider ' + req.params.providerId + ' from the fake server ...'
provider = {}
for p of providerList
if providerList[p].id == req.params.providerId
provider = providerList[p]
break
res.json {
provider: provider,
access_token: 'PI:PASSWORD:<PASSWORD>END_PI'
}
|
[
{
"context": " .del('baz')\n .put('pass', 'xyzzy')\n .write(afterWrite);\n }\n\n ",
"end": 531,
"score": 0.999060869216919,
"start": 526,
"tag": "PASSWORD",
"value": "xyzzy"
}
] | src/coffee/leveldb/batch.coffee | kyledrake/node-leveldb | 1 | binding = require '../../build/Release/leveldb.node'
noop = ->
###
A batch holds a sequence of put/delete operations to atomically write to
the database.
Usage:
var leveldb = require('leveldb');
var db, db2, batch, batch2 = new leveldb.Batch, writes = 2;
leveldb.open('/tmp/test.db', onOpen);
function onOpen(err, handle) {
db = handle;
batch = db.batch();
batch
.put('foo', 'bar')
.del('baz')
.put('pass', 'xyzzy')
.write(afterWrite);
}
function afterWrite(err) {
leveldb.open('/tmp/test2.db', onOpen2);
}
function onOpen2(err, handle) {
db2 = handle;
batch2
.put('foo', 'coconut')
.del('pass');
db.write(batch2, afterWrite2);
db2.write(batch2, afterWrite2);
}
function afterWrite2(err) {
writes -= 1;
if (writes <= 0) {
// batch2 has not been cleared to allow for reuse.
batch2.clear();
// works because the batch is cleared after committing when using
// batch.commit()
batch
.put('hello', 'world')
.put('goodbye', 'world');
db.write(batch);
db2.write(batch);
}
}
###
exports.Batch = class Batch
###
Constructor.
@param {leveldb.Handle} [handle] Pass a database handle to use with
`batch.write()` or `batch.writeSync()`.
###
constructor: (@handle) ->
@self = new binding.Batch
@readLock_ = 0
###
Add a put operation to the batch.
@param {String|Buffer} key The key to put.
@param {String|Buffer} val The value to put.
###
put: (key, val) ->
throw 'Read locked' if @readLock_ > 0
# to buffer if string
key = new Buffer key unless Buffer.isBuffer key
val = new Buffer val unless Buffer.isBuffer val
# call native binding
@self.put key, val
@
###
Add a delete operation to the batch.
@param {String|Buffer} key The key to delete.
###
del: (key) ->
throw 'Read locked' if @readLock_ > 0
# to buffer if string
key = new Buffer key unless Buffer.isBuffer key
# call native binding
@self.del key
@
###
Commit the batch operations to disk.
See `Handle.write()`.
###
write: (options, callback) ->
# require handle
throw new Error 'No handle' unless @handle
# read lock
++@readLock_
# optional options
if typeof options is 'function'
callback = options
options = null
# optional callback
callback or= noop
# call native method
@handle.write @self, options, (err) =>
# read unlock
--@readLock_
# clear batch
@self.clear() unless err
# call callback
callback err
# no chaining while buffer is in use async
###
Reset this batch instance by removing all pending operations.
###
clear: ->
throw 'Read locked' if @readLock_ > 0
@self.clear()
@
| 1146 | binding = require '../../build/Release/leveldb.node'
noop = ->
###
A batch holds a sequence of put/delete operations to atomically write to
the database.
Usage:
var leveldb = require('leveldb');
var db, db2, batch, batch2 = new leveldb.Batch, writes = 2;
leveldb.open('/tmp/test.db', onOpen);
function onOpen(err, handle) {
db = handle;
batch = db.batch();
batch
.put('foo', 'bar')
.del('baz')
.put('pass', '<PASSWORD>')
.write(afterWrite);
}
function afterWrite(err) {
leveldb.open('/tmp/test2.db', onOpen2);
}
function onOpen2(err, handle) {
db2 = handle;
batch2
.put('foo', 'coconut')
.del('pass');
db.write(batch2, afterWrite2);
db2.write(batch2, afterWrite2);
}
function afterWrite2(err) {
writes -= 1;
if (writes <= 0) {
// batch2 has not been cleared to allow for reuse.
batch2.clear();
// works because the batch is cleared after committing when using
// batch.commit()
batch
.put('hello', 'world')
.put('goodbye', 'world');
db.write(batch);
db2.write(batch);
}
}
###
exports.Batch = class Batch
###
Constructor.
@param {leveldb.Handle} [handle] Pass a database handle to use with
`batch.write()` or `batch.writeSync()`.
###
constructor: (@handle) ->
@self = new binding.Batch
@readLock_ = 0
###
Add a put operation to the batch.
@param {String|Buffer} key The key to put.
@param {String|Buffer} val The value to put.
###
put: (key, val) ->
throw 'Read locked' if @readLock_ > 0
# to buffer if string
key = new Buffer key unless Buffer.isBuffer key
val = new Buffer val unless Buffer.isBuffer val
# call native binding
@self.put key, val
@
###
Add a delete operation to the batch.
@param {String|Buffer} key The key to delete.
###
del: (key) ->
throw 'Read locked' if @readLock_ > 0
# to buffer if string
key = new Buffer key unless Buffer.isBuffer key
# call native binding
@self.del key
@
###
Commit the batch operations to disk.
See `Handle.write()`.
###
write: (options, callback) ->
# require handle
throw new Error 'No handle' unless @handle
# read lock
++@readLock_
# optional options
if typeof options is 'function'
callback = options
options = null
# optional callback
callback or= noop
# call native method
@handle.write @self, options, (err) =>
# read unlock
--@readLock_
# clear batch
@self.clear() unless err
# call callback
callback err
# no chaining while buffer is in use async
###
Reset this batch instance by removing all pending operations.
###
clear: ->
throw 'Read locked' if @readLock_ > 0
@self.clear()
@
| true | binding = require '../../build/Release/leveldb.node'
noop = ->
###
A batch holds a sequence of put/delete operations to atomically write to
the database.
Usage:
var leveldb = require('leveldb');
var db, db2, batch, batch2 = new leveldb.Batch, writes = 2;
leveldb.open('/tmp/test.db', onOpen);
function onOpen(err, handle) {
db = handle;
batch = db.batch();
batch
.put('foo', 'bar')
.del('baz')
.put('pass', 'PI:PASSWORD:<PASSWORD>END_PI')
.write(afterWrite);
}
function afterWrite(err) {
leveldb.open('/tmp/test2.db', onOpen2);
}
function onOpen2(err, handle) {
db2 = handle;
batch2
.put('foo', 'coconut')
.del('pass');
db.write(batch2, afterWrite2);
db2.write(batch2, afterWrite2);
}
function afterWrite2(err) {
writes -= 1;
if (writes <= 0) {
// batch2 has not been cleared to allow for reuse.
batch2.clear();
// works because the batch is cleared after committing when using
// batch.commit()
batch
.put('hello', 'world')
.put('goodbye', 'world');
db.write(batch);
db2.write(batch);
}
}
###
exports.Batch = class Batch
###
Constructor.
@param {leveldb.Handle} [handle] Pass a database handle to use with
`batch.write()` or `batch.writeSync()`.
###
constructor: (@handle) ->
@self = new binding.Batch
@readLock_ = 0
###
Add a put operation to the batch.
@param {String|Buffer} key The key to put.
@param {String|Buffer} val The value to put.
###
put: (key, val) ->
throw 'Read locked' if @readLock_ > 0
# to buffer if string
key = new Buffer key unless Buffer.isBuffer key
val = new Buffer val unless Buffer.isBuffer val
# call native binding
@self.put key, val
@
###
Add a delete operation to the batch.
@param {String|Buffer} key The key to delete.
###
del: (key) ->
throw 'Read locked' if @readLock_ > 0
# to buffer if string
key = new Buffer key unless Buffer.isBuffer key
# call native binding
@self.del key
@
###
Commit the batch operations to disk.
See `Handle.write()`.
###
write: (options, callback) ->
# require handle
throw new Error 'No handle' unless @handle
# read lock
++@readLock_
# optional options
if typeof options is 'function'
callback = options
options = null
# optional callback
callback or= noop
# call native method
@handle.write @self, options, (err) =>
# read unlock
--@readLock_
# clear batch
@self.clear() unless err
# call callback
callback err
# no chaining while buffer is in use async
###
Reset this batch instance by removing all pending operations.
###
clear: ->
throw 'Read locked' if @readLock_ > 0
@self.clear()
@
|
[
{
"context": "nt: 'https://api-staging.hanzo.io'\n key: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJiaXQiOjI0LCJqdGkiOiJhajNhTUpPcUlfWSIsInN1YiI6IkVxVEdveHA1dTMifQ.dwz3XXRPSHzhFIXYIW-GrU1ovf1alEvRN9syqRKlfAwapXwVxp5Twort3ibaDd6V-yQtLHfziy2PHNin1VfZ4A'\n\n # endpoint: 'https://api.hanzo.io'\n # ke",
... | test/server/helper.coffee | hanzo-io/hanzo.js | 147 | chai = require 'chai'
chai.should()
chai.use require 'chai-as-promised'
hanzo = require '../../'
before ->
global.sleep = (time) ->
new Promise (resolve, reject) ->
setTimeout ->
resolve()
, time
global.api = new hanzo.Api
debug: true
endpoint: 'https://api-staging.hanzo.io'
key: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJiaXQiOjI0LCJqdGkiOiJhajNhTUpPcUlfWSIsInN1YiI6IkVxVEdveHA1dTMifQ.dwz3XXRPSHzhFIXYIW-GrU1ovf1alEvRN9syqRKlfAwapXwVxp5Twort3ibaDd6V-yQtLHfziy2PHNin1VfZ4A'
# endpoint: 'https://api.hanzo.io'
# key: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJiaXQiOjQ1MDM2MTcwNzU2NzUxNzIsImp0aSI6InlJVFF2NTZwWXBVIiwic3ViIjoiRXFUR294cDV1MyJ9.TM_aCV2SCSLbRVMgezSCLr0UvkcXhpupCfDWC8bvkzaMuqGv6N-g4DnTNtUJNk_70nO6gA0seCpEvuMSkerSsw'
global.randomToken = (n) ->
Math.random().toString(36).replace(/[^a-z0-9A-Z]+/g, '').substr 0, n
global.randomEmail = ->
randomToken(4) + '@email.com'
global.email = randomEmail()
global.firstName = randomToken 4
global.newFirstName = randomToken 4
global.lastName = randomToken 4
global.goodPass1 = randomToken 6
global.goodPass2 = randomToken 6
global.badPass1 = randomToken 5
| 120299 | chai = require 'chai'
chai.should()
chai.use require 'chai-as-promised'
hanzo = require '../../'
before ->
global.sleep = (time) ->
new Promise (resolve, reject) ->
setTimeout ->
resolve()
, time
global.api = new hanzo.Api
debug: true
endpoint: 'https://api-staging.hanzo.io'
key: '<KEY>'
# endpoint: 'https://api.hanzo.io'
# key: '<KEY>'
global.randomToken = (n) ->
Math.random().toString(36).replace(/[^a-z0-9A-Z]+/g, '').substr 0, n
global.randomEmail = ->
randomToken(4) + '@email.com'
global.email = randomEmail()
global.firstName = randomToken 4
global.newFirstName = randomToken 4
global.lastName = randomToken 4
global.goodPass1 = randomToken 6
global.goodPass2 = randomToken 6
global.badPass1 = randomToken 5
| true | chai = require 'chai'
chai.should()
chai.use require 'chai-as-promised'
hanzo = require '../../'
before ->
global.sleep = (time) ->
new Promise (resolve, reject) ->
setTimeout ->
resolve()
, time
global.api = new hanzo.Api
debug: true
endpoint: 'https://api-staging.hanzo.io'
key: 'PI:KEY:<KEY>END_PI'
# endpoint: 'https://api.hanzo.io'
# key: 'PI:KEY:<KEY>END_PI'
global.randomToken = (n) ->
Math.random().toString(36).replace(/[^a-z0-9A-Z]+/g, '').substr 0, n
global.randomEmail = ->
randomToken(4) + '@email.com'
global.email = randomEmail()
global.firstName = randomToken 4
global.newFirstName = randomToken 4
global.lastName = randomToken 4
global.goodPass1 = randomToken 6
global.goodPass2 = randomToken 6
global.badPass1 = randomToken 5
|
[
{
"context": "ed attempts, just return the user\n # thanks De Morgan\n unless user.loginAttempts || user.lockUnt",
"end": 2908,
"score": 0.9744172096252441,
"start": 2899,
"tag": "NAME",
"value": "De Morgan"
}
] | server/models/user.coffee | switz/backbone-express-coffee-mongo-boilerplate | 1 | mongoose = require("mongoose")
Schema = mongoose.Schema
bcrypt = require('bcrypt')
SALT_WORK_FACTOR = 10
MAX_LOGIN_ATTEMPTS = 5
LOCK_TIME = 2 * 60 * 60 * 1000
EMAIL_REGEX = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i
validateEmail = (email) ->
EMAIL_REGEX.test email
UserSchema = new Schema
email: type: String, index: { unique: true }
password: type: String
loginAttempts: type: Number, required: true, default: 0
lockUntil: type: Number
UserSchema.virtual("isLocked").get ->
# check for a future lockUntil timestamp
!!(@lockUntil and @lockUntil > Date.now())
# Pre save hook
UserSchema.pre 'save', (next) ->
user = this
return false unless (user.email && user.password)
return next() unless user.isModified('password')
bcrypt.genSalt SALT_WORK_FACTOR, (err, salt) ->
return next(err) if err
bcrypt.hash user.password, salt, (err, hash) ->
return next(err) if err
user.password = hash
next()
# Methods
UserSchema.methods.comparePassword = (candidatePassword, callback) ->
bcrypt.compare candidatePassword, @password, (err, isMatch) ->
return callback(err) if err
callback null, isMatch
UserSchema.methods.incLoginAttempts = (callback) ->
# if we have a previous lock that has expired, restart at 1
if @lockUntil and @lockUntil < Date.now()
return @update(
$set:
loginAttempts: 1
$unset:
lockUntil: 1
, callback)
# otherwise we're incrementing
updates = $inc:
loginAttempts: 1
# lock the account if we've reached max attempts and it's not locked already
updates.$set = lockUntil: Date.now() + LOCK_TIME if @loginAttempts + 1 >= MAX_LOGIN_ATTEMPTS and not @isLocked
@update updates, callback
# Statics
reasons = UserSchema.statics.failedLogin =
NOT_FOUND: 0
PASSWORD_INCORRECT: 1
MAX_ATTEMPTS: 2
UserSchema.statics.authenticate = (email, password, callback) ->
@findOne
email: email
, (err, user) ->
return callback(err) if err
# make sure the user exists
return callback(null, null, reasons.NOT_FOUND) unless user
if user.isLocked
# increment login attempts if account is already locked
return user.incLoginAttempts (err) ->
return callback(err) if err
callback null, null, reasons.MAX_ATTEMPTS
# test for a matching password
user.comparePassword password, (err, isMatch) ->
return callback(err) if err
if isMatch
# if there's no lock or failed attempts, just return the user
# thanks De Morgan
unless user.loginAttempts || user.lockUntil
return callback(null, user)
# reset attempts and lock info
updates =
$set:
loginAttempts: 0
$unset:
lockUntil: 1
return user.update updates, (err) ->
return callback(err) if err
callback null, user
# password is incorrect, so increment login attempts before responding
user.incLoginAttempts (err) ->
return callback(err) if err
callback null, null, reasons.PASSWORD_INCORRECT
# Set Mongoose Model
module.exports = mongoose.model "User", UserSchema
| 19301 | mongoose = require("mongoose")
Schema = mongoose.Schema
bcrypt = require('bcrypt')
SALT_WORK_FACTOR = 10
MAX_LOGIN_ATTEMPTS = 5
LOCK_TIME = 2 * 60 * 60 * 1000
EMAIL_REGEX = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i
validateEmail = (email) ->
EMAIL_REGEX.test email
UserSchema = new Schema
email: type: String, index: { unique: true }
password: type: String
loginAttempts: type: Number, required: true, default: 0
lockUntil: type: Number
UserSchema.virtual("isLocked").get ->
# check for a future lockUntil timestamp
!!(@lockUntil and @lockUntil > Date.now())
# Pre save hook
UserSchema.pre 'save', (next) ->
user = this
return false unless (user.email && user.password)
return next() unless user.isModified('password')
bcrypt.genSalt SALT_WORK_FACTOR, (err, salt) ->
return next(err) if err
bcrypt.hash user.password, salt, (err, hash) ->
return next(err) if err
user.password = hash
next()
# Methods
UserSchema.methods.comparePassword = (candidatePassword, callback) ->
bcrypt.compare candidatePassword, @password, (err, isMatch) ->
return callback(err) if err
callback null, isMatch
UserSchema.methods.incLoginAttempts = (callback) ->
# if we have a previous lock that has expired, restart at 1
if @lockUntil and @lockUntil < Date.now()
return @update(
$set:
loginAttempts: 1
$unset:
lockUntil: 1
, callback)
# otherwise we're incrementing
updates = $inc:
loginAttempts: 1
# lock the account if we've reached max attempts and it's not locked already
updates.$set = lockUntil: Date.now() + LOCK_TIME if @loginAttempts + 1 >= MAX_LOGIN_ATTEMPTS and not @isLocked
@update updates, callback
# Statics
reasons = UserSchema.statics.failedLogin =
NOT_FOUND: 0
PASSWORD_INCORRECT: 1
MAX_ATTEMPTS: 2
UserSchema.statics.authenticate = (email, password, callback) ->
@findOne
email: email
, (err, user) ->
return callback(err) if err
# make sure the user exists
return callback(null, null, reasons.NOT_FOUND) unless user
if user.isLocked
# increment login attempts if account is already locked
return user.incLoginAttempts (err) ->
return callback(err) if err
callback null, null, reasons.MAX_ATTEMPTS
# test for a matching password
user.comparePassword password, (err, isMatch) ->
return callback(err) if err
if isMatch
# if there's no lock or failed attempts, just return the user
# thanks <NAME>
unless user.loginAttempts || user.lockUntil
return callback(null, user)
# reset attempts and lock info
updates =
$set:
loginAttempts: 0
$unset:
lockUntil: 1
return user.update updates, (err) ->
return callback(err) if err
callback null, user
# password is incorrect, so increment login attempts before responding
user.incLoginAttempts (err) ->
return callback(err) if err
callback null, null, reasons.PASSWORD_INCORRECT
# Set Mongoose Model
module.exports = mongoose.model "User", UserSchema
| true | mongoose = require("mongoose")
Schema = mongoose.Schema
bcrypt = require('bcrypt')
SALT_WORK_FACTOR = 10
MAX_LOGIN_ATTEMPTS = 5
LOCK_TIME = 2 * 60 * 60 * 1000
EMAIL_REGEX = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i
validateEmail = (email) ->
EMAIL_REGEX.test email
UserSchema = new Schema
email: type: String, index: { unique: true }
password: type: String
loginAttempts: type: Number, required: true, default: 0
lockUntil: type: Number
UserSchema.virtual("isLocked").get ->
# check for a future lockUntil timestamp
!!(@lockUntil and @lockUntil > Date.now())
# Pre save hook
UserSchema.pre 'save', (next) ->
user = this
return false unless (user.email && user.password)
return next() unless user.isModified('password')
bcrypt.genSalt SALT_WORK_FACTOR, (err, salt) ->
return next(err) if err
bcrypt.hash user.password, salt, (err, hash) ->
return next(err) if err
user.password = hash
next()
# Methods
UserSchema.methods.comparePassword = (candidatePassword, callback) ->
bcrypt.compare candidatePassword, @password, (err, isMatch) ->
return callback(err) if err
callback null, isMatch
UserSchema.methods.incLoginAttempts = (callback) ->
# if we have a previous lock that has expired, restart at 1
if @lockUntil and @lockUntil < Date.now()
return @update(
$set:
loginAttempts: 1
$unset:
lockUntil: 1
, callback)
# otherwise we're incrementing
updates = $inc:
loginAttempts: 1
# lock the account if we've reached max attempts and it's not locked already
updates.$set = lockUntil: Date.now() + LOCK_TIME if @loginAttempts + 1 >= MAX_LOGIN_ATTEMPTS and not @isLocked
@update updates, callback
# Statics
reasons = UserSchema.statics.failedLogin =
NOT_FOUND: 0
PASSWORD_INCORRECT: 1
MAX_ATTEMPTS: 2
UserSchema.statics.authenticate = (email, password, callback) ->
@findOne
email: email
, (err, user) ->
return callback(err) if err
# make sure the user exists
return callback(null, null, reasons.NOT_FOUND) unless user
if user.isLocked
# increment login attempts if account is already locked
return user.incLoginAttempts (err) ->
return callback(err) if err
callback null, null, reasons.MAX_ATTEMPTS
# test for a matching password
user.comparePassword password, (err, isMatch) ->
return callback(err) if err
if isMatch
# if there's no lock or failed attempts, just return the user
# thanks PI:NAME:<NAME>END_PI
unless user.loginAttempts || user.lockUntil
return callback(null, user)
# reset attempts and lock info
updates =
$set:
loginAttempts: 0
$unset:
lockUntil: 1
return user.update updates, (err) ->
return callback(err) if err
callback null, user
# password is incorrect, so increment login attempts before responding
user.incLoginAttempts (err) ->
return callback(err) if err
callback null, null, reasons.PASSWORD_INCORRECT
# Set Mongoose Model
module.exports = mongoose.model "User", UserSchema
|
[
{
"context": "), { path: '/' }\n\n initSidebarTab: ->\n key = \"dashboard_sidebar_filter\"\n\n # store selection in cookie\n $('.dash-si",
"end": 1300,
"score": 0.9907568693161011,
"start": 1276,
"tag": "KEY",
"value": "dashboard_sidebar_filter"
}
] | app/assets/javascripts/dashboard.js.coffee | allanim/gitlabhq | 1 | class Dashboard
constructor: ->
Pager.init 20, true
@initSidebarTab()
$(".event_filter_link").bind "click", (event) =>
event.preventDefault()
@toggleFilter($(event.currentTarget))
@reloadActivities()
$(".dash-filter").keyup ->
terms = $(this).val()
uiBox = $(this).parents('.ui-box').first()
if terms == "" || terms == undefined
uiBox.find(".dash-list li").show()
else
uiBox.find(".dash-list li").each (index) ->
name = $(this).find(".filter-title").text()
if name.toLowerCase().search(terms.toLowerCase()) == -1
$(this).hide()
else
$(this).show()
reloadActivities: ->
$(".content_list").html ''
Pager.init 20, true
toggleFilter: (sender) ->
sender.parent().toggleClass "inactive"
event_filters = $.cookie("event_filter")
filter = sender.attr("id").split("_")[0]
if event_filters
event_filters = event_filters.split(",")
else
event_filters = new Array()
index = event_filters.indexOf(filter)
if index is -1
event_filters.push filter
else
event_filters.splice index, 1
$.cookie "event_filter", event_filters.join(","), { path: '/' }
initSidebarTab: ->
key = "dashboard_sidebar_filter"
# store selection in cookie
$('.dash-sidebar-tabs a').on 'click', (e) ->
$.cookie(key, $(e.target).attr('id'))
# show tab from cookie
sidebar_filter = $.cookie(key)
$("#" + sidebar_filter).tab('show') if sidebar_filter
@Dashboard = Dashboard
| 70770 | class Dashboard
constructor: ->
Pager.init 20, true
@initSidebarTab()
$(".event_filter_link").bind "click", (event) =>
event.preventDefault()
@toggleFilter($(event.currentTarget))
@reloadActivities()
$(".dash-filter").keyup ->
terms = $(this).val()
uiBox = $(this).parents('.ui-box').first()
if terms == "" || terms == undefined
uiBox.find(".dash-list li").show()
else
uiBox.find(".dash-list li").each (index) ->
name = $(this).find(".filter-title").text()
if name.toLowerCase().search(terms.toLowerCase()) == -1
$(this).hide()
else
$(this).show()
reloadActivities: ->
$(".content_list").html ''
Pager.init 20, true
toggleFilter: (sender) ->
sender.parent().toggleClass "inactive"
event_filters = $.cookie("event_filter")
filter = sender.attr("id").split("_")[0]
if event_filters
event_filters = event_filters.split(",")
else
event_filters = new Array()
index = event_filters.indexOf(filter)
if index is -1
event_filters.push filter
else
event_filters.splice index, 1
$.cookie "event_filter", event_filters.join(","), { path: '/' }
initSidebarTab: ->
key = "<KEY>"
# store selection in cookie
$('.dash-sidebar-tabs a').on 'click', (e) ->
$.cookie(key, $(e.target).attr('id'))
# show tab from cookie
sidebar_filter = $.cookie(key)
$("#" + sidebar_filter).tab('show') if sidebar_filter
@Dashboard = Dashboard
| true | class Dashboard
constructor: ->
Pager.init 20, true
@initSidebarTab()
$(".event_filter_link").bind "click", (event) =>
event.preventDefault()
@toggleFilter($(event.currentTarget))
@reloadActivities()
$(".dash-filter").keyup ->
terms = $(this).val()
uiBox = $(this).parents('.ui-box').first()
if terms == "" || terms == undefined
uiBox.find(".dash-list li").show()
else
uiBox.find(".dash-list li").each (index) ->
name = $(this).find(".filter-title").text()
if name.toLowerCase().search(terms.toLowerCase()) == -1
$(this).hide()
else
$(this).show()
reloadActivities: ->
$(".content_list").html ''
Pager.init 20, true
toggleFilter: (sender) ->
sender.parent().toggleClass "inactive"
event_filters = $.cookie("event_filter")
filter = sender.attr("id").split("_")[0]
if event_filters
event_filters = event_filters.split(",")
else
event_filters = new Array()
index = event_filters.indexOf(filter)
if index is -1
event_filters.push filter
else
event_filters.splice index, 1
$.cookie "event_filter", event_filters.join(","), { path: '/' }
initSidebarTab: ->
key = "PI:KEY:<KEY>END_PI"
# store selection in cookie
$('.dash-sidebar-tabs a').on 'click', (e) ->
$.cookie(key, $(e.target).attr('id'))
# show tab from cookie
sidebar_filter = $.cookie(key)
$("#" + sidebar_filter).tab('show') if sidebar_filter
@Dashboard = Dashboard
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999107122421265,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/beatmapset-page/scoreboard-mod.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 { Mod } from 'mod'
import { img, div } from 'react-dom-factories'
el = React.createElement
export class ScoreboardMod extends React.Component
onClick: =>
$.publish 'beatmapset:scoreboard:set', enabledMod: @props.mod
render: ->
className = 'beatmapset-scoreboard__mod-box'
className += ' beatmapset-scoreboard__mod-box--enabled' if @props.enabled
div
className: className
onClick: @onClick
div
className: 'beatmapset-scoreboard__mod'
el Mod, mod: @props.mod
| 50418 | # 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 { Mod } from 'mod'
import { img, div } from 'react-dom-factories'
el = React.createElement
export class ScoreboardMod extends React.Component
onClick: =>
$.publish 'beatmapset:scoreboard:set', enabledMod: @props.mod
render: ->
className = 'beatmapset-scoreboard__mod-box'
className += ' beatmapset-scoreboard__mod-box--enabled' if @props.enabled
div
className: className
onClick: @onClick
div
className: 'beatmapset-scoreboard__mod'
el Mod, mod: @props.mod
| 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 { Mod } from 'mod'
import { img, div } from 'react-dom-factories'
el = React.createElement
export class ScoreboardMod extends React.Component
onClick: =>
$.publish 'beatmapset:scoreboard:set', enabledMod: @props.mod
render: ->
className = 'beatmapset-scoreboard__mod-box'
className += ' beatmapset-scoreboard__mod-box--enabled' if @props.enabled
div
className: className
onClick: @onClick
div
className: 'beatmapset-scoreboard__mod'
el Mod, mod: @props.mod
|
[
{
"context": " = require \"ical\"\nfs = require \"fs\"\n\nletters =\n \"Gelbe(r) Tonne/Sack\": \"G\"\n \"Bioabfall-Tonne\": \"B\"\n \"P",
"end": 59,
"score": 0.7590640187263489,
"start": 54,
"tag": "NAME",
"value": "Gelbe"
},
{
"context": "re \"ical\"\nfs = require \"fs\"\n\nlette... | lib/awigo.coffee | naltatis/kindle-display | 16 | ical = require "ical"
fs = require "fs"
letters =
"Gelbe(r) Tonne/Sack": "G"
"Bioabfall-Tonne": "B"
"Papier-Tonne": "P"
"Restmuelltonne": "R"
names =
"Gelbe(r) Tonne/Sack": "Gelbe Tonne"
"Bioabfall-Tonne": "Biomüll"
"Papier-Tonne": "Papiermüll"
"Restmuelltonne": "Restmüll"
class Awigo
constructor: (conf) ->
@result = @_transformEvents(@_readIcal(conf.file))
data: (cb) ->
nextResults = {}
nextResults[day] = @result[day] for day in @_nextDays(5)
cb(null, nextResults)
_nextDays: (number) ->
now = new Date().getTime()
msPerDay = 24*60*60*1000
(@_simpleDate(new Date(now + i*msPerDay)) for i in [0..number-1])
_simpleDate: (date) ->
date.getFullYear()+"-"+date.getMonth()+"-"+date.getDate()
_readIcal: (file) ->
string = fs.readFileSync file, "utf8"
ical.parseICS(string)
_transformEvents: (icalEvents) ->
events = {}
for key, value of icalEvents
if value? and value.start?
date = @_simpleDate(value.start)
garbage = value.summary.val
if not events[date]?
events[date] = []
events[date].push {letter: letters[garbage], name: names[garbage]}
events
module.exports = Awigo | 137493 | ical = require "ical"
fs = require "fs"
letters =
"<NAME>(r) <NAME>/<NAME>": "G"
"Bioabfall-Tonne": "B"
"Papier-Tonne": "P"
"Restmuelltonne": "R"
names =
"<NAME>(<NAME>": "<NAME>"
"<NAME>": "<NAME>"
"<NAME>-<NAME>": "<NAME>"
"Restmuelltonne": "Rest<NAME>"
class Awigo
constructor: (conf) ->
@result = @_transformEvents(@_readIcal(conf.file))
data: (cb) ->
nextResults = {}
nextResults[day] = @result[day] for day in @_nextDays(5)
cb(null, nextResults)
_nextDays: (number) ->
now = new Date().getTime()
msPerDay = 24*60*60*1000
(@_simpleDate(new Date(now + i*msPerDay)) for i in [0..number-1])
_simpleDate: (date) ->
date.getFullYear()+"-"+date.getMonth()+"-"+date.getDate()
_readIcal: (file) ->
string = fs.readFileSync file, "utf8"
ical.parseICS(string)
_transformEvents: (icalEvents) ->
events = {}
for key, value of icalEvents
if value? and value.start?
date = @_simpleDate(value.start)
garbage = value.summary.val
if not events[date]?
events[date] = []
events[date].push {letter: letters[garbage], name: names[garbage]}
events
module.exports = Awigo | true | ical = require "ical"
fs = require "fs"
letters =
"PI:NAME:<NAME>END_PI(r) PI:NAME:<NAME>END_PI/PI:NAME:<NAME>END_PI": "G"
"Bioabfall-Tonne": "B"
"Papier-Tonne": "P"
"Restmuelltonne": "R"
names =
"PI:NAME:<NAME>END_PI(PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI": "PI:NAME:<NAME>END_PI"
"Restmuelltonne": "RestPI:NAME:<NAME>END_PI"
class Awigo
constructor: (conf) ->
@result = @_transformEvents(@_readIcal(conf.file))
data: (cb) ->
nextResults = {}
nextResults[day] = @result[day] for day in @_nextDays(5)
cb(null, nextResults)
_nextDays: (number) ->
now = new Date().getTime()
msPerDay = 24*60*60*1000
(@_simpleDate(new Date(now + i*msPerDay)) for i in [0..number-1])
_simpleDate: (date) ->
date.getFullYear()+"-"+date.getMonth()+"-"+date.getDate()
_readIcal: (file) ->
string = fs.readFileSync file, "utf8"
ical.parseICS(string)
_transformEvents: (icalEvents) ->
events = {}
for key, value of icalEvents
if value? and value.start?
date = @_simpleDate(value.start)
garbage = value.summary.val
if not events[date]?
events[date] = []
events[date].push {letter: letters[garbage], name: names[garbage]}
events
module.exports = Awigo |
[
{
"context": " [\n# {\n# name: 'first',\n# amount: '$0.00'\n# ",
"end": 100,
"score": 0.9996798038482666,
"start": 95,
"tag": "NAME",
"value": "first"
},
{
"context": " },\n# {\n# name: 'sec... | lib/mixins/table.coffee | trexglobal/pdfkit | 0 | # Add table support
#
# doc.table(20, 20,
# [
# {
# name: 'first',
# amount: '$0.00'
# },
# {
# name: 'second',
# amount: '$0.00'
# }
# ],
# {
# name: {
# label: 'name',
# width: 100
# },
# amount: {
# label: 'amount',
# width: 100
# }
# }
# )
module.exports =
initTable: ->
# Current coordinates
@tx = 0
@ty = 0
# Track new line Y
@_newLineY = 0
# Cotain row data
@data = []
@options = {
new_page: {} # New page table position
}
# Carriage for printing each table element in it's place
@carriage = {
x: @tx,
y: @ty
}
# Contain cols cols definition
@cols_definition = {}
return this
# Set carriage for first and new page position
_initCarriage: ( newPage = false ) ->
if newPage
@addPage()
@carriage = {
x: @tx,
y: @currentLineHeight(true)
}
@_newLineY = 0
else
@carriage = {
x: @tx,
y: @ty
}
# Indent carriage
_indent: ( indent ) ->
@carriage.x += indent
# Keep current col next line position
# if it's bigger than previous col
if @y > @_newLineY
@_newLineY = @y
# Move carriage to new line
_return: () ->
# New Page
# TODO: Fix issue when mutiline col is at the end of page
if ( @_newLineY + @currentLineHeight(true)*2 ) > this.page.height
@_initCarriage(true)
# Normal Return
else
@carriage.y = @_newLineY
@carriage.x = @tx
_theader: () ->
# Loop Col Definitions
for id, col of @cols_definition
added_col = this.text col.label, @carriage.x, @carriage.y,
width: col.width
align: col.align
@_indent col.width
@_return()
_tbody: () ->
@_rows @data
_rows: ( data ) ->
# Loop Rows
for row in data
@_row row
@_return()
_row: ( row ) ->
# Loop Col Definitions
for id, column_options of @cols_definition
@_col row[id], column_options
@_indent column_options.width
_col: ( value, column_options ) ->
# Get col static value
col_value = value || column_options.value || ''
# Prevent white space which is causing issues in Acrobat Reader
if String(col_value).replace(/^\s+|\s+$/g,'') == ''
col_value = ''
# Print Column
this.text col_value, @carriage.x, @carriage.y,
width: column_options.width
align: column_options.align
table: ( x, y, data = [], cols_definition, options ) ->
# Update the current position
if x? or y?
@tx = x or @tx
@ty = y or @ty
# Assign options and data to instance
## Rows
@data = data
## Cols
@cols_definition = cols_definition if cols_definition?
## Other Options
@options extends options
# Setup Carriage
@_initCarriage()
# Build Table Header
@_theader()
# Build Table Body
@_tbody()
| 82719 | # Add table support
#
# doc.table(20, 20,
# [
# {
# name: '<NAME>',
# amount: '$0.00'
# },
# {
# name: '<NAME>',
# amount: '$0.00'
# }
# ],
# {
# name: {
# label: 'name',
# width: 100
# },
# amount: {
# label: 'amount',
# width: 100
# }
# }
# )
module.exports =
initTable: ->
# Current coordinates
@tx = 0
@ty = 0
# Track new line Y
@_newLineY = 0
# Cotain row data
@data = []
@options = {
new_page: {} # New page table position
}
# Carriage for printing each table element in it's place
@carriage = {
x: @tx,
y: @ty
}
# Contain cols cols definition
@cols_definition = {}
return this
# Set carriage for first and new page position
_initCarriage: ( newPage = false ) ->
if newPage
@addPage()
@carriage = {
x: @tx,
y: @currentLineHeight(true)
}
@_newLineY = 0
else
@carriage = {
x: @tx,
y: @ty
}
# Indent carriage
_indent: ( indent ) ->
@carriage.x += indent
# Keep current col next line position
# if it's bigger than previous col
if @y > @_newLineY
@_newLineY = @y
# Move carriage to new line
_return: () ->
# New Page
# TODO: Fix issue when mutiline col is at the end of page
if ( @_newLineY + @currentLineHeight(true)*2 ) > this.page.height
@_initCarriage(true)
# Normal Return
else
@carriage.y = @_newLineY
@carriage.x = @tx
_theader: () ->
# Loop Col Definitions
for id, col of @cols_definition
added_col = this.text col.label, @carriage.x, @carriage.y,
width: col.width
align: col.align
@_indent col.width
@_return()
_tbody: () ->
@_rows @data
_rows: ( data ) ->
# Loop Rows
for row in data
@_row row
@_return()
_row: ( row ) ->
# Loop Col Definitions
for id, column_options of @cols_definition
@_col row[id], column_options
@_indent column_options.width
_col: ( value, column_options ) ->
# Get col static value
col_value = value || column_options.value || ''
# Prevent white space which is causing issues in Acrobat Reader
if String(col_value).replace(/^\s+|\s+$/g,'') == ''
col_value = ''
# Print Column
this.text col_value, @carriage.x, @carriage.y,
width: column_options.width
align: column_options.align
table: ( x, y, data = [], cols_definition, options ) ->
# Update the current position
if x? or y?
@tx = x or @tx
@ty = y or @ty
# Assign options and data to instance
## Rows
@data = data
## Cols
@cols_definition = cols_definition if cols_definition?
## Other Options
@options extends options
# Setup Carriage
@_initCarriage()
# Build Table Header
@_theader()
# Build Table Body
@_tbody()
| true | # Add table support
#
# doc.table(20, 20,
# [
# {
# name: 'PI:NAME:<NAME>END_PI',
# amount: '$0.00'
# },
# {
# name: 'PI:NAME:<NAME>END_PI',
# amount: '$0.00'
# }
# ],
# {
# name: {
# label: 'name',
# width: 100
# },
# amount: {
# label: 'amount',
# width: 100
# }
# }
# )
module.exports =
initTable: ->
# Current coordinates
@tx = 0
@ty = 0
# Track new line Y
@_newLineY = 0
# Cotain row data
@data = []
@options = {
new_page: {} # New page table position
}
# Carriage for printing each table element in it's place
@carriage = {
x: @tx,
y: @ty
}
# Contain cols cols definition
@cols_definition = {}
return this
# Set carriage for first and new page position
_initCarriage: ( newPage = false ) ->
if newPage
@addPage()
@carriage = {
x: @tx,
y: @currentLineHeight(true)
}
@_newLineY = 0
else
@carriage = {
x: @tx,
y: @ty
}
# Indent carriage
_indent: ( indent ) ->
@carriage.x += indent
# Keep current col next line position
# if it's bigger than previous col
if @y > @_newLineY
@_newLineY = @y
# Move carriage to new line
_return: () ->
# New Page
# TODO: Fix issue when mutiline col is at the end of page
if ( @_newLineY + @currentLineHeight(true)*2 ) > this.page.height
@_initCarriage(true)
# Normal Return
else
@carriage.y = @_newLineY
@carriage.x = @tx
_theader: () ->
# Loop Col Definitions
for id, col of @cols_definition
added_col = this.text col.label, @carriage.x, @carriage.y,
width: col.width
align: col.align
@_indent col.width
@_return()
_tbody: () ->
@_rows @data
_rows: ( data ) ->
# Loop Rows
for row in data
@_row row
@_return()
_row: ( row ) ->
# Loop Col Definitions
for id, column_options of @cols_definition
@_col row[id], column_options
@_indent column_options.width
_col: ( value, column_options ) ->
# Get col static value
col_value = value || column_options.value || ''
# Prevent white space which is causing issues in Acrobat Reader
if String(col_value).replace(/^\s+|\s+$/g,'') == ''
col_value = ''
# Print Column
this.text col_value, @carriage.x, @carriage.y,
width: column_options.width
align: column_options.align
table: ( x, y, data = [], cols_definition, options ) ->
# Update the current position
if x? or y?
@tx = x or @tx
@ty = y or @ty
# Assign options and data to instance
## Rows
@data = data
## Cols
@cols_definition = cols_definition if cols_definition?
## Other Options
@options extends options
# Setup Carriage
@_initCarriage()
# Build Table Header
@_theader()
# Build Table Body
@_tbody()
|
[
{
"context": "ame : jQuery DragDrop Draggable\n# Author : Steven Luscher, https://twitter.com/steveluscher\n# Version : 0",
"end": 70,
"score": 0.9999114274978638,
"start": 56,
"tag": "NAME",
"value": "Steven Luscher"
},
{
"context": "# Author : Steven Luscher, https://t... | src/draggable.coffee | steveluscher/jquery.dragdrop | 3 | #
# Name : jQuery DragDrop Draggable
# Author : Steven Luscher, https://twitter.com/steveluscher
# Version : 0.0.1-dev
# Repo : https://github.com/steveluscher/jquery.dragdrop
# Donations : http://lakefieldmusic.com
#
jQuery ->
class jQuery.draggable extends jQuery.dragdrop
vendors = ["ms", "moz", "webkit", "o"]
getCamelizedVendor = (vendor) ->
if vendor is 'webkit' then 'WebKit'
else vendor.charAt(0).toUpperCase() + vendor.slice(1)
#
# requestAnimationFrame polyfill
#
implementRequestAnimationFramePolyfill =
# http://paulirish.com/2011/requestanimationframe-for-smart-animating/
# http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
# requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
# MIT license
->
lastTime = 0
for vendor in vendors
window.requestAnimationFrame ||= window[vendor + "RequestAnimationFrame"]
window.cancelAnimationFrame ||= window[vendor + "CancelAnimationFrame"] or window[vendor + "CancelRequestAnimationFrame"]
break if window.requestAnimationFrame and window.cancelAnimationFrame
unless window.requestAnimationFrame
window.requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
id = window.setTimeout(->
callback currTime + timeToCall
, timeToCall)
lastTime = currTime + timeToCall
id
unless window.cancelAnimationFrame
window.cancelAnimationFrame = (id) ->
clearTimeout id
# Prevent this function from running again
implementRequestAnimationFramePolyfill = -> # noop
#
# convertPoint polyfill
#
implementConvertPointPolyfill = ->
for vendor in vendors
window.convertPointFromPageToNode ||= window[vendor + "ConvertPointFromPageToNode"]
window.convertPointFromNodeToPage ||= window[vendor + "ConvertPointFromNodeToPage"]
window.Point ||= window[getCamelizedVendor(vendor) + "Point"]
break if window.convertPointFromPageToNode and window.convertPointFromNodeToPage and window.Point
unless window.Point
# TODO: Implement Point() polyfill'
throw '[jQuery DragDrop] TODO: Implement Point() polyfill'
unless window.convertPointFromPageToNode
# TODO: Implement convertPointFromPageToNode() polyfill
throw '[jQuery DragDrop] TODO: Implement convertPointFromPageToNode() polyfill'
unless window.convertPointFromNodeToPage
# TODO: Implement convertPointFromNodeToPage() polyfill
throw '[jQuery DragDrop] TODO: Implement convertPointFromNodeToPage() polyfill'
# Prevent this function from running again
implementConvertPointPolyfill = -> #noop
#
# Config
#
defaults:
# Applied when the draggable is initialized
draggableClass: 'ui-draggable'
# Applied when a draggable is in mid-drag
draggingClass: 'ui-draggable-dragging'
# Helper options:
# * original: drag the actual element
# * clone: stick a copy of the element to the mouse
# * ($draggable, e) ->: stick the return value of this function to the mouse; must return something that produces a DOM element when run through jQuery
helper: 'original'
# Stack options:
# * selector string: elements that match this selector are members of the stack
# * ($draggable, e) ->: a function that returns a jQuery collection, or a collection of DOM elements
stack: false
# Containment options:
# * an array of coordinates: a bounding box, relative to the page, in the form [x1, y1, x2, y2]
# * ‘parent’: bound the draggable helper to the draggable's parent element
# * ‘document’: bound the draggable helper to the document element
# * ‘window’: bound the draggable helper to the viewport
# * selector string: bound the draggable helper to the first element matched by a selector
# * element: a jQuery object, or a DOM element
containment: false
# Cursor anchor point options:
# * { top: …, right: …, bottom: …, left: … }: an object specifying a waypoint from a draggable's edge, the nearest of which should snap to the cursor when the draggable is dragged
cursorAt: false
# Distance option:
# * The distance in pixels that the mouse needs to move before drag is initiated
distance: false
#
# Initialization
#
constructor: (element, @options = {}) ->
super
# Lazily implement a requestAnimationFrame polyfill
implementRequestAnimationFramePolyfill()
# jQuery version of DOM element attached to the plugin
@$element = $ element
@$element
# Attach the element event handlers
.on
mousedown: @handleElementMouseDown
click: @handleElementClick
# Mark this element as draggable with a class
.addClass(@getConfig().draggableClass)
# Make the plugin chainable
this
setupElement: ->
config = @getConfig()
# Position the draggable relative if it's currently statically positioned
@$element.css(position: 'relative') if config.helper is 'original' and @$element.css('position') is 'static'
# Bind any supplied callbacks to this plugin
for callbackName in ['start', 'drag', 'stop']
config[callbackName] = config[callbackName].bind(this) if typeof config[callbackName] is 'function'
# Done!
@setupPerformed = true
#
# Mouse events
#
handleElementMouseDown: (e) =>
# If another draggable received this mousedown before we did, bail.
return if e.originalEvent.jQueryDragdropAlreadyHandled is true
isLeftButton = e.which is 1
return unless isLeftButton # Left clicks only, please
@cancelAnyScheduledDrag()
# Until told otherwise, the interaction started by this mousedown should not cancel any subsequent click event
@shouldCancelClick = false
# Bail if a canceling agent has been clicked on
return if @isCancelingAgent(e.target)
# Bail if this is not a valid handle
return unless @isValidHandle(e.target)
# Lazily implement a set of coordinate conversion polyfills
implementConvertPointPolyfill()
# Set a flag on the event. Any draggables that contain this one will check for this flag. If they find it, they will ignore the mousedown
e.originalEvent.jQueryDragdropAlreadyHandled = true
$(document.body).one 'mousedown', (e) ->
# Prevent the default mousedown event on the body; This disables text selection.
e.preventDefault()
# Since we've prevented the default action, we have to blur the active element manually, unless it's the body (silly Internet Explorer)
# https://github.com/jquery/jquery-ui/commit/fcd1cafac8afe3a947676ec018e844eeada5b9de#commitcomment-3956626
activeElement = $(document.activeElement)
activeElement.blur() unless activeElement.is(this)
# Store the mousedown event that started this drag
@mousedownEvent = e
# Start to listen for mouse events on the document
$(document).on
mousemove: @handleDocumentMouseMove
mouseup: @handleDocumentMouseUp
handleDocumentMouseMove: (e) =>
if @dragStarted
# Trigger the drag event
@handleDrag(e)
else
thresholdDistance = @getConfig().distance
if thresholdDistance?
# Find the actual distance travelled by the mouse
deltaX = e.clientX - @mousedownEvent.clientX
deltaY = e.clientY - @mousedownEvent.clientY
distanceMoved = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2))
# Prevent the drag start if the distance moved is less than the threshold distance
return true if distanceMoved < thresholdDistance
# Trigger the start event
@handleDragStart(e)
if @dragStarted
# Trigger the drag event immediately
@handleDrag(e, true)
# Broadcast to interested subscribers that this droppable is now in the air
@broadcast('start', e)
handleDocumentMouseUp: (e) =>
isLeftButton = e.which is 1
return unless isLeftButton # Left clicks only, please
# Trigger the stop event
@handleDragStop(e)
handleElementClick: (e) =>
# Clicks should be cancelled if the last mousedown/mouseup interaction resulted in a drag
if @shouldCancelClick
# Cancel the click
e.stopImmediatePropagation()
false
#
# Draggable events
#
handleDragStart: (e) ->
# Lazily perform setup on the element
@setupElement() unless @setupPerformed
# Will we use the original element as the helper, or will we synthesize a new one?
helperConfig = @getConfig().helper
helperIsSynthesized = helperConfig isnt 'original'
# Get (or synthesize temporarily) a placeholder for the drag helper
helperPlaceholder =
if helperIsSynthesized then $('<div style="height: 0; width: 0; visibility: none">').appendTo('body')
else @$element # Use the element itself
# Store the helper's parent; we will use it to map between the page coordinate space and the helper's parent coordinate space
@parent = if helperIsSynthesized
# Go to the target attachment point of the syntheized helper, and search up the DOM for a parent
@getOffsetParentOrTransformedParent(helperPlaceholder)
else
# Start from the original element, and search up the DOM for a parent
@getOffsetParentOrTransformedParent(@$element)
# Thanks, drag helper placeholder; you can go now
helperPlaceholder.remove() if helperIsSynthesized
# Should we calculate the helper's offset, or simply read its 'top' and 'left' CSS properties?
shouldCalculateOffset =
# Always calculate the offset if a synthesized helper is involved
helperIsSynthesized or
# …or if the original element behaves as though it is absolutely positioned, but has no explicit top or left
(@isAbsoluteish(@$element) and @isPositionedImplicitly(@$element))
# Store the start offset of the draggable, with respect to the page
@elementStartPageOffset = convertPointFromNodeToPage @$element.get(0), new Point(0, 0)
@helperStartPosition = if shouldCalculateOffset
elementPreTransformStartPageOffset = if not helperIsSynthesized and @isTransformed(@$element.get(0))
# Save the element's current transform
savedTransform = @$element.css('transform')
# Disable the transform before calculating the element's position
@$element.css('transform', 'none')
# Get the element's pre-transform offset, with respect to the page
preTransformOffset = convertPointFromNodeToPage @$element.get(0), new Point(0, 0)
# Restore the transform
@$element.css('transform', savedTransform)
# Store the pre-transform offset
preTransformOffset
else
@elementStartPageOffset
# Convert between the offset with respect to the page, and one with respect to its offset or transformed parent's coordinate system
startPosition = convertPointFromPageToNode @parent, elementPreTransformStartPageOffset
if @isTransformed(@parent)
# Apply the scroll offset of the element's transformed parent
startPosition.x += @parent.scrollLeft
startPosition.y += @parent.scrollTop
# Store the result
startPosition
else
# Store the start position of the element with respect to its location in the document flow
new Point @getCSSLeft(@$element), @getCSSTop(@$element)
if cursorAtConfig = @getConfig().cursorAt
# Where is the cursor, in node coordinates?
cursorNodeOffset = convertPointFromPageToNode @$element.get(0), new Point(@mousedownEvent.clientX, @mousedownEvent.clientY)
# What are the cursor anchors' offsets in node coordinates?
leftAnchorNodeOffset = cursorAtConfig.left
rightAnchorNodeOffset = @$element.width() - cursorAtConfig.right if cursorAtConfig.right?
topAnchorNodeOffset = cursorAtConfig.top
bottomAnchorNodeOffset = @$element.height() - cursorAtConfig.bottom if cursorAtConfig.bottom?
# Choose the anchor nearest the cursor
horizontalAnchorOffset = if leftAnchorNodeOffset? and rightAnchorNodeOffset?
if Math.abs(cursorNodeOffset.x - leftAnchorNodeOffset) < Math.abs(cursorNodeOffset.x - rightAnchorNodeOffset)
leftAnchorNodeOffset
else
rightAnchorNodeOffset
else
leftAnchorNodeOffset or rightAnchorNodeOffset or cursorNodeOffset.x
verticalAnchorOffset = if topAnchorNodeOffset? and bottomAnchorNodeOffset?
if Math.abs(cursorNodeOffset.y - topAnchorNodeOffset) < Math.abs(cursorNodeOffset.y - bottomAnchorNodeOffset)
topAnchorNodeOffset
else
bottomAnchorNodeOffset
else
topAnchorNodeOffset or bottomAnchorNodeOffset or cursorNodeOffset.y
# Calculate the point to which the mouse should be anchored
mouseAnchorPageOffset = convertPointFromNodeToPage @$element.get(0), new Point(horizontalAnchorOffset , verticalAnchorOffset)
# Calculate the delta between where the mouse is and where we would like it to appear
delta =
left: @mousedownEvent.clientX - mouseAnchorPageOffset.x
top: @mousedownEvent.clientY - mouseAnchorPageOffset.y
# Translate the element to place it under the cursor at the desired anchor point
@helperStartPosition.x += delta.left
@helperStartPosition.y += delta.top
@elementStartPageOffset.x += delta.left
@elementStartPageOffset.y += delta.top
# Compute the event metadata
startPosition = @pointToPosition @helperStartPosition
startOffset = @pointToPosition @elementStartPageOffset
eventMetadata = @getEventMetadata(startPosition, startOffset)
# Synthesize a new event to represent this drag start
dragStartEvent = @synthesizeEvent('dragstart', e)
# Call any user-supplied drag callback; cancel the start if it returns false
if @getConfig().start?(dragStartEvent, eventMetadata) is false
@handleDragStop(e)
return
@cancelAnyScheduledDrag()
# Save the original value of the pointer-events CSS property
@originalPointerEventsPropertyValue = @$element.css('pointerEvents')
# Configure the drag helper
@$helper =
if helperConfig is 'clone' then @synthesizeHelperByCloning @$element
else if typeof helperConfig is 'function' then @synthesizeHelperUsingFactory helperConfig, e
else @$element # Use the element itself
@$helper
# Apply the dragging class
.addClass(@getConfig().draggingClass)
# Kill pointer events while in mid-drag
.css(pointerEvents: 'none')
if helperIsSynthesized
@$helper
# Append the helper to the body
.appendTo('body')
@moveHelperToTopOfStack(stackConfig, e) if not helperIsSynthesized and stackConfig = @getConfig().stack
# Cache the helper's bounds
@bounds = @calculateContainmentBounds() unless @getConfig().containment is false
# Map the mouse coordinates into the helper's coordinate space
{
x: @mousedownEvent.LocalX
y: @mousedownEvent.LocalY
} = convertPointFromPageToNode @parent, new Point(@mousedownEvent.pageX, @mousedownEvent.pageY)
# Mark the drag as having started
@dragStarted = true
# Store a reference to this droppable in the class
jQuery.draggable.draggableAloft = @
# Trigger the drag start event on this draggable's element
@$element.trigger(dragStartEvent, eventMetadata)
handleDrag: (e, immediate = false) ->
dragHandler = =>
# Map the mouse coordinates into the element's coordinate space
localMousePosition = convertPointFromPageToNode @parent, new Point(e.pageX, e.pageY)
# How far has the object moved from its original position?
delta =
x: localMousePosition.x - @mousedownEvent.LocalX
y: localMousePosition.y - @mousedownEvent.LocalY
# Calculate the helper's target position
targetPosition =
left: @helperStartPosition.x + delta.x
top: @helperStartPosition.y + delta.y
# Calculate the target offset
targetOffset =
left: @elementStartPageOffset.x + (e.pageX - @mousedownEvent.pageX)
top: @elementStartPageOffset.y + (e.pageY - @mousedownEvent.pageY)
if @bounds
# Store the helper's original position in case we need to move it back
helperOriginalPosition =
top: @$helper.css('top')
left: @$helper.css('left')
# Move the drag helper into its candidate position
@$helper.css targetPosition
# Get the page-relative bounds of the drag helper in its candidate position
pageRelativeHelperBoundsWithMargin = @getPageRelativeBoundingBox @$helper, [
0 # Top
@helperSize.width # Right
@helperSize.height # Bottom
0 # Left
]
# Calculate the number of pixels the drag delper overflows the containment boundary
overflowTop = @bounds[0] - pageRelativeHelperBoundsWithMargin[0]
overflowRight = pageRelativeHelperBoundsWithMargin[1] - @bounds[1]
overflowBottom = pageRelativeHelperBoundsWithMargin[2] - @bounds[2]
overflowLeft = @bounds[3] - pageRelativeHelperBoundsWithMargin[3]
if overflowLeft > 0 or overflowRight > 0
# What's the target vertical overlap?
targetOverlap = Math.max 0, (overflowLeft + overflowRight) / 2
# What's the adjustment to get there?
pageRelativeXAdjustment = if overflowLeft > overflowRight
overflowLeft - targetOverlap
else
targetOverlap - overflowRight
if overflowTop > 0 or overflowBottom > 0
# What's the target horizontal overlap?
targetOverlap = Math.max 0, (overflowTop + overflowBottom) / 2
# What's the adjustment to get there?
pageRelativeYAdjustment = if overflowTop > overflowBottom
overflowTop - targetOverlap
else
targetOverlap - overflowBottom
if pageRelativeXAdjustment or pageRelativeYAdjustment
# Adjust the drag helper's target offset
targetOffset.left += pageRelativeXAdjustment if pageRelativeXAdjustment
targetOffset.top += pageRelativeYAdjustment if pageRelativeYAdjustment
# Adjust the drag helper's target position
adjustedLocalMousePosition = convertPointFromPageToNode @parent, new Point(e.pageX + (pageRelativeXAdjustment or 0), e.pageY + (pageRelativeYAdjustment or 0))
targetPosition.left += adjustedLocalMousePosition.x - localMousePosition.x
targetPosition.top += adjustedLocalMousePosition.y - localMousePosition.y
else
helperPositionIsFinal = true
# Compute the event metadata
eventMetadata = @getEventMetadata(targetPosition, targetOffset)
# Synthesize a new event to represent this drag
dragEvent = @synthesizeEvent('drag', e)
# Call any user-supplied drag callback; cancel the drag if it returns false
if @getConfig().drag?(dragEvent, eventMetadata) is false
@$helper.css helperOriginalPosition if helperOriginalPosition # Put the helper back where you found it
@handleDragStop(e)
return
# Move the helper
@$helper.css eventMetadata.position unless helperPositionIsFinal
# Trigger the drag event on this draggable's element
@$element.trigger(dragEvent, eventMetadata)
if immediate
# Call the drag handler right away
dragHandler()
else
# Schedule the drag handler to be called when the next frame is about to be drawn
@scheduleDrag dragHandler
handleDragStop: (e) ->
@cancelAnyScheduledDrag()
# Stop listening for mouse events on the document
$(document).off
mousemove: @handleMouseMove
mouseup: @handleMouseUp
if @dragStarted
# The draggable is no longer aloft
delete jQuery.draggable.draggableAloft
delete jQuery.draggable.latestEvent
# Lest a click event occur before cleanup is called, decide whether it should be permitted or not
@shouldCancelClick = !!@dragStarted
# Synthesize a new event to represent this drag start
dragStopEvent = @synthesizeEvent('dragstop', e)
# Compute the event metadata
eventMetadata = @getEventMetadata()
# Call any user-supplied stop callback
@getConfig().stop?(dragStopEvent, eventMetadata)
# Trigger the drag stop on this draggable's element
@$element.trigger(dragStopEvent, eventMetadata)
# Broadcast to interested subscribers that this droppable has been dropped
@broadcast('stop', e)
if @getConfig().helper is 'original'
# Remove the dragging class
@$helper.removeClass @getConfig().draggingClass
else
# Destroy the helper
@$helper.remove()
# Trigger the click event on the original element
@$element.trigger('click', e)
# Restore the original value of the pointer-events property
@$element.css(pointerEvents: @originalPointerEventsPropertyValue)
# Clean up
@cleanUp()
#
# Validators
#
isAbsoluteish: (element) ->
/fixed|absolute/.test $(element).css('position')
isPositionedImplicitly: (element) ->
$element = $(element)
return true if $element.css('top') is 'auto' and $element.css('bottom') is 'auto'
return true if $element.css('left') is 'auto' and $element.css('right') is 'auto'
isCancelingAgent: (element) ->
if @getConfig().cancel
# Is this element the canceling agent itself, or a descendant of the canceling agent?
!!$(element).closest(@getConfig().cancel).length
else
# No canceling agent was specified; don't cancel
false
isValidHandle: (element) ->
if @getConfig().handle
# Is this element the handle itself, or a descendant of the handle?
!!$(element).closest(@getConfig().handle).length
else
# No handle was specified; anything is fair game
true
isTransformed: (element) ->
getTransformMatrixString(element) isnt 'none'
#
# Helpers
#
broadcast: (type, originalEvent) ->
# Synthesize a new event with this type
event = @synthesizeEvent(type, originalEvent)
# Store the event in the class; droppables instantiated after this draggable became aloft might be interested in it
jQuery.draggable.latestEvent = event
# Broadcast!
$(jQuery.draggable::).trigger(event, @)
getPageRelativeBoundingBox: (element, elementEdges) ->
xCoords = []
yCoords = []
# Store an array of element-relative coordinates
elementCoords = [
[elementEdges[3], elementEdges[0]] # Top-left corner
[elementEdges[1], elementEdges[0]] # Top-right corner
[elementEdges[1], elementEdges[2]] # Bottom-right corner
[elementEdges[3], elementEdges[2]] # Bottom-left corner
]
# Convert the coordinates to page-relative ones
for coord in elementCoords
p = convertPointFromNodeToPage(element.get(0), new Point(coord[0], coord[1]))
xCoords.push p.x
yCoords.push p.y
# Calculate the page-relative bounding box
[
Math.min.apply this, yCoords
Math.max.apply this, xCoords
Math.max.apply this, yCoords
Math.min.apply this, xCoords
]
calculateContainmentBounds: ->
containmentConfig = @getConfig().containment
# Get the page-relative bounds of the container
pageRelativeContainmentBounds = if @isArray containmentConfig
# Clone the config; use it as-is
containmentConfig.slice(0)
else
# Get the container
container =
switch containmentConfig
when 'parent' then @$element.parent()
when 'window' then $(window)
when 'document' then $(document.documentElement)
else $(containmentConfig)
if container.length
if $(window).is(container)
# Get the page-relative edges of the window
windowLeftEdge = container.scrollLeft()
windowTopEdge = container.scrollTop()
# Store the viewport's page-relative bounding box
[
windowLeftEdge # Top
windowLeftEdge + container.width() # Right
windowTopEdge + container.height() # Bottom
windowLeftEdge # Left
]
else
# Get the container's size
containerWidth = container.width()
containerHeight = container.height()
# Get the container's padding
containerTopPadding = parseFloat(container.css('paddingTop')) or 0
containerLeftPadding = parseFloat(container.css('paddingLeft')) or 0
# Get the container's border width
containerTopBorder = parseFloat(container.css('borderTopWidth')) or 0
containerLeftBorder = parseFloat(container.css('borderLeftWidth')) or 0
# Calculate the edges
topEdge = containerTopPadding + containerTopBorder
bottomEdge = topEdge + containerHeight
leftEdge = containerLeftPadding + containerLeftBorder
rightEdge = leftEdge + containerWidth
# Store the container's page-relative bounding box
@getPageRelativeBoundingBox container, [
topEdge
rightEdge
bottomEdge
leftEdge
]
return unless pageRelativeContainmentBounds
# Get (and cache) the margins of the drag helper
@helperMargins =
top: parseFloat(@$helper.css('marginTop')) or 0
right: parseFloat(@$helper.css('marginRight')) or 0
bottom: parseFloat(@$helper.css('marginBottom')) or 0
left: parseFloat(@$helper.css('marginLeft')) or 0
# Get (and cache) the size of the drag helper
@helperSize =
height: @$helper.outerHeight()
width: @$helper.outerWidth()
if @helperMargins.top or @helperMargins.right or @helperMargins.bottom or @helperMargins.left # …we must adjust the size of the containment boundary
# Get the page-relative bounds of the drag helper
pageRelativeHelperBounds = @getPageRelativeBoundingBox @$helper, [
0 # Top
@helperSize.width # Right
@helperSize.height # Bottom
0 # Left
]
# Get the page-relative bounds of the drag helper including its margins
pageRelativeHelperBoundsWithMargin = @getPageRelativeBoundingBox @$helper, [
-@helperMargins.top # Top
@helperSize.width + @helperMargins.right # Right
@helperSize.height + @helperMargins.bottom # Bottom
-@helperMargins.left # Left
]
# Adjust the containment bounds by the difference between those two bounding boxes
pageRelativeContainmentBounds[0] -= pageRelativeHelperBoundsWithMargin[0] - pageRelativeHelperBounds[0]
pageRelativeContainmentBounds[1] -= pageRelativeHelperBoundsWithMargin[1] - pageRelativeHelperBounds[1]
pageRelativeContainmentBounds[2] -= pageRelativeHelperBoundsWithMargin[2] - pageRelativeHelperBounds[2]
pageRelativeContainmentBounds[3] -= pageRelativeHelperBoundsWithMargin[3] - pageRelativeHelperBounds[3]
# If the containment bounding box has collapsed, expand it to a midpoint between the collapsed edges
if pageRelativeContainmentBounds[0] > pageRelativeContainmentBounds[2]
pageRelativeContainmentBounds[0] =
pageRelativeContainmentBounds[2] =
pageRelativeContainmentBounds[2] + (pageRelativeContainmentBounds[0] - pageRelativeContainmentBounds[2]) / 2
if pageRelativeContainmentBounds[1] < pageRelativeContainmentBounds[3]
pageRelativeContainmentBounds[1] =
pageRelativeContainmentBounds[3] =
pageRelativeContainmentBounds[1] + (pageRelativeContainmentBounds[3] - pageRelativeContainmentBounds[1]) / 2
# Return the page-relative bounding box
pageRelativeContainmentBounds
cancelAnyScheduledDrag: ->
return unless @scheduledDragId
cancelAnimationFrame(@scheduledDragId)
@scheduledDragId = null
getTransformMatrixString = (element) ->
# Get the computed styles
return 'none' unless computedStyle = getComputedStyle(element)
# Return the matrix string
computedStyle.WebkitTransform or computedStyle.msTransform or computedStyle.MozTransform or computedStyle.OTransform or 'none'
getOffsetParentOrTransformedParent: (element) ->
$element = $(element)
# If we don't find anything, we'll return the document element
foundAncestor = document.documentElement
# Crawl up the DOM, starting at this element's parent
for ancestor in $element.parents().get()
# Look for an ancestor of element that is either positioned, or transformed
if $(ancestor).css('position') isnt 'static' or @isTransformed(ancestor)
foundAncestor = ancestor
break
# Return the ancestor we found
foundAncestor
scheduleDrag: (invocation) ->
@cancelAnyScheduledDrag()
@scheduledDragId = requestAnimationFrame =>
invocation()
@scheduledDragId = null
synthesizeHelperByCloning: (element) ->
# Clone the original element
helper = element.clone()
# Remove the ID attribute
helper.removeAttr('id')
# Post process the helper element
@prepareHelper helper
synthesizeHelperUsingFactory: (factory, e) ->
# Run the factory
output = factory @$element, e
# Process the output with jQuery
helper = $(output).first()
throw new Error '[jQuery DragDrop – Draggable] Helper factory methods must produce a jQuery object, a DOM Element, or a string of HTML' unless helper.length
# Post process the helper element
@prepareHelper helper.first()
moveHelperToTopOfStack: (stackConfig, e) ->
# Get the members of the stack
$stackMembers = $(stackConfig?(@$helper, e) or stackConfig)
return unless $stackMembers.length
# Sort the stack members by z-index
sortedStackMembers = $stackMembers.get().sort (a, b) ->
(parseInt($(b).css('zIndex'), 10) or 0) - (parseInt($(a).css('zIndex'), 10) or 0)
return if @$helper.is(topStackMember = sortedStackMembers[0])
# Get the top element's index
topIndex = $(topStackMember).css('zIndex')
# Move this helper to the top of the stack
@$helper.css('zIndex', parseInt(topIndex, 10) + 1)
positionToPoint: (position) ->
new Point position.left, position.top
pointToPosition: (point) ->
left: point.x
top: point.y
prepareHelper: ($helper) ->
css = {}
# Position the helper absolutely, unless it already is
css.position = 'absolute' unless $helper.css('position') is 'absolute'
# Move the clone to the position of the original
css.left = @elementStartPageOffset.x
css.top = @elementStartPageOffset.y
# Style it
$helper.css(css)
cleanUp: ->
# Clean up
@dragStarted = false
delete @$helper
delete @bounds
delete @elementStartPageOffset
delete @helperMargins
delete @helperSize
delete @helperStartPosition
delete @mousedownEvent
delete @originalPointerEventsPropertyValue
delete @parent
$.fn.draggable = (options) ->
this.each ->
unless $(this).data('draggable')?
plugin = new $.draggable(this, options)
$(this).data('draggable', plugin)
| 56162 | #
# Name : jQuery DragDrop Draggable
# Author : <NAME>, https://twitter.com/steveluscher
# Version : 0.0.1-dev
# Repo : https://github.com/steveluscher/jquery.dragdrop
# Donations : http://lakefieldmusic.com
#
jQuery ->
class jQuery.draggable extends jQuery.dragdrop
vendors = ["ms", "moz", "webkit", "o"]
getCamelizedVendor = (vendor) ->
if vendor is 'webkit' then 'WebKit'
else vendor.charAt(0).toUpperCase() + vendor.slice(1)
#
# requestAnimationFrame polyfill
#
implementRequestAnimationFramePolyfill =
# http://paulirish.com/2011/requestanimationframe-for-smart-animating/
# http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
# requestAnimationFrame polyfill by <NAME>. fixes from <NAME> and <NAME>
# MIT license
->
lastTime = 0
for vendor in vendors
window.requestAnimationFrame ||= window[vendor + "RequestAnimationFrame"]
window.cancelAnimationFrame ||= window[vendor + "CancelAnimationFrame"] or window[vendor + "CancelRequestAnimationFrame"]
break if window.requestAnimationFrame and window.cancelAnimationFrame
unless window.requestAnimationFrame
window.requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
id = window.setTimeout(->
callback currTime + timeToCall
, timeToCall)
lastTime = currTime + timeToCall
id
unless window.cancelAnimationFrame
window.cancelAnimationFrame = (id) ->
clearTimeout id
# Prevent this function from running again
implementRequestAnimationFramePolyfill = -> # noop
#
# convertPoint polyfill
#
implementConvertPointPolyfill = ->
for vendor in vendors
window.convertPointFromPageToNode ||= window[vendor + "ConvertPointFromPageToNode"]
window.convertPointFromNodeToPage ||= window[vendor + "ConvertPointFromNodeToPage"]
window.Point ||= window[getCamelizedVendor(vendor) + "Point"]
break if window.convertPointFromPageToNode and window.convertPointFromNodeToPage and window.Point
unless window.Point
# TODO: Implement Point() polyfill'
throw '[jQuery DragDrop] TODO: Implement Point() polyfill'
unless window.convertPointFromPageToNode
# TODO: Implement convertPointFromPageToNode() polyfill
throw '[jQuery DragDrop] TODO: Implement convertPointFromPageToNode() polyfill'
unless window.convertPointFromNodeToPage
# TODO: Implement convertPointFromNodeToPage() polyfill
throw '[jQuery DragDrop] TODO: Implement convertPointFromNodeToPage() polyfill'
# Prevent this function from running again
implementConvertPointPolyfill = -> #noop
#
# Config
#
defaults:
# Applied when the draggable is initialized
draggableClass: 'ui-draggable'
# Applied when a draggable is in mid-drag
draggingClass: 'ui-draggable-dragging'
# Helper options:
# * original: drag the actual element
# * clone: stick a copy of the element to the mouse
# * ($draggable, e) ->: stick the return value of this function to the mouse; must return something that produces a DOM element when run through jQuery
helper: 'original'
# Stack options:
# * selector string: elements that match this selector are members of the stack
# * ($draggable, e) ->: a function that returns a jQuery collection, or a collection of DOM elements
stack: false
# Containment options:
# * an array of coordinates: a bounding box, relative to the page, in the form [x1, y1, x2, y2]
# * ‘parent’: bound the draggable helper to the draggable's parent element
# * ‘document’: bound the draggable helper to the document element
# * ‘window’: bound the draggable helper to the viewport
# * selector string: bound the draggable helper to the first element matched by a selector
# * element: a jQuery object, or a DOM element
containment: false
# Cursor anchor point options:
# * { top: …, right: …, bottom: …, left: … }: an object specifying a waypoint from a draggable's edge, the nearest of which should snap to the cursor when the draggable is dragged
cursorAt: false
# Distance option:
# * The distance in pixels that the mouse needs to move before drag is initiated
distance: false
#
# Initialization
#
constructor: (element, @options = {}) ->
super
# Lazily implement a requestAnimationFrame polyfill
implementRequestAnimationFramePolyfill()
# jQuery version of DOM element attached to the plugin
@$element = $ element
@$element
# Attach the element event handlers
.on
mousedown: @handleElementMouseDown
click: @handleElementClick
# Mark this element as draggable with a class
.addClass(@getConfig().draggableClass)
# Make the plugin chainable
this
setupElement: ->
config = @getConfig()
# Position the draggable relative if it's currently statically positioned
@$element.css(position: 'relative') if config.helper is 'original' and @$element.css('position') is 'static'
# Bind any supplied callbacks to this plugin
for callbackName in ['start', 'drag', 'stop']
config[callbackName] = config[callbackName].bind(this) if typeof config[callbackName] is 'function'
# Done!
@setupPerformed = true
#
# Mouse events
#
handleElementMouseDown: (e) =>
# If another draggable received this mousedown before we did, bail.
return if e.originalEvent.jQueryDragdropAlreadyHandled is true
isLeftButton = e.which is 1
return unless isLeftButton # Left clicks only, please
@cancelAnyScheduledDrag()
# Until told otherwise, the interaction started by this mousedown should not cancel any subsequent click event
@shouldCancelClick = false
# Bail if a canceling agent has been clicked on
return if @isCancelingAgent(e.target)
# Bail if this is not a valid handle
return unless @isValidHandle(e.target)
# Lazily implement a set of coordinate conversion polyfills
implementConvertPointPolyfill()
# Set a flag on the event. Any draggables that contain this one will check for this flag. If they find it, they will ignore the mousedown
e.originalEvent.jQueryDragdropAlreadyHandled = true
$(document.body).one 'mousedown', (e) ->
# Prevent the default mousedown event on the body; This disables text selection.
e.preventDefault()
# Since we've prevented the default action, we have to blur the active element manually, unless it's the body (silly Internet Explorer)
# https://github.com/jquery/jquery-ui/commit/fcd1cafac8afe3a947676ec018e844eeada5b9de#commitcomment-3956626
activeElement = $(document.activeElement)
activeElement.blur() unless activeElement.is(this)
# Store the mousedown event that started this drag
@mousedownEvent = e
# Start to listen for mouse events on the document
$(document).on
mousemove: @handleDocumentMouseMove
mouseup: @handleDocumentMouseUp
handleDocumentMouseMove: (e) =>
if @dragStarted
# Trigger the drag event
@handleDrag(e)
else
thresholdDistance = @getConfig().distance
if thresholdDistance?
# Find the actual distance travelled by the mouse
deltaX = e.clientX - @mousedownEvent.clientX
deltaY = e.clientY - @mousedownEvent.clientY
distanceMoved = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2))
# Prevent the drag start if the distance moved is less than the threshold distance
return true if distanceMoved < thresholdDistance
# Trigger the start event
@handleDragStart(e)
if @dragStarted
# Trigger the drag event immediately
@handleDrag(e, true)
# Broadcast to interested subscribers that this droppable is now in the air
@broadcast('start', e)
handleDocumentMouseUp: (e) =>
isLeftButton = e.which is 1
return unless isLeftButton # Left clicks only, please
# Trigger the stop event
@handleDragStop(e)
handleElementClick: (e) =>
# Clicks should be cancelled if the last mousedown/mouseup interaction resulted in a drag
if @shouldCancelClick
# Cancel the click
e.stopImmediatePropagation()
false
#
# Draggable events
#
handleDragStart: (e) ->
# Lazily perform setup on the element
@setupElement() unless @setupPerformed
# Will we use the original element as the helper, or will we synthesize a new one?
helperConfig = @getConfig().helper
helperIsSynthesized = helperConfig isnt 'original'
# Get (or synthesize temporarily) a placeholder for the drag helper
helperPlaceholder =
if helperIsSynthesized then $('<div style="height: 0; width: 0; visibility: none">').appendTo('body')
else @$element # Use the element itself
# Store the helper's parent; we will use it to map between the page coordinate space and the helper's parent coordinate space
@parent = if helperIsSynthesized
# Go to the target attachment point of the syntheized helper, and search up the DOM for a parent
@getOffsetParentOrTransformedParent(helperPlaceholder)
else
# Start from the original element, and search up the DOM for a parent
@getOffsetParentOrTransformedParent(@$element)
# Thanks, drag helper placeholder; you can go now
helperPlaceholder.remove() if helperIsSynthesized
# Should we calculate the helper's offset, or simply read its 'top' and 'left' CSS properties?
shouldCalculateOffset =
# Always calculate the offset if a synthesized helper is involved
helperIsSynthesized or
# …or if the original element behaves as though it is absolutely positioned, but has no explicit top or left
(@isAbsoluteish(@$element) and @isPositionedImplicitly(@$element))
# Store the start offset of the draggable, with respect to the page
@elementStartPageOffset = convertPointFromNodeToPage @$element.get(0), new Point(0, 0)
@helperStartPosition = if shouldCalculateOffset
elementPreTransformStartPageOffset = if not helperIsSynthesized and @isTransformed(@$element.get(0))
# Save the element's current transform
savedTransform = @$element.css('transform')
# Disable the transform before calculating the element's position
@$element.css('transform', 'none')
# Get the element's pre-transform offset, with respect to the page
preTransformOffset = convertPointFromNodeToPage @$element.get(0), new Point(0, 0)
# Restore the transform
@$element.css('transform', savedTransform)
# Store the pre-transform offset
preTransformOffset
else
@elementStartPageOffset
# Convert between the offset with respect to the page, and one with respect to its offset or transformed parent's coordinate system
startPosition = convertPointFromPageToNode @parent, elementPreTransformStartPageOffset
if @isTransformed(@parent)
# Apply the scroll offset of the element's transformed parent
startPosition.x += @parent.scrollLeft
startPosition.y += @parent.scrollTop
# Store the result
startPosition
else
# Store the start position of the element with respect to its location in the document flow
new Point @getCSSLeft(@$element), @getCSSTop(@$element)
if cursorAtConfig = @getConfig().cursorAt
# Where is the cursor, in node coordinates?
cursorNodeOffset = convertPointFromPageToNode @$element.get(0), new Point(@mousedownEvent.clientX, @mousedownEvent.clientY)
# What are the cursor anchors' offsets in node coordinates?
leftAnchorNodeOffset = cursorAtConfig.left
rightAnchorNodeOffset = @$element.width() - cursorAtConfig.right if cursorAtConfig.right?
topAnchorNodeOffset = cursorAtConfig.top
bottomAnchorNodeOffset = @$element.height() - cursorAtConfig.bottom if cursorAtConfig.bottom?
# Choose the anchor nearest the cursor
horizontalAnchorOffset = if leftAnchorNodeOffset? and rightAnchorNodeOffset?
if Math.abs(cursorNodeOffset.x - leftAnchorNodeOffset) < Math.abs(cursorNodeOffset.x - rightAnchorNodeOffset)
leftAnchorNodeOffset
else
rightAnchorNodeOffset
else
leftAnchorNodeOffset or rightAnchorNodeOffset or cursorNodeOffset.x
verticalAnchorOffset = if topAnchorNodeOffset? and bottomAnchorNodeOffset?
if Math.abs(cursorNodeOffset.y - topAnchorNodeOffset) < Math.abs(cursorNodeOffset.y - bottomAnchorNodeOffset)
topAnchorNodeOffset
else
bottomAnchorNodeOffset
else
topAnchorNodeOffset or bottomAnchorNodeOffset or cursorNodeOffset.y
# Calculate the point to which the mouse should be anchored
mouseAnchorPageOffset = convertPointFromNodeToPage @$element.get(0), new Point(horizontalAnchorOffset , verticalAnchorOffset)
# Calculate the delta between where the mouse is and where we would like it to appear
delta =
left: @mousedownEvent.clientX - mouseAnchorPageOffset.x
top: @mousedownEvent.clientY - mouseAnchorPageOffset.y
# Translate the element to place it under the cursor at the desired anchor point
@helperStartPosition.x += delta.left
@helperStartPosition.y += delta.top
@elementStartPageOffset.x += delta.left
@elementStartPageOffset.y += delta.top
# Compute the event metadata
startPosition = @pointToPosition @helperStartPosition
startOffset = @pointToPosition @elementStartPageOffset
eventMetadata = @getEventMetadata(startPosition, startOffset)
# Synthesize a new event to represent this drag start
dragStartEvent = @synthesizeEvent('dragstart', e)
# Call any user-supplied drag callback; cancel the start if it returns false
if @getConfig().start?(dragStartEvent, eventMetadata) is false
@handleDragStop(e)
return
@cancelAnyScheduledDrag()
# Save the original value of the pointer-events CSS property
@originalPointerEventsPropertyValue = @$element.css('pointerEvents')
# Configure the drag helper
@$helper =
if helperConfig is 'clone' then @synthesizeHelperByCloning @$element
else if typeof helperConfig is 'function' then @synthesizeHelperUsingFactory helperConfig, e
else @$element # Use the element itself
@$helper
# Apply the dragging class
.addClass(@getConfig().draggingClass)
# Kill pointer events while in mid-drag
.css(pointerEvents: 'none')
if helperIsSynthesized
@$helper
# Append the helper to the body
.appendTo('body')
@moveHelperToTopOfStack(stackConfig, e) if not helperIsSynthesized and stackConfig = @getConfig().stack
# Cache the helper's bounds
@bounds = @calculateContainmentBounds() unless @getConfig().containment is false
# Map the mouse coordinates into the helper's coordinate space
{
x: @mousedownEvent.LocalX
y: @mousedownEvent.LocalY
} = convertPointFromPageToNode @parent, new Point(@mousedownEvent.pageX, @mousedownEvent.pageY)
# Mark the drag as having started
@dragStarted = true
# Store a reference to this droppable in the class
jQuery.draggable.draggableAloft = @
# Trigger the drag start event on this draggable's element
@$element.trigger(dragStartEvent, eventMetadata)
handleDrag: (e, immediate = false) ->
dragHandler = =>
# Map the mouse coordinates into the element's coordinate space
localMousePosition = convertPointFromPageToNode @parent, new Point(e.pageX, e.pageY)
# How far has the object moved from its original position?
delta =
x: localMousePosition.x - @mousedownEvent.LocalX
y: localMousePosition.y - @mousedownEvent.LocalY
# Calculate the helper's target position
targetPosition =
left: @helperStartPosition.x + delta.x
top: @helperStartPosition.y + delta.y
# Calculate the target offset
targetOffset =
left: @elementStartPageOffset.x + (e.pageX - @mousedownEvent.pageX)
top: @elementStartPageOffset.y + (e.pageY - @mousedownEvent.pageY)
if @bounds
# Store the helper's original position in case we need to move it back
helperOriginalPosition =
top: @$helper.css('top')
left: @$helper.css('left')
# Move the drag helper into its candidate position
@$helper.css targetPosition
# Get the page-relative bounds of the drag helper in its candidate position
pageRelativeHelperBoundsWithMargin = @getPageRelativeBoundingBox @$helper, [
0 # Top
@helperSize.width # Right
@helperSize.height # Bottom
0 # Left
]
# Calculate the number of pixels the drag delper overflows the containment boundary
overflowTop = @bounds[0] - pageRelativeHelperBoundsWithMargin[0]
overflowRight = pageRelativeHelperBoundsWithMargin[1] - @bounds[1]
overflowBottom = pageRelativeHelperBoundsWithMargin[2] - @bounds[2]
overflowLeft = @bounds[3] - pageRelativeHelperBoundsWithMargin[3]
if overflowLeft > 0 or overflowRight > 0
# What's the target vertical overlap?
targetOverlap = Math.max 0, (overflowLeft + overflowRight) / 2
# What's the adjustment to get there?
pageRelativeXAdjustment = if overflowLeft > overflowRight
overflowLeft - targetOverlap
else
targetOverlap - overflowRight
if overflowTop > 0 or overflowBottom > 0
# What's the target horizontal overlap?
targetOverlap = Math.max 0, (overflowTop + overflowBottom) / 2
# What's the adjustment to get there?
pageRelativeYAdjustment = if overflowTop > overflowBottom
overflowTop - targetOverlap
else
targetOverlap - overflowBottom
if pageRelativeXAdjustment or pageRelativeYAdjustment
# Adjust the drag helper's target offset
targetOffset.left += pageRelativeXAdjustment if pageRelativeXAdjustment
targetOffset.top += pageRelativeYAdjustment if pageRelativeYAdjustment
# Adjust the drag helper's target position
adjustedLocalMousePosition = convertPointFromPageToNode @parent, new Point(e.pageX + (pageRelativeXAdjustment or 0), e.pageY + (pageRelativeYAdjustment or 0))
targetPosition.left += adjustedLocalMousePosition.x - localMousePosition.x
targetPosition.top += adjustedLocalMousePosition.y - localMousePosition.y
else
helperPositionIsFinal = true
# Compute the event metadata
eventMetadata = @getEventMetadata(targetPosition, targetOffset)
# Synthesize a new event to represent this drag
dragEvent = @synthesizeEvent('drag', e)
# Call any user-supplied drag callback; cancel the drag if it returns false
if @getConfig().drag?(dragEvent, eventMetadata) is false
@$helper.css helperOriginalPosition if helperOriginalPosition # Put the helper back where you found it
@handleDragStop(e)
return
# Move the helper
@$helper.css eventMetadata.position unless helperPositionIsFinal
# Trigger the drag event on this draggable's element
@$element.trigger(dragEvent, eventMetadata)
if immediate
# Call the drag handler right away
dragHandler()
else
# Schedule the drag handler to be called when the next frame is about to be drawn
@scheduleDrag dragHandler
handleDragStop: (e) ->
@cancelAnyScheduledDrag()
# Stop listening for mouse events on the document
$(document).off
mousemove: @handleMouseMove
mouseup: @handleMouseUp
if @dragStarted
# The draggable is no longer aloft
delete jQuery.draggable.draggableAloft
delete jQuery.draggable.latestEvent
# Lest a click event occur before cleanup is called, decide whether it should be permitted or not
@shouldCancelClick = !!@dragStarted
# Synthesize a new event to represent this drag start
dragStopEvent = @synthesizeEvent('dragstop', e)
# Compute the event metadata
eventMetadata = @getEventMetadata()
# Call any user-supplied stop callback
@getConfig().stop?(dragStopEvent, eventMetadata)
# Trigger the drag stop on this draggable's element
@$element.trigger(dragStopEvent, eventMetadata)
# Broadcast to interested subscribers that this droppable has been dropped
@broadcast('stop', e)
if @getConfig().helper is 'original'
# Remove the dragging class
@$helper.removeClass @getConfig().draggingClass
else
# Destroy the helper
@$helper.remove()
# Trigger the click event on the original element
@$element.trigger('click', e)
# Restore the original value of the pointer-events property
@$element.css(pointerEvents: @originalPointerEventsPropertyValue)
# Clean up
@cleanUp()
#
# Validators
#
isAbsoluteish: (element) ->
/fixed|absolute/.test $(element).css('position')
isPositionedImplicitly: (element) ->
$element = $(element)
return true if $element.css('top') is 'auto' and $element.css('bottom') is 'auto'
return true if $element.css('left') is 'auto' and $element.css('right') is 'auto'
isCancelingAgent: (element) ->
if @getConfig().cancel
# Is this element the canceling agent itself, or a descendant of the canceling agent?
!!$(element).closest(@getConfig().cancel).length
else
# No canceling agent was specified; don't cancel
false
isValidHandle: (element) ->
if @getConfig().handle
# Is this element the handle itself, or a descendant of the handle?
!!$(element).closest(@getConfig().handle).length
else
# No handle was specified; anything is fair game
true
isTransformed: (element) ->
getTransformMatrixString(element) isnt 'none'
#
# Helpers
#
broadcast: (type, originalEvent) ->
# Synthesize a new event with this type
event = @synthesizeEvent(type, originalEvent)
# Store the event in the class; droppables instantiated after this draggable became aloft might be interested in it
jQuery.draggable.latestEvent = event
# Broadcast!
$(jQuery.draggable::).trigger(event, @)
getPageRelativeBoundingBox: (element, elementEdges) ->
xCoords = []
yCoords = []
# Store an array of element-relative coordinates
elementCoords = [
[elementEdges[3], elementEdges[0]] # Top-left corner
[elementEdges[1], elementEdges[0]] # Top-right corner
[elementEdges[1], elementEdges[2]] # Bottom-right corner
[elementEdges[3], elementEdges[2]] # Bottom-left corner
]
# Convert the coordinates to page-relative ones
for coord in elementCoords
p = convertPointFromNodeToPage(element.get(0), new Point(coord[0], coord[1]))
xCoords.push p.x
yCoords.push p.y
# Calculate the page-relative bounding box
[
Math.min.apply this, yCoords
Math.max.apply this, xCoords
Math.max.apply this, yCoords
Math.min.apply this, xCoords
]
calculateContainmentBounds: ->
containmentConfig = @getConfig().containment
# Get the page-relative bounds of the container
pageRelativeContainmentBounds = if @isArray containmentConfig
# Clone the config; use it as-is
containmentConfig.slice(0)
else
# Get the container
container =
switch containmentConfig
when 'parent' then @$element.parent()
when 'window' then $(window)
when 'document' then $(document.documentElement)
else $(containmentConfig)
if container.length
if $(window).is(container)
# Get the page-relative edges of the window
windowLeftEdge = container.scrollLeft()
windowTopEdge = container.scrollTop()
# Store the viewport's page-relative bounding box
[
windowLeftEdge # Top
windowLeftEdge + container.width() # Right
windowTopEdge + container.height() # Bottom
windowLeftEdge # Left
]
else
# Get the container's size
containerWidth = container.width()
containerHeight = container.height()
# Get the container's padding
containerTopPadding = parseFloat(container.css('paddingTop')) or 0
containerLeftPadding = parseFloat(container.css('paddingLeft')) or 0
# Get the container's border width
containerTopBorder = parseFloat(container.css('borderTopWidth')) or 0
containerLeftBorder = parseFloat(container.css('borderLeftWidth')) or 0
# Calculate the edges
topEdge = containerTopPadding + containerTopBorder
bottomEdge = topEdge + containerHeight
leftEdge = containerLeftPadding + containerLeftBorder
rightEdge = leftEdge + containerWidth
# Store the container's page-relative bounding box
@getPageRelativeBoundingBox container, [
topEdge
rightEdge
bottomEdge
leftEdge
]
return unless pageRelativeContainmentBounds
# Get (and cache) the margins of the drag helper
@helperMargins =
top: parseFloat(@$helper.css('marginTop')) or 0
right: parseFloat(@$helper.css('marginRight')) or 0
bottom: parseFloat(@$helper.css('marginBottom')) or 0
left: parseFloat(@$helper.css('marginLeft')) or 0
# Get (and cache) the size of the drag helper
@helperSize =
height: @$helper.outerHeight()
width: @$helper.outerWidth()
if @helperMargins.top or @helperMargins.right or @helperMargins.bottom or @helperMargins.left # …we must adjust the size of the containment boundary
# Get the page-relative bounds of the drag helper
pageRelativeHelperBounds = @getPageRelativeBoundingBox @$helper, [
0 # Top
@helperSize.width # Right
@helperSize.height # Bottom
0 # Left
]
# Get the page-relative bounds of the drag helper including its margins
pageRelativeHelperBoundsWithMargin = @getPageRelativeBoundingBox @$helper, [
-@helperMargins.top # Top
@helperSize.width + @helperMargins.right # Right
@helperSize.height + @helperMargins.bottom # Bottom
-@helperMargins.left # Left
]
# Adjust the containment bounds by the difference between those two bounding boxes
pageRelativeContainmentBounds[0] -= pageRelativeHelperBoundsWithMargin[0] - pageRelativeHelperBounds[0]
pageRelativeContainmentBounds[1] -= pageRelativeHelperBoundsWithMargin[1] - pageRelativeHelperBounds[1]
pageRelativeContainmentBounds[2] -= pageRelativeHelperBoundsWithMargin[2] - pageRelativeHelperBounds[2]
pageRelativeContainmentBounds[3] -= pageRelativeHelperBoundsWithMargin[3] - pageRelativeHelperBounds[3]
# If the containment bounding box has collapsed, expand it to a midpoint between the collapsed edges
if pageRelativeContainmentBounds[0] > pageRelativeContainmentBounds[2]
pageRelativeContainmentBounds[0] =
pageRelativeContainmentBounds[2] =
pageRelativeContainmentBounds[2] + (pageRelativeContainmentBounds[0] - pageRelativeContainmentBounds[2]) / 2
if pageRelativeContainmentBounds[1] < pageRelativeContainmentBounds[3]
pageRelativeContainmentBounds[1] =
pageRelativeContainmentBounds[3] =
pageRelativeContainmentBounds[1] + (pageRelativeContainmentBounds[3] - pageRelativeContainmentBounds[1]) / 2
# Return the page-relative bounding box
pageRelativeContainmentBounds
cancelAnyScheduledDrag: ->
return unless @scheduledDragId
cancelAnimationFrame(@scheduledDragId)
@scheduledDragId = null
getTransformMatrixString = (element) ->
# Get the computed styles
return 'none' unless computedStyle = getComputedStyle(element)
# Return the matrix string
computedStyle.WebkitTransform or computedStyle.msTransform or computedStyle.MozTransform or computedStyle.OTransform or 'none'
getOffsetParentOrTransformedParent: (element) ->
$element = $(element)
# If we don't find anything, we'll return the document element
foundAncestor = document.documentElement
# Crawl up the DOM, starting at this element's parent
for ancestor in $element.parents().get()
# Look for an ancestor of element that is either positioned, or transformed
if $(ancestor).css('position') isnt 'static' or @isTransformed(ancestor)
foundAncestor = ancestor
break
# Return the ancestor we found
foundAncestor
scheduleDrag: (invocation) ->
@cancelAnyScheduledDrag()
@scheduledDragId = requestAnimationFrame =>
invocation()
@scheduledDragId = null
synthesizeHelperByCloning: (element) ->
# Clone the original element
helper = element.clone()
# Remove the ID attribute
helper.removeAttr('id')
# Post process the helper element
@prepareHelper helper
synthesizeHelperUsingFactory: (factory, e) ->
# Run the factory
output = factory @$element, e
# Process the output with jQuery
helper = $(output).first()
throw new Error '[jQuery DragDrop – Draggable] Helper factory methods must produce a jQuery object, a DOM Element, or a string of HTML' unless helper.length
# Post process the helper element
@prepareHelper helper.first()
moveHelperToTopOfStack: (stackConfig, e) ->
# Get the members of the stack
$stackMembers = $(stackConfig?(@$helper, e) or stackConfig)
return unless $stackMembers.length
# Sort the stack members by z-index
sortedStackMembers = $stackMembers.get().sort (a, b) ->
(parseInt($(b).css('zIndex'), 10) or 0) - (parseInt($(a).css('zIndex'), 10) or 0)
return if @$helper.is(topStackMember = sortedStackMembers[0])
# Get the top element's index
topIndex = $(topStackMember).css('zIndex')
# Move this helper to the top of the stack
@$helper.css('zIndex', parseInt(topIndex, 10) + 1)
positionToPoint: (position) ->
new Point position.left, position.top
pointToPosition: (point) ->
left: point.x
top: point.y
prepareHelper: ($helper) ->
css = {}
# Position the helper absolutely, unless it already is
css.position = 'absolute' unless $helper.css('position') is 'absolute'
# Move the clone to the position of the original
css.left = @elementStartPageOffset.x
css.top = @elementStartPageOffset.y
# Style it
$helper.css(css)
cleanUp: ->
# Clean up
@dragStarted = false
delete @$helper
delete @bounds
delete @elementStartPageOffset
delete @helperMargins
delete @helperSize
delete @helperStartPosition
delete @mousedownEvent
delete @originalPointerEventsPropertyValue
delete @parent
$.fn.draggable = (options) ->
this.each ->
unless $(this).data('draggable')?
plugin = new $.draggable(this, options)
$(this).data('draggable', plugin)
| true | #
# Name : jQuery DragDrop Draggable
# Author : PI:NAME:<NAME>END_PI, https://twitter.com/steveluscher
# Version : 0.0.1-dev
# Repo : https://github.com/steveluscher/jquery.dragdrop
# Donations : http://lakefieldmusic.com
#
jQuery ->
class jQuery.draggable extends jQuery.dragdrop
vendors = ["ms", "moz", "webkit", "o"]
getCamelizedVendor = (vendor) ->
if vendor is 'webkit' then 'WebKit'
else vendor.charAt(0).toUpperCase() + vendor.slice(1)
#
# requestAnimationFrame polyfill
#
implementRequestAnimationFramePolyfill =
# http://paulirish.com/2011/requestanimationframe-for-smart-animating/
# http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
# requestAnimationFrame polyfill by PI:NAME:<NAME>END_PI. fixes from PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
# MIT license
->
lastTime = 0
for vendor in vendors
window.requestAnimationFrame ||= window[vendor + "RequestAnimationFrame"]
window.cancelAnimationFrame ||= window[vendor + "CancelAnimationFrame"] or window[vendor + "CancelRequestAnimationFrame"]
break if window.requestAnimationFrame and window.cancelAnimationFrame
unless window.requestAnimationFrame
window.requestAnimationFrame = (callback, element) ->
currTime = new Date().getTime()
timeToCall = Math.max(0, 16 - (currTime - lastTime))
id = window.setTimeout(->
callback currTime + timeToCall
, timeToCall)
lastTime = currTime + timeToCall
id
unless window.cancelAnimationFrame
window.cancelAnimationFrame = (id) ->
clearTimeout id
# Prevent this function from running again
implementRequestAnimationFramePolyfill = -> # noop
#
# convertPoint polyfill
#
implementConvertPointPolyfill = ->
for vendor in vendors
window.convertPointFromPageToNode ||= window[vendor + "ConvertPointFromPageToNode"]
window.convertPointFromNodeToPage ||= window[vendor + "ConvertPointFromNodeToPage"]
window.Point ||= window[getCamelizedVendor(vendor) + "Point"]
break if window.convertPointFromPageToNode and window.convertPointFromNodeToPage and window.Point
unless window.Point
# TODO: Implement Point() polyfill'
throw '[jQuery DragDrop] TODO: Implement Point() polyfill'
unless window.convertPointFromPageToNode
# TODO: Implement convertPointFromPageToNode() polyfill
throw '[jQuery DragDrop] TODO: Implement convertPointFromPageToNode() polyfill'
unless window.convertPointFromNodeToPage
# TODO: Implement convertPointFromNodeToPage() polyfill
throw '[jQuery DragDrop] TODO: Implement convertPointFromNodeToPage() polyfill'
# Prevent this function from running again
implementConvertPointPolyfill = -> #noop
#
# Config
#
defaults:
# Applied when the draggable is initialized
draggableClass: 'ui-draggable'
# Applied when a draggable is in mid-drag
draggingClass: 'ui-draggable-dragging'
# Helper options:
# * original: drag the actual element
# * clone: stick a copy of the element to the mouse
# * ($draggable, e) ->: stick the return value of this function to the mouse; must return something that produces a DOM element when run through jQuery
helper: 'original'
# Stack options:
# * selector string: elements that match this selector are members of the stack
# * ($draggable, e) ->: a function that returns a jQuery collection, or a collection of DOM elements
stack: false
# Containment options:
# * an array of coordinates: a bounding box, relative to the page, in the form [x1, y1, x2, y2]
# * ‘parent’: bound the draggable helper to the draggable's parent element
# * ‘document’: bound the draggable helper to the document element
# * ‘window’: bound the draggable helper to the viewport
# * selector string: bound the draggable helper to the first element matched by a selector
# * element: a jQuery object, or a DOM element
containment: false
# Cursor anchor point options:
# * { top: …, right: …, bottom: …, left: … }: an object specifying a waypoint from a draggable's edge, the nearest of which should snap to the cursor when the draggable is dragged
cursorAt: false
# Distance option:
# * The distance in pixels that the mouse needs to move before drag is initiated
distance: false
#
# Initialization
#
constructor: (element, @options = {}) ->
super
# Lazily implement a requestAnimationFrame polyfill
implementRequestAnimationFramePolyfill()
# jQuery version of DOM element attached to the plugin
@$element = $ element
@$element
# Attach the element event handlers
.on
mousedown: @handleElementMouseDown
click: @handleElementClick
# Mark this element as draggable with a class
.addClass(@getConfig().draggableClass)
# Make the plugin chainable
this
setupElement: ->
config = @getConfig()
# Position the draggable relative if it's currently statically positioned
@$element.css(position: 'relative') if config.helper is 'original' and @$element.css('position') is 'static'
# Bind any supplied callbacks to this plugin
for callbackName in ['start', 'drag', 'stop']
config[callbackName] = config[callbackName].bind(this) if typeof config[callbackName] is 'function'
# Done!
@setupPerformed = true
#
# Mouse events
#
handleElementMouseDown: (e) =>
# If another draggable received this mousedown before we did, bail.
return if e.originalEvent.jQueryDragdropAlreadyHandled is true
isLeftButton = e.which is 1
return unless isLeftButton # Left clicks only, please
@cancelAnyScheduledDrag()
# Until told otherwise, the interaction started by this mousedown should not cancel any subsequent click event
@shouldCancelClick = false
# Bail if a canceling agent has been clicked on
return if @isCancelingAgent(e.target)
# Bail if this is not a valid handle
return unless @isValidHandle(e.target)
# Lazily implement a set of coordinate conversion polyfills
implementConvertPointPolyfill()
# Set a flag on the event. Any draggables that contain this one will check for this flag. If they find it, they will ignore the mousedown
e.originalEvent.jQueryDragdropAlreadyHandled = true
$(document.body).one 'mousedown', (e) ->
# Prevent the default mousedown event on the body; This disables text selection.
e.preventDefault()
# Since we've prevented the default action, we have to blur the active element manually, unless it's the body (silly Internet Explorer)
# https://github.com/jquery/jquery-ui/commit/fcd1cafac8afe3a947676ec018e844eeada5b9de#commitcomment-3956626
activeElement = $(document.activeElement)
activeElement.blur() unless activeElement.is(this)
# Store the mousedown event that started this drag
@mousedownEvent = e
# Start to listen for mouse events on the document
$(document).on
mousemove: @handleDocumentMouseMove
mouseup: @handleDocumentMouseUp
handleDocumentMouseMove: (e) =>
if @dragStarted
# Trigger the drag event
@handleDrag(e)
else
thresholdDistance = @getConfig().distance
if thresholdDistance?
# Find the actual distance travelled by the mouse
deltaX = e.clientX - @mousedownEvent.clientX
deltaY = e.clientY - @mousedownEvent.clientY
distanceMoved = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2))
# Prevent the drag start if the distance moved is less than the threshold distance
return true if distanceMoved < thresholdDistance
# Trigger the start event
@handleDragStart(e)
if @dragStarted
# Trigger the drag event immediately
@handleDrag(e, true)
# Broadcast to interested subscribers that this droppable is now in the air
@broadcast('start', e)
handleDocumentMouseUp: (e) =>
isLeftButton = e.which is 1
return unless isLeftButton # Left clicks only, please
# Trigger the stop event
@handleDragStop(e)
handleElementClick: (e) =>
# Clicks should be cancelled if the last mousedown/mouseup interaction resulted in a drag
if @shouldCancelClick
# Cancel the click
e.stopImmediatePropagation()
false
#
# Draggable events
#
handleDragStart: (e) ->
# Lazily perform setup on the element
@setupElement() unless @setupPerformed
# Will we use the original element as the helper, or will we synthesize a new one?
helperConfig = @getConfig().helper
helperIsSynthesized = helperConfig isnt 'original'
# Get (or synthesize temporarily) a placeholder for the drag helper
helperPlaceholder =
if helperIsSynthesized then $('<div style="height: 0; width: 0; visibility: none">').appendTo('body')
else @$element # Use the element itself
# Store the helper's parent; we will use it to map between the page coordinate space and the helper's parent coordinate space
@parent = if helperIsSynthesized
# Go to the target attachment point of the syntheized helper, and search up the DOM for a parent
@getOffsetParentOrTransformedParent(helperPlaceholder)
else
# Start from the original element, and search up the DOM for a parent
@getOffsetParentOrTransformedParent(@$element)
# Thanks, drag helper placeholder; you can go now
helperPlaceholder.remove() if helperIsSynthesized
# Should we calculate the helper's offset, or simply read its 'top' and 'left' CSS properties?
shouldCalculateOffset =
# Always calculate the offset if a synthesized helper is involved
helperIsSynthesized or
# …or if the original element behaves as though it is absolutely positioned, but has no explicit top or left
(@isAbsoluteish(@$element) and @isPositionedImplicitly(@$element))
# Store the start offset of the draggable, with respect to the page
@elementStartPageOffset = convertPointFromNodeToPage @$element.get(0), new Point(0, 0)
@helperStartPosition = if shouldCalculateOffset
elementPreTransformStartPageOffset = if not helperIsSynthesized and @isTransformed(@$element.get(0))
# Save the element's current transform
savedTransform = @$element.css('transform')
# Disable the transform before calculating the element's position
@$element.css('transform', 'none')
# Get the element's pre-transform offset, with respect to the page
preTransformOffset = convertPointFromNodeToPage @$element.get(0), new Point(0, 0)
# Restore the transform
@$element.css('transform', savedTransform)
# Store the pre-transform offset
preTransformOffset
else
@elementStartPageOffset
# Convert between the offset with respect to the page, and one with respect to its offset or transformed parent's coordinate system
startPosition = convertPointFromPageToNode @parent, elementPreTransformStartPageOffset
if @isTransformed(@parent)
# Apply the scroll offset of the element's transformed parent
startPosition.x += @parent.scrollLeft
startPosition.y += @parent.scrollTop
# Store the result
startPosition
else
# Store the start position of the element with respect to its location in the document flow
new Point @getCSSLeft(@$element), @getCSSTop(@$element)
if cursorAtConfig = @getConfig().cursorAt
# Where is the cursor, in node coordinates?
cursorNodeOffset = convertPointFromPageToNode @$element.get(0), new Point(@mousedownEvent.clientX, @mousedownEvent.clientY)
# What are the cursor anchors' offsets in node coordinates?
leftAnchorNodeOffset = cursorAtConfig.left
rightAnchorNodeOffset = @$element.width() - cursorAtConfig.right if cursorAtConfig.right?
topAnchorNodeOffset = cursorAtConfig.top
bottomAnchorNodeOffset = @$element.height() - cursorAtConfig.bottom if cursorAtConfig.bottom?
# Choose the anchor nearest the cursor
horizontalAnchorOffset = if leftAnchorNodeOffset? and rightAnchorNodeOffset?
if Math.abs(cursorNodeOffset.x - leftAnchorNodeOffset) < Math.abs(cursorNodeOffset.x - rightAnchorNodeOffset)
leftAnchorNodeOffset
else
rightAnchorNodeOffset
else
leftAnchorNodeOffset or rightAnchorNodeOffset or cursorNodeOffset.x
verticalAnchorOffset = if topAnchorNodeOffset? and bottomAnchorNodeOffset?
if Math.abs(cursorNodeOffset.y - topAnchorNodeOffset) < Math.abs(cursorNodeOffset.y - bottomAnchorNodeOffset)
topAnchorNodeOffset
else
bottomAnchorNodeOffset
else
topAnchorNodeOffset or bottomAnchorNodeOffset or cursorNodeOffset.y
# Calculate the point to which the mouse should be anchored
mouseAnchorPageOffset = convertPointFromNodeToPage @$element.get(0), new Point(horizontalAnchorOffset , verticalAnchorOffset)
# Calculate the delta between where the mouse is and where we would like it to appear
delta =
left: @mousedownEvent.clientX - mouseAnchorPageOffset.x
top: @mousedownEvent.clientY - mouseAnchorPageOffset.y
# Translate the element to place it under the cursor at the desired anchor point
@helperStartPosition.x += delta.left
@helperStartPosition.y += delta.top
@elementStartPageOffset.x += delta.left
@elementStartPageOffset.y += delta.top
# Compute the event metadata
startPosition = @pointToPosition @helperStartPosition
startOffset = @pointToPosition @elementStartPageOffset
eventMetadata = @getEventMetadata(startPosition, startOffset)
# Synthesize a new event to represent this drag start
dragStartEvent = @synthesizeEvent('dragstart', e)
# Call any user-supplied drag callback; cancel the start if it returns false
if @getConfig().start?(dragStartEvent, eventMetadata) is false
@handleDragStop(e)
return
@cancelAnyScheduledDrag()
# Save the original value of the pointer-events CSS property
@originalPointerEventsPropertyValue = @$element.css('pointerEvents')
# Configure the drag helper
@$helper =
if helperConfig is 'clone' then @synthesizeHelperByCloning @$element
else if typeof helperConfig is 'function' then @synthesizeHelperUsingFactory helperConfig, e
else @$element # Use the element itself
@$helper
# Apply the dragging class
.addClass(@getConfig().draggingClass)
# Kill pointer events while in mid-drag
.css(pointerEvents: 'none')
if helperIsSynthesized
@$helper
# Append the helper to the body
.appendTo('body')
@moveHelperToTopOfStack(stackConfig, e) if not helperIsSynthesized and stackConfig = @getConfig().stack
# Cache the helper's bounds
@bounds = @calculateContainmentBounds() unless @getConfig().containment is false
# Map the mouse coordinates into the helper's coordinate space
{
x: @mousedownEvent.LocalX
y: @mousedownEvent.LocalY
} = convertPointFromPageToNode @parent, new Point(@mousedownEvent.pageX, @mousedownEvent.pageY)
# Mark the drag as having started
@dragStarted = true
# Store a reference to this droppable in the class
jQuery.draggable.draggableAloft = @
# Trigger the drag start event on this draggable's element
@$element.trigger(dragStartEvent, eventMetadata)
handleDrag: (e, immediate = false) ->
dragHandler = =>
# Map the mouse coordinates into the element's coordinate space
localMousePosition = convertPointFromPageToNode @parent, new Point(e.pageX, e.pageY)
# How far has the object moved from its original position?
delta =
x: localMousePosition.x - @mousedownEvent.LocalX
y: localMousePosition.y - @mousedownEvent.LocalY
# Calculate the helper's target position
targetPosition =
left: @helperStartPosition.x + delta.x
top: @helperStartPosition.y + delta.y
# Calculate the target offset
targetOffset =
left: @elementStartPageOffset.x + (e.pageX - @mousedownEvent.pageX)
top: @elementStartPageOffset.y + (e.pageY - @mousedownEvent.pageY)
if @bounds
# Store the helper's original position in case we need to move it back
helperOriginalPosition =
top: @$helper.css('top')
left: @$helper.css('left')
# Move the drag helper into its candidate position
@$helper.css targetPosition
# Get the page-relative bounds of the drag helper in its candidate position
pageRelativeHelperBoundsWithMargin = @getPageRelativeBoundingBox @$helper, [
0 # Top
@helperSize.width # Right
@helperSize.height # Bottom
0 # Left
]
# Calculate the number of pixels the drag delper overflows the containment boundary
overflowTop = @bounds[0] - pageRelativeHelperBoundsWithMargin[0]
overflowRight = pageRelativeHelperBoundsWithMargin[1] - @bounds[1]
overflowBottom = pageRelativeHelperBoundsWithMargin[2] - @bounds[2]
overflowLeft = @bounds[3] - pageRelativeHelperBoundsWithMargin[3]
if overflowLeft > 0 or overflowRight > 0
# What's the target vertical overlap?
targetOverlap = Math.max 0, (overflowLeft + overflowRight) / 2
# What's the adjustment to get there?
pageRelativeXAdjustment = if overflowLeft > overflowRight
overflowLeft - targetOverlap
else
targetOverlap - overflowRight
if overflowTop > 0 or overflowBottom > 0
# What's the target horizontal overlap?
targetOverlap = Math.max 0, (overflowTop + overflowBottom) / 2
# What's the adjustment to get there?
pageRelativeYAdjustment = if overflowTop > overflowBottom
overflowTop - targetOverlap
else
targetOverlap - overflowBottom
if pageRelativeXAdjustment or pageRelativeYAdjustment
# Adjust the drag helper's target offset
targetOffset.left += pageRelativeXAdjustment if pageRelativeXAdjustment
targetOffset.top += pageRelativeYAdjustment if pageRelativeYAdjustment
# Adjust the drag helper's target position
adjustedLocalMousePosition = convertPointFromPageToNode @parent, new Point(e.pageX + (pageRelativeXAdjustment or 0), e.pageY + (pageRelativeYAdjustment or 0))
targetPosition.left += adjustedLocalMousePosition.x - localMousePosition.x
targetPosition.top += adjustedLocalMousePosition.y - localMousePosition.y
else
helperPositionIsFinal = true
# Compute the event metadata
eventMetadata = @getEventMetadata(targetPosition, targetOffset)
# Synthesize a new event to represent this drag
dragEvent = @synthesizeEvent('drag', e)
# Call any user-supplied drag callback; cancel the drag if it returns false
if @getConfig().drag?(dragEvent, eventMetadata) is false
@$helper.css helperOriginalPosition if helperOriginalPosition # Put the helper back where you found it
@handleDragStop(e)
return
# Move the helper
@$helper.css eventMetadata.position unless helperPositionIsFinal
# Trigger the drag event on this draggable's element
@$element.trigger(dragEvent, eventMetadata)
if immediate
# Call the drag handler right away
dragHandler()
else
# Schedule the drag handler to be called when the next frame is about to be drawn
@scheduleDrag dragHandler
handleDragStop: (e) ->
@cancelAnyScheduledDrag()
# Stop listening for mouse events on the document
$(document).off
mousemove: @handleMouseMove
mouseup: @handleMouseUp
if @dragStarted
# The draggable is no longer aloft
delete jQuery.draggable.draggableAloft
delete jQuery.draggable.latestEvent
# Lest a click event occur before cleanup is called, decide whether it should be permitted or not
@shouldCancelClick = !!@dragStarted
# Synthesize a new event to represent this drag start
dragStopEvent = @synthesizeEvent('dragstop', e)
# Compute the event metadata
eventMetadata = @getEventMetadata()
# Call any user-supplied stop callback
@getConfig().stop?(dragStopEvent, eventMetadata)
# Trigger the drag stop on this draggable's element
@$element.trigger(dragStopEvent, eventMetadata)
# Broadcast to interested subscribers that this droppable has been dropped
@broadcast('stop', e)
if @getConfig().helper is 'original'
# Remove the dragging class
@$helper.removeClass @getConfig().draggingClass
else
# Destroy the helper
@$helper.remove()
# Trigger the click event on the original element
@$element.trigger('click', e)
# Restore the original value of the pointer-events property
@$element.css(pointerEvents: @originalPointerEventsPropertyValue)
# Clean up
@cleanUp()
#
# Validators
#
isAbsoluteish: (element) ->
/fixed|absolute/.test $(element).css('position')
isPositionedImplicitly: (element) ->
$element = $(element)
return true if $element.css('top') is 'auto' and $element.css('bottom') is 'auto'
return true if $element.css('left') is 'auto' and $element.css('right') is 'auto'
isCancelingAgent: (element) ->
if @getConfig().cancel
# Is this element the canceling agent itself, or a descendant of the canceling agent?
!!$(element).closest(@getConfig().cancel).length
else
# No canceling agent was specified; don't cancel
false
isValidHandle: (element) ->
if @getConfig().handle
# Is this element the handle itself, or a descendant of the handle?
!!$(element).closest(@getConfig().handle).length
else
# No handle was specified; anything is fair game
true
isTransformed: (element) ->
getTransformMatrixString(element) isnt 'none'
#
# Helpers
#
broadcast: (type, originalEvent) ->
# Synthesize a new event with this type
event = @synthesizeEvent(type, originalEvent)
# Store the event in the class; droppables instantiated after this draggable became aloft might be interested in it
jQuery.draggable.latestEvent = event
# Broadcast!
$(jQuery.draggable::).trigger(event, @)
getPageRelativeBoundingBox: (element, elementEdges) ->
xCoords = []
yCoords = []
# Store an array of element-relative coordinates
elementCoords = [
[elementEdges[3], elementEdges[0]] # Top-left corner
[elementEdges[1], elementEdges[0]] # Top-right corner
[elementEdges[1], elementEdges[2]] # Bottom-right corner
[elementEdges[3], elementEdges[2]] # Bottom-left corner
]
# Convert the coordinates to page-relative ones
for coord in elementCoords
p = convertPointFromNodeToPage(element.get(0), new Point(coord[0], coord[1]))
xCoords.push p.x
yCoords.push p.y
# Calculate the page-relative bounding box
[
Math.min.apply this, yCoords
Math.max.apply this, xCoords
Math.max.apply this, yCoords
Math.min.apply this, xCoords
]
calculateContainmentBounds: ->
containmentConfig = @getConfig().containment
# Get the page-relative bounds of the container
pageRelativeContainmentBounds = if @isArray containmentConfig
# Clone the config; use it as-is
containmentConfig.slice(0)
else
# Get the container
container =
switch containmentConfig
when 'parent' then @$element.parent()
when 'window' then $(window)
when 'document' then $(document.documentElement)
else $(containmentConfig)
if container.length
if $(window).is(container)
# Get the page-relative edges of the window
windowLeftEdge = container.scrollLeft()
windowTopEdge = container.scrollTop()
# Store the viewport's page-relative bounding box
[
windowLeftEdge # Top
windowLeftEdge + container.width() # Right
windowTopEdge + container.height() # Bottom
windowLeftEdge # Left
]
else
# Get the container's size
containerWidth = container.width()
containerHeight = container.height()
# Get the container's padding
containerTopPadding = parseFloat(container.css('paddingTop')) or 0
containerLeftPadding = parseFloat(container.css('paddingLeft')) or 0
# Get the container's border width
containerTopBorder = parseFloat(container.css('borderTopWidth')) or 0
containerLeftBorder = parseFloat(container.css('borderLeftWidth')) or 0
# Calculate the edges
topEdge = containerTopPadding + containerTopBorder
bottomEdge = topEdge + containerHeight
leftEdge = containerLeftPadding + containerLeftBorder
rightEdge = leftEdge + containerWidth
# Store the container's page-relative bounding box
@getPageRelativeBoundingBox container, [
topEdge
rightEdge
bottomEdge
leftEdge
]
return unless pageRelativeContainmentBounds
# Get (and cache) the margins of the drag helper
@helperMargins =
top: parseFloat(@$helper.css('marginTop')) or 0
right: parseFloat(@$helper.css('marginRight')) or 0
bottom: parseFloat(@$helper.css('marginBottom')) or 0
left: parseFloat(@$helper.css('marginLeft')) or 0
# Get (and cache) the size of the drag helper
@helperSize =
height: @$helper.outerHeight()
width: @$helper.outerWidth()
if @helperMargins.top or @helperMargins.right or @helperMargins.bottom or @helperMargins.left # …we must adjust the size of the containment boundary
# Get the page-relative bounds of the drag helper
pageRelativeHelperBounds = @getPageRelativeBoundingBox @$helper, [
0 # Top
@helperSize.width # Right
@helperSize.height # Bottom
0 # Left
]
# Get the page-relative bounds of the drag helper including its margins
pageRelativeHelperBoundsWithMargin = @getPageRelativeBoundingBox @$helper, [
-@helperMargins.top # Top
@helperSize.width + @helperMargins.right # Right
@helperSize.height + @helperMargins.bottom # Bottom
-@helperMargins.left # Left
]
# Adjust the containment bounds by the difference between those two bounding boxes
pageRelativeContainmentBounds[0] -= pageRelativeHelperBoundsWithMargin[0] - pageRelativeHelperBounds[0]
pageRelativeContainmentBounds[1] -= pageRelativeHelperBoundsWithMargin[1] - pageRelativeHelperBounds[1]
pageRelativeContainmentBounds[2] -= pageRelativeHelperBoundsWithMargin[2] - pageRelativeHelperBounds[2]
pageRelativeContainmentBounds[3] -= pageRelativeHelperBoundsWithMargin[3] - pageRelativeHelperBounds[3]
# If the containment bounding box has collapsed, expand it to a midpoint between the collapsed edges
if pageRelativeContainmentBounds[0] > pageRelativeContainmentBounds[2]
pageRelativeContainmentBounds[0] =
pageRelativeContainmentBounds[2] =
pageRelativeContainmentBounds[2] + (pageRelativeContainmentBounds[0] - pageRelativeContainmentBounds[2]) / 2
if pageRelativeContainmentBounds[1] < pageRelativeContainmentBounds[3]
pageRelativeContainmentBounds[1] =
pageRelativeContainmentBounds[3] =
pageRelativeContainmentBounds[1] + (pageRelativeContainmentBounds[3] - pageRelativeContainmentBounds[1]) / 2
# Return the page-relative bounding box
pageRelativeContainmentBounds
cancelAnyScheduledDrag: ->
return unless @scheduledDragId
cancelAnimationFrame(@scheduledDragId)
@scheduledDragId = null
getTransformMatrixString = (element) ->
# Get the computed styles
return 'none' unless computedStyle = getComputedStyle(element)
# Return the matrix string
computedStyle.WebkitTransform or computedStyle.msTransform or computedStyle.MozTransform or computedStyle.OTransform or 'none'
getOffsetParentOrTransformedParent: (element) ->
$element = $(element)
# If we don't find anything, we'll return the document element
foundAncestor = document.documentElement
# Crawl up the DOM, starting at this element's parent
for ancestor in $element.parents().get()
# Look for an ancestor of element that is either positioned, or transformed
if $(ancestor).css('position') isnt 'static' or @isTransformed(ancestor)
foundAncestor = ancestor
break
# Return the ancestor we found
foundAncestor
scheduleDrag: (invocation) ->
@cancelAnyScheduledDrag()
@scheduledDragId = requestAnimationFrame =>
invocation()
@scheduledDragId = null
synthesizeHelperByCloning: (element) ->
# Clone the original element
helper = element.clone()
# Remove the ID attribute
helper.removeAttr('id')
# Post process the helper element
@prepareHelper helper
synthesizeHelperUsingFactory: (factory, e) ->
# Run the factory
output = factory @$element, e
# Process the output with jQuery
helper = $(output).first()
throw new Error '[jQuery DragDrop – Draggable] Helper factory methods must produce a jQuery object, a DOM Element, or a string of HTML' unless helper.length
# Post process the helper element
@prepareHelper helper.first()
moveHelperToTopOfStack: (stackConfig, e) ->
# Get the members of the stack
$stackMembers = $(stackConfig?(@$helper, e) or stackConfig)
return unless $stackMembers.length
# Sort the stack members by z-index
sortedStackMembers = $stackMembers.get().sort (a, b) ->
(parseInt($(b).css('zIndex'), 10) or 0) - (parseInt($(a).css('zIndex'), 10) or 0)
return if @$helper.is(topStackMember = sortedStackMembers[0])
# Get the top element's index
topIndex = $(topStackMember).css('zIndex')
# Move this helper to the top of the stack
@$helper.css('zIndex', parseInt(topIndex, 10) + 1)
positionToPoint: (position) ->
new Point position.left, position.top
pointToPosition: (point) ->
left: point.x
top: point.y
prepareHelper: ($helper) ->
css = {}
# Position the helper absolutely, unless it already is
css.position = 'absolute' unless $helper.css('position') is 'absolute'
# Move the clone to the position of the original
css.left = @elementStartPageOffset.x
css.top = @elementStartPageOffset.y
# Style it
$helper.css(css)
cleanUp: ->
# Clean up
@dragStarted = false
delete @$helper
delete @bounds
delete @elementStartPageOffset
delete @helperMargins
delete @helperSize
delete @helperStartPosition
delete @mousedownEvent
delete @originalPointerEventsPropertyValue
delete @parent
$.fn.draggable = (options) ->
this.each ->
unless $(this).data('draggable')?
plugin = new $.draggable(this, options)
$(this).data('draggable', plugin)
|
[
{
"context": " msg.channel?.send [\n \"Hey #{reply}, I’m Haruka.\"\n \"Hi #{reply}, I’m Haruka.\"\n \"Hel",
"end": 636,
"score": 0.9667209386825562,
"start": 630,
"tag": "NAME",
"value": "Haruka"
},
{
"context": "y #{reply}, I’m Haruka.\"\n \"Hi #{reply... | src/specials/dad.coffee | MindfulMinun/discord-haruka | 2 | #! ========================================
#! Special: Dad
imRegex = /^(?:i(?:['’]|(?:\s+a))?m)\s+/i
handler = (msg, Haruka) ->
# Matches "im ", "i'm ", "i’m ", and "i am "
# Case insensitive, whitespace required.
# Break if regex doesn't match.
if (not imRegex.test(msg.content)) or msg.author.bot then return no
# If the person's fortunate enough to get a number higher than
# 1 / 10, they’re spared.
if (1 / 10) <= Math.random() then return no
#! Likewise, if they're unlucky, send the reply.
reply = msg.content.replace imRegex, ''
msg.channel?.send [
"Hey #{reply}, I’m Haruka."
"Hi #{reply}, I’m Haruka."
"Hello #{reply}, I’m Haruka. Nice to meet you."
].choose(), disableEveryone: yes
# Message doesn't call Haruka, exit prematurely
yes
module.exports = {
name: "Dad"
handler: handler
}
| 39374 | #! ========================================
#! Special: Dad
imRegex = /^(?:i(?:['’]|(?:\s+a))?m)\s+/i
handler = (msg, Haruka) ->
# Matches "im ", "i'm ", "i’m ", and "i am "
# Case insensitive, whitespace required.
# Break if regex doesn't match.
if (not imRegex.test(msg.content)) or msg.author.bot then return no
# If the person's fortunate enough to get a number higher than
# 1 / 10, they’re spared.
if (1 / 10) <= Math.random() then return no
#! Likewise, if they're unlucky, send the reply.
reply = msg.content.replace imRegex, ''
msg.channel?.send [
"Hey #{reply}, I’m <NAME>."
"Hi #{reply}, I’m <NAME>."
"Hello #{reply}, I’m <NAME>. Nice to meet you."
].choose(), disableEveryone: yes
# Message doesn't call Haruka, exit prematurely
yes
module.exports = {
name: "<NAME>"
handler: handler
}
| true | #! ========================================
#! Special: Dad
imRegex = /^(?:i(?:['’]|(?:\s+a))?m)\s+/i
handler = (msg, Haruka) ->
# Matches "im ", "i'm ", "i’m ", and "i am "
# Case insensitive, whitespace required.
# Break if regex doesn't match.
if (not imRegex.test(msg.content)) or msg.author.bot then return no
# If the person's fortunate enough to get a number higher than
# 1 / 10, they’re spared.
if (1 / 10) <= Math.random() then return no
#! Likewise, if they're unlucky, send the reply.
reply = msg.content.replace imRegex, ''
msg.channel?.send [
"Hey #{reply}, I’m PI:NAME:<NAME>END_PI."
"Hi #{reply}, I’m PI:NAME:<NAME>END_PI."
"Hello #{reply}, I’m PI:NAME:<NAME>END_PI. Nice to meet you."
].choose(), disableEveryone: yes
# Message doesn't call Haruka, exit prematurely
yes
module.exports = {
name: "PI:NAME:<NAME>END_PI"
handler: handler
}
|
[
{
"context": "l_needed_talk_power: 99999\n channel_password: \"youcantjointhisskrub\"\n \"Bounce\":\n channel_name: \"Bounce\"\n chann",
"end": 3497,
"score": 0.9990341663360596,
"start": 3477,
"tag": "PASSWORD",
"value": "youcantjointhisskrub"
},
{
"context": "r\"\n cl.... | index.coffee | paralin/WebLeagueTS | 2 | mongoose = require "mongoose"
ActiveMatch = require "./model/activeMatch"
User = require "./model/user"
League = require "./model/league"
TeamSpeakClient = require "node-teamspeak"
util = require "util"
_ = require "lodash"
typeIsArray = ( value ) ->
value and
typeof value is 'object' and
value instanceof Array and
typeof value.length is 'number' and
typeof value.splice is 'function' and
not ( value.propertyIsEnumerable 'length' )
log = console.log
if process.env.IGNORE_ERRORS?
process.on 'uncaughtException', (err)->
console.log "Uncaught exception! #{err}"
console.log "Setting up our database connection..."
if !process.env.MONGODB_URL?
console.log "MONGODB_URL env variable required!"
return
tsIp = process.env.TEAMSPEAK_IP
if !tsIp?
console.log "TEAMSPEAK_IP env variable required!"
return
tsPort = process.env.TEAMSPEAK_PORT
if !tsPort?
parts = tsIp.split ":"
if parts? && parts.length is 2
tsPort = parseInt parts[1]
tsIp = parts[0]
else
console.log "Using default teamspeak_port"
tsPort = 10011
tsUser = process.env.TEAMSPEAK_USER
if !tsUser?
console.log "TEAMSPEAK_USER env variable required!"
return
tsPassword = process.env.TEAMSPEAK_PASSWORD
if !tsPassword?
console.log "TEAMSPEAK_PASSWORD env variable required!"
return
mongoose.connect(process.env.MONGODB_URL)
User.update {}, {$set: {tsonline: false}}, {multi: true}, (err)->
if err?
console.log "Unable to set tsonline to false on everyone, #{err}"
defaultChannels =
"Lobby":
channel_name: "Lobby"
channel_codec_quality: 10
#channel_flag_default: 1
channel_flag_permanent: 1
channel_description: "General chat."
"[spacer2]":
channel_name: "[spacer2]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
"Lounge 1":
channel_name: "Lounge 1"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 1"
"Lounge 2":
channel_name: "Lounge 2"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 2"
"Lounge 3":
channel_name: "Lounge 3"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 3"
"Lounge 4":
channel_name: "Lounge 4"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 4"
"Lounge 5":
channel_name: "Lounge 5"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 5"
"Lounge 6":
channel_name: "Lounge 6"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 6"
"[spacer1]":
channel_name: "[spacer1]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
"AFK":
channel_name: "AFK"
channel_codec_quality: 1
channel_flag_permanent: 1
channel_forced_silence: 1
channel_needed_talk_power: 99999
"Unknown":
channel_name: "Unknown"
channel_codec_quality: 1
channel_description: "To verify your identity, follow these steps:\n 1. Left click your name at the top right of the FPL client.\n 2. Click \"Teamspeak Info\".\n 3. Copy the token in the window, and paste it into the text chat with the user \"FPL Server\" who will send you a message."
channel_flag_permanent: 1
channel_forced_silence: 1
channel_needed_talk_power: 99999
channel_password: "youcantjointhisskrub"
"Bounce":
channel_name: "Bounce"
channel_codec_quality: 1
channel_description: "This is a temporary channel, the bot should move you out immediately."
channel_flag_permanent: 1
channel_flag_default: 1
"Lobby":
channel_name: "Lobby"
channel_codec_quality: 10
#channel_flag_default: 1
channel_flag_permanent: 1
channel_description: "General chat."
"[spacer0]":
channel_name: "[spacer0]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
"[spacer3]":
channel_name: "[spacer3]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
serverGroups = {}
cl = null
updateInterval = null
cid = 0
me = null
connected = false
clientCache = {}
userCache = {}
lastCurrentServerChannels = {}
checkedUids = []
messagedUids = []
onlineUsers = []
onlineUsersNow = []
lastClients = null
lastLeagues = null
moveClientToHome = (client, currentServerChannels)->
user = userCache[client.client_unique_identifier]
if user?
if user.vouch.leagues.length > 0
if lastLeagues?
league = _.findWhere lastLeagues, {_id: user.vouch.leagues[0]}
if league?
chan = currentServerChannels[league.Name]
if chan? and chan.cid?
cl.send 'clientmove', {cid: chan.cid, clid: client.clid}, (err)->
if err?
console.log "Can't move client to his home, #{err}"
else
console.log "Unable to move client home, channel #{league.Name} not found."
else
console.log "Unable to move client home, league #{user.profile.leagues[0]} not found."
else
chan = currentServerChannels.Lobby
if chan? and chan.cid?
cl.send 'clientmove', {cid: chan.cid, clid: client.clid}, (err)->
if err?
console.log "Can't move client to his home, #{err}"
initServerGroups = (cb)->
cl.send 'servergrouplist', (err, resp)->
if err?
log "error fetching server group list! #{err}"
else
if resp?
resp = [resp] unless typeIsArray resp
for group in resp
continue if group.type != 1
serverGroups[parseInt(group.sgid)] = group.name
console.log "#{group.sgid} = #{group.name}"
else
log "no server group response! this will be broken..."
cb()
initNotify = (cb)->
cl.send 'servernotifyregister', {event: "textprivate", id: 0}, (err)->
if err?
log "error registering text message notify! #{err}"
cb()
initClient = ->
cl = new TeamSpeakClient(tsIp, tsPort)
cl.on "connect", ->
connected = true
cid++
log "connected to the server"
cl.send 'login', {
client_login_name: tsUser
client_login_password: tsPassword
}, (err, response, rawResponse) ->
cl.send 'use', { sid: 1 }, (err, response, rawResponse) ->
if err?
log "unable to select server, #{err}"
return
cl.send 'instanceedit', {serverinstance_serverquery_flood_commands: 999, serverinstance_serverquery_flood_time: 5}, (err)->
log "error changing query flood limit, #{util.inspect err}" if err?
initServerGroups ->
initNotify ->
cl.send 'whoami', (err, resp)->
if err?
log "error checking whoami!"
log err
return
me = resp
cl.send 'clientupdate', {clid: me.client_id, client_nickname: "FPL Server"}, (err)->
if err?
log "unable to change nickname, #{util.inspect err}"
log "ready, starting update loop..."
cid++
updateTeamspeak(cid)
cl.on "error", (err)->
log "socket error, #{err}"
cl.on "textmessage", (msg)->
return if msg.targetmode isnt 1 or msg.invokerid is me.client_id
log "CHAT #{msg.invokername}: #{msg.msg}"
cl.send 'clientinfo', {clid: msg.invokerid}, (err, client)->
if err?
log "can't lookup client, #{util.inspect err}"
return
if !client?
log "no client for #{msg.invokerid}"
return
client.clid = msg.invokerid
return moveClientToHome(client, lastCurrentServerChannels) if msg.msg is "moveme"
uid = client.client_unique_identifier
User.findOne {tsonetimeid: msg.msg.trim()}, (err, usr)->
if err?
log "unable to lookup tsonetimeid #{msg.msg}, #{util.inspect err}"
return
if usr?
cl.send 'sendtextmessage', {targetmode: 1, target: msg.invokerid, msg: "Welcome, #{usr.profile.name}!"}
cl.send 'clientedit', {clid: msg.invokerid, client_description: usr.profile.name}, (err)->
if err?
log "Unable to edit client #{client.cid}, #{util.inspect err}"
user = userCache[uid] = usr.toObject()
user.nextUpdate = new Date().getTime()+300000 #5 minutes
user.tsuniqueids = user.tsuniqueids || [uid]
user.tsuniqueids.push uid if uid not in user.tsuniqueids
User.update {_id: usr._id}, {$set: {tsuniqueids: user.tsuniqueids, tsonetimeid: null}}, (err)->
if err?
log "unable to save tsuniqueid, #{err}"
else
cl.send 'sendtextmessage', {targetmode: 1, target: msg.invokerid, msg: "Your message, #{msg.msg}, isn't a valid token. Please try again."}
cl.on "close", (err)->
log "connection closed, reconnecting in 10 sec"
connected = false
if updateInterval?
clearInterval updateInterval
updateInterval = null
setTimeout ->
initClient()
, 10000
currentServerChannels = {}
updateTeamspeak = (myid)->
if myid != cid or !connected
log "terminating old update loop #{myid}"
return
currentChannels = {}
lastCurrentServerChannels = currentServerChannels
currentServerChannels = {}
pend = cl.getPending()
updcalled = false
nextUpdate = ->
return if npdcalled
npdcalled = true
setTimeout ->
updateTeamspeak(myid)
, 2000
if pend.length > 0
log "commands still pending, deferring update"
nextUpdate()
return
cl.send 'channellist', ['topic', 'flags', 'limits'], (err, resp)->
if err?
log "error fetching client list, #{util.inspect err}"
return nextUpdate()
for chan in resp
currentServerChannels[chan.channel_name] = chan
echan = defaultChannels[chan.channel_name]
if echan?
echan.cid = chan.cid
echan.pid = chan.pid
League.find {}, (err, leagues)->
if err?
log "error finding active leagues, #{util.inspect err}"
return nextUpdate()
lastLeagues = leagues
leagues.forEach (league)->
lid = league._id
rchan = league.Name
if !league.Archived && !league.NoChannel
exist = currentServerChannels[rchan]
if exist?
currentChannels[rchan] = exist
else
currentChannels[rchan] =
channel_name: rchan
channel_codec_quality: 10
channel_description: "Lobby for league #{league.Name}."
channel_flag_permanent: 1
ActiveMatch.find {}, (err, matches)->
if err?
log "error fetching active matches, #{util.inspect err}"
return nextUpdate()
matches.forEach (match)->
mid = match.Details.MatchId || 0
rchann = ""
if match.Info.MatchType == 0
capt = _.findWhere match.Details.Players, {SID: match.Info.Owner}
rchann = "#{capt.Name}'s Startgame"
else if match.Info.MatchType == 2
return
else if match.Info.MatchType == 1
capts = _.filter match.Details.Players, (plyr)-> plyr.IsCaptain
rchann = "#{capts[0].Name} vs. #{capts[1].Name}"
schan = currentServerChannels[rchann]
if schan?
currentChannels[rchann] = schan
subs = _.filter _.values(currentServerChannels), (chan)-> chan.pid is schan.cid
for sub in subs
currentChannels[sub.channel_name] = sub
else
currentChannels[rchann] =
channel_name: rchann
channel_codec_quality: 10
channel_description: "Root channel for match #{mid}."
channel_flag_permanent: 1
channel_password: "#{match.Info.Owner}"
currentChannels["Radiant #{mid}"] =
channel_name: "Radiant #{mid}"
channel_codec_quality: 10
channel_description: "Radiant channel for match #{mid}."
channel_flag_permanent: 1
channel_password: "#{match.Info.Owner}"
pid: rchann
currentChannels["Dire #{mid}"] =
channel_name: "Dire #{mid}"
channel_codec_quality: 10
channel_description: "Dire channel for match #{mid}."
channel_flag_permanent: 1
channel_password: "#{match.Info.Owner}"
pid: rchann
currentChannels["Spectator #{mid} #1"] =
channel_name: "Spectator #{mid} #1"
channel_codec_quality: 10
channel_description: "Spectator #1 channel for match #{mid}."
channel_flag_permanent: 1
#channel_password: "#{match.Info.Owner}"
pid: rchann
for id, chan of defaultChannels
currentChannels[id] = chan
for id, chan of currentServerChannels
continue unless defaultChannels[id]?
currentChannels[id] = chan if currentChannels[id]?
_.keys(currentChannels).forEach (id)->
chan = currentChannels[id]
return if _.isString(chan.pid)
if !currentServerChannels[id]?
cl.send 'channelcreate', chan, (err, res)->
if err?
log "unable to create channel #{id}, #{util.inspect err}"
else
cl.send 'channelfind', {pattern: id}, (err, pchan)->
if err?
log "can't find channel I just created, #{util.inspect err}"
return
chan.cid = pchan.cid
log "created channel #{chan.channel_name}"
subchans = _.filter _.values(currentChannels), (schan)-> schan.pid is id
subchans.forEach (schan)->
schan.cpid = schan.pid = chan.cid
log schan
cl.send 'channelcreate', schan, (err, resp)->
if err?
log "unable to create channel #{schan.channel_name}, #{util.inspect err}"
else
log "created channel #{schan.channel_name}"
for id, chan of currentServerChannels
if !currentChannels[id]? and !(chan.channel_flag_permanent == 1 && chan.channel_topic.indexOf("adminperm") > -1)
log util.inspect chan
if lastClients?
for client in lastClients
moveClientToHome(client, currentServerChannels) if client.cid is chan.cid
cl.send 'channeldelete', {force: 1, cid: chan.cid}, (err)->
if err?
log "unable to delete #{id}, #{util.inspect err}"
else
log "deleted channel #{id}"
cl.send 'clientlist', ['uid', 'away', 'voice', 'times', 'groups', 'info'], (err, clients)->
if err?
log "unable to fetch clients, #{util.inspect err}"
return nextUpdate()
return nextUpdate() if !clients?
clients = [clients] if _.isObject(clients) and !_.isArray(clients)
invGroups = _.invert serverGroups
lastClients = clients
nUsrCache = {}
for id, usr of userCache
if _.findWhere(clients, {client_unique_identifier: id})? && usr.nextUpdate<(new Date().getTime())
nUsrCache[id] = usr
userCache = nUsrCache
checkClient = (client, user)->
targetGroups = []
if user?
if user._id not in onlineUsers
User.update {_id: user._id}, {$set: {tsonline: true}}, (err)->
if err?
console.log "Unable to mark #{user._id} as tsonline, #{err}"
else
console.log "Marked #{user._id} as online"
onlineUsersNow.push user._id if user._id not in onlineUsersNow
if !user? or !user.vouch?
targetGroups.push parseInt invGroups["Guest"]
else if "admin" in user.authItems
targetGroups.push parseInt invGroups["Server Admin"]
else
targetGroups.push parseInt invGroups["Normal"]
groups = []
if _.isNumber client.client_servergroups
groups.push client.client_servergroups
else if _.isString client.client_servergroups
groups = client.client_servergroups.split(',').map(parseInt)
for id in targetGroups
unless id in groups
log "adding server group #{serverGroups[id]} to #{client.client_nickname}"
cl.send 'servergroupaddclient', {sgid: id, cldbid: client.client_database_id}, (err)->
if err?
log "unable to assign group, #{util.inspect err}"
for id in groups
unless id in targetGroups
log "removing server group #{serverGroups[id]} from #{client.client_nickname}"
cl.send 'servergroupdelclient', {sgid: id, cldbid: client.client_database_id}, (err, resp)->
if err?
log "unable to remove group, #{util.inspect err}"
uchan = currentChannels["Unknown"]
if user?
if !user.vouch? or !user.vouch.leagues? or user.vouch.leagues.length is 0
cl.send 'clientkick', {clid: client.clid, reasonid: 5, reasonmsg: "You are not vouched into the league."}, (err)->
if err?
console.log "Cannot kick #{client.clid}, #{err}"
else
uplyr = null
umatch = _.find matches, (match)->
return false if match.Info.MatchType > 1
uplyr = _.findWhere(match.Details.Players, {SID: user.steam.steamid})
uplyr? and uplyr.Team < 2
mid = null
teamn = null
cname = null
if umatch?
mid = umatch.Details.MatchId
teamn = if uplyr.Team is 0 then "Radiant" else "Dire"
cname = teamn+" "+mid
if umatch? && currentChannels[cname]? && currentChannels[cname].cid? && currentChannels[cname].cid isnt 0
tchan = currentChannels[cname]
if tchan.cid isnt client.cid
log "moving client #{client.client_nickname} into #{cname}"
cl.send 'clientmove', {cid: tchan.cid, clid: client.clid}, (err)->
if err?
log "unable to move client to channel... #{util.inspect err}"
else
tchan = currentChannels["Lobby"]
bchan = currentChannels["Bounce"]
if ((bchan? and bchan.cid? and client.cid is bchan.cid) or (uchan.cid? && client.cid is uchan.cid)) && (tchan.cid? && tchan.cid != 0)
log "moving client #{client.client_nickname} out of unknown/bounce channel"
if user.vouch.leagues? && user.vouch.leagues.length > 0
moveClientToHome(client, currentServerChannels)
else
cl.send 'clientmove', {cid: tchan.cid, clid: client.clid}, (err)->
if err?
log "unable to move client to lobby... #{util.inspect err}"
else
tchan = currentChannels["Unknown"]
if tchan.cid? && tchan.cid != 0 && client.cid isnt tchan.cid
log "moving client #{client.client_nickname} to the unknown channel"
cl.send 'clientmove', {cid: tchan.cid, clid: client.clid}, (err)->
if err?
log "unable to move client to unknown channel... #{util.inspect err}"
unless client.clid in messagedUids
messagedUids.push client.clid
cl.send 'sendtextmessage', {targetmode: 1, target: client.clid, msg: "Welcome to the FPL teamspeak. Please paste your token here. Read the description of this channel for instructions if needed."}, (err)->
if err?
log "can't send text message to #{client.client_nickname}, #{util.inspect err}"
setTimeout ->
messagedUids = _.without messagedUids, client.clid
, 30000
clids = []
invGroups = _.invert serverGroups
nonPlayer = invGroups["NonPlayer"]
clients.forEach (client)->
return unless client.client_type is 0
return if nonPlayer? and "#{client.client_servergroups}" is nonPlayer
clids.push client.clid
uid = client.client_unique_identifier
user = userCache[uid]
if !user? and uid not in checkedUids
checkedUids.push uid
User.findOne {tsuniqueids: uid}, (err, usr)->
if err?
log "unable to lookup #{uid}, #{util.inspect err}"
return
if usr?
user = userCache[uid] = usr.toObject()
user.nextUpdate = new Date().getTime()+300000 #5 minutes
cl.send 'clientedit', {clid: client.clid, client_description: usr.profile.name}, (err)->
if err?
log "Unable to edit client #{client.clid}, #{util.inspect err}"
checkClient client, user
else
checkClient client, user
checkedUids = _.union clids
for onlineu in onlineUsers
unless onlineu in onlineUsersNow
User.update {_id: onlineu}, {$set: {tsonline: false}}, (err)->
if err?
console.log "Unable to set user #{onlineu} to offline, #{err}"
else
console.log "Marked user #{onlineu} as offline"
onlineUsers = onlineUsersNow
onlineUsersNow = []
nextUpdate()
initClient()
| 28619 | mongoose = require "mongoose"
ActiveMatch = require "./model/activeMatch"
User = require "./model/user"
League = require "./model/league"
TeamSpeakClient = require "node-teamspeak"
util = require "util"
_ = require "lodash"
typeIsArray = ( value ) ->
value and
typeof value is 'object' and
value instanceof Array and
typeof value.length is 'number' and
typeof value.splice is 'function' and
not ( value.propertyIsEnumerable 'length' )
log = console.log
if process.env.IGNORE_ERRORS?
process.on 'uncaughtException', (err)->
console.log "Uncaught exception! #{err}"
console.log "Setting up our database connection..."
if !process.env.MONGODB_URL?
console.log "MONGODB_URL env variable required!"
return
tsIp = process.env.TEAMSPEAK_IP
if !tsIp?
console.log "TEAMSPEAK_IP env variable required!"
return
tsPort = process.env.TEAMSPEAK_PORT
if !tsPort?
parts = tsIp.split ":"
if parts? && parts.length is 2
tsPort = parseInt parts[1]
tsIp = parts[0]
else
console.log "Using default teamspeak_port"
tsPort = 10011
tsUser = process.env.TEAMSPEAK_USER
if !tsUser?
console.log "TEAMSPEAK_USER env variable required!"
return
tsPassword = process.env.TEAMSPEAK_PASSWORD
if !tsPassword?
console.log "TEAMSPEAK_PASSWORD env variable required!"
return
mongoose.connect(process.env.MONGODB_URL)
User.update {}, {$set: {tsonline: false}}, {multi: true}, (err)->
if err?
console.log "Unable to set tsonline to false on everyone, #{err}"
defaultChannels =
"Lobby":
channel_name: "Lobby"
channel_codec_quality: 10
#channel_flag_default: 1
channel_flag_permanent: 1
channel_description: "General chat."
"[spacer2]":
channel_name: "[spacer2]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
"Lounge 1":
channel_name: "Lounge 1"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 1"
"Lounge 2":
channel_name: "Lounge 2"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 2"
"Lounge 3":
channel_name: "Lounge 3"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 3"
"Lounge 4":
channel_name: "Lounge 4"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 4"
"Lounge 5":
channel_name: "Lounge 5"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 5"
"Lounge 6":
channel_name: "Lounge 6"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 6"
"[spacer1]":
channel_name: "[spacer1]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
"AFK":
channel_name: "AFK"
channel_codec_quality: 1
channel_flag_permanent: 1
channel_forced_silence: 1
channel_needed_talk_power: 99999
"Unknown":
channel_name: "Unknown"
channel_codec_quality: 1
channel_description: "To verify your identity, follow these steps:\n 1. Left click your name at the top right of the FPL client.\n 2. Click \"Teamspeak Info\".\n 3. Copy the token in the window, and paste it into the text chat with the user \"FPL Server\" who will send you a message."
channel_flag_permanent: 1
channel_forced_silence: 1
channel_needed_talk_power: 99999
channel_password: "<PASSWORD>"
"Bounce":
channel_name: "Bounce"
channel_codec_quality: 1
channel_description: "This is a temporary channel, the bot should move you out immediately."
channel_flag_permanent: 1
channel_flag_default: 1
"Lobby":
channel_name: "Lobby"
channel_codec_quality: 10
#channel_flag_default: 1
channel_flag_permanent: 1
channel_description: "General chat."
"[spacer0]":
channel_name: "[spacer0]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
"[spacer3]":
channel_name: "[spacer3]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
serverGroups = {}
cl = null
updateInterval = null
cid = 0
me = null
connected = false
clientCache = {}
userCache = {}
lastCurrentServerChannels = {}
checkedUids = []
messagedUids = []
onlineUsers = []
onlineUsersNow = []
lastClients = null
lastLeagues = null
moveClientToHome = (client, currentServerChannels)->
user = userCache[client.client_unique_identifier]
if user?
if user.vouch.leagues.length > 0
if lastLeagues?
league = _.findWhere lastLeagues, {_id: user.vouch.leagues[0]}
if league?
chan = currentServerChannels[league.Name]
if chan? and chan.cid?
cl.send 'clientmove', {cid: chan.cid, clid: client.clid}, (err)->
if err?
console.log "Can't move client to his home, #{err}"
else
console.log "Unable to move client home, channel #{league.Name} not found."
else
console.log "Unable to move client home, league #{user.profile.leagues[0]} not found."
else
chan = currentServerChannels.Lobby
if chan? and chan.cid?
cl.send 'clientmove', {cid: chan.cid, clid: client.clid}, (err)->
if err?
console.log "Can't move client to his home, #{err}"
initServerGroups = (cb)->
cl.send 'servergrouplist', (err, resp)->
if err?
log "error fetching server group list! #{err}"
else
if resp?
resp = [resp] unless typeIsArray resp
for group in resp
continue if group.type != 1
serverGroups[parseInt(group.sgid)] = group.name
console.log "#{group.sgid} = #{group.name}"
else
log "no server group response! this will be broken..."
cb()
initNotify = (cb)->
cl.send 'servernotifyregister', {event: "textprivate", id: 0}, (err)->
if err?
log "error registering text message notify! #{err}"
cb()
initClient = ->
cl = new TeamSpeakClient(tsIp, tsPort)
cl.on "connect", ->
connected = true
cid++
log "connected to the server"
cl.send 'login', {
client_login_name: tsUser
client_login_password: <PASSWORD>
}, (err, response, rawResponse) ->
cl.send 'use', { sid: 1 }, (err, response, rawResponse) ->
if err?
log "unable to select server, #{err}"
return
cl.send 'instanceedit', {serverinstance_serverquery_flood_commands: 999, serverinstance_serverquery_flood_time: 5}, (err)->
log "error changing query flood limit, #{util.inspect err}" if err?
initServerGroups ->
initNotify ->
cl.send 'whoami', (err, resp)->
if err?
log "error checking whoami!"
log err
return
me = resp
cl.send 'clientupdate', {clid: me.client_id, client_nickname: "FPL Server"}, (err)->
if err?
log "unable to change nickname, #{util.inspect err}"
log "ready, starting update loop..."
cid++
updateTeamspeak(cid)
cl.on "error", (err)->
log "socket error, #{err}"
cl.on "textmessage", (msg)->
return if msg.targetmode isnt 1 or msg.invokerid is me.client_id
log "CHAT #{msg.invokername}: #{msg.msg}"
cl.send 'clientinfo', {clid: msg.invokerid}, (err, client)->
if err?
log "can't lookup client, #{util.inspect err}"
return
if !client?
log "no client for #{msg.invokerid}"
return
client.clid = msg.invokerid
return moveClientToHome(client, lastCurrentServerChannels) if msg.msg is "moveme"
uid = client.client_unique_identifier
User.findOne {tsonetimeid: msg.msg.trim()}, (err, usr)->
if err?
log "unable to lookup tsonetimeid #{msg.msg}, #{util.inspect err}"
return
if usr?
cl.send 'sendtextmessage', {targetmode: 1, target: msg.invokerid, msg: "Welcome, #{usr.profile.name}!"}
cl.send 'clientedit', {clid: msg.invokerid, client_description: usr.profile.name}, (err)->
if err?
log "Unable to edit client #{client.cid}, #{util.inspect err}"
user = userCache[uid] = usr.toObject()
user.nextUpdate = new Date().getTime()+300000 #5 minutes
user.tsuniqueids = user.tsuniqueids || [uid]
user.tsuniqueids.push uid if uid not in user.tsuniqueids
User.update {_id: usr._id}, {$set: {tsuniqueids: user.tsuniqueids, tsonetimeid: null}}, (err)->
if err?
log "unable to save tsuniqueid, #{err}"
else
cl.send 'sendtextmessage', {targetmode: 1, target: msg.invokerid, msg: "Your message, #{msg.msg}, isn't a valid token. Please try again."}
cl.on "close", (err)->
log "connection closed, reconnecting in 10 sec"
connected = false
if updateInterval?
clearInterval updateInterval
updateInterval = null
setTimeout ->
initClient()
, 10000
currentServerChannels = {}
updateTeamspeak = (myid)->
if myid != cid or !connected
log "terminating old update loop #{myid}"
return
currentChannels = {}
lastCurrentServerChannels = currentServerChannels
currentServerChannels = {}
pend = cl.getPending()
updcalled = false
nextUpdate = ->
return if npdcalled
npdcalled = true
setTimeout ->
updateTeamspeak(myid)
, 2000
if pend.length > 0
log "commands still pending, deferring update"
nextUpdate()
return
cl.send 'channellist', ['topic', 'flags', 'limits'], (err, resp)->
if err?
log "error fetching client list, #{util.inspect err}"
return nextUpdate()
for chan in resp
currentServerChannels[chan.channel_name] = chan
echan = defaultChannels[chan.channel_name]
if echan?
echan.cid = chan.cid
echan.pid = chan.pid
League.find {}, (err, leagues)->
if err?
log "error finding active leagues, #{util.inspect err}"
return nextUpdate()
lastLeagues = leagues
leagues.forEach (league)->
lid = league._id
rchan = league.Name
if !league.Archived && !league.NoChannel
exist = currentServerChannels[rchan]
if exist?
currentChannels[rchan] = exist
else
currentChannels[rchan] =
channel_name: rchan
channel_codec_quality: 10
channel_description: "Lobby for league #{league.Name}."
channel_flag_permanent: 1
ActiveMatch.find {}, (err, matches)->
if err?
log "error fetching active matches, #{util.inspect err}"
return nextUpdate()
matches.forEach (match)->
mid = match.Details.MatchId || 0
rchann = ""
if match.Info.MatchType == 0
capt = _.findWhere match.Details.Players, {SID: match.Info.Owner}
rchann = "#{capt.Name}'s Startgame"
else if match.Info.MatchType == 2
return
else if match.Info.MatchType == 1
capts = _.filter match.Details.Players, (plyr)-> plyr.IsCaptain
rchann = "#{capts[0].Name} vs. #{capts[1].Name}"
schan = currentServerChannels[rchann]
if schan?
currentChannels[rchann] = schan
subs = _.filter _.values(currentServerChannels), (chan)-> chan.pid is schan.cid
for sub in subs
currentChannels[sub.channel_name] = sub
else
currentChannels[rchann] =
channel_name: rchann
channel_codec_quality: 10
channel_description: "Root channel for match #{mid}."
channel_flag_permanent: 1
channel_password: "#{match.Info.Owner}"
currentChannels["Radiant #{mid}"] =
channel_name: "Radiant #{mid}"
channel_codec_quality: 10
channel_description: "Radiant channel for match #{mid}."
channel_flag_permanent: 1
channel_password: "#{match.Info.Owner}"
pid: rchann
currentChannels["Dire #{mid}"] =
channel_name: "Dire #{mid}"
channel_codec_quality: 10
channel_description: "Dire channel for match #{mid}."
channel_flag_permanent: 1
channel_password: "#{match.Info.Owner}"
pid: rchann
currentChannels["Spectator #{mid} #1"] =
channel_name: "Spectator #{mid} #1"
channel_codec_quality: 10
channel_description: "Spectator #1 channel for match #{mid}."
channel_flag_permanent: 1
#channel_password: "#{match.Info.Owner}"
pid: rchann
for id, chan of defaultChannels
currentChannels[id] = chan
for id, chan of currentServerChannels
continue unless defaultChannels[id]?
currentChannels[id] = chan if currentChannels[id]?
_.keys(currentChannels).forEach (id)->
chan = currentChannels[id]
return if _.isString(chan.pid)
if !currentServerChannels[id]?
cl.send 'channelcreate', chan, (err, res)->
if err?
log "unable to create channel #{id}, #{util.inspect err}"
else
cl.send 'channelfind', {pattern: id}, (err, pchan)->
if err?
log "can't find channel I just created, #{util.inspect err}"
return
chan.cid = pchan.cid
log "created channel #{chan.channel_name}"
subchans = _.filter _.values(currentChannels), (schan)-> schan.pid is id
subchans.forEach (schan)->
schan.cpid = schan.pid = chan.cid
log schan
cl.send 'channelcreate', schan, (err, resp)->
if err?
log "unable to create channel #{schan.channel_name}, #{util.inspect err}"
else
log "created channel #{schan.channel_name}"
for id, chan of currentServerChannels
if !currentChannels[id]? and !(chan.channel_flag_permanent == 1 && chan.channel_topic.indexOf("adminperm") > -1)
log util.inspect chan
if lastClients?
for client in lastClients
moveClientToHome(client, currentServerChannels) if client.cid is chan.cid
cl.send 'channeldelete', {force: 1, cid: chan.cid}, (err)->
if err?
log "unable to delete #{id}, #{util.inspect err}"
else
log "deleted channel #{id}"
cl.send 'clientlist', ['uid', 'away', 'voice', 'times', 'groups', 'info'], (err, clients)->
if err?
log "unable to fetch clients, #{util.inspect err}"
return nextUpdate()
return nextUpdate() if !clients?
clients = [clients] if _.isObject(clients) and !_.isArray(clients)
invGroups = _.invert serverGroups
lastClients = clients
nUsrCache = {}
for id, usr of userCache
if _.findWhere(clients, {client_unique_identifier: id})? && usr.nextUpdate<(new Date().getTime())
nUsrCache[id] = usr
userCache = nUsrCache
checkClient = (client, user)->
targetGroups = []
if user?
if user._id not in onlineUsers
User.update {_id: user._id}, {$set: {tsonline: true}}, (err)->
if err?
console.log "Unable to mark #{user._id} as tsonline, #{err}"
else
console.log "Marked #{user._id} as online"
onlineUsersNow.push user._id if user._id not in onlineUsersNow
if !user? or !user.vouch?
targetGroups.push parseInt invGroups["Guest"]
else if "admin" in user.authItems
targetGroups.push parseInt invGroups["Server Admin"]
else
targetGroups.push parseInt invGroups["Normal"]
groups = []
if _.isNumber client.client_servergroups
groups.push client.client_servergroups
else if _.isString client.client_servergroups
groups = client.client_servergroups.split(',').map(parseInt)
for id in targetGroups
unless id in groups
log "adding server group #{serverGroups[id]} to #{client.client_nickname}"
cl.send 'servergroupaddclient', {sgid: id, cldbid: client.client_database_id}, (err)->
if err?
log "unable to assign group, #{util.inspect err}"
for id in groups
unless id in targetGroups
log "removing server group #{serverGroups[id]} from #{client.client_nickname}"
cl.send 'servergroupdelclient', {sgid: id, cldbid: client.client_database_id}, (err, resp)->
if err?
log "unable to remove group, #{util.inspect err}"
uchan = currentChannels["Unknown"]
if user?
if !user.vouch? or !user.vouch.leagues? or user.vouch.leagues.length is 0
cl.send 'clientkick', {clid: client.clid, reasonid: 5, reasonmsg: "You are not vouched into the league."}, (err)->
if err?
console.log "Cannot kick #{client.clid}, #{err}"
else
uplyr = null
umatch = _.find matches, (match)->
return false if match.Info.MatchType > 1
uplyr = _.findWhere(match.Details.Players, {SID: user.steam.steamid})
uplyr? and uplyr.Team < 2
mid = null
teamn = null
cname = null
if umatch?
mid = umatch.Details.MatchId
teamn = if uplyr.Team is 0 then "Radiant" else "Dire"
cname = teamn+" "+mid
if umatch? && currentChannels[cname]? && currentChannels[cname].cid? && currentChannels[cname].cid isnt 0
tchan = currentChannels[cname]
if tchan.cid isnt client.cid
log "moving client #{client.client_nickname} into #{cname}"
cl.send 'clientmove', {cid: tchan.cid, clid: client.clid}, (err)->
if err?
log "unable to move client to channel... #{util.inspect err}"
else
tchan = currentChannels["Lobby"]
bchan = currentChannels["Bounce"]
if ((bchan? and bchan.cid? and client.cid is bchan.cid) or (uchan.cid? && client.cid is uchan.cid)) && (tchan.cid? && tchan.cid != 0)
log "moving client #{client.client_nickname} out of unknown/bounce channel"
if user.vouch.leagues? && user.vouch.leagues.length > 0
moveClientToHome(client, currentServerChannels)
else
cl.send 'clientmove', {cid: tchan.cid, clid: client.clid}, (err)->
if err?
log "unable to move client to lobby... #{util.inspect err}"
else
tchan = currentChannels["Unknown"]
if tchan.cid? && tchan.cid != 0 && client.cid isnt tchan.cid
log "moving client #{client.client_nickname} to the unknown channel"
cl.send 'clientmove', {cid: tchan.cid, clid: client.clid}, (err)->
if err?
log "unable to move client to unknown channel... #{util.inspect err}"
unless client.clid in messagedUids
messagedUids.push client.clid
cl.send 'sendtextmessage', {targetmode: 1, target: client.clid, msg: "Welcome to the FPL teamspeak. Please paste your token here. Read the description of this channel for instructions if needed."}, (err)->
if err?
log "can't send text message to #{client.client_nickname}, #{util.inspect err}"
setTimeout ->
messagedUids = _.without messagedUids, client.clid
, 30000
clids = []
invGroups = _.invert serverGroups
nonPlayer = invGroups["NonPlayer"]
clients.forEach (client)->
return unless client.client_type is 0
return if nonPlayer? and "#{client.client_servergroups}" is nonPlayer
clids.push client.clid
uid = client.client_unique_identifier
user = userCache[uid]
if !user? and uid not in checkedUids
checkedUids.push uid
User.findOne {tsuniqueids: uid}, (err, usr)->
if err?
log "unable to lookup #{uid}, #{util.inspect err}"
return
if usr?
user = userCache[uid] = usr.toObject()
user.nextUpdate = new Date().getTime()+300000 #5 minutes
cl.send 'clientedit', {clid: client.clid, client_description: usr.profile.name}, (err)->
if err?
log "Unable to edit client #{client.clid}, #{util.inspect err}"
checkClient client, user
else
checkClient client, user
checkedUids = _.union clids
for onlineu in onlineUsers
unless onlineu in onlineUsersNow
User.update {_id: onlineu}, {$set: {tsonline: false}}, (err)->
if err?
console.log "Unable to set user #{onlineu} to offline, #{err}"
else
console.log "Marked user #{onlineu} as offline"
onlineUsers = onlineUsersNow
onlineUsersNow = []
nextUpdate()
initClient()
| true | mongoose = require "mongoose"
ActiveMatch = require "./model/activeMatch"
User = require "./model/user"
League = require "./model/league"
TeamSpeakClient = require "node-teamspeak"
util = require "util"
_ = require "lodash"
typeIsArray = ( value ) ->
value and
typeof value is 'object' and
value instanceof Array and
typeof value.length is 'number' and
typeof value.splice is 'function' and
not ( value.propertyIsEnumerable 'length' )
log = console.log
if process.env.IGNORE_ERRORS?
process.on 'uncaughtException', (err)->
console.log "Uncaught exception! #{err}"
console.log "Setting up our database connection..."
if !process.env.MONGODB_URL?
console.log "MONGODB_URL env variable required!"
return
tsIp = process.env.TEAMSPEAK_IP
if !tsIp?
console.log "TEAMSPEAK_IP env variable required!"
return
tsPort = process.env.TEAMSPEAK_PORT
if !tsPort?
parts = tsIp.split ":"
if parts? && parts.length is 2
tsPort = parseInt parts[1]
tsIp = parts[0]
else
console.log "Using default teamspeak_port"
tsPort = 10011
tsUser = process.env.TEAMSPEAK_USER
if !tsUser?
console.log "TEAMSPEAK_USER env variable required!"
return
tsPassword = process.env.TEAMSPEAK_PASSWORD
if !tsPassword?
console.log "TEAMSPEAK_PASSWORD env variable required!"
return
mongoose.connect(process.env.MONGODB_URL)
User.update {}, {$set: {tsonline: false}}, {multi: true}, (err)->
if err?
console.log "Unable to set tsonline to false on everyone, #{err}"
defaultChannels =
"Lobby":
channel_name: "Lobby"
channel_codec_quality: 10
#channel_flag_default: 1
channel_flag_permanent: 1
channel_description: "General chat."
"[spacer2]":
channel_name: "[spacer2]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
"Lounge 1":
channel_name: "Lounge 1"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 1"
"Lounge 2":
channel_name: "Lounge 2"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 2"
"Lounge 3":
channel_name: "Lounge 3"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 3"
"Lounge 4":
channel_name: "Lounge 4"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 4"
"Lounge 5":
channel_name: "Lounge 5"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 5"
"Lounge 6":
channel_name: "Lounge 6"
channel_codec_quality: 10
channel_flag_permanent: 1
channel_description: "Lounge 6"
"[spacer1]":
channel_name: "[spacer1]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
"AFK":
channel_name: "AFK"
channel_codec_quality: 1
channel_flag_permanent: 1
channel_forced_silence: 1
channel_needed_talk_power: 99999
"Unknown":
channel_name: "Unknown"
channel_codec_quality: 1
channel_description: "To verify your identity, follow these steps:\n 1. Left click your name at the top right of the FPL client.\n 2. Click \"Teamspeak Info\".\n 3. Copy the token in the window, and paste it into the text chat with the user \"FPL Server\" who will send you a message."
channel_flag_permanent: 1
channel_forced_silence: 1
channel_needed_talk_power: 99999
channel_password: "PI:PASSWORD:<PASSWORD>END_PI"
"Bounce":
channel_name: "Bounce"
channel_codec_quality: 1
channel_description: "This is a temporary channel, the bot should move you out immediately."
channel_flag_permanent: 1
channel_flag_default: 1
"Lobby":
channel_name: "Lobby"
channel_codec_quality: 10
#channel_flag_default: 1
channel_flag_permanent: 1
channel_description: "General chat."
"[spacer0]":
channel_name: "[spacer0]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
"[spacer3]":
channel_name: "[spacer3]"
channel_flag_permanent: 1
channel_max_clients: 0
channel_flag_maxclients_unlimited: 0
serverGroups = {}
cl = null
updateInterval = null
cid = 0
me = null
connected = false
clientCache = {}
userCache = {}
lastCurrentServerChannels = {}
checkedUids = []
messagedUids = []
onlineUsers = []
onlineUsersNow = []
lastClients = null
lastLeagues = null
moveClientToHome = (client, currentServerChannels)->
user = userCache[client.client_unique_identifier]
if user?
if user.vouch.leagues.length > 0
if lastLeagues?
league = _.findWhere lastLeagues, {_id: user.vouch.leagues[0]}
if league?
chan = currentServerChannels[league.Name]
if chan? and chan.cid?
cl.send 'clientmove', {cid: chan.cid, clid: client.clid}, (err)->
if err?
console.log "Can't move client to his home, #{err}"
else
console.log "Unable to move client home, channel #{league.Name} not found."
else
console.log "Unable to move client home, league #{user.profile.leagues[0]} not found."
else
chan = currentServerChannels.Lobby
if chan? and chan.cid?
cl.send 'clientmove', {cid: chan.cid, clid: client.clid}, (err)->
if err?
console.log "Can't move client to his home, #{err}"
initServerGroups = (cb)->
cl.send 'servergrouplist', (err, resp)->
if err?
log "error fetching server group list! #{err}"
else
if resp?
resp = [resp] unless typeIsArray resp
for group in resp
continue if group.type != 1
serverGroups[parseInt(group.sgid)] = group.name
console.log "#{group.sgid} = #{group.name}"
else
log "no server group response! this will be broken..."
cb()
initNotify = (cb)->
cl.send 'servernotifyregister', {event: "textprivate", id: 0}, (err)->
if err?
log "error registering text message notify! #{err}"
cb()
initClient = ->
cl = new TeamSpeakClient(tsIp, tsPort)
cl.on "connect", ->
connected = true
cid++
log "connected to the server"
cl.send 'login', {
client_login_name: tsUser
client_login_password: PI:PASSWORD:<PASSWORD>END_PI
}, (err, response, rawResponse) ->
cl.send 'use', { sid: 1 }, (err, response, rawResponse) ->
if err?
log "unable to select server, #{err}"
return
cl.send 'instanceedit', {serverinstance_serverquery_flood_commands: 999, serverinstance_serverquery_flood_time: 5}, (err)->
log "error changing query flood limit, #{util.inspect err}" if err?
initServerGroups ->
initNotify ->
cl.send 'whoami', (err, resp)->
if err?
log "error checking whoami!"
log err
return
me = resp
cl.send 'clientupdate', {clid: me.client_id, client_nickname: "FPL Server"}, (err)->
if err?
log "unable to change nickname, #{util.inspect err}"
log "ready, starting update loop..."
cid++
updateTeamspeak(cid)
cl.on "error", (err)->
log "socket error, #{err}"
cl.on "textmessage", (msg)->
return if msg.targetmode isnt 1 or msg.invokerid is me.client_id
log "CHAT #{msg.invokername}: #{msg.msg}"
cl.send 'clientinfo', {clid: msg.invokerid}, (err, client)->
if err?
log "can't lookup client, #{util.inspect err}"
return
if !client?
log "no client for #{msg.invokerid}"
return
client.clid = msg.invokerid
return moveClientToHome(client, lastCurrentServerChannels) if msg.msg is "moveme"
uid = client.client_unique_identifier
User.findOne {tsonetimeid: msg.msg.trim()}, (err, usr)->
if err?
log "unable to lookup tsonetimeid #{msg.msg}, #{util.inspect err}"
return
if usr?
cl.send 'sendtextmessage', {targetmode: 1, target: msg.invokerid, msg: "Welcome, #{usr.profile.name}!"}
cl.send 'clientedit', {clid: msg.invokerid, client_description: usr.profile.name}, (err)->
if err?
log "Unable to edit client #{client.cid}, #{util.inspect err}"
user = userCache[uid] = usr.toObject()
user.nextUpdate = new Date().getTime()+300000 #5 minutes
user.tsuniqueids = user.tsuniqueids || [uid]
user.tsuniqueids.push uid if uid not in user.tsuniqueids
User.update {_id: usr._id}, {$set: {tsuniqueids: user.tsuniqueids, tsonetimeid: null}}, (err)->
if err?
log "unable to save tsuniqueid, #{err}"
else
cl.send 'sendtextmessage', {targetmode: 1, target: msg.invokerid, msg: "Your message, #{msg.msg}, isn't a valid token. Please try again."}
cl.on "close", (err)->
log "connection closed, reconnecting in 10 sec"
connected = false
if updateInterval?
clearInterval updateInterval
updateInterval = null
setTimeout ->
initClient()
, 10000
currentServerChannels = {}
updateTeamspeak = (myid)->
if myid != cid or !connected
log "terminating old update loop #{myid}"
return
currentChannels = {}
lastCurrentServerChannels = currentServerChannels
currentServerChannels = {}
pend = cl.getPending()
updcalled = false
nextUpdate = ->
return if npdcalled
npdcalled = true
setTimeout ->
updateTeamspeak(myid)
, 2000
if pend.length > 0
log "commands still pending, deferring update"
nextUpdate()
return
cl.send 'channellist', ['topic', 'flags', 'limits'], (err, resp)->
if err?
log "error fetching client list, #{util.inspect err}"
return nextUpdate()
for chan in resp
currentServerChannels[chan.channel_name] = chan
echan = defaultChannels[chan.channel_name]
if echan?
echan.cid = chan.cid
echan.pid = chan.pid
League.find {}, (err, leagues)->
if err?
log "error finding active leagues, #{util.inspect err}"
return nextUpdate()
lastLeagues = leagues
leagues.forEach (league)->
lid = league._id
rchan = league.Name
if !league.Archived && !league.NoChannel
exist = currentServerChannels[rchan]
if exist?
currentChannels[rchan] = exist
else
currentChannels[rchan] =
channel_name: rchan
channel_codec_quality: 10
channel_description: "Lobby for league #{league.Name}."
channel_flag_permanent: 1
ActiveMatch.find {}, (err, matches)->
if err?
log "error fetching active matches, #{util.inspect err}"
return nextUpdate()
matches.forEach (match)->
mid = match.Details.MatchId || 0
rchann = ""
if match.Info.MatchType == 0
capt = _.findWhere match.Details.Players, {SID: match.Info.Owner}
rchann = "#{capt.Name}'s Startgame"
else if match.Info.MatchType == 2
return
else if match.Info.MatchType == 1
capts = _.filter match.Details.Players, (plyr)-> plyr.IsCaptain
rchann = "#{capts[0].Name} vs. #{capts[1].Name}"
schan = currentServerChannels[rchann]
if schan?
currentChannels[rchann] = schan
subs = _.filter _.values(currentServerChannels), (chan)-> chan.pid is schan.cid
for sub in subs
currentChannels[sub.channel_name] = sub
else
currentChannels[rchann] =
channel_name: rchann
channel_codec_quality: 10
channel_description: "Root channel for match #{mid}."
channel_flag_permanent: 1
channel_password: "#{match.Info.Owner}"
currentChannels["Radiant #{mid}"] =
channel_name: "Radiant #{mid}"
channel_codec_quality: 10
channel_description: "Radiant channel for match #{mid}."
channel_flag_permanent: 1
channel_password: "#{match.Info.Owner}"
pid: rchann
currentChannels["Dire #{mid}"] =
channel_name: "Dire #{mid}"
channel_codec_quality: 10
channel_description: "Dire channel for match #{mid}."
channel_flag_permanent: 1
channel_password: "#{match.Info.Owner}"
pid: rchann
currentChannels["Spectator #{mid} #1"] =
channel_name: "Spectator #{mid} #1"
channel_codec_quality: 10
channel_description: "Spectator #1 channel for match #{mid}."
channel_flag_permanent: 1
#channel_password: "#{match.Info.Owner}"
pid: rchann
for id, chan of defaultChannels
currentChannels[id] = chan
for id, chan of currentServerChannels
continue unless defaultChannels[id]?
currentChannels[id] = chan if currentChannels[id]?
_.keys(currentChannels).forEach (id)->
chan = currentChannels[id]
return if _.isString(chan.pid)
if !currentServerChannels[id]?
cl.send 'channelcreate', chan, (err, res)->
if err?
log "unable to create channel #{id}, #{util.inspect err}"
else
cl.send 'channelfind', {pattern: id}, (err, pchan)->
if err?
log "can't find channel I just created, #{util.inspect err}"
return
chan.cid = pchan.cid
log "created channel #{chan.channel_name}"
subchans = _.filter _.values(currentChannels), (schan)-> schan.pid is id
subchans.forEach (schan)->
schan.cpid = schan.pid = chan.cid
log schan
cl.send 'channelcreate', schan, (err, resp)->
if err?
log "unable to create channel #{schan.channel_name}, #{util.inspect err}"
else
log "created channel #{schan.channel_name}"
for id, chan of currentServerChannels
if !currentChannels[id]? and !(chan.channel_flag_permanent == 1 && chan.channel_topic.indexOf("adminperm") > -1)
log util.inspect chan
if lastClients?
for client in lastClients
moveClientToHome(client, currentServerChannels) if client.cid is chan.cid
cl.send 'channeldelete', {force: 1, cid: chan.cid}, (err)->
if err?
log "unable to delete #{id}, #{util.inspect err}"
else
log "deleted channel #{id}"
cl.send 'clientlist', ['uid', 'away', 'voice', 'times', 'groups', 'info'], (err, clients)->
if err?
log "unable to fetch clients, #{util.inspect err}"
return nextUpdate()
return nextUpdate() if !clients?
clients = [clients] if _.isObject(clients) and !_.isArray(clients)
invGroups = _.invert serverGroups
lastClients = clients
nUsrCache = {}
for id, usr of userCache
if _.findWhere(clients, {client_unique_identifier: id})? && usr.nextUpdate<(new Date().getTime())
nUsrCache[id] = usr
userCache = nUsrCache
checkClient = (client, user)->
targetGroups = []
if user?
if user._id not in onlineUsers
User.update {_id: user._id}, {$set: {tsonline: true}}, (err)->
if err?
console.log "Unable to mark #{user._id} as tsonline, #{err}"
else
console.log "Marked #{user._id} as online"
onlineUsersNow.push user._id if user._id not in onlineUsersNow
if !user? or !user.vouch?
targetGroups.push parseInt invGroups["Guest"]
else if "admin" in user.authItems
targetGroups.push parseInt invGroups["Server Admin"]
else
targetGroups.push parseInt invGroups["Normal"]
groups = []
if _.isNumber client.client_servergroups
groups.push client.client_servergroups
else if _.isString client.client_servergroups
groups = client.client_servergroups.split(',').map(parseInt)
for id in targetGroups
unless id in groups
log "adding server group #{serverGroups[id]} to #{client.client_nickname}"
cl.send 'servergroupaddclient', {sgid: id, cldbid: client.client_database_id}, (err)->
if err?
log "unable to assign group, #{util.inspect err}"
for id in groups
unless id in targetGroups
log "removing server group #{serverGroups[id]} from #{client.client_nickname}"
cl.send 'servergroupdelclient', {sgid: id, cldbid: client.client_database_id}, (err, resp)->
if err?
log "unable to remove group, #{util.inspect err}"
uchan = currentChannels["Unknown"]
if user?
if !user.vouch? or !user.vouch.leagues? or user.vouch.leagues.length is 0
cl.send 'clientkick', {clid: client.clid, reasonid: 5, reasonmsg: "You are not vouched into the league."}, (err)->
if err?
console.log "Cannot kick #{client.clid}, #{err}"
else
uplyr = null
umatch = _.find matches, (match)->
return false if match.Info.MatchType > 1
uplyr = _.findWhere(match.Details.Players, {SID: user.steam.steamid})
uplyr? and uplyr.Team < 2
mid = null
teamn = null
cname = null
if umatch?
mid = umatch.Details.MatchId
teamn = if uplyr.Team is 0 then "Radiant" else "Dire"
cname = teamn+" "+mid
if umatch? && currentChannels[cname]? && currentChannels[cname].cid? && currentChannels[cname].cid isnt 0
tchan = currentChannels[cname]
if tchan.cid isnt client.cid
log "moving client #{client.client_nickname} into #{cname}"
cl.send 'clientmove', {cid: tchan.cid, clid: client.clid}, (err)->
if err?
log "unable to move client to channel... #{util.inspect err}"
else
tchan = currentChannels["Lobby"]
bchan = currentChannels["Bounce"]
if ((bchan? and bchan.cid? and client.cid is bchan.cid) or (uchan.cid? && client.cid is uchan.cid)) && (tchan.cid? && tchan.cid != 0)
log "moving client #{client.client_nickname} out of unknown/bounce channel"
if user.vouch.leagues? && user.vouch.leagues.length > 0
moveClientToHome(client, currentServerChannels)
else
cl.send 'clientmove', {cid: tchan.cid, clid: client.clid}, (err)->
if err?
log "unable to move client to lobby... #{util.inspect err}"
else
tchan = currentChannels["Unknown"]
if tchan.cid? && tchan.cid != 0 && client.cid isnt tchan.cid
log "moving client #{client.client_nickname} to the unknown channel"
cl.send 'clientmove', {cid: tchan.cid, clid: client.clid}, (err)->
if err?
log "unable to move client to unknown channel... #{util.inspect err}"
unless client.clid in messagedUids
messagedUids.push client.clid
cl.send 'sendtextmessage', {targetmode: 1, target: client.clid, msg: "Welcome to the FPL teamspeak. Please paste your token here. Read the description of this channel for instructions if needed."}, (err)->
if err?
log "can't send text message to #{client.client_nickname}, #{util.inspect err}"
setTimeout ->
messagedUids = _.without messagedUids, client.clid
, 30000
clids = []
invGroups = _.invert serverGroups
nonPlayer = invGroups["NonPlayer"]
clients.forEach (client)->
return unless client.client_type is 0
return if nonPlayer? and "#{client.client_servergroups}" is nonPlayer
clids.push client.clid
uid = client.client_unique_identifier
user = userCache[uid]
if !user? and uid not in checkedUids
checkedUids.push uid
User.findOne {tsuniqueids: uid}, (err, usr)->
if err?
log "unable to lookup #{uid}, #{util.inspect err}"
return
if usr?
user = userCache[uid] = usr.toObject()
user.nextUpdate = new Date().getTime()+300000 #5 minutes
cl.send 'clientedit', {clid: client.clid, client_description: usr.profile.name}, (err)->
if err?
log "Unable to edit client #{client.clid}, #{util.inspect err}"
checkClient client, user
else
checkClient client, user
checkedUids = _.union clids
for onlineu in onlineUsers
unless onlineu in onlineUsersNow
User.update {_id: onlineu}, {$set: {tsonline: false}}, (err)->
if err?
console.log "Unable to set user #{onlineu} to offline, #{err}"
else
console.log "Marked user #{onlineu} as offline"
onlineUsers = onlineUsersNow
onlineUsersNow = []
nextUpdate()
initClient()
|
[
{
"context": "ation?.annotations ? []\n annotation._key ?= Math.random()\n isPriorAnnotation = annotation isnt @pr",
"end": 1238,
"score": 0.9068441987037659,
"start": 1227,
"tag": "KEY",
"value": "Math.random"
},
{
"context": " parseInt(@props.frame)\n mar... | app/classifier/tasks/drawing/markings-renderer.cjsx | Crentist/Panoptes-frontend-spanish | 1 | React = require 'react'
drawingTools = require '../../drawing-tools'
module.exports = React.createClass
displayName: 'MarkingsRenderer'
getDefaultProps: ->
classification: null
annotation: null
workflow: null
scale: null
getInitialState: ->
selection: null
oldSetOfMarks: []
componentWillReceiveProps: (nextProps) ->
# console.log 'Old marks were', @state.oldSetOfMarks
newSetOfMarks = []
# Automatically select new marks.
annotations = nextProps.classification?.annotations ? []
annotation = annotations[annotations.length - 1]
if annotation?
taskDescription = @props.workflow?.tasks[annotation.task]
if taskDescription?.type is 'drawing' and Array.isArray annotation.value
for mark in annotation.value
newSetOfMarks.push mark
if nextProps.annotation is @props.annotation and mark not in @state.oldSetOfMarks
# console.log 'New mark!', mark
@setState selection: mark
else
@setState selection: null
@setState oldSetOfMarks: newSetOfMarks
# console.log 'Marks are now', newSetOfMarks
render: ->
<g>
{for annotation in @props.classification?.annotations ? []
annotation._key ?= Math.random()
isPriorAnnotation = annotation isnt @props.annotation
taskDescription = @props.workflow.tasks[annotation.task]
if taskDescription.type is 'drawing'
<g key={annotation._key} className="marks-for-annotation" data-disabled={isPriorAnnotation || null}>
{for mark, i in annotation.value when parseInt(mark.frame) is parseInt(@props.frame)
mark._key ?= Math.random()
toolDescription = taskDescription.tools[mark.tool]
toolEnv =
containerRect: @props.containerRect
scale: @props.scale
disabled: isPriorAnnotation
selected: mark is @state.selection and not isPriorAnnotation
getEventOffset: @props.getEventOffset
toolProps =
classification: @props.classification
mark: mark
details: toolDescription.details
color: toolDescription.color
toolMethods =
onChange: @handleChange.bind this, i
onSelect: @handleSelect.bind this, annotation, mark
onDeselect: @handleDeselect
onDestroy: @handleDestroy.bind this, annotation, mark
ToolComponent = drawingTools[toolDescription.type]
<ToolComponent key={mark._key} {...toolProps} {...toolEnv} {...toolMethods} />}
</g>}
</g>
handleChange: (markIndex, mark) ->
@props.annotation.value[markIndex] = mark
@props.onChange @props.annotation
handleSelect: (annotation, mark) ->
@setState selection: mark
markIndex = annotation.value.indexOf mark
annotation.value.splice markIndex, 1
annotation.value.push mark
@props.classification.update 'annotations'
handleDeselect: ->
@setState selection: null
handleDestroy: (annotation, mark) ->
if mark is @state.selection
@setState selection: null
markIndex = annotation.value.indexOf mark
annotation.value.splice markIndex, 1
@props.classification.update 'annotations'
| 174355 | React = require 'react'
drawingTools = require '../../drawing-tools'
module.exports = React.createClass
displayName: 'MarkingsRenderer'
getDefaultProps: ->
classification: null
annotation: null
workflow: null
scale: null
getInitialState: ->
selection: null
oldSetOfMarks: []
componentWillReceiveProps: (nextProps) ->
# console.log 'Old marks were', @state.oldSetOfMarks
newSetOfMarks = []
# Automatically select new marks.
annotations = nextProps.classification?.annotations ? []
annotation = annotations[annotations.length - 1]
if annotation?
taskDescription = @props.workflow?.tasks[annotation.task]
if taskDescription?.type is 'drawing' and Array.isArray annotation.value
for mark in annotation.value
newSetOfMarks.push mark
if nextProps.annotation is @props.annotation and mark not in @state.oldSetOfMarks
# console.log 'New mark!', mark
@setState selection: mark
else
@setState selection: null
@setState oldSetOfMarks: newSetOfMarks
# console.log 'Marks are now', newSetOfMarks
render: ->
<g>
{for annotation in @props.classification?.annotations ? []
annotation._key ?= <KEY>()
isPriorAnnotation = annotation isnt @props.annotation
taskDescription = @props.workflow.tasks[annotation.task]
if taskDescription.type is 'drawing'
<g key={annotation._key} className="marks-for-annotation" data-disabled={isPriorAnnotation || null}>
{for mark, i in annotation.value when parseInt(mark.frame) is parseInt(@props.frame)
mark._key ?= <KEY>()
toolDescription = taskDescription.tools[mark.tool]
toolEnv =
containerRect: @props.containerRect
scale: @props.scale
disabled: isPriorAnnotation
selected: mark is @state.selection and not isPriorAnnotation
getEventOffset: @props.getEventOffset
toolProps =
classification: @props.classification
mark: mark
details: toolDescription.details
color: toolDescription.color
toolMethods =
onChange: @handleChange.bind this, i
onSelect: @handleSelect.bind this, annotation, mark
onDeselect: @handleDeselect
onDestroy: @handleDestroy.bind this, annotation, mark
ToolComponent = drawingTools[toolDescription.type]
<ToolComponent key={mark._key} {...toolProps} {...toolEnv} {...toolMethods} />}
</g>}
</g>
handleChange: (markIndex, mark) ->
@props.annotation.value[markIndex] = mark
@props.onChange @props.annotation
handleSelect: (annotation, mark) ->
@setState selection: mark
markIndex = annotation.value.indexOf mark
annotation.value.splice markIndex, 1
annotation.value.push mark
@props.classification.update 'annotations'
handleDeselect: ->
@setState selection: null
handleDestroy: (annotation, mark) ->
if mark is @state.selection
@setState selection: null
markIndex = annotation.value.indexOf mark
annotation.value.splice markIndex, 1
@props.classification.update 'annotations'
| true | React = require 'react'
drawingTools = require '../../drawing-tools'
module.exports = React.createClass
displayName: 'MarkingsRenderer'
getDefaultProps: ->
classification: null
annotation: null
workflow: null
scale: null
getInitialState: ->
selection: null
oldSetOfMarks: []
componentWillReceiveProps: (nextProps) ->
# console.log 'Old marks were', @state.oldSetOfMarks
newSetOfMarks = []
# Automatically select new marks.
annotations = nextProps.classification?.annotations ? []
annotation = annotations[annotations.length - 1]
if annotation?
taskDescription = @props.workflow?.tasks[annotation.task]
if taskDescription?.type is 'drawing' and Array.isArray annotation.value
for mark in annotation.value
newSetOfMarks.push mark
if nextProps.annotation is @props.annotation and mark not in @state.oldSetOfMarks
# console.log 'New mark!', mark
@setState selection: mark
else
@setState selection: null
@setState oldSetOfMarks: newSetOfMarks
# console.log 'Marks are now', newSetOfMarks
render: ->
<g>
{for annotation in @props.classification?.annotations ? []
annotation._key ?= PI:KEY:<KEY>END_PI()
isPriorAnnotation = annotation isnt @props.annotation
taskDescription = @props.workflow.tasks[annotation.task]
if taskDescription.type is 'drawing'
<g key={annotation._key} className="marks-for-annotation" data-disabled={isPriorAnnotation || null}>
{for mark, i in annotation.value when parseInt(mark.frame) is parseInt(@props.frame)
mark._key ?= PI:KEY:<KEY>END_PI()
toolDescription = taskDescription.tools[mark.tool]
toolEnv =
containerRect: @props.containerRect
scale: @props.scale
disabled: isPriorAnnotation
selected: mark is @state.selection and not isPriorAnnotation
getEventOffset: @props.getEventOffset
toolProps =
classification: @props.classification
mark: mark
details: toolDescription.details
color: toolDescription.color
toolMethods =
onChange: @handleChange.bind this, i
onSelect: @handleSelect.bind this, annotation, mark
onDeselect: @handleDeselect
onDestroy: @handleDestroy.bind this, annotation, mark
ToolComponent = drawingTools[toolDescription.type]
<ToolComponent key={mark._key} {...toolProps} {...toolEnv} {...toolMethods} />}
</g>}
</g>
handleChange: (markIndex, mark) ->
@props.annotation.value[markIndex] = mark
@props.onChange @props.annotation
handleSelect: (annotation, mark) ->
@setState selection: mark
markIndex = annotation.value.indexOf mark
annotation.value.splice markIndex, 1
annotation.value.push mark
@props.classification.update 'annotations'
handleDeselect: ->
@setState selection: null
handleDestroy: (annotation, mark) ->
if mark is @state.selection
@setState selection: null
markIndex = annotation.value.indexOf mark
annotation.value.splice markIndex, 1
@props.classification.update 'annotations'
|
[
{
"context": "enQuerying('project').respondWith [{\n Name: 'test Project'\n _ref: '/project/2'\n }]\n\n @_createApp",
"end": 2474,
"score": 0.7926523089408875,
"start": 2462,
"tag": "NAME",
"value": "test Project"
}
] | test/spec/portfoliohierarchy/PortfolioHierarchyAppSpec.coffee | RallyHackathon/app-catalog | 1 | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.app.Context'
'Rally.test.mock.data.WsapiModelFactory'
'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp'
]
describe 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', ->
helpers
_createApp: (settings) ->
globalContext = Rally.environment.getContext()
context = Ext.create 'Rally.app.Context',
initialValues:
project: globalContext.getProject()
workspace: globalContext.getWorkspace()
user: globalContext.getUser()
subscription: globalContext.getSubscription()
options =
context: context
renderTo: 'testDiv'
if settings
options.settings = settings
@app = Ext.create 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', options
@waitForComponentReady(@app)
beforeEach ->
Rally.environment.getContext().context.subscription.Modules = ['Rally Portfolio Manager']
@userStoryModel = Rally.test.mock.data.WsapiModelFactory.getUserStoryModel()
@ajax.whenQuerying('typedefinition').respondWith [
Rally.test.mock.data.WsapiModelFactory.getModelDefinition('PortfolioItemStrategy')
]
afterEach ->
@app?.destroy()
it 'test draws portfolio tree', ->
interceptor = @ajax.whenQuerying('PortfolioItem/Strategy').respondWith [
{FormattedID: 'S1', ObjectID: '1', Name: 'Strategy 1'}
]
@_createApp().then =>
sinon.assert.calledOnce(interceptor)
expect(@app.query('rallyportfolioitemtreeitem').length).toBe 1
it 'test filter info displayed', ->
@ajax.whenQuerying('PortfolioItem/Strategy').respondWith()
@_createApp().then =>
expect(@app.getEl().down('.filterInfo')).toBeInstanceOf Ext.Element
it 'test project setting label is shown if following a specific project scope', ->
@ajax.whenQuerying('PortfolioItem/Strategy').respondWith()
@_createApp(
project: '/project/431439'
).then =>
@app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0])
expect(tooltipContent.dom.innerHTML).toContain 'Project'
expect(tooltipContent.dom.innerHTML).toContain 'Project 1'
@app.down('rallyfilterinfo').tooltip.destroy()
it 'test project setting label shows "Following Global Project Setting" if following global project scope', ->
@ajax.whenQuerying('project').respondWith [{
Name: 'test Project'
_ref: '/project/2'
}]
@_createApp().then =>
@app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0])
expect(tooltipContent.dom.innerHTML).toContain 'Following Global Project Setting'
@app.down('rallyfilterinfo').tooltip.destroy()
it 'test help component is shown', ->
@ajax.whenQuerying('PortfolioItem/Strategy').respondWith()
@_createApp().then =>
expect(@app.down('#header').getEl().down('.rally-help-icon').dom.innerHTML).toContain 'Help & Training'
it 'test empty query string does not create a filter', ->
@_createApp(
query: ''
).then =>
tree = @app.down('rallytree')
expect(tree.topLevelStoreConfig.filters.length).toBe 0
it 'test non-empty query string creates a filter', ->
@_createApp(
query: '(Name = "blah")'
).then =>
tree = @app.down('rallytree')
expect(tree.topLevelStoreConfig.filters.length).toBe 1
expect(tree.topLevelStoreConfig.filters[0].toString()).toEqual '(Name = "blah")'
it 'should display an error message if you do not have RPM turned on ', ->
Rally.environment.getContext().context.subscription.Modules = []
loadSpy = @spy Rally.data.util.PortfolioItemHelper, 'loadTypeOrDefault'
@_createApp().then =>
expect(loadSpy.callCount).toBe 0
expect(@app.down('#bodyContainer').getEl().dom.innerHTML).toContain 'You do not have RPM enabled for your subscription' | 201818 | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.app.Context'
'Rally.test.mock.data.WsapiModelFactory'
'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp'
]
describe 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', ->
helpers
_createApp: (settings) ->
globalContext = Rally.environment.getContext()
context = Ext.create 'Rally.app.Context',
initialValues:
project: globalContext.getProject()
workspace: globalContext.getWorkspace()
user: globalContext.getUser()
subscription: globalContext.getSubscription()
options =
context: context
renderTo: 'testDiv'
if settings
options.settings = settings
@app = Ext.create 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', options
@waitForComponentReady(@app)
beforeEach ->
Rally.environment.getContext().context.subscription.Modules = ['Rally Portfolio Manager']
@userStoryModel = Rally.test.mock.data.WsapiModelFactory.getUserStoryModel()
@ajax.whenQuerying('typedefinition').respondWith [
Rally.test.mock.data.WsapiModelFactory.getModelDefinition('PortfolioItemStrategy')
]
afterEach ->
@app?.destroy()
it 'test draws portfolio tree', ->
interceptor = @ajax.whenQuerying('PortfolioItem/Strategy').respondWith [
{FormattedID: 'S1', ObjectID: '1', Name: 'Strategy 1'}
]
@_createApp().then =>
sinon.assert.calledOnce(interceptor)
expect(@app.query('rallyportfolioitemtreeitem').length).toBe 1
it 'test filter info displayed', ->
@ajax.whenQuerying('PortfolioItem/Strategy').respondWith()
@_createApp().then =>
expect(@app.getEl().down('.filterInfo')).toBeInstanceOf Ext.Element
it 'test project setting label is shown if following a specific project scope', ->
@ajax.whenQuerying('PortfolioItem/Strategy').respondWith()
@_createApp(
project: '/project/431439'
).then =>
@app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0])
expect(tooltipContent.dom.innerHTML).toContain 'Project'
expect(tooltipContent.dom.innerHTML).toContain 'Project 1'
@app.down('rallyfilterinfo').tooltip.destroy()
it 'test project setting label shows "Following Global Project Setting" if following global project scope', ->
@ajax.whenQuerying('project').respondWith [{
Name: '<NAME>'
_ref: '/project/2'
}]
@_createApp().then =>
@app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0])
expect(tooltipContent.dom.innerHTML).toContain 'Following Global Project Setting'
@app.down('rallyfilterinfo').tooltip.destroy()
it 'test help component is shown', ->
@ajax.whenQuerying('PortfolioItem/Strategy').respondWith()
@_createApp().then =>
expect(@app.down('#header').getEl().down('.rally-help-icon').dom.innerHTML).toContain 'Help & Training'
it 'test empty query string does not create a filter', ->
@_createApp(
query: ''
).then =>
tree = @app.down('rallytree')
expect(tree.topLevelStoreConfig.filters.length).toBe 0
it 'test non-empty query string creates a filter', ->
@_createApp(
query: '(Name = "blah")'
).then =>
tree = @app.down('rallytree')
expect(tree.topLevelStoreConfig.filters.length).toBe 1
expect(tree.topLevelStoreConfig.filters[0].toString()).toEqual '(Name = "blah")'
it 'should display an error message if you do not have RPM turned on ', ->
Rally.environment.getContext().context.subscription.Modules = []
loadSpy = @spy Rally.data.util.PortfolioItemHelper, 'loadTypeOrDefault'
@_createApp().then =>
expect(loadSpy.callCount).toBe 0
expect(@app.down('#bodyContainer').getEl().dom.innerHTML).toContain 'You do not have RPM enabled for your subscription' | true | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.app.Context'
'Rally.test.mock.data.WsapiModelFactory'
'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp'
]
describe 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', ->
helpers
_createApp: (settings) ->
globalContext = Rally.environment.getContext()
context = Ext.create 'Rally.app.Context',
initialValues:
project: globalContext.getProject()
workspace: globalContext.getWorkspace()
user: globalContext.getUser()
subscription: globalContext.getSubscription()
options =
context: context
renderTo: 'testDiv'
if settings
options.settings = settings
@app = Ext.create 'Rally.apps.portfoliohierarchy.PortfolioHierarchyApp', options
@waitForComponentReady(@app)
beforeEach ->
Rally.environment.getContext().context.subscription.Modules = ['Rally Portfolio Manager']
@userStoryModel = Rally.test.mock.data.WsapiModelFactory.getUserStoryModel()
@ajax.whenQuerying('typedefinition').respondWith [
Rally.test.mock.data.WsapiModelFactory.getModelDefinition('PortfolioItemStrategy')
]
afterEach ->
@app?.destroy()
it 'test draws portfolio tree', ->
interceptor = @ajax.whenQuerying('PortfolioItem/Strategy').respondWith [
{FormattedID: 'S1', ObjectID: '1', Name: 'Strategy 1'}
]
@_createApp().then =>
sinon.assert.calledOnce(interceptor)
expect(@app.query('rallyportfolioitemtreeitem').length).toBe 1
it 'test filter info displayed', ->
@ajax.whenQuerying('PortfolioItem/Strategy').respondWith()
@_createApp().then =>
expect(@app.getEl().down('.filterInfo')).toBeInstanceOf Ext.Element
it 'test project setting label is shown if following a specific project scope', ->
@ajax.whenQuerying('PortfolioItem/Strategy').respondWith()
@_createApp(
project: '/project/431439'
).then =>
@app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0])
expect(tooltipContent.dom.innerHTML).toContain 'Project'
expect(tooltipContent.dom.innerHTML).toContain 'Project 1'
@app.down('rallyfilterinfo').tooltip.destroy()
it 'test project setting label shows "Following Global Project Setting" if following global project scope', ->
@ajax.whenQuerying('project').respondWith [{
Name: 'PI:NAME:<NAME>END_PI'
_ref: '/project/2'
}]
@_createApp().then =>
@app.down('rallyfilterinfo').tooltip.show()
tooltipContent = Ext.get(Ext.query('.filterInfoTooltip')[0])
expect(tooltipContent.dom.innerHTML).toContain 'Following Global Project Setting'
@app.down('rallyfilterinfo').tooltip.destroy()
it 'test help component is shown', ->
@ajax.whenQuerying('PortfolioItem/Strategy').respondWith()
@_createApp().then =>
expect(@app.down('#header').getEl().down('.rally-help-icon').dom.innerHTML).toContain 'Help & Training'
it 'test empty query string does not create a filter', ->
@_createApp(
query: ''
).then =>
tree = @app.down('rallytree')
expect(tree.topLevelStoreConfig.filters.length).toBe 0
it 'test non-empty query string creates a filter', ->
@_createApp(
query: '(Name = "blah")'
).then =>
tree = @app.down('rallytree')
expect(tree.topLevelStoreConfig.filters.length).toBe 1
expect(tree.topLevelStoreConfig.filters[0].toString()).toEqual '(Name = "blah")'
it 'should display an error message if you do not have RPM turned on ', ->
Rally.environment.getContext().context.subscription.Modules = []
loadSpy = @spy Rally.data.util.PortfolioItemHelper, 'loadTypeOrDefault'
@_createApp().then =>
expect(loadSpy.callCount).toBe 0
expect(@app.down('#bodyContainer').getEl().dom.innerHTML).toContain 'You do not have RPM enabled for your subscription' |
[
{
"context": "ull\n\n beforeEach ->\n alice = {alice: 'alice'}\n bob = {bob: 'bob'}\n charlie = {c",
"end": 949,
"score": 0.5720887184143066,
"start": 944,
"tag": "NAME",
"value": "alice"
},
{
"context": " alice = {alice: 'alice'}\n bob = {bob: 'bo... | test/server/common/crudControllerFactory.coffee | valueflowquality/gi-util-update | 0 | path = require 'path'
sinon = require 'sinon'
assert = require 'assert'
assert = require('chai').assert
expect = require('chai').expect
mocks = require '../mocks'
proxyquire = require 'proxyquire'
dir = path.normalize __dirname + '../../../../server'
module.exports = () ->
describe 'CrudControllerFactory', ->
stubs =
'../controllers/helper':
getOptions: ->
crudControllerFactory = proxyquire dir +
'/common/crudControllerFactory', stubs
it 'Exports a factory function', (done) ->
expect(crudControllerFactory).to.be.a 'function'
done()
describe 'Function: (model) -> { object } ', ->
mockModel =
name: "mockModel"
create: ->
update: ->
destroy: ->
findById: ->
find: ->
count: ->
controller = null
alice = null
bob = null
charlie = null
beforeEach ->
alice = {alice: 'alice'}
bob = {bob: 'bob'}
charlie = {charlie: 'charlie'}
controller = crudControllerFactory mockModel
describe 'returns an object with properties:', ->
it 'name: String', (done) ->
expect(controller).to.have.ownProperty 'name'
expect(controller.name).to.be.a 'string'
done()
it 'index: Function', (done) ->
expect(controller).to.have.ownProperty 'index'
expect(controller.index).to.be.a 'function'
done()
it 'create: Function', (done) ->
expect(controller).to.have.ownProperty 'create'
expect(controller.create).to.be.a 'function'
done()
it 'show: Function', (done) ->
expect(controller).to.have.ownProperty 'show'
expect(controller.show).to.be.a 'function'
done()
it 'update: Function', (done) ->
expect(controller).to.have.ownProperty 'update'
expect(controller.update).to.be.a 'function'
done()
it 'destroy: Function', (done) ->
expect(controller).to.have.ownProperty 'destroy'
expect(controller.destroy).to.be.a 'function'
done()
it 'count: Function', (done) ->
expect(controller).to.have.ownProperty 'count'
expect(controller.count).to.be.a 'function'
done()
describe 'name: String', ->
it 'exposes model.name as its name', (done) ->
expect(controller.name).to.equal mockModel.name
done()
describe 'index: Function: (req, res, next) -> next() or res.json', ->
req =
any: 'thing'
systemId: '123'
body: {}
res =
json: ->
options =
some: 'options'
beforeEach () ->
sinon.stub mockModel, 'find'
sinon.stub stubs['../controllers/helper'], 'getOptions'
stubs['../controllers/helper'].getOptions.returns options
res.json = sinon.spy()
afterEach () ->
mockModel.find.restore()
res.json.reset()
stubs['../controllers/helper'].getOptions.restore()
it 'gets options by passing req and model to helper.getOptions'
, (done) ->
mockModel.find.callsArg 1
controller.index req, {}, () ->
assert(
stubs['../controllers/helper'].getOptions.calledWith(
req, mockModel
), 'did not call helper.getOptions with req and /or model'
)
done()
it 'uses the options returned as the argument for model.find'
, (done) ->
mockModel.find.callsArg 1
controller.index req, {}, () ->
assert mockModel.find.calledWith(options)
, 'options not passed to model.find'
done()
it 'returns 404 code and the error if model.find returns an error'
, (done) ->
mockModel.find.callsArgWith 1, "an error", null, 0
controller.index req, res
assert res.json.calledWith(404, "an error")
, 'res.json did not 404 an error finding'
done()
it 'populates res.giResult with the result if next() is given'
, (done) ->
mockModel.find.callsArgWith 1, null, {a: 'result'}, 1
controller.index req, res, () ->
expect(res.giResult).to.deep.equal {a: 'result'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
mockModel.find.callsArgWith 1, null, {a: 'result'}, 1
controller.index req, res
assert res.json.calledWith(200, {a: 'result'})
, 'res.json not called with 200 code and/or result'
done()
describe 'create: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'create'
res.json = sinon.spy()
afterEach () ->
mockModel.create.restore()
res.json.reset()
it 'checks to see if body is an array', (done) ->
req.body = []
controller.create req, res, () ->
expect(res.giResult).to.be.an 'array'
expect(res.giResult.length).to.equal 0
done()
it 'calls model create once for each object', (done) ->
req.body = [alice, bob]
mockModel.create.callsArgWith 1, null, null
controller.create req, res
expect(mockModel.create.calledTwice).to.be.true
done()
it 'returns error messages for any failed objects ' +
'together with sucess results', (done) ->
req.body = [alice, bob, charlie]
mockModel.create.callsArgWith 1, "an error", null
mockModel.create.callsArgWith 1, null, bob
mockModel.create.callsArgWith 1, null, null
controller.create req, res
expect(res.json.calledWith 500).to.be.true
expect(res.json.getCall(0).args[1]).to.deep.equal [
{message: "an error", obj: alice},
{message: "create failed for reasons unknown", obj: charlie},
{message: "ok", obj: bob}
]
done()
it 'sets res.giResult if all sucessfully inserted', (done) ->
req.body = [alice, bob, charlie]
mockModel.create.callsArgWith 1, null, alice
mockModel.create.callsArgWith 1, null, bob
mockModel.create.callsArgWith 1, null, charlie
controller.create req, res, () ->
expect(res.json.called).to.be.false
expect(res.giResult).to.deep.equal [
{message: "ok", obj: alice},
{message: "ok", obj: bob},
{message: "ok", obj: charlie}
]
done()
it 'sets res.giResultCode to 200 if sucessful', (done) ->
req.body = [alice, bob, charlie]
mockModel.create.callsArgWith 1, null, alice
mockModel.create.callsArgWith 1, null, bob
mockModel.create.callsArgWith 1, null, charlie
controller.create req, res, () ->
expect(res.json.called).to.be.false
expect(res.giResultCode).to.equal 200
done()
it 'sets res.giResultCode to 500 if there are errors', (done) ->
req.body = [alice, bob, charlie]
mockModel.create.callsArgWith 1, null, alice
mockModel.create.callsArgWith 1, "an error", bob
mockModel.create.callsArgWith 1, null, charlie
controller.create req, res, () ->
expect(res.json.called).to.be.false
expect(res.giResultCode).to.equal 500
done()
it 'calls res.json with 200 if no callback specified', (done) ->
alice = {alice: 'alice'}
bob = {bob: 'bob'}
charlie = {charlie: 'charlie'}
req.body = [alice, bob, charlie]
mockModel.create.callsArgWith 1, null, alice
mockModel.create.callsArgWith 1, null, bob
mockModel.create.callsArgWith 1, null, charlie
controller.create req, res
expect(res.json.calledWith 200).to.be.true
expect(res.json.getCall(0).args[1]).to.deep.equal [
{message: "ok", obj: alice},
{message: "ok", obj: bob},
{message: "ok", obj: charlie}
]
done()
it 'sets req.body.systemId to the value given in req.systemId'
, (done) ->
mockModel.create.callsArgWith 1, null, null
expect(req.body.systemId).to.not.exist
controller.create req, res
expect(req.body.systemId).to.equal req.systemId
done()
it 'uses req.body as the first arg for model.create', (done) ->
mockModel.create.callsArgWith 1
req.body =
bob: 'bob'
expected =
bob: 'bob'
systemId: req.systemId
controller.create req, res
assert mockModel.create.calledWith(req.body)
, 'req.body not passed to model.create'
done()
it 'returns 500 code and the error if model.create returns an error'
, (done) ->
mockModel.create.callsArgWith 1, "an error", null
controller.create req, res
assert res.json.calledWith(500, {error: "an error"})
, 'res.json did not 500 an error creating'
done()
it 'populates res.giResult with the result if next() is given'
, (done) ->
mockModel.create.callsArgWith 1, null, {a: 'result'}
controller.create req, res, () ->
expect(res.giResult).to.deep.equal {a: 'result'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
mockModel.create.callsArgWith 1, null, {a: 'result'}
controller.create req, res
assert res.json.calledWith(200, {a: 'result'})
, 'res.json not called with 200 code and/or result'
done()
describe 'show: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'findById'
res.json = sinon.spy()
afterEach () ->
mockModel.findById.restore()
res.json.reset()
it 'returns 404 if req.params missing', (done) ->
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when req.params missing'
done()
it 'returns 404 if req.systemId missing', (done) ->
req.params =
some: 'thing'
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when req.params.id missing'
done()
it 'returns 404 if req.params.id missing', (done) ->
req.params =
id: 'anId'
delete req.systemId
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when req.systemId missing'
done()
it 'passes req.params.id to model.findById as first argument'
, (done) ->
req.params =
id: 'anId'
controller.show req, res
assert mockModel.findById.calledWith(req.params.id)
, 'req.params.id not passed to findById'
done()
it 'passes req.systemId to model.findById as second argument'
, (done) ->
req.params =
id: 'anId'
controller.show req, res
assert mockModel.findById.calledWith(sinon.match.any, req.systemId)
, 'req.systemId not passed to findbyId'
done()
it 'returns 404 if model.findById returns an error', (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, "an error", null
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when findbyId errors'
done()
it 'returns 404 if model.findById returns no object', (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, null, null
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when findbyId returns no object'
done()
it 'sets res.giResult with result and calls next if next given'
, (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, null, {a: 'result'}
controller.show req, res, () ->
expect(res.giResult).to.deep.equal {a: 'result'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, null, {a: 'result'}
controller.show req, res
assert res.json.calledWith(200, {a: 'result'})
, 'res.json not called with 200 code and/or result'
done()
describe 'update: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'update'
res.json = sinon.spy()
afterEach () ->
mockModel.update.restore()
res.json.reset()
it 'returns 400 if req.params missing', (done) ->
controller.update req, res
assert res.json.calledWith(400)
, '400 not returned when req.params missing'
done()
it 'returns 400 if req.params.id missing', (done) ->
req.params =
bob: 'bob'
controller.update req, res
assert res.json.calledWith(400)
, '400 not returned when req.params.id missing'
done()
it 'returns 400 if if req.systemId is missing', (done) ->
req.params =
id: 'bob'
delete req.systemId
controller.update req, res
assert res.json.calledWith(400)
, '400 not returne when req.systemId is missing'
done()
it 'sets req.body.systemId to the value given in req.systemId'
, (done) ->
req.params =
id: 'bob'
expect(req.body.systemId).to.not.exist
controller.update req, res
expect(req.body.systemId).to.equal req.systemId
done()
it 'removes _id if it is set on req.body', (done) ->
req.params =
id: 'bob'
req.body._id = 'bob'
controller.update req, res
payload = mockModel.update.getCall(0).args[1]
expect(payload).to.not.have.property '_id'
done()
it 'passes req.params.id to model.update as first argument'
, (done) ->
req.params =
id: 'anId'
controller.update req, res
assert mockModel.update.calledWith(req.params.id)
, 'req.params.id not passed to update'
done()
it 'passes req.body as the second arg for model.update', (done) ->
req.params =
id: 'anId'
req.body =
bob: 'bob'
_id: 'will be removed'
expected =
bob: 'bob'
systemId: req.systemId
controller.update req, res
assert mockModel.update.calledWith(sinon.match.any, expected)
, 'req.body not passed to model.update'
done()
it 'returns 404 if model.update returns an error', (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, "an error", null
controller.update req, res
assert res.json.calledWith(400, {message: "an error"})
, '400 not returned with error message when update errors'
done()
it 'returns 200 if model.update returns no object', (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, null, null
controller.update req, res
assert res.json.calledWith(200)
, '404 not returned when update returns no object'
done()
it 'sets res.giResult with obj and calls next if next given'
, (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, null, {a: 'obj'}
controller.update req, res, () ->
expect(res.giResult).to.deep.equal {a: 'obj'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, null, {a: 'obj'}
controller.update req, res
assert res.json.calledWith(200, {a: 'obj'})
, 'res.json not called with 200 code and/or result'
done()
describe 'destroy: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'destroy'
res.json = sinon.spy()
afterEach () ->
mockModel.destroy.restore()
res.json.reset()
it 'returns 404 if req.params missing', (done) ->
controller.destroy req, res
assert res.json.calledWith(404)
, '404 not returned when req.params missing'
done()
it 'returns 404 if req.params.id missing', (done) ->
req.params =
bob: 'bob'
controller.destroy req, res
assert res.json.calledWith(404)
, '404 not returned when req.params.id missing'
done()
it 'returns 404 if if req.systemId is missing'
, (done) ->
req.params =
id: 'bob'
delete req.systemId
controller.destroy req, res
assert res.json.calledWith(404)
, '404 not returned when req.systemId is missing'
done()
it 'passes req.params.id to model.destroy as first argument'
, (done) ->
req.params =
id: 'anId'
controller.destroy req, res
assert mockModel.destroy.calledWith(req.params.id)
, 'req.params.id not passed to model.destroy'
done()
it 'passes req.systemId to model.destroy as second argument'
, (done) ->
req.params =
id: 'anId'
controller.destroy req, res
assert mockModel.destroy.calledWith(sinon.match.any, req.systemId)
, 'req.systemId not passed to model.destroy'
done()
it 'returns 400 if model.destroy returns an error', (done) ->
req.params =
id: 'anId'
mockModel.destroy.callsArgWith 2, "an error"
controller.destroy req, res
assert res.json.calledWith(400, {message: "an error"})
, '400 not returned with error message when destroy errors'
done()
it 'sets res.giResult to Ok and calls next if next given'
, (done) ->
req.params =
id: 'anId'
mockModel.destroy.callsArgWith 2, null
controller.destroy req, res, () ->
expect(res.giResult).to.equal 'Ok'
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.destroy.callsArgWith 2, null
controller.destroy req, res
assert res.json.calledWith(200)
, 'res.json not called with 200 code'
done()
describe 'count: Function: (req, res, next) -> next() or res.json', ->
req =
any: 'thing'
systemId: '123'
body: {}
res =
json: ->
options =
query:
some: 'query'
beforeEach () ->
sinon.stub mockModel, 'count'
sinon.stub stubs['../controllers/helper'], 'getOptions'
stubs['../controllers/helper'].getOptions.returns options
res.json = sinon.spy()
afterEach () ->
mockModel.count.restore()
res.json.reset()
stubs['../controllers/helper'].getOptions.restore()
it 'gets options by passing req to helper.getOptions', (done) ->
mockModel.count.callsArg 1
controller.count req, {}, () ->
assert stubs['../controllers/helper'].getOptions.calledWith(
req, mockModel
), 'did not call helper.getOptions with req and/or model'
done()
it 'uses the options.query returned as the argument for model.count'
, (done) ->
mockModel.count.callsArg 1
controller.count req, {}, () ->
assert mockModel.count.calledWith(options.query)
, 'options.query not passed to model.count'
done()
it 'returns 404 and the error if model.count returns an error'
, (done) ->
mockModel.count.callsArgWith 1, "an error"
controller.count req, res
assert res.json.calledWith(404, {message: "an error"})
, '404 not returned with error message when destroy errors'
done()
it 'sets res.giResult to count:result and calls next if next given'
, (done) ->
mockModel.count.callsArgWith 1, null, 15
controller.count req, res, () ->
expect(res.giResult).to.deep.equal {count: 15}
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.count.callsArgWith 1, null, 16
controller.count req, res
assert res.json.calledWith(200, 16)
, 'res.json not called with 200 code and/or correct result'
done() | 38742 | path = require 'path'
sinon = require 'sinon'
assert = require 'assert'
assert = require('chai').assert
expect = require('chai').expect
mocks = require '../mocks'
proxyquire = require 'proxyquire'
dir = path.normalize __dirname + '../../../../server'
module.exports = () ->
describe 'CrudControllerFactory', ->
stubs =
'../controllers/helper':
getOptions: ->
crudControllerFactory = proxyquire dir +
'/common/crudControllerFactory', stubs
it 'Exports a factory function', (done) ->
expect(crudControllerFactory).to.be.a 'function'
done()
describe 'Function: (model) -> { object } ', ->
mockModel =
name: "mockModel"
create: ->
update: ->
destroy: ->
findById: ->
find: ->
count: ->
controller = null
alice = null
bob = null
charlie = null
beforeEach ->
alice = {alice: '<NAME>'}
bob = {bob: '<PASSWORD>'}
charlie = {charlie: 'charlie'}
controller = crudControllerFactory mockModel
describe 'returns an object with properties:', ->
it 'name: String', (done) ->
expect(controller).to.have.ownProperty 'name'
expect(controller.name).to.be.a 'string'
done()
it 'index: Function', (done) ->
expect(controller).to.have.ownProperty 'index'
expect(controller.index).to.be.a 'function'
done()
it 'create: Function', (done) ->
expect(controller).to.have.ownProperty 'create'
expect(controller.create).to.be.a 'function'
done()
it 'show: Function', (done) ->
expect(controller).to.have.ownProperty 'show'
expect(controller.show).to.be.a 'function'
done()
it 'update: Function', (done) ->
expect(controller).to.have.ownProperty 'update'
expect(controller.update).to.be.a 'function'
done()
it 'destroy: Function', (done) ->
expect(controller).to.have.ownProperty 'destroy'
expect(controller.destroy).to.be.a 'function'
done()
it 'count: Function', (done) ->
expect(controller).to.have.ownProperty 'count'
expect(controller.count).to.be.a 'function'
done()
describe 'name: String', ->
it 'exposes model.name as its name', (done) ->
expect(controller.name).to.equal mockModel.name
done()
describe 'index: Function: (req, res, next) -> next() or res.json', ->
req =
any: 'thing'
systemId: '123'
body: {}
res =
json: ->
options =
some: 'options'
beforeEach () ->
sinon.stub mockModel, 'find'
sinon.stub stubs['../controllers/helper'], 'getOptions'
stubs['../controllers/helper'].getOptions.returns options
res.json = sinon.spy()
afterEach () ->
mockModel.find.restore()
res.json.reset()
stubs['../controllers/helper'].getOptions.restore()
it 'gets options by passing req and model to helper.getOptions'
, (done) ->
mockModel.find.callsArg 1
controller.index req, {}, () ->
assert(
stubs['../controllers/helper'].getOptions.calledWith(
req, mockModel
), 'did not call helper.getOptions with req and /or model'
)
done()
it 'uses the options returned as the argument for model.find'
, (done) ->
mockModel.find.callsArg 1
controller.index req, {}, () ->
assert mockModel.find.calledWith(options)
, 'options not passed to model.find'
done()
it 'returns 404 code and the error if model.find returns an error'
, (done) ->
mockModel.find.callsArgWith 1, "an error", null, 0
controller.index req, res
assert res.json.calledWith(404, "an error")
, 'res.json did not 404 an error finding'
done()
it 'populates res.giResult with the result if next() is given'
, (done) ->
mockModel.find.callsArgWith 1, null, {a: 'result'}, 1
controller.index req, res, () ->
expect(res.giResult).to.deep.equal {a: 'result'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
mockModel.find.callsArgWith 1, null, {a: 'result'}, 1
controller.index req, res
assert res.json.calledWith(200, {a: 'result'})
, 'res.json not called with 200 code and/or result'
done()
describe 'create: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'create'
res.json = sinon.spy()
afterEach () ->
mockModel.create.restore()
res.json.reset()
it 'checks to see if body is an array', (done) ->
req.body = []
controller.create req, res, () ->
expect(res.giResult).to.be.an 'array'
expect(res.giResult.length).to.equal 0
done()
it 'calls model create once for each object', (done) ->
req.body = [<NAME>, <PASSWORD>]
mockModel.create.callsArgWith 1, null, null
controller.create req, res
expect(mockModel.create.calledTwice).to.be.true
done()
it 'returns error messages for any failed objects ' +
'together with sucess results', (done) ->
req.body = [<NAME>, <PASSWORD>, <NAME>]
mockModel.create.callsArgWith 1, "an error", null
mockModel.create.callsArgWith 1, null, bob
mockModel.create.callsArgWith 1, null, null
controller.create req, res
expect(res.json.calledWith 500).to.be.true
expect(res.json.getCall(0).args[1]).to.deep.equal [
{message: "an error", obj: alice},
{message: "create failed for reasons unknown", obj: charlie},
{message: "ok", obj: bob}
]
done()
it 'sets res.giResult if all sucessfully inserted', (done) ->
req.body = [<NAME>, <PASSWORD>, <NAME>]
mockModel.create.callsArgWith 1, null, <NAME>
mockModel.create.callsArgWith 1, null, <PASSWORD>
mockModel.create.callsArgWith 1, null, <NAME>lie
controller.create req, res, () ->
expect(res.json.called).to.be.false
expect(res.giResult).to.deep.equal [
{message: "ok", obj: <NAME>},
{message: "ok", obj: <PASSWORD>},
{message: "ok", obj: charlie}
]
done()
it 'sets res.giResultCode to 200 if sucessful', (done) ->
req.body = [<NAME>, <PASSWORD>, <NAME>]
mockModel.create.callsArgWith 1, null, <NAME>
mockModel.create.callsArgWith 1, null, <PASSWORD>
mockModel.create.callsArgWith 1, null, <NAME>lie
controller.create req, res, () ->
expect(res.json.called).to.be.false
expect(res.giResultCode).to.equal 200
done()
it 'sets res.giResultCode to 500 if there are errors', (done) ->
req.body = [<NAME>, <PASSWORD>, <NAME>]
mockModel.create.callsArgWith 1, null, <NAME>
mockModel.create.callsArgWith 1, "an error", <PASSWORD>
mockModel.create.callsArgWith 1, null, charlie
controller.create req, res, () ->
expect(res.json.called).to.be.false
expect(res.giResultCode).to.equal 500
done()
it 'calls res.json with 200 if no callback specified', (done) ->
alice = {alice: '<NAME>'}
bob = {bob: '<PASSWORD>'}
charlie = {charlie: 'charlie'}
req.body = [<NAME>, <PASSWORD>, <NAME>lie]
mockModel.create.callsArgWith 1, null, alice
mockModel.create.callsArgWith 1, null, <PASSWORD>
mockModel.create.callsArgWith 1, null, <NAME>
controller.create req, res
expect(res.json.calledWith 200).to.be.true
expect(res.json.getCall(0).args[1]).to.deep.equal [
{message: "ok", obj: <NAME>},
{message: "ok", obj: <PASSWORD>},
{message: "ok", obj: <NAME>}
]
done()
it 'sets req.body.systemId to the value given in req.systemId'
, (done) ->
mockModel.create.callsArgWith 1, null, null
expect(req.body.systemId).to.not.exist
controller.create req, res
expect(req.body.systemId).to.equal req.systemId
done()
it 'uses req.body as the first arg for model.create', (done) ->
mockModel.create.callsArgWith 1
req.body =
bob: '<PASSWORD>'
expected =
bob: '<PASSWORD>'
systemId: req.systemId
controller.create req, res
assert mockModel.create.calledWith(req.body)
, 'req.body not passed to model.create'
done()
it 'returns 500 code and the error if model.create returns an error'
, (done) ->
mockModel.create.callsArgWith 1, "an error", null
controller.create req, res
assert res.json.calledWith(500, {error: "an error"})
, 'res.json did not 500 an error creating'
done()
it 'populates res.giResult with the result if next() is given'
, (done) ->
mockModel.create.callsArgWith 1, null, {a: 'result'}
controller.create req, res, () ->
expect(res.giResult).to.deep.equal {a: 'result'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
mockModel.create.callsArgWith 1, null, {a: 'result'}
controller.create req, res
assert res.json.calledWith(200, {a: 'result'})
, 'res.json not called with 200 code and/or result'
done()
describe 'show: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'findById'
res.json = sinon.spy()
afterEach () ->
mockModel.findById.restore()
res.json.reset()
it 'returns 404 if req.params missing', (done) ->
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when req.params missing'
done()
it 'returns 404 if req.systemId missing', (done) ->
req.params =
some: 'thing'
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when req.params.id missing'
done()
it 'returns 404 if req.params.id missing', (done) ->
req.params =
id: 'anId'
delete req.systemId
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when req.systemId missing'
done()
it 'passes req.params.id to model.findById as first argument'
, (done) ->
req.params =
id: 'anId'
controller.show req, res
assert mockModel.findById.calledWith(req.params.id)
, 'req.params.id not passed to findById'
done()
it 'passes req.systemId to model.findById as second argument'
, (done) ->
req.params =
id: 'anId'
controller.show req, res
assert mockModel.findById.calledWith(sinon.match.any, req.systemId)
, 'req.systemId not passed to findbyId'
done()
it 'returns 404 if model.findById returns an error', (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, "an error", null
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when findbyId errors'
done()
it 'returns 404 if model.findById returns no object', (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, null, null
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when findbyId returns no object'
done()
it 'sets res.giResult with result and calls next if next given'
, (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, null, {a: 'result'}
controller.show req, res, () ->
expect(res.giResult).to.deep.equal {a: 'result'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, null, {a: 'result'}
controller.show req, res
assert res.json.calledWith(200, {a: 'result'})
, 'res.json not called with 200 code and/or result'
done()
describe 'update: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'update'
res.json = sinon.spy()
afterEach () ->
mockModel.update.restore()
res.json.reset()
it 'returns 400 if req.params missing', (done) ->
controller.update req, res
assert res.json.calledWith(400)
, '400 not returned when req.params missing'
done()
it 'returns 400 if req.params.id missing', (done) ->
req.params =
bob: 'bob'
controller.update req, res
assert res.json.calledWith(400)
, '400 not returned when req.params.id missing'
done()
it 'returns 400 if if req.systemId is missing', (done) ->
req.params =
id: 'bob'
delete req.systemId
controller.update req, res
assert res.json.calledWith(400)
, '400 not returne when req.systemId is missing'
done()
it 'sets req.body.systemId to the value given in req.systemId'
, (done) ->
req.params =
id: 'bob'
expect(req.body.systemId).to.not.exist
controller.update req, res
expect(req.body.systemId).to.equal req.systemId
done()
it 'removes _id if it is set on req.body', (done) ->
req.params =
id: 'bob'
req.body._id = 'bob'
controller.update req, res
payload = mockModel.update.getCall(0).args[1]
expect(payload).to.not.have.property '_id'
done()
it 'passes req.params.id to model.update as first argument'
, (done) ->
req.params =
id: 'anId'
controller.update req, res
assert mockModel.update.calledWith(req.params.id)
, 'req.params.id not passed to update'
done()
it 'passes req.body as the second arg for model.update', (done) ->
req.params =
id: 'anId'
req.body =
bob: 'bob'
_id: 'will be removed'
expected =
bob: 'bob'
systemId: req.systemId
controller.update req, res
assert mockModel.update.calledWith(sinon.match.any, expected)
, 'req.body not passed to model.update'
done()
it 'returns 404 if model.update returns an error', (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, "an error", null
controller.update req, res
assert res.json.calledWith(400, {message: "an error"})
, '400 not returned with error message when update errors'
done()
it 'returns 200 if model.update returns no object', (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, null, null
controller.update req, res
assert res.json.calledWith(200)
, '404 not returned when update returns no object'
done()
it 'sets res.giResult with obj and calls next if next given'
, (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, null, {a: 'obj'}
controller.update req, res, () ->
expect(res.giResult).to.deep.equal {a: 'obj'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, null, {a: 'obj'}
controller.update req, res
assert res.json.calledWith(200, {a: 'obj'})
, 'res.json not called with 200 code and/or result'
done()
describe 'destroy: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'destroy'
res.json = sinon.spy()
afterEach () ->
mockModel.destroy.restore()
res.json.reset()
it 'returns 404 if req.params missing', (done) ->
controller.destroy req, res
assert res.json.calledWith(404)
, '404 not returned when req.params missing'
done()
it 'returns 404 if req.params.id missing', (done) ->
req.params =
bob: 'bob'
controller.destroy req, res
assert res.json.calledWith(404)
, '404 not returned when req.params.id missing'
done()
it 'returns 404 if if req.systemId is missing'
, (done) ->
req.params =
id: 'bob'
delete req.systemId
controller.destroy req, res
assert res.json.calledWith(404)
, '404 not returned when req.systemId is missing'
done()
it 'passes req.params.id to model.destroy as first argument'
, (done) ->
req.params =
id: 'anId'
controller.destroy req, res
assert mockModel.destroy.calledWith(req.params.id)
, 'req.params.id not passed to model.destroy'
done()
it 'passes req.systemId to model.destroy as second argument'
, (done) ->
req.params =
id: 'anId'
controller.destroy req, res
assert mockModel.destroy.calledWith(sinon.match.any, req.systemId)
, 'req.systemId not passed to model.destroy'
done()
it 'returns 400 if model.destroy returns an error', (done) ->
req.params =
id: 'anId'
mockModel.destroy.callsArgWith 2, "an error"
controller.destroy req, res
assert res.json.calledWith(400, {message: "an error"})
, '400 not returned with error message when destroy errors'
done()
it 'sets res.giResult to Ok and calls next if next given'
, (done) ->
req.params =
id: 'anId'
mockModel.destroy.callsArgWith 2, null
controller.destroy req, res, () ->
expect(res.giResult).to.equal 'Ok'
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.destroy.callsArgWith 2, null
controller.destroy req, res
assert res.json.calledWith(200)
, 'res.json not called with 200 code'
done()
describe 'count: Function: (req, res, next) -> next() or res.json', ->
req =
any: 'thing'
systemId: '123'
body: {}
res =
json: ->
options =
query:
some: 'query'
beforeEach () ->
sinon.stub mockModel, 'count'
sinon.stub stubs['../controllers/helper'], 'getOptions'
stubs['../controllers/helper'].getOptions.returns options
res.json = sinon.spy()
afterEach () ->
mockModel.count.restore()
res.json.reset()
stubs['../controllers/helper'].getOptions.restore()
it 'gets options by passing req to helper.getOptions', (done) ->
mockModel.count.callsArg 1
controller.count req, {}, () ->
assert stubs['../controllers/helper'].getOptions.calledWith(
req, mockModel
), 'did not call helper.getOptions with req and/or model'
done()
it 'uses the options.query returned as the argument for model.count'
, (done) ->
mockModel.count.callsArg 1
controller.count req, {}, () ->
assert mockModel.count.calledWith(options.query)
, 'options.query not passed to model.count'
done()
it 'returns 404 and the error if model.count returns an error'
, (done) ->
mockModel.count.callsArgWith 1, "an error"
controller.count req, res
assert res.json.calledWith(404, {message: "an error"})
, '404 not returned with error message when destroy errors'
done()
it 'sets res.giResult to count:result and calls next if next given'
, (done) ->
mockModel.count.callsArgWith 1, null, 15
controller.count req, res, () ->
expect(res.giResult).to.deep.equal {count: 15}
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.count.callsArgWith 1, null, 16
controller.count req, res
assert res.json.calledWith(200, 16)
, 'res.json not called with 200 code and/or correct result'
done() | true | path = require 'path'
sinon = require 'sinon'
assert = require 'assert'
assert = require('chai').assert
expect = require('chai').expect
mocks = require '../mocks'
proxyquire = require 'proxyquire'
dir = path.normalize __dirname + '../../../../server'
module.exports = () ->
describe 'CrudControllerFactory', ->
stubs =
'../controllers/helper':
getOptions: ->
crudControllerFactory = proxyquire dir +
'/common/crudControllerFactory', stubs
it 'Exports a factory function', (done) ->
expect(crudControllerFactory).to.be.a 'function'
done()
describe 'Function: (model) -> { object } ', ->
mockModel =
name: "mockModel"
create: ->
update: ->
destroy: ->
findById: ->
find: ->
count: ->
controller = null
alice = null
bob = null
charlie = null
beforeEach ->
alice = {alice: 'PI:NAME:<NAME>END_PI'}
bob = {bob: 'PI:PASSWORD:<PASSWORD>END_PI'}
charlie = {charlie: 'charlie'}
controller = crudControllerFactory mockModel
describe 'returns an object with properties:', ->
it 'name: String', (done) ->
expect(controller).to.have.ownProperty 'name'
expect(controller.name).to.be.a 'string'
done()
it 'index: Function', (done) ->
expect(controller).to.have.ownProperty 'index'
expect(controller.index).to.be.a 'function'
done()
it 'create: Function', (done) ->
expect(controller).to.have.ownProperty 'create'
expect(controller.create).to.be.a 'function'
done()
it 'show: Function', (done) ->
expect(controller).to.have.ownProperty 'show'
expect(controller.show).to.be.a 'function'
done()
it 'update: Function', (done) ->
expect(controller).to.have.ownProperty 'update'
expect(controller.update).to.be.a 'function'
done()
it 'destroy: Function', (done) ->
expect(controller).to.have.ownProperty 'destroy'
expect(controller.destroy).to.be.a 'function'
done()
it 'count: Function', (done) ->
expect(controller).to.have.ownProperty 'count'
expect(controller.count).to.be.a 'function'
done()
describe 'name: String', ->
it 'exposes model.name as its name', (done) ->
expect(controller.name).to.equal mockModel.name
done()
describe 'index: Function: (req, res, next) -> next() or res.json', ->
req =
any: 'thing'
systemId: '123'
body: {}
res =
json: ->
options =
some: 'options'
beforeEach () ->
sinon.stub mockModel, 'find'
sinon.stub stubs['../controllers/helper'], 'getOptions'
stubs['../controllers/helper'].getOptions.returns options
res.json = sinon.spy()
afterEach () ->
mockModel.find.restore()
res.json.reset()
stubs['../controllers/helper'].getOptions.restore()
it 'gets options by passing req and model to helper.getOptions'
, (done) ->
mockModel.find.callsArg 1
controller.index req, {}, () ->
assert(
stubs['../controllers/helper'].getOptions.calledWith(
req, mockModel
), 'did not call helper.getOptions with req and /or model'
)
done()
it 'uses the options returned as the argument for model.find'
, (done) ->
mockModel.find.callsArg 1
controller.index req, {}, () ->
assert mockModel.find.calledWith(options)
, 'options not passed to model.find'
done()
it 'returns 404 code and the error if model.find returns an error'
, (done) ->
mockModel.find.callsArgWith 1, "an error", null, 0
controller.index req, res
assert res.json.calledWith(404, "an error")
, 'res.json did not 404 an error finding'
done()
it 'populates res.giResult with the result if next() is given'
, (done) ->
mockModel.find.callsArgWith 1, null, {a: 'result'}, 1
controller.index req, res, () ->
expect(res.giResult).to.deep.equal {a: 'result'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
mockModel.find.callsArgWith 1, null, {a: 'result'}, 1
controller.index req, res
assert res.json.calledWith(200, {a: 'result'})
, 'res.json not called with 200 code and/or result'
done()
describe 'create: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'create'
res.json = sinon.spy()
afterEach () ->
mockModel.create.restore()
res.json.reset()
it 'checks to see if body is an array', (done) ->
req.body = []
controller.create req, res, () ->
expect(res.giResult).to.be.an 'array'
expect(res.giResult.length).to.equal 0
done()
it 'calls model create once for each object', (done) ->
req.body = [PI:NAME:<NAME>END_PI, PI:NAME:<PASSWORD>END_PI]
mockModel.create.callsArgWith 1, null, null
controller.create req, res
expect(mockModel.create.calledTwice).to.be.true
done()
it 'returns error messages for any failed objects ' +
'together with sucess results', (done) ->
req.body = [PI:NAME:<NAME>END_PI, PI:NAME:<PASSWORD>END_PI, PI:NAME:<NAME>END_PI]
mockModel.create.callsArgWith 1, "an error", null
mockModel.create.callsArgWith 1, null, bob
mockModel.create.callsArgWith 1, null, null
controller.create req, res
expect(res.json.calledWith 500).to.be.true
expect(res.json.getCall(0).args[1]).to.deep.equal [
{message: "an error", obj: alice},
{message: "create failed for reasons unknown", obj: charlie},
{message: "ok", obj: bob}
]
done()
it 'sets res.giResult if all sucessfully inserted', (done) ->
req.body = [PI:NAME:<NAME>END_PI, PI:NAME:<PASSWORD>END_PI, PI:NAME:<NAME>END_PI]
mockModel.create.callsArgWith 1, null, PI:NAME:<NAME>END_PI
mockModel.create.callsArgWith 1, null, PI:NAME:<PASSWORD>END_PI
mockModel.create.callsArgWith 1, null, PI:NAME:<NAME>END_PIlie
controller.create req, res, () ->
expect(res.json.called).to.be.false
expect(res.giResult).to.deep.equal [
{message: "ok", obj: PI:NAME:<NAME>END_PI},
{message: "ok", obj: PI:NAME:<PASSWORD>END_PI},
{message: "ok", obj: charlie}
]
done()
it 'sets res.giResultCode to 200 if sucessful', (done) ->
req.body = [PI:NAME:<NAME>END_PI, PI:NAME:<PASSWORD>END_PI, PI:NAME:<NAME>END_PI]
mockModel.create.callsArgWith 1, null, PI:NAME:<NAME>END_PI
mockModel.create.callsArgWith 1, null, PI:NAME:<PASSWORD>END_PI
mockModel.create.callsArgWith 1, null, PI:NAME:<NAME>END_PIlie
controller.create req, res, () ->
expect(res.json.called).to.be.false
expect(res.giResultCode).to.equal 200
done()
it 'sets res.giResultCode to 500 if there are errors', (done) ->
req.body = [PI:NAME:<NAME>END_PI, PI:NAME:<PASSWORD>END_PI, PI:NAME:<NAME>END_PI]
mockModel.create.callsArgWith 1, null, PI:NAME:<NAME>END_PI
mockModel.create.callsArgWith 1, "an error", PI:NAME:<PASSWORD>END_PI
mockModel.create.callsArgWith 1, null, charlie
controller.create req, res, () ->
expect(res.json.called).to.be.false
expect(res.giResultCode).to.equal 500
done()
it 'calls res.json with 200 if no callback specified', (done) ->
alice = {alice: 'PI:NAME:<NAME>END_PI'}
bob = {bob: 'PI:PASSWORD:<PASSWORD>END_PI'}
charlie = {charlie: 'charlie'}
req.body = [PI:NAME:<NAME>END_PI, PI:NAME:<PASSWORD>END_PI, PI:NAME:<NAME>END_PIlie]
mockModel.create.callsArgWith 1, null, alice
mockModel.create.callsArgWith 1, null, PI:NAME:<PASSWORD>END_PI
mockModel.create.callsArgWith 1, null, PI:NAME:<NAME>END_PI
controller.create req, res
expect(res.json.calledWith 200).to.be.true
expect(res.json.getCall(0).args[1]).to.deep.equal [
{message: "ok", obj: PI:NAME:<NAME>END_PI},
{message: "ok", obj: PI:NAME:<PASSWORD>END_PI},
{message: "ok", obj: PI:NAME:<NAME>END_PI}
]
done()
it 'sets req.body.systemId to the value given in req.systemId'
, (done) ->
mockModel.create.callsArgWith 1, null, null
expect(req.body.systemId).to.not.exist
controller.create req, res
expect(req.body.systemId).to.equal req.systemId
done()
it 'uses req.body as the first arg for model.create', (done) ->
mockModel.create.callsArgWith 1
req.body =
bob: 'PI:NAME:<PASSWORD>END_PI'
expected =
bob: 'PI:NAME:<PASSWORD>END_PI'
systemId: req.systemId
controller.create req, res
assert mockModel.create.calledWith(req.body)
, 'req.body not passed to model.create'
done()
it 'returns 500 code and the error if model.create returns an error'
, (done) ->
mockModel.create.callsArgWith 1, "an error", null
controller.create req, res
assert res.json.calledWith(500, {error: "an error"})
, 'res.json did not 500 an error creating'
done()
it 'populates res.giResult with the result if next() is given'
, (done) ->
mockModel.create.callsArgWith 1, null, {a: 'result'}
controller.create req, res, () ->
expect(res.giResult).to.deep.equal {a: 'result'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
mockModel.create.callsArgWith 1, null, {a: 'result'}
controller.create req, res
assert res.json.calledWith(200, {a: 'result'})
, 'res.json not called with 200 code and/or result'
done()
describe 'show: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'findById'
res.json = sinon.spy()
afterEach () ->
mockModel.findById.restore()
res.json.reset()
it 'returns 404 if req.params missing', (done) ->
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when req.params missing'
done()
it 'returns 404 if req.systemId missing', (done) ->
req.params =
some: 'thing'
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when req.params.id missing'
done()
it 'returns 404 if req.params.id missing', (done) ->
req.params =
id: 'anId'
delete req.systemId
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when req.systemId missing'
done()
it 'passes req.params.id to model.findById as first argument'
, (done) ->
req.params =
id: 'anId'
controller.show req, res
assert mockModel.findById.calledWith(req.params.id)
, 'req.params.id not passed to findById'
done()
it 'passes req.systemId to model.findById as second argument'
, (done) ->
req.params =
id: 'anId'
controller.show req, res
assert mockModel.findById.calledWith(sinon.match.any, req.systemId)
, 'req.systemId not passed to findbyId'
done()
it 'returns 404 if model.findById returns an error', (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, "an error", null
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when findbyId errors'
done()
it 'returns 404 if model.findById returns no object', (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, null, null
controller.show req, res
assert res.json.calledWith(404)
, '404 not returned when findbyId returns no object'
done()
it 'sets res.giResult with result and calls next if next given'
, (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, null, {a: 'result'}
controller.show req, res, () ->
expect(res.giResult).to.deep.equal {a: 'result'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.findById.callsArgWith 2, null, {a: 'result'}
controller.show req, res
assert res.json.calledWith(200, {a: 'result'})
, 'res.json not called with 200 code and/or result'
done()
describe 'update: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'update'
res.json = sinon.spy()
afterEach () ->
mockModel.update.restore()
res.json.reset()
it 'returns 400 if req.params missing', (done) ->
controller.update req, res
assert res.json.calledWith(400)
, '400 not returned when req.params missing'
done()
it 'returns 400 if req.params.id missing', (done) ->
req.params =
bob: 'bob'
controller.update req, res
assert res.json.calledWith(400)
, '400 not returned when req.params.id missing'
done()
it 'returns 400 if if req.systemId is missing', (done) ->
req.params =
id: 'bob'
delete req.systemId
controller.update req, res
assert res.json.calledWith(400)
, '400 not returne when req.systemId is missing'
done()
it 'sets req.body.systemId to the value given in req.systemId'
, (done) ->
req.params =
id: 'bob'
expect(req.body.systemId).to.not.exist
controller.update req, res
expect(req.body.systemId).to.equal req.systemId
done()
it 'removes _id if it is set on req.body', (done) ->
req.params =
id: 'bob'
req.body._id = 'bob'
controller.update req, res
payload = mockModel.update.getCall(0).args[1]
expect(payload).to.not.have.property '_id'
done()
it 'passes req.params.id to model.update as first argument'
, (done) ->
req.params =
id: 'anId'
controller.update req, res
assert mockModel.update.calledWith(req.params.id)
, 'req.params.id not passed to update'
done()
it 'passes req.body as the second arg for model.update', (done) ->
req.params =
id: 'anId'
req.body =
bob: 'bob'
_id: 'will be removed'
expected =
bob: 'bob'
systemId: req.systemId
controller.update req, res
assert mockModel.update.calledWith(sinon.match.any, expected)
, 'req.body not passed to model.update'
done()
it 'returns 404 if model.update returns an error', (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, "an error", null
controller.update req, res
assert res.json.calledWith(400, {message: "an error"})
, '400 not returned with error message when update errors'
done()
it 'returns 200 if model.update returns no object', (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, null, null
controller.update req, res
assert res.json.calledWith(200)
, '404 not returned when update returns no object'
done()
it 'sets res.giResult with obj and calls next if next given'
, (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, null, {a: 'obj'}
controller.update req, res, () ->
expect(res.giResult).to.deep.equal {a: 'obj'}
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.update.callsArgWith 2, null, {a: 'obj'}
controller.update req, res
assert res.json.calledWith(200, {a: 'obj'})
, 'res.json not called with 200 code and/or result'
done()
describe 'destroy: Function: (req, res, next) -> next() or res.json', ->
req = null
res =
json: ->
beforeEach () ->
req =
any: 'thing'
systemId: '123'
body: {}
sinon.stub mockModel, 'destroy'
res.json = sinon.spy()
afterEach () ->
mockModel.destroy.restore()
res.json.reset()
it 'returns 404 if req.params missing', (done) ->
controller.destroy req, res
assert res.json.calledWith(404)
, '404 not returned when req.params missing'
done()
it 'returns 404 if req.params.id missing', (done) ->
req.params =
bob: 'bob'
controller.destroy req, res
assert res.json.calledWith(404)
, '404 not returned when req.params.id missing'
done()
it 'returns 404 if if req.systemId is missing'
, (done) ->
req.params =
id: 'bob'
delete req.systemId
controller.destroy req, res
assert res.json.calledWith(404)
, '404 not returned when req.systemId is missing'
done()
it 'passes req.params.id to model.destroy as first argument'
, (done) ->
req.params =
id: 'anId'
controller.destroy req, res
assert mockModel.destroy.calledWith(req.params.id)
, 'req.params.id not passed to model.destroy'
done()
it 'passes req.systemId to model.destroy as second argument'
, (done) ->
req.params =
id: 'anId'
controller.destroy req, res
assert mockModel.destroy.calledWith(sinon.match.any, req.systemId)
, 'req.systemId not passed to model.destroy'
done()
it 'returns 400 if model.destroy returns an error', (done) ->
req.params =
id: 'anId'
mockModel.destroy.callsArgWith 2, "an error"
controller.destroy req, res
assert res.json.calledWith(400, {message: "an error"})
, '400 not returned with error message when destroy errors'
done()
it 'sets res.giResult to Ok and calls next if next given'
, (done) ->
req.params =
id: 'anId'
mockModel.destroy.callsArgWith 2, null
controller.destroy req, res, () ->
expect(res.giResult).to.equal 'Ok'
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.destroy.callsArgWith 2, null
controller.destroy req, res
assert res.json.calledWith(200)
, 'res.json not called with 200 code'
done()
describe 'count: Function: (req, res, next) -> next() or res.json', ->
req =
any: 'thing'
systemId: '123'
body: {}
res =
json: ->
options =
query:
some: 'query'
beforeEach () ->
sinon.stub mockModel, 'count'
sinon.stub stubs['../controllers/helper'], 'getOptions'
stubs['../controllers/helper'].getOptions.returns options
res.json = sinon.spy()
afterEach () ->
mockModel.count.restore()
res.json.reset()
stubs['../controllers/helper'].getOptions.restore()
it 'gets options by passing req to helper.getOptions', (done) ->
mockModel.count.callsArg 1
controller.count req, {}, () ->
assert stubs['../controllers/helper'].getOptions.calledWith(
req, mockModel
), 'did not call helper.getOptions with req and/or model'
done()
it 'uses the options.query returned as the argument for model.count'
, (done) ->
mockModel.count.callsArg 1
controller.count req, {}, () ->
assert mockModel.count.calledWith(options.query)
, 'options.query not passed to model.count'
done()
it 'returns 404 and the error if model.count returns an error'
, (done) ->
mockModel.count.callsArgWith 1, "an error"
controller.count req, res
assert res.json.calledWith(404, {message: "an error"})
, '404 not returned with error message when destroy errors'
done()
it 'sets res.giResult to count:result and calls next if next given'
, (done) ->
mockModel.count.callsArgWith 1, null, 15
controller.count req, res, () ->
expect(res.giResult).to.deep.equal {count: 15}
done()
it 'returns 200 code and the results if next() not given', (done) ->
req.params =
id: 'anId'
mockModel.count.callsArgWith 1, null, 16
controller.count req, res
assert res.json.calledWith(200, 16)
, 'res.json not called with 200 code and/or correct result'
done() |
[
{
"context": "ência', parentId:10}\n users:\n 1: {id:1, name:'Alice'}\n 2: {id:2, name:'Bob'}\n groups:\n 1: {id:",
"end": 749,
"score": 0.999841570854187,
"start": 744,
"tag": "NAME",
"value": "Alice"
},
{
"context": ":\n 1: {id:1, name:'Alice'}\n 2: {id:2, name:'Bo... | conf/fixtures.coffee | kruschid/angular-resource-manager | 0 | module.exports =
chapters:
1: {id:1, title:'Intrudução', parentId:0}
2: {id:2, title:'Pré requisitos', parentId:1}
3: {id:3, title:'Typescript', parentId:1}
4: {id:4, title:'Além do Javascript', parentId:1}
5: {id:5, title:'Código fonte', parentId:1}
6: {id:6, title:'TypeScript', parentId:0}
7: {id:7, title:'Um pouco de prática', parentId:0}
8: {id:8, title:'Configurando o projeto', parentId:7}
9: {id:9, title:'Configurando a compilação do TypeScript', parentId:7}
10:{id:10, title:'Um pouco de teoria', parentId:0}
11:{id:11, title:'Visão geral', parentId:10}
12:{id:12, title:'Módulo', parentId:10}
13:{id:13, title:'Injeção de dependência', parentId:10}
users:
1: {id:1, name:'Alice'}
2: {id:2, name:'Bob'}
groups:
1: {id:1, name:'JavaScript lovers'}
2: {id:2, name:'I love Math.sqrt'}
3: {id:3, name:'My name is angluar'}
4: {id:4, name:'Shut up and take my money'}
5: {id:5, name:'I love MMA'}
6: {id:6, name:'Cat lovers'}
7: {id:7, name:'Eu falo portugês'}
8: {id:8, name:'Yes, here is dog'}
groupsUsers:
1: {id:1, userId:1, groupId:1}
2: {id:2, userId:1, groupId:2}
3: {id:3, userId:1, groupId:5}
4: {id:4, userId:1, groupId:8}
5: {id:5, userId:2, groupId:3}
6: {id:6, userId:2, groupId:6} | 127507 | module.exports =
chapters:
1: {id:1, title:'Intrudução', parentId:0}
2: {id:2, title:'Pré requisitos', parentId:1}
3: {id:3, title:'Typescript', parentId:1}
4: {id:4, title:'Além do Javascript', parentId:1}
5: {id:5, title:'Código fonte', parentId:1}
6: {id:6, title:'TypeScript', parentId:0}
7: {id:7, title:'Um pouco de prática', parentId:0}
8: {id:8, title:'Configurando o projeto', parentId:7}
9: {id:9, title:'Configurando a compilação do TypeScript', parentId:7}
10:{id:10, title:'Um pouco de teoria', parentId:0}
11:{id:11, title:'Visão geral', parentId:10}
12:{id:12, title:'Módulo', parentId:10}
13:{id:13, title:'Injeção de dependência', parentId:10}
users:
1: {id:1, name:'<NAME>'}
2: {id:2, name:'<NAME>'}
groups:
1: {id:1, name:'JavaScript lovers'}
2: {id:2, name:'I love Math.sqrt'}
3: {id:3, name:'My name is <NAME>'}
4: {id:4, name:'Shut up and take my money'}
5: {id:5, name:'I love MMA'}
6: {id:6, name:'Cat lovers'}
7: {id:7, name:'Eu falo portugês'}
8: {id:8, name:'Yes, here is dog'}
groupsUsers:
1: {id:1, userId:1, groupId:1}
2: {id:2, userId:1, groupId:2}
3: {id:3, userId:1, groupId:5}
4: {id:4, userId:1, groupId:8}
5: {id:5, userId:2, groupId:3}
6: {id:6, userId:2, groupId:6} | true | module.exports =
chapters:
1: {id:1, title:'Intrudução', parentId:0}
2: {id:2, title:'Pré requisitos', parentId:1}
3: {id:3, title:'Typescript', parentId:1}
4: {id:4, title:'Além do Javascript', parentId:1}
5: {id:5, title:'Código fonte', parentId:1}
6: {id:6, title:'TypeScript', parentId:0}
7: {id:7, title:'Um pouco de prática', parentId:0}
8: {id:8, title:'Configurando o projeto', parentId:7}
9: {id:9, title:'Configurando a compilação do TypeScript', parentId:7}
10:{id:10, title:'Um pouco de teoria', parentId:0}
11:{id:11, title:'Visão geral', parentId:10}
12:{id:12, title:'Módulo', parentId:10}
13:{id:13, title:'Injeção de dependência', parentId:10}
users:
1: {id:1, name:'PI:NAME:<NAME>END_PI'}
2: {id:2, name:'PI:NAME:<NAME>END_PI'}
groups:
1: {id:1, name:'JavaScript lovers'}
2: {id:2, name:'I love Math.sqrt'}
3: {id:3, name:'My name is PI:NAME:<NAME>END_PI'}
4: {id:4, name:'Shut up and take my money'}
5: {id:5, name:'I love MMA'}
6: {id:6, name:'Cat lovers'}
7: {id:7, name:'Eu falo portugês'}
8: {id:8, name:'Yes, here is dog'}
groupsUsers:
1: {id:1, userId:1, groupId:1}
2: {id:2, userId:1, groupId:2}
3: {id:3, userId:1, groupId:5}
4: {id:4, userId:1, groupId:8}
5: {id:5, userId:2, groupId:3}
6: {id:6, userId:2, groupId:6} |
[
{
"context": "# @file checkSupport.coffee\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice",
"end": 64,
"score": 0.9997504353523254,
"start": 50,
"tag": "NAME",
"value": "Taylor Siviter"
}
] | src/util/checkSupport.coffee | siviter-t/lampyridae.coffee | 4 | # @file checkSupport.coffee
# @Copyright (c) 2016 Taylor Siviter
# This source code is licensed under the MIT License.
# For full information, see the LICENSE file in the project root.
require 'lampyridae'
### Whether the Browser or environment supports the canvas drawing api.
#
# @return [Bool] True if it does, false if it does not
###
Lampyridae.checkSupport = () ->
return Boolean document.createElement('canvas').getContext
# end function Lampyridae.checkSupport
module.exports = Lampyridae.checkSupport | 102200 | # @file checkSupport.coffee
# @Copyright (c) 2016 <NAME>
# This source code is licensed under the MIT License.
# For full information, see the LICENSE file in the project root.
require 'lampyridae'
### Whether the Browser or environment supports the canvas drawing api.
#
# @return [Bool] True if it does, false if it does not
###
Lampyridae.checkSupport = () ->
return Boolean document.createElement('canvas').getContext
# end function Lampyridae.checkSupport
module.exports = Lampyridae.checkSupport | true | # @file checkSupport.coffee
# @Copyright (c) 2016 PI:NAME:<NAME>END_PI
# This source code is licensed under the MIT License.
# For full information, see the LICENSE file in the project root.
require 'lampyridae'
### Whether the Browser or environment supports the canvas drawing api.
#
# @return [Bool] True if it does, false if it does not
###
Lampyridae.checkSupport = () ->
return Boolean document.createElement('canvas').getContext
# end function Lampyridae.checkSupport
module.exports = Lampyridae.checkSupport |
[
{
"context": "f male then '' else ' not'} a male\"\n\n t.run \"John\", true, (res) ->\n should.exist res\n ",
"end": 486,
"score": 0.9985101819038391,
"start": 482,
"tag": "NAME",
"value": "John"
},
{
"context": " should.exist res\n res.should.equal \"J... | test/Thread.coffee | wearefractal/thread | 6 | {Thread} = require '../'
should = require 'should'
require 'mocha'
describe 'Thread', ->
describe 'constructor()', ->
it 'should create properly', (done) ->
task = -> console.log 'hi'
t = new Thread task
should.exist t.task
t.task.should.eql task
done()
describe 'run()', ->
it 'should work with a simple task', (done) ->
t = new Thread (name, male, cb) ->
cb "#{name} is#{if male then '' else ' not'} a male"
t.run "John", true, (res) ->
should.exist res
res.should.equal "John is a male"
done()
###
it 'should work with a complex task', (done) ->
t = new Thread (url, cb) ->
require('http').get {host: url}, cb
t.run "www.google.com", (res) ->
should.exist res
('<html' in res).should.equal true
done()
###
it 'should work with multiple simple tasks', (done) ->
c = 0
comp = -> done() if ++c is 2
t = new Thread (name, male, cb) ->
cb "#{name} is#{if male then '' else ' not'} a male"
t.run "John", true, (res) ->
should.exist res
res.should.equal "John is a male"
comp()
t.run "Mary", false, (res) ->
should.exist res
res.should.equal "Mary is not a male"
comp() | 185957 | {Thread} = require '../'
should = require 'should'
require 'mocha'
describe 'Thread', ->
describe 'constructor()', ->
it 'should create properly', (done) ->
task = -> console.log 'hi'
t = new Thread task
should.exist t.task
t.task.should.eql task
done()
describe 'run()', ->
it 'should work with a simple task', (done) ->
t = new Thread (name, male, cb) ->
cb "#{name} is#{if male then '' else ' not'} a male"
t.run "<NAME>", true, (res) ->
should.exist res
res.should.equal "<NAME> is a male"
done()
###
it 'should work with a complex task', (done) ->
t = new Thread (url, cb) ->
require('http').get {host: url}, cb
t.run "www.google.com", (res) ->
should.exist res
('<html' in res).should.equal true
done()
###
it 'should work with multiple simple tasks', (done) ->
c = 0
comp = -> done() if ++c is 2
t = new Thread (name, male, cb) ->
cb "#{name} is#{if male then '' else ' not'} a male"
t.run "<NAME>", true, (res) ->
should.exist res
res.should.equal "<NAME> is a male"
comp()
t.run "<NAME>", false, (res) ->
should.exist res
res.should.equal "<NAME> is not a male"
comp() | true | {Thread} = require '../'
should = require 'should'
require 'mocha'
describe 'Thread', ->
describe 'constructor()', ->
it 'should create properly', (done) ->
task = -> console.log 'hi'
t = new Thread task
should.exist t.task
t.task.should.eql task
done()
describe 'run()', ->
it 'should work with a simple task', (done) ->
t = new Thread (name, male, cb) ->
cb "#{name} is#{if male then '' else ' not'} a male"
t.run "PI:NAME:<NAME>END_PI", true, (res) ->
should.exist res
res.should.equal "PI:NAME:<NAME>END_PI is a male"
done()
###
it 'should work with a complex task', (done) ->
t = new Thread (url, cb) ->
require('http').get {host: url}, cb
t.run "www.google.com", (res) ->
should.exist res
('<html' in res).should.equal true
done()
###
it 'should work with multiple simple tasks', (done) ->
c = 0
comp = -> done() if ++c is 2
t = new Thread (name, male, cb) ->
cb "#{name} is#{if male then '' else ' not'} a male"
t.run "PI:NAME:<NAME>END_PI", true, (res) ->
should.exist res
res.should.equal "PI:NAME:<NAME>END_PI is a male"
comp()
t.run "PI:NAME:<NAME>END_PI", false, (res) ->
should.exist res
res.should.equal "PI:NAME:<NAME>END_PI is not a male"
comp() |
[
{
"context": "rt [\n\t\t{ id: 1, date: Date.now(), teamA: { name: 'PHI', score: 0, shots: 0 }, teamB: { name: 'BOS', sco",
"end": 595,
"score": 0.8209953308105469,
"start": 592,
"tag": "NAME",
"value": "PHI"
},
{
"context": "ame: 'PHI', score: 0, shots: 0 }, teamB: { name: 'BOS', sco... | index.coffee | BS-Harou/hockey-backend | 0 | #
# MONGO
#
# MongoClient = require('mongodb').MongoClient
MongoClient = require('./dumb-mongo').MongoClient
assert = require 'assert'
url = 'mongodb://localhost:27017/myproject'
dumbUrl = './db.json'
global.mongodb = mongodb = null
MongoClient.connect dumbUrl, (err, db) ->
assert.equal null, err
console.log 'Connected correctly to mongo server'
db.on 'close', ->
mongodb = null
console.log 'DB CLOSED'
global.mongodb = mongodb = db
return
insertDocuments = (db, cb) ->
collection = db.collection 'matches'
collection.insert [
{ id: 1, date: Date.now(), teamA: { name: 'PHI', score: 0, shots: 0 }, teamB: { name: 'BOS', score: 5, shots: 43 } }
], (err, result) ->
assert.equal err, null
console.log 'data inserted'
cb result
process.on 'exit', ->
console.log 'Closing mongodb connection'
mongodb.close() if mongodb
mongodb = null
#
# Express
#
app = require('express')()
http = require('http').Server app
io = require('socket.io')(http)
endpoints =
matches: require './endpoints/matches'
pairs: require './endpoints/pairs'
teams: require './endpoints/teams'
socketCount = 0
app.get '/', (req, res) ->
mongoState = if mongodb? then 'connected' else 'disconnected'
res.send """
<strong>Hockey app backend is up and running :)</strong>
<div>MongoDB state: #{mongoState}</div>
<div>Amount of connected users: #{socketCount}</div>
"""
global.getResponseCallback = (socket, endpoint) ->
(data) ->
socket.emit 'data',
endpoint: endpoint
value: JSON.stringify data
io.on 'connection', (socket) ->
socketCount++
console.log 'Socket.io: a client connected'
socket.on 'data', (msg) ->
console.log 'Socket.io message: ', msg
return unless msg?.endpoint and typeof(msg.endpoint) is 'string'
path = msg.endpoint.split '/'
path.shift() if path[0].length is 0
endpoints[path[0]]?[path[1]]? msg.value, getResponseCallback(socket, msg.endpoint), socket
socket.on 'disconnect', ->
socketCount--
console.log 'Socket.io: a client disconnected'
http.listen 3000, ->
console.log('listening on *:3000'); | 178619 | #
# MONGO
#
# MongoClient = require('mongodb').MongoClient
MongoClient = require('./dumb-mongo').MongoClient
assert = require 'assert'
url = 'mongodb://localhost:27017/myproject'
dumbUrl = './db.json'
global.mongodb = mongodb = null
MongoClient.connect dumbUrl, (err, db) ->
assert.equal null, err
console.log 'Connected correctly to mongo server'
db.on 'close', ->
mongodb = null
console.log 'DB CLOSED'
global.mongodb = mongodb = db
return
insertDocuments = (db, cb) ->
collection = db.collection 'matches'
collection.insert [
{ id: 1, date: Date.now(), teamA: { name: '<NAME>', score: 0, shots: 0 }, teamB: { name: '<NAME>', score: 5, shots: 43 } }
], (err, result) ->
assert.equal err, null
console.log 'data inserted'
cb result
process.on 'exit', ->
console.log 'Closing mongodb connection'
mongodb.close() if mongodb
mongodb = null
#
# Express
#
app = require('express')()
http = require('http').Server app
io = require('socket.io')(http)
endpoints =
matches: require './endpoints/matches'
pairs: require './endpoints/pairs'
teams: require './endpoints/teams'
socketCount = 0
app.get '/', (req, res) ->
mongoState = if mongodb? then 'connected' else 'disconnected'
res.send """
<strong>Hockey app backend is up and running :)</strong>
<div>MongoDB state: #{mongoState}</div>
<div>Amount of connected users: #{socketCount}</div>
"""
global.getResponseCallback = (socket, endpoint) ->
(data) ->
socket.emit 'data',
endpoint: endpoint
value: JSON.stringify data
io.on 'connection', (socket) ->
socketCount++
console.log 'Socket.io: a client connected'
socket.on 'data', (msg) ->
console.log 'Socket.io message: ', msg
return unless msg?.endpoint and typeof(msg.endpoint) is 'string'
path = msg.endpoint.split '/'
path.shift() if path[0].length is 0
endpoints[path[0]]?[path[1]]? msg.value, getResponseCallback(socket, msg.endpoint), socket
socket.on 'disconnect', ->
socketCount--
console.log 'Socket.io: a client disconnected'
http.listen 3000, ->
console.log('listening on *:3000'); | true | #
# MONGO
#
# MongoClient = require('mongodb').MongoClient
MongoClient = require('./dumb-mongo').MongoClient
assert = require 'assert'
url = 'mongodb://localhost:27017/myproject'
dumbUrl = './db.json'
global.mongodb = mongodb = null
MongoClient.connect dumbUrl, (err, db) ->
assert.equal null, err
console.log 'Connected correctly to mongo server'
db.on 'close', ->
mongodb = null
console.log 'DB CLOSED'
global.mongodb = mongodb = db
return
insertDocuments = (db, cb) ->
collection = db.collection 'matches'
collection.insert [
{ id: 1, date: Date.now(), teamA: { name: 'PI:NAME:<NAME>END_PI', score: 0, shots: 0 }, teamB: { name: 'PI:NAME:<NAME>END_PI', score: 5, shots: 43 } }
], (err, result) ->
assert.equal err, null
console.log 'data inserted'
cb result
process.on 'exit', ->
console.log 'Closing mongodb connection'
mongodb.close() if mongodb
mongodb = null
#
# Express
#
app = require('express')()
http = require('http').Server app
io = require('socket.io')(http)
endpoints =
matches: require './endpoints/matches'
pairs: require './endpoints/pairs'
teams: require './endpoints/teams'
socketCount = 0
app.get '/', (req, res) ->
mongoState = if mongodb? then 'connected' else 'disconnected'
res.send """
<strong>Hockey app backend is up and running :)</strong>
<div>MongoDB state: #{mongoState}</div>
<div>Amount of connected users: #{socketCount}</div>
"""
global.getResponseCallback = (socket, endpoint) ->
(data) ->
socket.emit 'data',
endpoint: endpoint
value: JSON.stringify data
io.on 'connection', (socket) ->
socketCount++
console.log 'Socket.io: a client connected'
socket.on 'data', (msg) ->
console.log 'Socket.io message: ', msg
return unless msg?.endpoint and typeof(msg.endpoint) is 'string'
path = msg.endpoint.split '/'
path.shift() if path[0].length is 0
endpoints[path[0]]?[path[1]]? msg.value, getResponseCallback(socket, msg.endpoint), socket
socket.on 'disconnect', ->
socketCount--
console.log 'Socket.io: a client disconnected'
http.listen 3000, ->
console.log('listening on *:3000'); |
[
{
"context": "lue username\r\n modal.inputs.password.setValue '123'\r\n modal.buttons.submit.click()\r\n client.pa",
"end": 562,
"score": 0.9992790222167969,
"start": 559,
"tag": "PASSWORD",
"value": "123"
}
] | features/step_definitions/common.coffee | eribeiro9/CoLabs | 0 | require.call this, '../lib/util.coffee'
app = require '../lib/app.coffee'
modal = app.modals.loginOrRegister
nav = app.views.nav
removeAllUsers = -> Meteor.users.remove username: $in: ['test', 'test2', 'test3']
getAllUsers = -> Meteor.users.find().fetch()
module.exports = ->
@Given /^I am signed in as "(.*)"$/, (username) ->
browser.url app.baseUrl
if !nav.links.signIn.isDisplayed()
nav.buttons.collapse.click()
nav.links.signIn.click()
modal.inputs.username.setValue username
modal.inputs.password.setValue '123'
modal.buttons.submit.click()
client.pause 500
@Given /^I am at the (.*) page$/, (page) ->
[page, data] = page.split ' '
switch page
when 'splash'
browser.url app.baseUrl
when 'profile'
browser.url app.pages.profile.url()
when 'user'
browser.url app.pages.user.url(data)
when 'inbox'
browser.url app.pages.inbox.url()
else
browser.url app.baseUrl
@When /^I remove all users$/, ->
server.execute removeAllUsers
@Then /^No users remain$/, ->
client.pause 500
users = (client.execute getAllUsers).value
expect(users.length).toBe 0
@Then /^I see a (.*) toast containing "(.*)"$/, (type, text) ->
client.waitForExist '.toast'
toastId = client.element('.toast').value.ELEMENT
toastClass = client.elementIdAttribute(toastId, 'class').value
toastText = client.elementIdText(toastId).value
expect(toastClass).toContain type
expect(toastText).toContain text
@Then /^I don't see a nav badge$/, ->
if !nav.links.signOut.isDisplayed()
nav.buttons.collapse.click()
client.pause 500
expect(client.elements('.badge').value.length).toBe 0
@Then /^I see a nav badge$/, ->
if !nav.links.signOut.isDisplayed()
nav.buttons.collapse.click()
client.pause 500
expect(client.elements('.badge').value.length).toBeGreaterThan 0
@Then /^I sign out$/, ->
client.pause 500
if !nav.links.signOut.isDisplayed()
nav.buttons.collapse.click()
client.pause 500
nav.links.signOut.click()
| 10927 | require.call this, '../lib/util.coffee'
app = require '../lib/app.coffee'
modal = app.modals.loginOrRegister
nav = app.views.nav
removeAllUsers = -> Meteor.users.remove username: $in: ['test', 'test2', 'test3']
getAllUsers = -> Meteor.users.find().fetch()
module.exports = ->
@Given /^I am signed in as "(.*)"$/, (username) ->
browser.url app.baseUrl
if !nav.links.signIn.isDisplayed()
nav.buttons.collapse.click()
nav.links.signIn.click()
modal.inputs.username.setValue username
modal.inputs.password.setValue '<PASSWORD>'
modal.buttons.submit.click()
client.pause 500
@Given /^I am at the (.*) page$/, (page) ->
[page, data] = page.split ' '
switch page
when 'splash'
browser.url app.baseUrl
when 'profile'
browser.url app.pages.profile.url()
when 'user'
browser.url app.pages.user.url(data)
when 'inbox'
browser.url app.pages.inbox.url()
else
browser.url app.baseUrl
@When /^I remove all users$/, ->
server.execute removeAllUsers
@Then /^No users remain$/, ->
client.pause 500
users = (client.execute getAllUsers).value
expect(users.length).toBe 0
@Then /^I see a (.*) toast containing "(.*)"$/, (type, text) ->
client.waitForExist '.toast'
toastId = client.element('.toast').value.ELEMENT
toastClass = client.elementIdAttribute(toastId, 'class').value
toastText = client.elementIdText(toastId).value
expect(toastClass).toContain type
expect(toastText).toContain text
@Then /^I don't see a nav badge$/, ->
if !nav.links.signOut.isDisplayed()
nav.buttons.collapse.click()
client.pause 500
expect(client.elements('.badge').value.length).toBe 0
@Then /^I see a nav badge$/, ->
if !nav.links.signOut.isDisplayed()
nav.buttons.collapse.click()
client.pause 500
expect(client.elements('.badge').value.length).toBeGreaterThan 0
@Then /^I sign out$/, ->
client.pause 500
if !nav.links.signOut.isDisplayed()
nav.buttons.collapse.click()
client.pause 500
nav.links.signOut.click()
| true | require.call this, '../lib/util.coffee'
app = require '../lib/app.coffee'
modal = app.modals.loginOrRegister
nav = app.views.nav
removeAllUsers = -> Meteor.users.remove username: $in: ['test', 'test2', 'test3']
getAllUsers = -> Meteor.users.find().fetch()
module.exports = ->
@Given /^I am signed in as "(.*)"$/, (username) ->
browser.url app.baseUrl
if !nav.links.signIn.isDisplayed()
nav.buttons.collapse.click()
nav.links.signIn.click()
modal.inputs.username.setValue username
modal.inputs.password.setValue 'PI:PASSWORD:<PASSWORD>END_PI'
modal.buttons.submit.click()
client.pause 500
@Given /^I am at the (.*) page$/, (page) ->
[page, data] = page.split ' '
switch page
when 'splash'
browser.url app.baseUrl
when 'profile'
browser.url app.pages.profile.url()
when 'user'
browser.url app.pages.user.url(data)
when 'inbox'
browser.url app.pages.inbox.url()
else
browser.url app.baseUrl
@When /^I remove all users$/, ->
server.execute removeAllUsers
@Then /^No users remain$/, ->
client.pause 500
users = (client.execute getAllUsers).value
expect(users.length).toBe 0
@Then /^I see a (.*) toast containing "(.*)"$/, (type, text) ->
client.waitForExist '.toast'
toastId = client.element('.toast').value.ELEMENT
toastClass = client.elementIdAttribute(toastId, 'class').value
toastText = client.elementIdText(toastId).value
expect(toastClass).toContain type
expect(toastText).toContain text
@Then /^I don't see a nav badge$/, ->
if !nav.links.signOut.isDisplayed()
nav.buttons.collapse.click()
client.pause 500
expect(client.elements('.badge').value.length).toBe 0
@Then /^I see a nav badge$/, ->
if !nav.links.signOut.isDisplayed()
nav.buttons.collapse.click()
client.pause 500
expect(client.elements('.badge').value.length).toBeGreaterThan 0
@Then /^I sign out$/, ->
client.pause 500
if !nav.links.signOut.isDisplayed()
nav.buttons.collapse.click()
client.pause 500
nav.links.signOut.click()
|
[
{
"context": "ady ->\n $(\"#submit\").click ->\n username = $(\"#myusername\").val()\n password = $(\"#mypassword\").val()\n ",
"end": 74,
"score": 0.9692689776420593,
"start": 64,
"tag": "USERNAME",
"value": "myusername"
},
{
"context": "rname = $(\"#myusername\").val()\n ... | assets/js/login.coffee | pribadi/facilityoperationsupport | 0 | $(document).ready ->
$("#submit").click ->
username = $("#myusername").val()
password = $("#mypassword").val()
if (username is "") or (password is "")
$("#message").html "<div class=\"alert alert-danger alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Please enter a username and a password</div>"
else
$.ajax
type: "POST"
url: "http://10.47.150.143/facilityoperationsupport_tso/main/login"
data: "myusername=" + username + "&mypassword=" + password
success: (html) ->
if html is "true"
window.location = "index.php"
else
$("#message").html html
beforeSend: ->
$("#message").html "<p class='text-center'><img src='images/ajax-loader.gif'></p>"
false
| 150395 | $(document).ready ->
$("#submit").click ->
username = $("#myusername").val()
password = $("#<PASSWORD>").val()
if (username is "") or (password is "")
$("#message").html "<div class=\"alert alert-danger alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Please enter a username and a password</div>"
else
$.ajax
type: "POST"
url: "http://10.47.150.143/facilityoperationsupport_tso/main/login"
data: "myusername=" + username + "&mypassword=" + password
success: (html) ->
if html is "true"
window.location = "index.php"
else
$("#message").html html
beforeSend: ->
$("#message").html "<p class='text-center'><img src='images/ajax-loader.gif'></p>"
false
| true | $(document).ready ->
$("#submit").click ->
username = $("#myusername").val()
password = $("#PI:PASSWORD:<PASSWORD>END_PI").val()
if (username is "") or (password is "")
$("#message").html "<div class=\"alert alert-danger alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Please enter a username and a password</div>"
else
$.ajax
type: "POST"
url: "http://10.47.150.143/facilityoperationsupport_tso/main/login"
data: "myusername=" + username + "&mypassword=" + password
success: (html) ->
if html is "true"
window.location = "index.php"
else
$("#message").html html
beforeSend: ->
$("#message").html "<p class='text-center'><img src='images/ajax-loader.gif'></p>"
false
|
[
{
"context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.",
"end": 17,
"score": 0.9558313488960266,
"start": 16,
"tag": "EMAIL",
"value": "j"
},
{
"context": "###\n# Copyright jtlebi.fr <admin@jtlebi.fr> and other contributors.\n#\n# Per",
"end": 25,
... | src/app.coffee | yadutaf/Weathermap-archive | 1 | ###
# Copyright jtlebi.fr <admin@jtlebi.fr> and other 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.
###
Restify = require 'restify'
Connect = require 'connect'
Logger = require 'bunyan'
Sanitize = require './lib/sanitize'
Workarounds = require './lib/workarounds'
Path = require 'path'
Fs = require 'fs'
package = JSON.parse Fs.readFileSync __dirname+'/../package.json'
require './lib/parsedir'
require './lib/utils'
# Configuration
config = {
staticFilesDir: Path.resolve(__dirname, "../static"),
ip: "0.0.0.0",
port: 3008,
throttle: {
burst: 100,
rate: 50,
ip: true
}
}
configfilename = Path.resolve __dirname, "../config/config.json"
configurator = require './lib/configurator'
configurator configfilename, (conf) ->
return if not conf
if conf.staticFilesDir
config.staticFilesDir = Path.resolve __dirname, conf.staticFilesDir
if conf.weathermapsDir
config.weathermapsDir = Path.resolve __dirname, conf.weathermapsDir
if conf.ip
config.ip = conf.ip
if conf.port
config.port = conf.port
if conf.throttle
config.throttle = conf.throttle
log = new Logger {
name: "WeatherMap viewer",
level: 'trace',
service: 'weathermap',
serializers: {
err: Logger.stdSerializers.err,
req: Logger.stdSerializers.req,
res: Restify.bunyan.serializers.response
}
}
# Main Application
Server = Restify.createServer {
name: "WeatherMap viewer"
Logger: log
version: package.version
}
Server.use Workarounds.forLogger()
Server.use Connect.logger('dev')
Server.use Restify.acceptParser Server.acceptable
Server.use Restify.authorizationParser()
Server.use Restify.dateParser()
Server.use Restify.queryParser()
Server.use Restify.urlEncodedBodyParser()
Server.use Restify.throttle config.throttle
Server.use Sanitize.sanitize {
'groupname': /^[a-zA-Z-_0-9]+$/i
'mapname': /^[a-zA-Z-_0-9]+$/i
'date': /^[a-zA-Z-_0-9]+$/i
# 'date': /^\d\d\d\d-\d\d-\d\d$/i
}
###
TODO:
* return bad method for paths under the API dir
* doc
* tests
* update static servers on config change
* add jsonp support
###
# API
V0_1 = require('./api/v0.1') Server, config
V0_1 = require('./api/v0.2') Server, config
Server.listen config.port, config.ip, () ->
log.info 'listening: %s', Server.url
| 52052 | ###
# Copyright <EMAIL>tlebi.fr <<EMAIL>> and other 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.
###
Restify = require 'restify'
Connect = require 'connect'
Logger = require 'bunyan'
Sanitize = require './lib/sanitize'
Workarounds = require './lib/workarounds'
Path = require 'path'
Fs = require 'fs'
package = JSON.parse Fs.readFileSync __dirname+'/../package.json'
require './lib/parsedir'
require './lib/utils'
# Configuration
config = {
staticFilesDir: Path.resolve(__dirname, "../static"),
ip: "0.0.0.0",
port: 3008,
throttle: {
burst: 100,
rate: 50,
ip: true
}
}
configfilename = Path.resolve __dirname, "../config/config.json"
configurator = require './lib/configurator'
configurator configfilename, (conf) ->
return if not conf
if conf.staticFilesDir
config.staticFilesDir = Path.resolve __dirname, conf.staticFilesDir
if conf.weathermapsDir
config.weathermapsDir = Path.resolve __dirname, conf.weathermapsDir
if conf.ip
config.ip = conf.ip
if conf.port
config.port = conf.port
if conf.throttle
config.throttle = conf.throttle
log = new Logger {
name: "WeatherMap viewer",
level: 'trace',
service: 'weathermap',
serializers: {
err: Logger.stdSerializers.err,
req: Logger.stdSerializers.req,
res: Restify.bunyan.serializers.response
}
}
# Main Application
Server = Restify.createServer {
name: "WeatherMap viewer"
Logger: log
version: package.version
}
Server.use Workarounds.forLogger()
Server.use Connect.logger('dev')
Server.use Restify.acceptParser Server.acceptable
Server.use Restify.authorizationParser()
Server.use Restify.dateParser()
Server.use Restify.queryParser()
Server.use Restify.urlEncodedBodyParser()
Server.use Restify.throttle config.throttle
Server.use Sanitize.sanitize {
'groupname': /^[a-zA-Z-_0-9]+$/i
'mapname': /^[a-zA-Z-_0-9]+$/i
'date': /^[a-zA-Z-_0-9]+$/i
# 'date': /^\d\d\d\d-\d\d-\d\d$/i
}
###
TODO:
* return bad method for paths under the API dir
* doc
* tests
* update static servers on config change
* add jsonp support
###
# API
V0_1 = require('./api/v0.1') Server, config
V0_1 = require('./api/v0.2') Server, config
Server.listen config.port, config.ip, () ->
log.info 'listening: %s', Server.url
| true | ###
# Copyright PI:EMAIL:<EMAIL>END_PItlebi.fr <PI:EMAIL:<EMAIL>END_PI> and other 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.
###
Restify = require 'restify'
Connect = require 'connect'
Logger = require 'bunyan'
Sanitize = require './lib/sanitize'
Workarounds = require './lib/workarounds'
Path = require 'path'
Fs = require 'fs'
package = JSON.parse Fs.readFileSync __dirname+'/../package.json'
require './lib/parsedir'
require './lib/utils'
# Configuration
config = {
staticFilesDir: Path.resolve(__dirname, "../static"),
ip: "0.0.0.0",
port: 3008,
throttle: {
burst: 100,
rate: 50,
ip: true
}
}
configfilename = Path.resolve __dirname, "../config/config.json"
configurator = require './lib/configurator'
configurator configfilename, (conf) ->
return if not conf
if conf.staticFilesDir
config.staticFilesDir = Path.resolve __dirname, conf.staticFilesDir
if conf.weathermapsDir
config.weathermapsDir = Path.resolve __dirname, conf.weathermapsDir
if conf.ip
config.ip = conf.ip
if conf.port
config.port = conf.port
if conf.throttle
config.throttle = conf.throttle
log = new Logger {
name: "WeatherMap viewer",
level: 'trace',
service: 'weathermap',
serializers: {
err: Logger.stdSerializers.err,
req: Logger.stdSerializers.req,
res: Restify.bunyan.serializers.response
}
}
# Main Application
Server = Restify.createServer {
name: "WeatherMap viewer"
Logger: log
version: package.version
}
Server.use Workarounds.forLogger()
Server.use Connect.logger('dev')
Server.use Restify.acceptParser Server.acceptable
Server.use Restify.authorizationParser()
Server.use Restify.dateParser()
Server.use Restify.queryParser()
Server.use Restify.urlEncodedBodyParser()
Server.use Restify.throttle config.throttle
Server.use Sanitize.sanitize {
'groupname': /^[a-zA-Z-_0-9]+$/i
'mapname': /^[a-zA-Z-_0-9]+$/i
'date': /^[a-zA-Z-_0-9]+$/i
# 'date': /^\d\d\d\d-\d\d-\d\d$/i
}
###
TODO:
* return bad method for paths under the API dir
* doc
* tests
* update static servers on config change
* add jsonp support
###
# API
V0_1 = require('./api/v0.1') Server, config
V0_1 = require('./api/v0.2') Server, config
Server.listen config.port, config.ip, () ->
log.info 'listening: %s', Server.url
|
[
{
"context": "/phpjs.org/functions/str_pad\r\n # + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\r\n # + namespaced",
"end": 3221,
"score": 0.9998260140419006,
"start": 3202,
"tag": "NAME",
"value": "Kevin van Zonneveld"
},
{
"context": "tp://kevin.vanzonneveld... | atom/packages/xml-formatter/lib/xml-formatter.coffee | dandrzejewski/rcfiles | 3 | module.exports =
config:
xmlUtf8Header:
type: 'boolean'
default: true
useTab:
type: 'string'
default:'false'
enum: ['false','true']
numberCharIndent:
type: 'integer'
default: 2
indentCharacter:
type: 'string'
default: " "
endLineCharacter:
type: 'string'
default: 'CR+LF (\\r\\n)'
enum: ['CR+LF (\\r\\n)','LF (\\n)']
activate: ->
atom.commands.add 'atom-workspace', "xml-formatter:indent", => @indent()
atom.config.observe 'xml-formatter.xmlUtf8Header', (value) =>
@xmlUtf8Header = value
atom.config.observe 'xml-formatter.useTab', (value) =>
@useTab = value
atom.config.observe 'xml-formatter.numberCharIndent', (value) =>
@numberCharIndent = value
atom.config.observe 'xml-formatter.indentCharacter', (value) =>
@indentCharacter = value
atom.config.observe 'xml-formatter.endLineCharacter', (value) =>
@endLineCharacter = value
indent: ->
opts = {}
opts.xml_utf8_header = atom.config.get('xml-formatter.xmlUtf8Header')
opts.use_tab = atom.config.get('xml-formatter.useTab')
opts.number_char_indent = atom.config.get('xml-formatter.numberCharIndent')
opts.indent_character = atom.config.get('xml-formatter.indentCharacter')
opts.indent_character = "\t" if opts.use_tab is "true"
opts.crlf = atom.config.get('xml-formatter.endLineCharacter')
if opts.crlf == "CR+LF (\\r\\n)"
opts.crlf = "\r\n";
else
opts.crlf = "\n";
editor = atom.workspace.getActiveTextEditor()
if editor
allText = editor.getText()
formatted = ''
if opts.xml_utf8_header
regXML = /^<\?xml.+\?>/
allText = allText.replace(regXML,'')
allText = '<?xml version="1.0" encoding="UTF-8"?>' + allText
xml = allText.replace(/\r|\n/g, '')
reg_cdata = /(<!\[)(.+?)(\]\]>)/g
xml = xml.replace(reg_cdata,'@cdata_ini@$2@cdata_end@')
reg = /(>)\s*(<)(\/*)/g
xml = xml.replace(reg, '$1\r\n$2$3')
pad = 0;
for node, i in xml.split('\r\n')
indent = 0
if node.match(/.+<\/\w[^>]*>$/)
indent = 0
else if node.match(/^<\/\w/)
pad -= 1 unless pad is 0
else if node.match(/^<\w/) and !node.match(/\/>/)
indent = 1
else
indent = 0
padding = ""
i = 0
while i < pad
padding += str_pad "", opts.number_char_indent, opts.indent_character
i++
formatted += padding + node + opts.crlf
pad += indent
replace_cdata_ini = /@cdata_ini@/g
replace_cdata_end = /@cdata_end@/g
formatted = formatted.replace(replace_cdata_ini,'<![')
formatted = formatted.replace(replace_cdata_end,']]>')
editor.setText(formatted)
str_pad = (input, pad_length, pad_string, pad_type) ->
# Returns input string padded on the left or right to specified length with pad_string
#
# version: 1009.2513
# discuss at: http://phpjs.org/functions/str_pad
# + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
# + namespaced by: Michael White (http://getsprink.com)
# + input by: Marco van Oort
# + bugfixed by: Brett Zamir (http://brett-zamir.me)
# * example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
# * returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
# * example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
# * returns 2: '------Kevin van Zonneveld-----'
half = ""
pad_to_go = undefined
str_pad_repeater = (s, len) ->
collect = ""
i = undefined
collect += s while collect.length < len
collect = collect.substr(0, len)
collect
input += ""
pad_string = (if pad_string isnt `undefined` then pad_string else " ")
pad_type = "STR_PAD_RIGHT" if pad_type isnt "STR_PAD_LEFT" and pad_type isnt "STR_PAD_RIGHT" and pad_type isnt "STR_PAD_BOTH"
if (pad_to_go = pad_length - input.length) > 0
if pad_type is "STR_PAD_LEFT"
input = str_pad_repeater(pad_string, pad_to_go) + input
else if pad_type is "STR_PAD_RIGHT"
input = input + str_pad_repeater(pad_string, pad_to_go)
else if pad_type is "STR_PAD_BOTH"
half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2))
input = half + input + half
input = input.substr(0, pad_length)
input
| 184853 | module.exports =
config:
xmlUtf8Header:
type: 'boolean'
default: true
useTab:
type: 'string'
default:'false'
enum: ['false','true']
numberCharIndent:
type: 'integer'
default: 2
indentCharacter:
type: 'string'
default: " "
endLineCharacter:
type: 'string'
default: 'CR+LF (\\r\\n)'
enum: ['CR+LF (\\r\\n)','LF (\\n)']
activate: ->
atom.commands.add 'atom-workspace', "xml-formatter:indent", => @indent()
atom.config.observe 'xml-formatter.xmlUtf8Header', (value) =>
@xmlUtf8Header = value
atom.config.observe 'xml-formatter.useTab', (value) =>
@useTab = value
atom.config.observe 'xml-formatter.numberCharIndent', (value) =>
@numberCharIndent = value
atom.config.observe 'xml-formatter.indentCharacter', (value) =>
@indentCharacter = value
atom.config.observe 'xml-formatter.endLineCharacter', (value) =>
@endLineCharacter = value
indent: ->
opts = {}
opts.xml_utf8_header = atom.config.get('xml-formatter.xmlUtf8Header')
opts.use_tab = atom.config.get('xml-formatter.useTab')
opts.number_char_indent = atom.config.get('xml-formatter.numberCharIndent')
opts.indent_character = atom.config.get('xml-formatter.indentCharacter')
opts.indent_character = "\t" if opts.use_tab is "true"
opts.crlf = atom.config.get('xml-formatter.endLineCharacter')
if opts.crlf == "CR+LF (\\r\\n)"
opts.crlf = "\r\n";
else
opts.crlf = "\n";
editor = atom.workspace.getActiveTextEditor()
if editor
allText = editor.getText()
formatted = ''
if opts.xml_utf8_header
regXML = /^<\?xml.+\?>/
allText = allText.replace(regXML,'')
allText = '<?xml version="1.0" encoding="UTF-8"?>' + allText
xml = allText.replace(/\r|\n/g, '')
reg_cdata = /(<!\[)(.+?)(\]\]>)/g
xml = xml.replace(reg_cdata,'@cdata_ini@$2@cdata_end@')
reg = /(>)\s*(<)(\/*)/g
xml = xml.replace(reg, '$1\r\n$2$3')
pad = 0;
for node, i in xml.split('\r\n')
indent = 0
if node.match(/.+<\/\w[^>]*>$/)
indent = 0
else if node.match(/^<\/\w/)
pad -= 1 unless pad is 0
else if node.match(/^<\w/) and !node.match(/\/>/)
indent = 1
else
indent = 0
padding = ""
i = 0
while i < pad
padding += str_pad "", opts.number_char_indent, opts.indent_character
i++
formatted += padding + node + opts.crlf
pad += indent
replace_cdata_ini = /@cdata_ini@/g
replace_cdata_end = /@cdata_end@/g
formatted = formatted.replace(replace_cdata_ini,'<![')
formatted = formatted.replace(replace_cdata_end,']]>')
editor.setText(formatted)
str_pad = (input, pad_length, pad_string, pad_type) ->
# Returns input string padded on the left or right to specified length with pad_string
#
# version: 1009.2513
# discuss at: http://phpjs.org/functions/str_pad
# + original by: <NAME> (http://kevin.vanzonneveld.net)
# + namespaced by: <NAME> (http://getsprink.com)
# + input by: <NAME>
# + bugfixed by: <NAME> (http://brett-zamir.me)
# * example 1: str_pad('<NAME>', 30, '-=', 'STR_PAD_LEFT');
# * returns 1: '-=-=-=-=-=-<NAME>'
# * example 2: str_pad('<NAME>', 30, '-', 'STR_PAD_BOTH');
# * returns 2: '------<NAME>-----'
half = ""
pad_to_go = undefined
str_pad_repeater = (s, len) ->
collect = ""
i = undefined
collect += s while collect.length < len
collect = collect.substr(0, len)
collect
input += ""
pad_string = (if pad_string isnt `undefined` then pad_string else " ")
pad_type = "STR_PAD_RIGHT" if pad_type isnt "STR_PAD_LEFT" and pad_type isnt "STR_PAD_RIGHT" and pad_type isnt "STR_PAD_BOTH"
if (pad_to_go = pad_length - input.length) > 0
if pad_type is "STR_PAD_LEFT"
input = str_pad_repeater(pad_string, pad_to_go) + input
else if pad_type is "STR_PAD_RIGHT"
input = input + str_pad_repeater(pad_string, pad_to_go)
else if pad_type is "STR_PAD_BOTH"
half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2))
input = half + input + half
input = input.substr(0, pad_length)
input
| true | module.exports =
config:
xmlUtf8Header:
type: 'boolean'
default: true
useTab:
type: 'string'
default:'false'
enum: ['false','true']
numberCharIndent:
type: 'integer'
default: 2
indentCharacter:
type: 'string'
default: " "
endLineCharacter:
type: 'string'
default: 'CR+LF (\\r\\n)'
enum: ['CR+LF (\\r\\n)','LF (\\n)']
activate: ->
atom.commands.add 'atom-workspace', "xml-formatter:indent", => @indent()
atom.config.observe 'xml-formatter.xmlUtf8Header', (value) =>
@xmlUtf8Header = value
atom.config.observe 'xml-formatter.useTab', (value) =>
@useTab = value
atom.config.observe 'xml-formatter.numberCharIndent', (value) =>
@numberCharIndent = value
atom.config.observe 'xml-formatter.indentCharacter', (value) =>
@indentCharacter = value
atom.config.observe 'xml-formatter.endLineCharacter', (value) =>
@endLineCharacter = value
indent: ->
opts = {}
opts.xml_utf8_header = atom.config.get('xml-formatter.xmlUtf8Header')
opts.use_tab = atom.config.get('xml-formatter.useTab')
opts.number_char_indent = atom.config.get('xml-formatter.numberCharIndent')
opts.indent_character = atom.config.get('xml-formatter.indentCharacter')
opts.indent_character = "\t" if opts.use_tab is "true"
opts.crlf = atom.config.get('xml-formatter.endLineCharacter')
if opts.crlf == "CR+LF (\\r\\n)"
opts.crlf = "\r\n";
else
opts.crlf = "\n";
editor = atom.workspace.getActiveTextEditor()
if editor
allText = editor.getText()
formatted = ''
if opts.xml_utf8_header
regXML = /^<\?xml.+\?>/
allText = allText.replace(regXML,'')
allText = '<?xml version="1.0" encoding="UTF-8"?>' + allText
xml = allText.replace(/\r|\n/g, '')
reg_cdata = /(<!\[)(.+?)(\]\]>)/g
xml = xml.replace(reg_cdata,'@cdata_ini@$2@cdata_end@')
reg = /(>)\s*(<)(\/*)/g
xml = xml.replace(reg, '$1\r\n$2$3')
pad = 0;
for node, i in xml.split('\r\n')
indent = 0
if node.match(/.+<\/\w[^>]*>$/)
indent = 0
else if node.match(/^<\/\w/)
pad -= 1 unless pad is 0
else if node.match(/^<\w/) and !node.match(/\/>/)
indent = 1
else
indent = 0
padding = ""
i = 0
while i < pad
padding += str_pad "", opts.number_char_indent, opts.indent_character
i++
formatted += padding + node + opts.crlf
pad += indent
replace_cdata_ini = /@cdata_ini@/g
replace_cdata_end = /@cdata_end@/g
formatted = formatted.replace(replace_cdata_ini,'<![')
formatted = formatted.replace(replace_cdata_end,']]>')
editor.setText(formatted)
str_pad = (input, pad_length, pad_string, pad_type) ->
# Returns input string padded on the left or right to specified length with pad_string
#
# version: 1009.2513
# discuss at: http://phpjs.org/functions/str_pad
# + original by: PI:NAME:<NAME>END_PI (http://kevin.vanzonneveld.net)
# + namespaced by: PI:NAME:<NAME>END_PI (http://getsprink.com)
# + input by: PI:NAME:<NAME>END_PI
# + bugfixed by: PI:NAME:<NAME>END_PI (http://brett-zamir.me)
# * example 1: str_pad('PI:NAME:<NAME>END_PI', 30, '-=', 'STR_PAD_LEFT');
# * returns 1: '-=-=-=-=-=-PI:NAME:<NAME>END_PI'
# * example 2: str_pad('PI:NAME:<NAME>END_PI', 30, '-', 'STR_PAD_BOTH');
# * returns 2: '------PI:NAME:<NAME>END_PI-----'
half = ""
pad_to_go = undefined
str_pad_repeater = (s, len) ->
collect = ""
i = undefined
collect += s while collect.length < len
collect = collect.substr(0, len)
collect
input += ""
pad_string = (if pad_string isnt `undefined` then pad_string else " ")
pad_type = "STR_PAD_RIGHT" if pad_type isnt "STR_PAD_LEFT" and pad_type isnt "STR_PAD_RIGHT" and pad_type isnt "STR_PAD_BOTH"
if (pad_to_go = pad_length - input.length) > 0
if pad_type is "STR_PAD_LEFT"
input = str_pad_repeater(pad_string, pad_to_go) + input
else if pad_type is "STR_PAD_RIGHT"
input = input + str_pad_repeater(pad_string, pad_to_go)
else if pad_type is "STR_PAD_BOTH"
half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2))
input = half + input + half
input = input.substr(0, pad_length)
input
|
[
{
"context": "rUrl = @expandUrl receiverPath\n @storageKey = \"dropbox_js_#{@scope}_credentials\"\n\n # Saves token informatio",
"end": 3540,
"score": 0.7263168096542358,
"start": 3529,
"tag": "KEY",
"value": "dropbox_js_"
},
{
"context": "eceiverPath\n @storageKey = \"dropbox... | src/auth_driver/chrome.coffee | fatihacet/dropbox-js | 1 | DropboxChromeOnMessage = null
DropboxChromeSendMessage = null
if chrome?
# v2 manifest APIs.
if chrome.runtime
if chrome.runtime.onMessage
DropboxChromeOnMessage = chrome.runtime.onMessage
if chrome.runtime.sendMessage
DropboxChromeSendMessage = (m) -> chrome.runtime.sendMessage m
# v1 manifest APIs.
if chrome.extension
if chrome.extension.onMessage
DropboxChromeOnMessage or= chrome.extension.onMessage
if chrome.extension.sendMessage
DropboxChromeSendMessage or= (m) -> chrome.extension.sendMessage m
# Apps that use the v2 manifest don't get messenging in Chrome 25.
unless DropboxChromeOnMessage
do ->
pageHack = (page) ->
if page.Dropbox
Dropbox.AuthDriver.Chrome::onMessage =
page.Dropbox.AuthDriver.Chrome.onMessage
Dropbox.AuthDriver.Chrome::sendMessage =
page.Dropbox.AuthDriver.Chrome.sendMessage
else
page.Dropbox = Dropbox
Dropbox.AuthDriver.Chrome::onMessage = new Dropbox.Util.EventSource
Dropbox.AuthDriver.Chrome::sendMessage =
(m) -> Dropbox.AuthDriver.Chrome::onMessage.dispatch m
if chrome.extension and chrome.extension.getBackgroundPage
if page = chrome.extension.getBackgroundPage()
return pageHack(page)
if chrome.runtime and chrome.runtime.getBackgroundPage
return chrome.runtime.getBackgroundPage (page) -> pageHack page
# OAuth driver specialized for Chrome apps and extensions.
class Dropbox.AuthDriver.Chrome extends Dropbox.AuthDriver.BrowserBase
# @property {Chrome.Event<Object>, Dropbox.Util.EventSource<Object>} fires
# non-cancelable events when Dropbox.AuthDriver.Chrome#sendMessage is
# called; the message is a parsed JSON object
#
# @private
# This should only be used to communicate between
# {Dropbox.AuthDriver.Chrome#doAuthorize} and
# {Dropbox.AuthDriver.Chrome.oauthReceiver}.
onMessage: DropboxChromeOnMessage
# Sends a message across the Chrome extension / application.
#
# This causes {Dropbox.AuthDriver.Chrome#onMessage} to fire an event
# containing the given message.
#
# @private
# This should only be used to communicate between
# {Dropbox.AuthDriver.Chrome#doAuthorize} and
# {Dropbox.AuthDriver.Chrome.oauthReceiver}.
#
# @param {Object} message an object that can be serialized to JSON
# @return unspecified; may vary across platforms and dropbox.js versions
sendMessage: DropboxChromeSendMessage
# Expands an URL relative to the Chrome extension / application root.
#
# @param {String} url a resource URL relative to the extension root
# @return {String} the absolute resource URL
expandUrl: (url) ->
if chrome.runtime and chrome.runtime.getURL
return chrome.runtime.getURL(url)
if chrome.extension and chrome.extension.getURL
return chrome.extension.getURL(url)
url
# Sets up an OAuth driver for Chrome.
#
# @param {Object} options (optional) one or more of the options below
# @option options {String} receiverPath the path of page that receives the
# /authorize redirect and calls {Dropbox.AuthDriver.Chrome.oauthReceiver};
# the path should be relative to the extension folder; by default, is
# 'chrome_oauth_receiver.html'
constructor: (options) ->
super options
receiverPath = (options and options.receiverPath) or
'chrome_oauth_receiver.html'
@useQuery = true
@receiverUrl = @expandUrl receiverPath
@storageKey = "dropbox_js_#{@scope}_credentials"
# Saves token information when appropriate.
onAuthStepChange: (client, callback) ->
switch client.authStep
when Dropbox.Client.RESET
@loadCredentials (credentials) =>
if credentials
if credentials.authStep
# Stuck authentication process, reset.
return @forgetCredentials(callback)
client.setCredentials credentials
callback()
when Dropbox.Client.DONE
@storeCredentials client.credentials(), callback
when Dropbox.Client.SIGNED_OUT
@forgetCredentials callback
when Dropbox.Client.ERROR
@forgetCredentials callback
else
callback()
# Shows the authorization URL in a new tab, waits for it to send a message.
#
# @see Dropbox.AuthDriver#doAuthorize
doAuthorize: (authUrl, stateParam, client, callback) ->
if chrome.identity?.launchWebAuthFlow
# Apps V2 after the identity API hits stable?
chrome.identity.launchWebAuthFlow url: authUrl, interactive: true,
(redirectUrl) =>
if @locationStateParam(redirectUrl) is stateParam
stateParam = false # Avoid having this matched in the future.
callback Dropbox.Util.Oauth.queryParamsFromUrl(redirectUrl)
else if chrome.experimental?.identity?.launchWebAuthFlow
# Apps V2 with identity in experimental
chrome.experimental.identity.launchWebAuthFlow
url: authUrl, interactive: true, (redirectUrl) =>
if @locationStateParam(redirectUrl) is stateParam
stateParam = false # Avoid having this matched in the future.
callback Dropbox.Util.Oauth.queryParamsFromUrl(redirectUrl)
else
# Extensions and Apps V1.
window = handle: null
@listenForMessage stateParam, window, callback
@openWindow authUrl, (handle) -> window.handle = handle
# Creates a popup window.
#
# @param {String} url the URL that will be loaded in the popup window
# @param {function(Object)} callback called with a handle that can be passed
# to Dropbox.AuthDriver.Chrome#closeWindow
# @return {Dropbox.AuthDriver.Chrome} this
openWindow: (url, callback) ->
if chrome.tabs and chrome.tabs.create
chrome.tabs.create url: url, active: true, pinned: false, (tab) ->
callback tab
return @
@
# Closes a window that was previously opened with openWindow.
#
# @private
# This should only be used by {Dropbox.AuthDriver.Chrome#oauthReceiver}.
#
# @param {Object} handle the object passed to an openWindow callback
closeWindow: (handle) ->
if chrome.tabs and chrome.tabs.remove and handle.id
chrome.tabs.remove handle.id
return @
if chrome.app and chrome.app.window and handle.close
handle.close()
return @
@
# URL of the redirect receiver page that messages the app / extension.
#
# @see Dropbox.AuthDriver#url
url: ->
@receiverUrl
# Listens for a postMessage from a previously opened tab.
#
# @private
# This should only be used by {Dropbox.AuthDriver.Chrome#doAuthorize}.
#
# @param {String} stateParam the state parameter passed to the OAuth 2
# /authorize endpoint
# @param {Object} window a JavaScript object whose "handle" property is a
# window handle passed to the callback of a
# Dropbox.AuthDriver.Chrome#openWindow call
# @param {function()} called when the received message matches stateParam
listenForMessage: (stateParam, window, callback) ->
listener = (message, sender) =>
# Reject messages not coming from the OAuth receiver window.
if sender and sender.tab
unless sender.tab.url.substring(0, @receiverUrl.length) is @receiverUrl
return
# Reject improperly formatted messages.
return unless message.dropbox_oauth_receiver_href
receiverHref = message.dropbox_oauth_receiver_href
if @locationStateParam(receiverHref) is stateParam
stateParam = false # Avoid having this matched in the future.
@closeWindow window.handle if window.handle
@onMessage.removeListener listener
callback Dropbox.Util.Oauth.queryParamsFromUrl(receiverHref)
@onMessage.addListener listener
# Stores a Dropbox.Client's credentials in local storage.
#
# @private
# onAuthStepChange calls this method during the authentication flow.
#
# @param {Object} credentials the result of a Drobpox.Client#credentials call
# @param {function()} callback called when the storing operation is complete
# @return {Dropbox.AuthDriver.BrowserBase} this, for easy call chaining
storeCredentials: (credentials, callback) ->
items= {}
items[@storageKey] = credentials
chrome.storage.local.set items, callback
@
# Retrieves a token and secret from localStorage.
#
# @private
# onAuthStepChange calls this method during the authentication flow.
#
# @param {function(?Object)} callback supplied with the credentials object
# stored by a previous call to
# Dropbox.AuthDriver.BrowserBase#storeCredentials; null if no credentials
# were stored, or if the previously stored credentials were deleted
# @return {Dropbox.AuthDriver.BrowserBase} this, for easy call chaining
loadCredentials: (callback) ->
chrome.storage.local.get @storageKey, (items) =>
callback items[@storageKey] or null
@
# Deletes information previously stored by a call to storeCredentials.
#
# @private
# onAuthStepChange calls this method during the authentication flow.
#
# @param {function()} callback called after the credentials are deleted
# @return {Dropbox.AuthDriver.BrowserBase} this, for easy call chaining
forgetCredentials: (callback) ->
chrome.storage.local.remove @storageKey, callback
@
# Communicates with the driver from the OAuth receiver page.
#
# The easiest way for a Chrome application or extension to keep up to date
# with dropbox.js is to set up a popup receiver page that loads dropbox.js
# and calls this method. This guarantees that the code used to communicate
# between the popup receiver page and {Dropbox.AuthDriver.Popup#doAuthorize}
# stays up to date as dropbox.js is updated.
@oauthReceiver: ->
window.addEventListener 'load', ->
driver = new Dropbox.AuthDriver.Chrome()
pageUrl = window.location.href
window.location.hash = '' # Remove the token from the browser history.
driver.sendMessage dropbox_oauth_receiver_href: pageUrl
window.close() if window.close
| 119927 | DropboxChromeOnMessage = null
DropboxChromeSendMessage = null
if chrome?
# v2 manifest APIs.
if chrome.runtime
if chrome.runtime.onMessage
DropboxChromeOnMessage = chrome.runtime.onMessage
if chrome.runtime.sendMessage
DropboxChromeSendMessage = (m) -> chrome.runtime.sendMessage m
# v1 manifest APIs.
if chrome.extension
if chrome.extension.onMessage
DropboxChromeOnMessage or= chrome.extension.onMessage
if chrome.extension.sendMessage
DropboxChromeSendMessage or= (m) -> chrome.extension.sendMessage m
# Apps that use the v2 manifest don't get messenging in Chrome 25.
unless DropboxChromeOnMessage
do ->
pageHack = (page) ->
if page.Dropbox
Dropbox.AuthDriver.Chrome::onMessage =
page.Dropbox.AuthDriver.Chrome.onMessage
Dropbox.AuthDriver.Chrome::sendMessage =
page.Dropbox.AuthDriver.Chrome.sendMessage
else
page.Dropbox = Dropbox
Dropbox.AuthDriver.Chrome::onMessage = new Dropbox.Util.EventSource
Dropbox.AuthDriver.Chrome::sendMessage =
(m) -> Dropbox.AuthDriver.Chrome::onMessage.dispatch m
if chrome.extension and chrome.extension.getBackgroundPage
if page = chrome.extension.getBackgroundPage()
return pageHack(page)
if chrome.runtime and chrome.runtime.getBackgroundPage
return chrome.runtime.getBackgroundPage (page) -> pageHack page
# OAuth driver specialized for Chrome apps and extensions.
class Dropbox.AuthDriver.Chrome extends Dropbox.AuthDriver.BrowserBase
# @property {Chrome.Event<Object>, Dropbox.Util.EventSource<Object>} fires
# non-cancelable events when Dropbox.AuthDriver.Chrome#sendMessage is
# called; the message is a parsed JSON object
#
# @private
# This should only be used to communicate between
# {Dropbox.AuthDriver.Chrome#doAuthorize} and
# {Dropbox.AuthDriver.Chrome.oauthReceiver}.
onMessage: DropboxChromeOnMessage
# Sends a message across the Chrome extension / application.
#
# This causes {Dropbox.AuthDriver.Chrome#onMessage} to fire an event
# containing the given message.
#
# @private
# This should only be used to communicate between
# {Dropbox.AuthDriver.Chrome#doAuthorize} and
# {Dropbox.AuthDriver.Chrome.oauthReceiver}.
#
# @param {Object} message an object that can be serialized to JSON
# @return unspecified; may vary across platforms and dropbox.js versions
sendMessage: DropboxChromeSendMessage
# Expands an URL relative to the Chrome extension / application root.
#
# @param {String} url a resource URL relative to the extension root
# @return {String} the absolute resource URL
expandUrl: (url) ->
if chrome.runtime and chrome.runtime.getURL
return chrome.runtime.getURL(url)
if chrome.extension and chrome.extension.getURL
return chrome.extension.getURL(url)
url
# Sets up an OAuth driver for Chrome.
#
# @param {Object} options (optional) one or more of the options below
# @option options {String} receiverPath the path of page that receives the
# /authorize redirect and calls {Dropbox.AuthDriver.Chrome.oauthReceiver};
# the path should be relative to the extension folder; by default, is
# 'chrome_oauth_receiver.html'
constructor: (options) ->
super options
receiverPath = (options and options.receiverPath) or
'chrome_oauth_receiver.html'
@useQuery = true
@receiverUrl = @expandUrl receiverPath
@storageKey = "<KEY>#{@scope}_<KEY>"
# Saves token information when appropriate.
onAuthStepChange: (client, callback) ->
switch client.authStep
when Dropbox.Client.RESET
@loadCredentials (credentials) =>
if credentials
if credentials.authStep
# Stuck authentication process, reset.
return @forgetCredentials(callback)
client.setCredentials credentials
callback()
when Dropbox.Client.DONE
@storeCredentials client.credentials(), callback
when Dropbox.Client.SIGNED_OUT
@forgetCredentials callback
when Dropbox.Client.ERROR
@forgetCredentials callback
else
callback()
# Shows the authorization URL in a new tab, waits for it to send a message.
#
# @see Dropbox.AuthDriver#doAuthorize
doAuthorize: (authUrl, stateParam, client, callback) ->
if chrome.identity?.launchWebAuthFlow
# Apps V2 after the identity API hits stable?
chrome.identity.launchWebAuthFlow url: authUrl, interactive: true,
(redirectUrl) =>
if @locationStateParam(redirectUrl) is stateParam
stateParam = false # Avoid having this matched in the future.
callback Dropbox.Util.Oauth.queryParamsFromUrl(redirectUrl)
else if chrome.experimental?.identity?.launchWebAuthFlow
# Apps V2 with identity in experimental
chrome.experimental.identity.launchWebAuthFlow
url: authUrl, interactive: true, (redirectUrl) =>
if @locationStateParam(redirectUrl) is stateParam
stateParam = false # Avoid having this matched in the future.
callback Dropbox.Util.Oauth.queryParamsFromUrl(redirectUrl)
else
# Extensions and Apps V1.
window = handle: null
@listenForMessage stateParam, window, callback
@openWindow authUrl, (handle) -> window.handle = handle
# Creates a popup window.
#
# @param {String} url the URL that will be loaded in the popup window
# @param {function(Object)} callback called with a handle that can be passed
# to Dropbox.AuthDriver.Chrome#closeWindow
# @return {Dropbox.AuthDriver.Chrome} this
openWindow: (url, callback) ->
if chrome.tabs and chrome.tabs.create
chrome.tabs.create url: url, active: true, pinned: false, (tab) ->
callback tab
return @
@
# Closes a window that was previously opened with openWindow.
#
# @private
# This should only be used by {Dropbox.AuthDriver.Chrome#oauthReceiver}.
#
# @param {Object} handle the object passed to an openWindow callback
closeWindow: (handle) ->
if chrome.tabs and chrome.tabs.remove and handle.id
chrome.tabs.remove handle.id
return @
if chrome.app and chrome.app.window and handle.close
handle.close()
return @
@
# URL of the redirect receiver page that messages the app / extension.
#
# @see Dropbox.AuthDriver#url
url: ->
@receiverUrl
# Listens for a postMessage from a previously opened tab.
#
# @private
# This should only be used by {Dropbox.AuthDriver.Chrome#doAuthorize}.
#
# @param {String} stateParam the state parameter passed to the OAuth 2
# /authorize endpoint
# @param {Object} window a JavaScript object whose "handle" property is a
# window handle passed to the callback of a
# Dropbox.AuthDriver.Chrome#openWindow call
# @param {function()} called when the received message matches stateParam
listenForMessage: (stateParam, window, callback) ->
listener = (message, sender) =>
# Reject messages not coming from the OAuth receiver window.
if sender and sender.tab
unless sender.tab.url.substring(0, @receiverUrl.length) is @receiverUrl
return
# Reject improperly formatted messages.
return unless message.dropbox_oauth_receiver_href
receiverHref = message.dropbox_oauth_receiver_href
if @locationStateParam(receiverHref) is stateParam
stateParam = false # Avoid having this matched in the future.
@closeWindow window.handle if window.handle
@onMessage.removeListener listener
callback Dropbox.Util.Oauth.queryParamsFromUrl(receiverHref)
@onMessage.addListener listener
# Stores a Dropbox.Client's credentials in local storage.
#
# @private
# onAuthStepChange calls this method during the authentication flow.
#
# @param {Object} credentials the result of a Drobpox.Client#credentials call
# @param {function()} callback called when the storing operation is complete
# @return {Dropbox.AuthDriver.BrowserBase} this, for easy call chaining
storeCredentials: (credentials, callback) ->
items= {}
items[@storageKey] = credentials
chrome.storage.local.set items, callback
@
# Retrieves a token and secret from localStorage.
#
# @private
# onAuthStepChange calls this method during the authentication flow.
#
# @param {function(?Object)} callback supplied with the credentials object
# stored by a previous call to
# Dropbox.AuthDriver.BrowserBase#storeCredentials; null if no credentials
# were stored, or if the previously stored credentials were deleted
# @return {Dropbox.AuthDriver.BrowserBase} this, for easy call chaining
loadCredentials: (callback) ->
chrome.storage.local.get @storageKey, (items) =>
callback items[@storageKey] or null
@
# Deletes information previously stored by a call to storeCredentials.
#
# @private
# onAuthStepChange calls this method during the authentication flow.
#
# @param {function()} callback called after the credentials are deleted
# @return {Dropbox.AuthDriver.BrowserBase} this, for easy call chaining
forgetCredentials: (callback) ->
chrome.storage.local.remove @storageKey, callback
@
# Communicates with the driver from the OAuth receiver page.
#
# The easiest way for a Chrome application or extension to keep up to date
# with dropbox.js is to set up a popup receiver page that loads dropbox.js
# and calls this method. This guarantees that the code used to communicate
# between the popup receiver page and {Dropbox.AuthDriver.Popup#doAuthorize}
# stays up to date as dropbox.js is updated.
@oauthReceiver: ->
window.addEventListener 'load', ->
driver = new Dropbox.AuthDriver.Chrome()
pageUrl = window.location.href
window.location.hash = '' # Remove the token from the browser history.
driver.sendMessage dropbox_oauth_receiver_href: pageUrl
window.close() if window.close
| true | DropboxChromeOnMessage = null
DropboxChromeSendMessage = null
if chrome?
# v2 manifest APIs.
if chrome.runtime
if chrome.runtime.onMessage
DropboxChromeOnMessage = chrome.runtime.onMessage
if chrome.runtime.sendMessage
DropboxChromeSendMessage = (m) -> chrome.runtime.sendMessage m
# v1 manifest APIs.
if chrome.extension
if chrome.extension.onMessage
DropboxChromeOnMessage or= chrome.extension.onMessage
if chrome.extension.sendMessage
DropboxChromeSendMessage or= (m) -> chrome.extension.sendMessage m
# Apps that use the v2 manifest don't get messenging in Chrome 25.
unless DropboxChromeOnMessage
do ->
pageHack = (page) ->
if page.Dropbox
Dropbox.AuthDriver.Chrome::onMessage =
page.Dropbox.AuthDriver.Chrome.onMessage
Dropbox.AuthDriver.Chrome::sendMessage =
page.Dropbox.AuthDriver.Chrome.sendMessage
else
page.Dropbox = Dropbox
Dropbox.AuthDriver.Chrome::onMessage = new Dropbox.Util.EventSource
Dropbox.AuthDriver.Chrome::sendMessage =
(m) -> Dropbox.AuthDriver.Chrome::onMessage.dispatch m
if chrome.extension and chrome.extension.getBackgroundPage
if page = chrome.extension.getBackgroundPage()
return pageHack(page)
if chrome.runtime and chrome.runtime.getBackgroundPage
return chrome.runtime.getBackgroundPage (page) -> pageHack page
# OAuth driver specialized for Chrome apps and extensions.
class Dropbox.AuthDriver.Chrome extends Dropbox.AuthDriver.BrowserBase
# @property {Chrome.Event<Object>, Dropbox.Util.EventSource<Object>} fires
# non-cancelable events when Dropbox.AuthDriver.Chrome#sendMessage is
# called; the message is a parsed JSON object
#
# @private
# This should only be used to communicate between
# {Dropbox.AuthDriver.Chrome#doAuthorize} and
# {Dropbox.AuthDriver.Chrome.oauthReceiver}.
onMessage: DropboxChromeOnMessage
# Sends a message across the Chrome extension / application.
#
# This causes {Dropbox.AuthDriver.Chrome#onMessage} to fire an event
# containing the given message.
#
# @private
# This should only be used to communicate between
# {Dropbox.AuthDriver.Chrome#doAuthorize} and
# {Dropbox.AuthDriver.Chrome.oauthReceiver}.
#
# @param {Object} message an object that can be serialized to JSON
# @return unspecified; may vary across platforms and dropbox.js versions
sendMessage: DropboxChromeSendMessage
# Expands an URL relative to the Chrome extension / application root.
#
# @param {String} url a resource URL relative to the extension root
# @return {String} the absolute resource URL
expandUrl: (url) ->
if chrome.runtime and chrome.runtime.getURL
return chrome.runtime.getURL(url)
if chrome.extension and chrome.extension.getURL
return chrome.extension.getURL(url)
url
# Sets up an OAuth driver for Chrome.
#
# @param {Object} options (optional) one or more of the options below
# @option options {String} receiverPath the path of page that receives the
# /authorize redirect and calls {Dropbox.AuthDriver.Chrome.oauthReceiver};
# the path should be relative to the extension folder; by default, is
# 'chrome_oauth_receiver.html'
constructor: (options) ->
super options
receiverPath = (options and options.receiverPath) or
'chrome_oauth_receiver.html'
@useQuery = true
@receiverUrl = @expandUrl receiverPath
@storageKey = "PI:KEY:<KEY>END_PI#{@scope}_PI:KEY:<KEY>END_PI"
# Saves token information when appropriate.
onAuthStepChange: (client, callback) ->
switch client.authStep
when Dropbox.Client.RESET
@loadCredentials (credentials) =>
if credentials
if credentials.authStep
# Stuck authentication process, reset.
return @forgetCredentials(callback)
client.setCredentials credentials
callback()
when Dropbox.Client.DONE
@storeCredentials client.credentials(), callback
when Dropbox.Client.SIGNED_OUT
@forgetCredentials callback
when Dropbox.Client.ERROR
@forgetCredentials callback
else
callback()
# Shows the authorization URL in a new tab, waits for it to send a message.
#
# @see Dropbox.AuthDriver#doAuthorize
doAuthorize: (authUrl, stateParam, client, callback) ->
if chrome.identity?.launchWebAuthFlow
# Apps V2 after the identity API hits stable?
chrome.identity.launchWebAuthFlow url: authUrl, interactive: true,
(redirectUrl) =>
if @locationStateParam(redirectUrl) is stateParam
stateParam = false # Avoid having this matched in the future.
callback Dropbox.Util.Oauth.queryParamsFromUrl(redirectUrl)
else if chrome.experimental?.identity?.launchWebAuthFlow
# Apps V2 with identity in experimental
chrome.experimental.identity.launchWebAuthFlow
url: authUrl, interactive: true, (redirectUrl) =>
if @locationStateParam(redirectUrl) is stateParam
stateParam = false # Avoid having this matched in the future.
callback Dropbox.Util.Oauth.queryParamsFromUrl(redirectUrl)
else
# Extensions and Apps V1.
window = handle: null
@listenForMessage stateParam, window, callback
@openWindow authUrl, (handle) -> window.handle = handle
# Creates a popup window.
#
# @param {String} url the URL that will be loaded in the popup window
# @param {function(Object)} callback called with a handle that can be passed
# to Dropbox.AuthDriver.Chrome#closeWindow
# @return {Dropbox.AuthDriver.Chrome} this
openWindow: (url, callback) ->
if chrome.tabs and chrome.tabs.create
chrome.tabs.create url: url, active: true, pinned: false, (tab) ->
callback tab
return @
@
# Closes a window that was previously opened with openWindow.
#
# @private
# This should only be used by {Dropbox.AuthDriver.Chrome#oauthReceiver}.
#
# @param {Object} handle the object passed to an openWindow callback
closeWindow: (handle) ->
if chrome.tabs and chrome.tabs.remove and handle.id
chrome.tabs.remove handle.id
return @
if chrome.app and chrome.app.window and handle.close
handle.close()
return @
@
# URL of the redirect receiver page that messages the app / extension.
#
# @see Dropbox.AuthDriver#url
url: ->
@receiverUrl
# Listens for a postMessage from a previously opened tab.
#
# @private
# This should only be used by {Dropbox.AuthDriver.Chrome#doAuthorize}.
#
# @param {String} stateParam the state parameter passed to the OAuth 2
# /authorize endpoint
# @param {Object} window a JavaScript object whose "handle" property is a
# window handle passed to the callback of a
# Dropbox.AuthDriver.Chrome#openWindow call
# @param {function()} called when the received message matches stateParam
listenForMessage: (stateParam, window, callback) ->
listener = (message, sender) =>
# Reject messages not coming from the OAuth receiver window.
if sender and sender.tab
unless sender.tab.url.substring(0, @receiverUrl.length) is @receiverUrl
return
# Reject improperly formatted messages.
return unless message.dropbox_oauth_receiver_href
receiverHref = message.dropbox_oauth_receiver_href
if @locationStateParam(receiverHref) is stateParam
stateParam = false # Avoid having this matched in the future.
@closeWindow window.handle if window.handle
@onMessage.removeListener listener
callback Dropbox.Util.Oauth.queryParamsFromUrl(receiverHref)
@onMessage.addListener listener
# Stores a Dropbox.Client's credentials in local storage.
#
# @private
# onAuthStepChange calls this method during the authentication flow.
#
# @param {Object} credentials the result of a Drobpox.Client#credentials call
# @param {function()} callback called when the storing operation is complete
# @return {Dropbox.AuthDriver.BrowserBase} this, for easy call chaining
storeCredentials: (credentials, callback) ->
items= {}
items[@storageKey] = credentials
chrome.storage.local.set items, callback
@
# Retrieves a token and secret from localStorage.
#
# @private
# onAuthStepChange calls this method during the authentication flow.
#
# @param {function(?Object)} callback supplied with the credentials object
# stored by a previous call to
# Dropbox.AuthDriver.BrowserBase#storeCredentials; null if no credentials
# were stored, or if the previously stored credentials were deleted
# @return {Dropbox.AuthDriver.BrowserBase} this, for easy call chaining
loadCredentials: (callback) ->
chrome.storage.local.get @storageKey, (items) =>
callback items[@storageKey] or null
@
# Deletes information previously stored by a call to storeCredentials.
#
# @private
# onAuthStepChange calls this method during the authentication flow.
#
# @param {function()} callback called after the credentials are deleted
# @return {Dropbox.AuthDriver.BrowserBase} this, for easy call chaining
forgetCredentials: (callback) ->
chrome.storage.local.remove @storageKey, callback
@
# Communicates with the driver from the OAuth receiver page.
#
# The easiest way for a Chrome application or extension to keep up to date
# with dropbox.js is to set up a popup receiver page that loads dropbox.js
# and calls this method. This guarantees that the code used to communicate
# between the popup receiver page and {Dropbox.AuthDriver.Popup#doAuthorize}
# stays up to date as dropbox.js is updated.
@oauthReceiver: ->
window.addEventListener 'load', ->
driver = new Dropbox.AuthDriver.Chrome()
pageUrl = window.location.href
window.location.hash = '' # Remove the token from the browser history.
driver.sendMessage dropbox_oauth_receiver_href: pageUrl
window.close() if window.close
|
[
{
"context": "ersion 1.0.0\n@file Ajax.js\n@author Welington Sampaio (http://welington.zaez.net/)\n@contact http://",
"end": 137,
"score": 0.9998912215232849,
"start": 120,
"tag": "NAME",
"value": "Welington Sampaio"
}
] | vendor/assets/javascripts/joker/Ajax.coffee | zaeznet/joker-rails | 0 | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file Ajax.js
@author Welington Sampaio (http://welington.zaez.net/)
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2013 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
###
###
###
class Joker.Ajax extends Joker.Core
settings:
###
Indicates whether the object should
be executed at the end of its creation
@type {Boolean}
###
autoExec: true
###
###
async: true
###
Indicates whether the object should use
a loader to stop, until the completion
of the request
@type {Boolean}
###
useLoader : true
###
Indicates the content type of the request
@type {String}
###
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
###
Indicates the url of the request
@type {String}
###
url : null
###
Indicates the method of the request
options : GET | POST | PUT | DELETE
@type {String}
###
method : 'GET'
###
Indicates the content of the request
@type {Object}
###
data : {}
###
Indicates the type of expected return
after the completion of request
@type {String}
###
dataType : 'json'
###
Callbacks run through the requisition
@see http://api.jquery.com/jQuery.ajax/
###
callbacks:
beforeSend: (jqXHR, settings)->
complete : (jqXHR, textStatus)->
error : (jqXHR, textStatus, errorThrown)->
success : (data, textStatus, jqXHR)->
constructor: (settings)->
super
@settings = @libSupport.extend true, {}, @settings, settings
@debug "Construindo o ajax com as configuracoes: ", @settings
@exec() if @settings.autoExec == true
###
Executa a requisicao javascript
###
exec: ->
@debug "Exec Ajax"
@libSupport.ajax
contentType: @settings.contentType
async : @settings.async
url : @settings.url
type : @settings.method
data : @get_data()
beforeSend : @settings.callbacks.beforeSend
complete : (jqXHR, textStatus)=>
@settings.callbacks.complete jqXHR, textStatus
@destroy()
error : (jqXHR, textStatus, errorThrown)=>
@debug "Error: ", jqXHR, textStatus, errorThrown
@testResponseUnauthorized jqXHR
@testResponseForbidden jqXHR
@settings.callbacks.error(jqXHR, textStatus, errorThrown)
success : (data, textStatus, jqXHR)=>
@debug "Success: ", data, textStatus, jqXHR
@settings.callbacks.success(data, textStatus, jqXHR)
###
Converte a data em string params
@returns {String}
###
get_data: ->
return @libSupport.param(@settings.data) if Object.isObject @settings.data
@settings.data
testResponseForbidden: (jqXHR)->
if jqXHR.status == 403
new Joker.Alert
type: Joker.Alert.TYPE_ERROR
message: 'Você não tem permissão para executar esta requisição.'
testResponseUnauthorized: (jqXHR)->
if jqXHR.status == 401
console.log "asd"
window.location.reload()
@debugPrefix: "Joker_Ajax"
@className : "Joker_Ajax"
# rails application and using csrf-token
Joker.Core.libSupport ->
Joker.Core.libSupport(document).ajaxSend (e, xhr, options)->
token = Joker.Core.libSupport("meta[name='csrf-token']").attr "content"
xhr.setRequestHeader("X-CSRF-Token", token) | 137504 | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file Ajax.js
@author <NAME> (http://welington.zaez.net/)
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2013 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
###
###
###
class Joker.Ajax extends Joker.Core
settings:
###
Indicates whether the object should
be executed at the end of its creation
@type {Boolean}
###
autoExec: true
###
###
async: true
###
Indicates whether the object should use
a loader to stop, until the completion
of the request
@type {Boolean}
###
useLoader : true
###
Indicates the content type of the request
@type {String}
###
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
###
Indicates the url of the request
@type {String}
###
url : null
###
Indicates the method of the request
options : GET | POST | PUT | DELETE
@type {String}
###
method : 'GET'
###
Indicates the content of the request
@type {Object}
###
data : {}
###
Indicates the type of expected return
after the completion of request
@type {String}
###
dataType : 'json'
###
Callbacks run through the requisition
@see http://api.jquery.com/jQuery.ajax/
###
callbacks:
beforeSend: (jqXHR, settings)->
complete : (jqXHR, textStatus)->
error : (jqXHR, textStatus, errorThrown)->
success : (data, textStatus, jqXHR)->
constructor: (settings)->
super
@settings = @libSupport.extend true, {}, @settings, settings
@debug "Construindo o ajax com as configuracoes: ", @settings
@exec() if @settings.autoExec == true
###
Executa a requisicao javascript
###
exec: ->
@debug "Exec Ajax"
@libSupport.ajax
contentType: @settings.contentType
async : @settings.async
url : @settings.url
type : @settings.method
data : @get_data()
beforeSend : @settings.callbacks.beforeSend
complete : (jqXHR, textStatus)=>
@settings.callbacks.complete jqXHR, textStatus
@destroy()
error : (jqXHR, textStatus, errorThrown)=>
@debug "Error: ", jqXHR, textStatus, errorThrown
@testResponseUnauthorized jqXHR
@testResponseForbidden jqXHR
@settings.callbacks.error(jqXHR, textStatus, errorThrown)
success : (data, textStatus, jqXHR)=>
@debug "Success: ", data, textStatus, jqXHR
@settings.callbacks.success(data, textStatus, jqXHR)
###
Converte a data em string params
@returns {String}
###
get_data: ->
return @libSupport.param(@settings.data) if Object.isObject @settings.data
@settings.data
testResponseForbidden: (jqXHR)->
if jqXHR.status == 403
new Joker.Alert
type: Joker.Alert.TYPE_ERROR
message: 'Você não tem permissão para executar esta requisição.'
testResponseUnauthorized: (jqXHR)->
if jqXHR.status == 401
console.log "asd"
window.location.reload()
@debugPrefix: "Joker_Ajax"
@className : "Joker_Ajax"
# rails application and using csrf-token
Joker.Core.libSupport ->
Joker.Core.libSupport(document).ajaxSend (e, xhr, options)->
token = Joker.Core.libSupport("meta[name='csrf-token']").attr "content"
xhr.setRequestHeader("X-CSRF-Token", token) | true | ###
@summary Joker
@description Framework of RIAs applications
@version 1.0.0
@file Ajax.js
@author PI:NAME:<NAME>END_PI (http://welington.zaez.net/)
@contact http://jokerjs.zaez.net/contato
@copyright Copyright 2013 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
###
###
###
class Joker.Ajax extends Joker.Core
settings:
###
Indicates whether the object should
be executed at the end of its creation
@type {Boolean}
###
autoExec: true
###
###
async: true
###
Indicates whether the object should use
a loader to stop, until the completion
of the request
@type {Boolean}
###
useLoader : true
###
Indicates the content type of the request
@type {String}
###
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
###
Indicates the url of the request
@type {String}
###
url : null
###
Indicates the method of the request
options : GET | POST | PUT | DELETE
@type {String}
###
method : 'GET'
###
Indicates the content of the request
@type {Object}
###
data : {}
###
Indicates the type of expected return
after the completion of request
@type {String}
###
dataType : 'json'
###
Callbacks run through the requisition
@see http://api.jquery.com/jQuery.ajax/
###
callbacks:
beforeSend: (jqXHR, settings)->
complete : (jqXHR, textStatus)->
error : (jqXHR, textStatus, errorThrown)->
success : (data, textStatus, jqXHR)->
constructor: (settings)->
super
@settings = @libSupport.extend true, {}, @settings, settings
@debug "Construindo o ajax com as configuracoes: ", @settings
@exec() if @settings.autoExec == true
###
Executa a requisicao javascript
###
exec: ->
@debug "Exec Ajax"
@libSupport.ajax
contentType: @settings.contentType
async : @settings.async
url : @settings.url
type : @settings.method
data : @get_data()
beforeSend : @settings.callbacks.beforeSend
complete : (jqXHR, textStatus)=>
@settings.callbacks.complete jqXHR, textStatus
@destroy()
error : (jqXHR, textStatus, errorThrown)=>
@debug "Error: ", jqXHR, textStatus, errorThrown
@testResponseUnauthorized jqXHR
@testResponseForbidden jqXHR
@settings.callbacks.error(jqXHR, textStatus, errorThrown)
success : (data, textStatus, jqXHR)=>
@debug "Success: ", data, textStatus, jqXHR
@settings.callbacks.success(data, textStatus, jqXHR)
###
Converte a data em string params
@returns {String}
###
get_data: ->
return @libSupport.param(@settings.data) if Object.isObject @settings.data
@settings.data
testResponseForbidden: (jqXHR)->
if jqXHR.status == 403
new Joker.Alert
type: Joker.Alert.TYPE_ERROR
message: 'Você não tem permissão para executar esta requisição.'
testResponseUnauthorized: (jqXHR)->
if jqXHR.status == 401
console.log "asd"
window.location.reload()
@debugPrefix: "Joker_Ajax"
@className : "Joker_Ajax"
# rails application and using csrf-token
Joker.Core.libSupport ->
Joker.Core.libSupport(document).ajaxSend (e, xhr, options)->
token = Joker.Core.libSupport("meta[name='csrf-token']").attr "content"
xhr.setRequestHeader("X-CSRF-Token", token) |
[
{
"context": "word', ->\n @view.$('[name=\"password\"]').val 'foobarbaz'\n @view.$('[name=\"password_confirmation\"]').",
"end": 996,
"score": 0.9994708895683289,
"start": 987,
"tag": "PASSWORD",
"value": "foobarbaz"
},
{
"context": " @view.$('[name=\"password_confirmatio... | src/desktop/apps/authentication/__tests__/reset_password.coffee | zephraph/force | 1 | benv = require 'benv'
sinon = require 'sinon'
Backbone = require 'backbone'
{ resolve } = require 'path'
{ PasswordResetView } = require '../client/reset_password'
describe 'PasswordResetView', ->
before (done) ->
benv.setup =>
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
Backbone.$ = $
done()
after ->
benv.teardown()
beforeEach (done) ->
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../templates/reset_password.jade'), { asset: (->), sd: {}, reset_password_token: 'secret' }, =>
@view = new PasswordResetView el: $('#reset-password-page')
done()
afterEach ->
Backbone.sync.restore()
describe '#initialize', ->
it 'creates a new model that saves to the reset password endpoint', ->
@view.model.url.should.containEql '/api/v1/users/reset_password'
describe '#submit', ->
it 'serializes the form and resets the password', ->
@view.$('[name="password"]').val 'foobarbaz'
@view.$('[name="password_confirmation"]').val 'foobarbaz'
@view.$('button').click()
Backbone.sync.args[0][0].should.equal 'update'
Backbone.sync.args[0][1].attributes.should.eql
reset_password_token: 'secret'
password: 'foobarbaz'
password_confirmation: 'foobarbaz'
| 63219 | benv = require 'benv'
sinon = require 'sinon'
Backbone = require 'backbone'
{ resolve } = require 'path'
{ PasswordResetView } = require '../client/reset_password'
describe 'PasswordResetView', ->
before (done) ->
benv.setup =>
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
Backbone.$ = $
done()
after ->
benv.teardown()
beforeEach (done) ->
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../templates/reset_password.jade'), { asset: (->), sd: {}, reset_password_token: 'secret' }, =>
@view = new PasswordResetView el: $('#reset-password-page')
done()
afterEach ->
Backbone.sync.restore()
describe '#initialize', ->
it 'creates a new model that saves to the reset password endpoint', ->
@view.model.url.should.containEql '/api/v1/users/reset_password'
describe '#submit', ->
it 'serializes the form and resets the password', ->
@view.$('[name="password"]').val '<PASSWORD>'
@view.$('[name="password_confirmation"]').val '<PASSWORD>'
@view.$('button').click()
Backbone.sync.args[0][0].should.equal 'update'
Backbone.sync.args[0][1].attributes.should.eql
reset_password_token: '<PASSWORD>'
password: '<PASSWORD>'
password_confirmation: '<PASSWORD>'
| true | benv = require 'benv'
sinon = require 'sinon'
Backbone = require 'backbone'
{ resolve } = require 'path'
{ PasswordResetView } = require '../client/reset_password'
describe 'PasswordResetView', ->
before (done) ->
benv.setup =>
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
Backbone.$ = $
done()
after ->
benv.teardown()
beforeEach (done) ->
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../templates/reset_password.jade'), { asset: (->), sd: {}, reset_password_token: 'secret' }, =>
@view = new PasswordResetView el: $('#reset-password-page')
done()
afterEach ->
Backbone.sync.restore()
describe '#initialize', ->
it 'creates a new model that saves to the reset password endpoint', ->
@view.model.url.should.containEql '/api/v1/users/reset_password'
describe '#submit', ->
it 'serializes the form and resets the password', ->
@view.$('[name="password"]').val 'PI:PASSWORD:<PASSWORD>END_PI'
@view.$('[name="password_confirmation"]').val 'PI:PASSWORD:<PASSWORD>END_PI'
@view.$('button').click()
Backbone.sync.args[0][0].should.equal 'update'
Backbone.sync.args[0][1].attributes.should.eql
reset_password_token: 'PI:PASSWORD:<PASSWORD>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
password_confirmation: 'PI:PASSWORD:<PASSWORD>END_PI'
|
[
{
"context": "asswords did not match'\ninvalidCurrentPassword = 'Old password did not match our records!'\nmin8Character = 'Passwords should be at least 8 ",
"end": 688,
"score": 0.9979425072669983,
"start": 650,
"tag": "PASSWORD",
"value": "Old password did not match our records"
},
{
... | client/test/lib/helpers/myaccounthelpers.coffee | lionheart1022/koding | 0 | utils = require '../utils/utils.js'
helpers = require '../helpers/helpers.js'
teamsHelpers = require '../helpers/teamshelpers.js'
myAccountLink = "#{helpers.getUrl(yes)}/Home/my-account"
nameSelector = 'input[name=firstName]'
lastnameSelector = 'input[name=lastName]'
emailSelector = 'input[name=email]'
saveButtonSelector = 'button[type=submit]'
pinSelector = 'input[name=pin]'
passwordSelector = '.kdview.kdtabpaneview.verifypasswordform div.kdview.formline.password div.input-wrapper input.kdinput.text'
notificationText = 'Password successfully changed!'
notMatchingPasswords = 'Passwords did not match'
invalidCurrentPassword = 'Old password did not match our records!'
min8Character = 'Passwords should be at least 8 characters!'
paragraph = helpers.getFakeText()
notificationSelector = '.kdnotification-title'
confirmEmailButton = '.kdbutton.GenericButton:nth-of-type(2)'
modalSelector = '.kdmodal-content'
updateEmailButton = '.ContentModal.kdmodal.with-form .kdtabpaneview .formline.button-field .kdbutton'
user = utils.getUser()
module.exports =
updateFirstName: (browser, callback) ->
newName = paragraph.split(' ')[0]
browser
.url myAccountLink
.pause 2000
.waitForElementVisible nameSelector, 20000
.clearValue nameSelector
.setValue nameSelector, newName + '\n'
.click saveButtonSelector
.waitForElementVisible '.kdnotification.main', 20000
.refresh()
.pause 3000
.waitForElementVisible nameSelector, 20000
.assert.value nameSelector, newName
.pause 1000, callback
updateLastName: (browser, callback) ->
newLastName = paragraph.split(' ')[1]
browser
.waitForElementVisible lastnameSelector, 20000
.clearValue lastnameSelector
.setValue lastnameSelector, newLastName + '\n'
.click saveButtonSelector
.waitForElementVisible '.kdnotification.main', 20000
.refresh()
.pause 2000
.waitForElementVisible lastnameSelector, 20000
.assert.value lastnameSelector, newLastName
.pause 1000, callback
updateEmailWithInvalidPassword: (browser, callback) ->
newEmail = 'wrongemail@koding.com'
browser
.refresh()
.waitForElementVisible emailSelector, 30000
.clearValue emailSelector
.setValue emailSelector, newEmail + '\n'
.click saveButtonSelector
.waitForElementVisible modalSelector, 20000
.assert.containsText '.ContentModal.content-modal header > h1', 'Please verify your current password'
.setValue passwordSelector, '123456'
.click confirmEmailButton
.waitForElementVisible notificationSelector, 20000
.assert.containsText notificationSelector, 'Current password cannot be confirmed'
.pause 1000, callback
updateEmailWithInvalidPin: (browser, callback) ->
newEmail = 'wrongemail2@koding.com'
browser
.refresh()
.waitForElementVisible emailSelector, 30000
.clearValue emailSelector
.setValue emailSelector, newEmail + '\n'
.click saveButtonSelector
.pause 2000
.waitForElementVisible modalSelector, 20000
.waitForElementVisible passwordSelector, 30000
.setValue passwordSelector, user.password
.click confirmEmailButton
.waitForElementVisible modalSelector, 20000
.waitForElementVisible pinSelector, 2000
.setValue pinSelector, '1234'
.click updateEmailButton
.waitForElementVisible notificationSelector, 20000
.assert.containsText notificationSelector, 'PIN is not confirmed.'
.pause 1, callback
updatePassword: (browser, callback) ->
currentPassword = user.password
newPassword = utils.getPassword()
browser
.refresh()
.waitForElementVisible emailSelector, 30000
.scrollToElement '.HomeAppView--section.password'
helpers.changePasswordHelper browser, newPassword, newPassword + 'test', null, notMatchingPasswords
helpers.changePasswordHelper browser, newPassword, newPassword, 'invalidpassword', invalidCurrentPassword
helpers.changePasswordHelper browser, '1234', '1234', user.password, min8Character
helpers.changePasswordHelper browser, newPassword, newPassword, user.password, notificationText
browser
.pause 3000
.scrollToElement '.HomeAppView--section.profile'
.scrollToElement '.HomeAppView--section.password'
.scrollToElement '.HomeAppView--section.security'
.waitForElementVisible '.HomeAppView--section.sessions', 20000, callback
| 188398 | utils = require '../utils/utils.js'
helpers = require '../helpers/helpers.js'
teamsHelpers = require '../helpers/teamshelpers.js'
myAccountLink = "#{helpers.getUrl(yes)}/Home/my-account"
nameSelector = 'input[name=firstName]'
lastnameSelector = 'input[name=lastName]'
emailSelector = 'input[name=email]'
saveButtonSelector = 'button[type=submit]'
pinSelector = 'input[name=pin]'
passwordSelector = '.kdview.kdtabpaneview.verifypasswordform div.kdview.formline.password div.input-wrapper input.kdinput.text'
notificationText = 'Password successfully changed!'
notMatchingPasswords = 'Passwords did not match'
invalidCurrentPassword = '<PASSWORD>!'
min8Character = 'Passwords should be at least 8 characters!'
paragraph = helpers.getFakeText()
notificationSelector = '.kdnotification-title'
confirmEmailButton = '.kdbutton.GenericButton:nth-of-type(2)'
modalSelector = '.kdmodal-content'
updateEmailButton = '.ContentModal.kdmodal.with-form .kdtabpaneview .formline.button-field .kdbutton'
user = utils.getUser()
module.exports =
updateFirstName: (browser, callback) ->
newName = paragraph.split(' ')[0]
browser
.url myAccountLink
.pause 2000
.waitForElementVisible nameSelector, 20000
.clearValue nameSelector
.setValue nameSelector, newName + '\n'
.click saveButtonSelector
.waitForElementVisible '.kdnotification.main', 20000
.refresh()
.pause 3000
.waitForElementVisible nameSelector, 20000
.assert.value nameSelector, newName
.pause 1000, callback
updateLastName: (browser, callback) ->
newLastName = paragraph.split(' ')[1]
browser
.waitForElementVisible lastnameSelector, 20000
.clearValue lastnameSelector
.setValue lastnameSelector, newLastName + '\n'
.click saveButtonSelector
.waitForElementVisible '.kdnotification.main', 20000
.refresh()
.pause 2000
.waitForElementVisible lastnameSelector, 20000
.assert.value lastnameSelector, newLastName
.pause 1000, callback
updateEmailWithInvalidPassword: (browser, callback) ->
newEmail = '<EMAIL>'
browser
.refresh()
.waitForElementVisible emailSelector, 30000
.clearValue emailSelector
.setValue emailSelector, newEmail + '\n'
.click saveButtonSelector
.waitForElementVisible modalSelector, 20000
.assert.containsText '.ContentModal.content-modal header > h1', 'Please verify your current password'
.setValue passwordSelector, '<PASSWORD>'
.click confirmEmailButton
.waitForElementVisible notificationSelector, 20000
.assert.containsText notificationSelector, 'Current password cannot be confirmed'
.pause 1000, callback
updateEmailWithInvalidPin: (browser, callback) ->
newEmail = '<EMAIL>'
browser
.refresh()
.waitForElementVisible emailSelector, 30000
.clearValue emailSelector
.setValue emailSelector, newEmail + '\n'
.click saveButtonSelector
.pause 2000
.waitForElementVisible modalSelector, 20000
.waitForElementVisible passwordSelector, 30000
.setValue passwordSelector, <PASSWORD>
.click confirmEmailButton
.waitForElementVisible modalSelector, 20000
.waitForElementVisible pinSelector, 2000
.setValue pinSelector, '1234'
.click updateEmailButton
.waitForElementVisible notificationSelector, 20000
.assert.containsText notificationSelector, 'PIN is not confirmed.'
.pause 1, callback
updatePassword: (browser, callback) ->
currentPassword = <PASSWORD>
newPassword = utils.getPassword()
browser
.refresh()
.waitForElementVisible emailSelector, 30000
.scrollToElement '.HomeAppView--section.password'
helpers.changePasswordHelper browser, newPassword, newPassword + '<PASSWORD>', null, notMatchingPasswords
helpers.changePasswordHelper browser, newPassword, newPassword, '<PASSWORD>', invalidCurrentPassword
helpers.changePasswordHelper browser, '<PASSWORD>', '<PASSWORD>', user.password, <PASSWORD>Character
helpers.changePasswordHelper browser, newPassword, newPassword, user.password, notificationText
browser
.pause 3000
.scrollToElement '.HomeAppView--section.profile'
.scrollToElement '.HomeAppView--section.password'
.scrollToElement '.HomeAppView--section.security'
.waitForElementVisible '.HomeAppView--section.sessions', 20000, callback
| true | utils = require '../utils/utils.js'
helpers = require '../helpers/helpers.js'
teamsHelpers = require '../helpers/teamshelpers.js'
myAccountLink = "#{helpers.getUrl(yes)}/Home/my-account"
nameSelector = 'input[name=firstName]'
lastnameSelector = 'input[name=lastName]'
emailSelector = 'input[name=email]'
saveButtonSelector = 'button[type=submit]'
pinSelector = 'input[name=pin]'
passwordSelector = '.kdview.kdtabpaneview.verifypasswordform div.kdview.formline.password div.input-wrapper input.kdinput.text'
notificationText = 'Password successfully changed!'
notMatchingPasswords = 'Passwords did not match'
invalidCurrentPassword = 'PI:PASSWORD:<PASSWORD>END_PI!'
min8Character = 'Passwords should be at least 8 characters!'
paragraph = helpers.getFakeText()
notificationSelector = '.kdnotification-title'
confirmEmailButton = '.kdbutton.GenericButton:nth-of-type(2)'
modalSelector = '.kdmodal-content'
updateEmailButton = '.ContentModal.kdmodal.with-form .kdtabpaneview .formline.button-field .kdbutton'
user = utils.getUser()
module.exports =
updateFirstName: (browser, callback) ->
newName = paragraph.split(' ')[0]
browser
.url myAccountLink
.pause 2000
.waitForElementVisible nameSelector, 20000
.clearValue nameSelector
.setValue nameSelector, newName + '\n'
.click saveButtonSelector
.waitForElementVisible '.kdnotification.main', 20000
.refresh()
.pause 3000
.waitForElementVisible nameSelector, 20000
.assert.value nameSelector, newName
.pause 1000, callback
updateLastName: (browser, callback) ->
newLastName = paragraph.split(' ')[1]
browser
.waitForElementVisible lastnameSelector, 20000
.clearValue lastnameSelector
.setValue lastnameSelector, newLastName + '\n'
.click saveButtonSelector
.waitForElementVisible '.kdnotification.main', 20000
.refresh()
.pause 2000
.waitForElementVisible lastnameSelector, 20000
.assert.value lastnameSelector, newLastName
.pause 1000, callback
updateEmailWithInvalidPassword: (browser, callback) ->
newEmail = 'PI:EMAIL:<EMAIL>END_PI'
browser
.refresh()
.waitForElementVisible emailSelector, 30000
.clearValue emailSelector
.setValue emailSelector, newEmail + '\n'
.click saveButtonSelector
.waitForElementVisible modalSelector, 20000
.assert.containsText '.ContentModal.content-modal header > h1', 'Please verify your current password'
.setValue passwordSelector, 'PI:PASSWORD:<PASSWORD>END_PI'
.click confirmEmailButton
.waitForElementVisible notificationSelector, 20000
.assert.containsText notificationSelector, 'Current password cannot be confirmed'
.pause 1000, callback
updateEmailWithInvalidPin: (browser, callback) ->
newEmail = 'PI:EMAIL:<EMAIL>END_PI'
browser
.refresh()
.waitForElementVisible emailSelector, 30000
.clearValue emailSelector
.setValue emailSelector, newEmail + '\n'
.click saveButtonSelector
.pause 2000
.waitForElementVisible modalSelector, 20000
.waitForElementVisible passwordSelector, 30000
.setValue passwordSelector, PI:PASSWORD:<PASSWORD>END_PI
.click confirmEmailButton
.waitForElementVisible modalSelector, 20000
.waitForElementVisible pinSelector, 2000
.setValue pinSelector, '1234'
.click updateEmailButton
.waitForElementVisible notificationSelector, 20000
.assert.containsText notificationSelector, 'PIN is not confirmed.'
.pause 1, callback
updatePassword: (browser, callback) ->
currentPassword = PI:PASSWORD:<PASSWORD>END_PI
newPassword = utils.getPassword()
browser
.refresh()
.waitForElementVisible emailSelector, 30000
.scrollToElement '.HomeAppView--section.password'
helpers.changePasswordHelper browser, newPassword, newPassword + 'PI:PASSWORD:<PASSWORD>END_PI', null, notMatchingPasswords
helpers.changePasswordHelper browser, newPassword, newPassword, 'PI:PASSWORD:<PASSWORD>END_PI', invalidCurrentPassword
helpers.changePasswordHelper browser, 'PI:PASSWORD:<PASSWORD>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI', user.password, PI:PASSWORD:<PASSWORD>END_PICharacter
helpers.changePasswordHelper browser, newPassword, newPassword, user.password, notificationText
browser
.pause 3000
.scrollToElement '.HomeAppView--section.profile'
.scrollToElement '.HomeAppView--section.password'
.scrollToElement '.HomeAppView--section.security'
.waitForElementVisible '.HomeAppView--section.sessions', 20000, callback
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999103546142578,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/modding-profile/posts.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 { div, h2, a, img, span } from 'react-dom-factories'
import { ValueDisplay } from 'value-display'
import { Post } from "../beatmap-discussions/post"
el = React.createElement
export class Posts extends React.Component
render: =>
div className: 'page-extra',
h2 className: 'title title--page-extra', osu.trans('users.show.extra.posts.title_longer')
div className: 'modding-profile-list',
if @props.posts.length == 0
div className: 'modding-profile-list__empty', osu.trans('users.show.extra.none')
else
[
for post in @props.posts
canModeratePosts = BeatmapDiscussionHelper.canModeratePosts(currentUser)
canBeDeleted = canModeratePosts || currentUser.id? == post.user_id
discussionClasses = 'beatmap-discussion beatmap-discussion--preview'
if post.deleted_at?
discussionClasses += ' beatmap-discussion--deleted'
div
key: post.id
className: 'modding-profile-list__row',
a
className: 'modding-profile-list__thumbnail'
href: BeatmapDiscussionHelper.url(discussion: post.beatmap_discussion),
img className: 'beatmapset-activities__beatmapset-cover', src: post.beatmap_discussion.beatmapset.covers.list
div className: "modding-profile-list__timestamp hidden-xs",
div className: "beatmap-discussion-timestamp",
div className: "beatmap-discussion-timestamp__icons-container",
span className: "fas fa-reply"
div className: discussionClasses,
div className: "beatmap-discussion__discussion",
el Post,
key: post.id
beatmapset: post.beatmap_discussion.beatmapset
discussion: post.beatmap_discussion
post: post
type: 'reply'
users: @props.users
user: @props.users[post.user_id]
read: true
lastEditor: @props.users[post.last_editor_id]
canBeEdited: currentUser.is_admin || currentUser.id? == post.user_id
canBeDeleted: canBeDeleted
canBeRestored: canModeratePosts
currentUser: currentUser
a
key: 'show-more'
className: 'modding-profile-list__show-more'
href: laroute.route('users.modding.posts', {user: @props.user.id}),
osu.trans('users.show.extra.posts.show_more')
]
| 27983 | # 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 { div, h2, a, img, span } from 'react-dom-factories'
import { ValueDisplay } from 'value-display'
import { Post } from "../beatmap-discussions/post"
el = React.createElement
export class Posts extends React.Component
render: =>
div className: 'page-extra',
h2 className: 'title title--page-extra', osu.trans('users.show.extra.posts.title_longer')
div className: 'modding-profile-list',
if @props.posts.length == 0
div className: 'modding-profile-list__empty', osu.trans('users.show.extra.none')
else
[
for post in @props.posts
canModeratePosts = BeatmapDiscussionHelper.canModeratePosts(currentUser)
canBeDeleted = canModeratePosts || currentUser.id? == post.user_id
discussionClasses = 'beatmap-discussion beatmap-discussion--preview'
if post.deleted_at?
discussionClasses += ' beatmap-discussion--deleted'
div
key: post.id
className: 'modding-profile-list__row',
a
className: 'modding-profile-list__thumbnail'
href: BeatmapDiscussionHelper.url(discussion: post.beatmap_discussion),
img className: 'beatmapset-activities__beatmapset-cover', src: post.beatmap_discussion.beatmapset.covers.list
div className: "modding-profile-list__timestamp hidden-xs",
div className: "beatmap-discussion-timestamp",
div className: "beatmap-discussion-timestamp__icons-container",
span className: "fas fa-reply"
div className: discussionClasses,
div className: "beatmap-discussion__discussion",
el Post,
key: post.id
beatmapset: post.beatmap_discussion.beatmapset
discussion: post.beatmap_discussion
post: post
type: 'reply'
users: @props.users
user: @props.users[post.user_id]
read: true
lastEditor: @props.users[post.last_editor_id]
canBeEdited: currentUser.is_admin || currentUser.id? == post.user_id
canBeDeleted: canBeDeleted
canBeRestored: canModeratePosts
currentUser: currentUser
a
key: 'show-more'
className: 'modding-profile-list__show-more'
href: laroute.route('users.modding.posts', {user: @props.user.id}),
osu.trans('users.show.extra.posts.show_more')
]
| 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 { div, h2, a, img, span } from 'react-dom-factories'
import { ValueDisplay } from 'value-display'
import { Post } from "../beatmap-discussions/post"
el = React.createElement
export class Posts extends React.Component
render: =>
div className: 'page-extra',
h2 className: 'title title--page-extra', osu.trans('users.show.extra.posts.title_longer')
div className: 'modding-profile-list',
if @props.posts.length == 0
div className: 'modding-profile-list__empty', osu.trans('users.show.extra.none')
else
[
for post in @props.posts
canModeratePosts = BeatmapDiscussionHelper.canModeratePosts(currentUser)
canBeDeleted = canModeratePosts || currentUser.id? == post.user_id
discussionClasses = 'beatmap-discussion beatmap-discussion--preview'
if post.deleted_at?
discussionClasses += ' beatmap-discussion--deleted'
div
key: post.id
className: 'modding-profile-list__row',
a
className: 'modding-profile-list__thumbnail'
href: BeatmapDiscussionHelper.url(discussion: post.beatmap_discussion),
img className: 'beatmapset-activities__beatmapset-cover', src: post.beatmap_discussion.beatmapset.covers.list
div className: "modding-profile-list__timestamp hidden-xs",
div className: "beatmap-discussion-timestamp",
div className: "beatmap-discussion-timestamp__icons-container",
span className: "fas fa-reply"
div className: discussionClasses,
div className: "beatmap-discussion__discussion",
el Post,
key: post.id
beatmapset: post.beatmap_discussion.beatmapset
discussion: post.beatmap_discussion
post: post
type: 'reply'
users: @props.users
user: @props.users[post.user_id]
read: true
lastEditor: @props.users[post.last_editor_id]
canBeEdited: currentUser.is_admin || currentUser.id? == post.user_id
canBeDeleted: canBeDeleted
canBeRestored: canModeratePosts
currentUser: currentUser
a
key: 'show-more'
className: 'modding-profile-list__show-more'
href: laroute.route('users.modding.posts', {user: @props.user.id}),
osu.trans('users.show.extra.posts.show_more')
]
|
[
{
"context": "equest.async = async isnt false\n request.user = user\n request.pass = pass\n # openned facade xhr ",
"end": 10040,
"score": 0.963742196559906,
"start": 10036,
"tag": "USERNAME",
"value": "user"
},
{
"context": "t false\n request.user = user\n request.pas... | src/xhook.coffee | mnaoumov/xhook | 0 | #for compression
document = window.document
BEFORE = 'before'
AFTER = 'after'
READY_STATE = 'readyState'
ON = 'addEventListener'
OFF = 'removeEventListener'
FIRE = 'dispatchEvent'
XMLHTTP = 'XMLHttpRequest'
FormData = 'FormData'
UPLOAD_EVENTS = ['load', 'loadend', 'loadstart']
COMMON_EVENTS = ['progress', 'abort', 'error', 'timeout']
#parse IE version
msie = parseInt((/msie (\d+)/.exec((navigator.userAgent).toLowerCase()) or [])[1])
msie = parseInt((/trident\/.*; rv:(\d+)/.exec((navigator.userAgent).toLowerCase()) or [])[1]) if isNaN(msie)
#if required, add 'indexOf' method to Array
Array::indexOf or= (item) ->
for x, i in this
return i if x is item
return -1
slice = (o,n) -> Array::slice.call o,n
depricatedProp = (p) ->
return p in ["returnValue","totalSize","position"]
mergeObjects = (src, dst) ->
for k,v of src
continue if depricatedProp k
try dst[k] = src[k]
return dst
#proxy events from one emitter to another
proxyEvents = (events, src, dst) ->
p = (event) -> (e) ->
clone = {}
#copies event, with dst emitter inplace of src
for k of e
continue if depricatedProp k
val = e[k]
clone[k] = if val is src then dst else val
#emits out the dst
dst[FIRE] event, clone
#dont proxy manual events
for event in events
if dst._has event
src["on#{event}"] = p(event)
return
#create fake event
fakeEvent = (type) ->
if document.createEventObject?
msieEventObject = document.createEventObject()
msieEventObject.type = type
msieEventObject
else
# on some platforms like android 4.1.2 and safari on windows, it appears
# that new Event is not allowed
try new Event(type)
catch then {type}
#tiny event emitter
EventEmitter = (nodeStyle) ->
#private
events = {}
listeners = (event) ->
events[event] or []
#public
emitter = {}
emitter[ON] = (event, callback, i) ->
events[event] = listeners event
return if events[event].indexOf(callback) >= 0
i = if i is `undefined` then events[event].length else i
events[event].splice i, 0, callback
return
emitter[OFF] = (event, callback) ->
#remove all
if event is `undefined`
events = {}
return
#remove all of type event
if callback is `undefined`
events[event] = []
#remove particular handler
i = listeners(event).indexOf callback
return if i is -1
listeners(event).splice i, 1
return
emitter[FIRE] = ->
args = slice arguments
event = args.shift()
unless nodeStyle
args[0] = mergeObjects args[0], fakeEvent event
legacylistener = emitter["on#{event}"]
if legacylistener
legacylistener.apply emitter, args
for listener, i in listeners(event).concat(listeners("*"))
listener.apply emitter, args
return
emitter._has = (event) ->
return !!(events[event] or emitter["on#{event}"])
#add extra aliases
if nodeStyle
emitter.listeners = (event) ->
slice listeners event
emitter.on = emitter[ON]
emitter.off = emitter[OFF]
emitter.fire = emitter[FIRE]
emitter.once = (e, fn) ->
fire = ->
emitter.off e, fire
fn.apply null, arguments
emitter.on e, fire
emitter.destroy = ->
events = {}
emitter
#use event emitter to store hooks
xhook = EventEmitter(true)
xhook.EventEmitter = EventEmitter
xhook[BEFORE] = (handler, i) ->
if handler.length < 1 or handler.length > 2
throw "invalid hook"
xhook[ON] BEFORE, handler, i
xhook[AFTER] = (handler, i) ->
if handler.length < 2 or handler.length > 3
throw "invalid hook"
xhook[ON] AFTER, handler, i
xhook.enable = ->
window[XMLHTTP] = XHookHttpRequest
window[FormData] = XHookFormData if NativeFormData
return
xhook.disable = ->
window[XMLHTTP] = xhook[XMLHTTP]
window[FormData] = NativeFormData if NativeFormData
return
#helper
convertHeaders = xhook.headers = (h, dest = {}) ->
switch typeof h
when "object"
headers = []
for k,v of h
name = k.toLowerCase()
headers.push "#{name}:\t#{v}"
return headers.join '\n'
when "string"
headers = h.split '\n'
for header in headers
if /([^:]+):\s*(.+)/.test(header)
name = RegExp.$1?.toLowerCase()
value = RegExp.$2
dest[name] ?= value
return dest
return
#patch FormData
# we can do this safely because all XHR
# is hooked, so we can ensure the real FormData
# object is used on send
NativeFormData = window[FormData]
XHookFormData = (form) ->
@fd = if form then new NativeFormData(form) else new NativeFormData()
@form = form
entries = []
Object.defineProperty @, 'entries', get: ->
#extract form entries
fentries = unless form then [] else
slice(form.querySelectorAll("input,select")).filter((e) ->
return e.type not in ['checkbox','radio'] or e.checked
).map((e) ->
[e.name, if e.type is "file" then e.files else e.value]
)
#combine with js entries
return fentries.concat entries
@append = =>
args = slice arguments
entries.push args
@fd.append.apply @fd, args
return
if NativeFormData
#expose native formdata as xhook.FormData incase its needed
xhook[FormData] = NativeFormData
window[FormData] = XHookFormData
#patch XHR
NativeXMLHttp = window[XMLHTTP]
xhook[XMLHTTP] = NativeXMLHttp
XHookHttpRequest = window[XMLHTTP] = ->
ABORTED = -1
xhr = new xhook[XMLHTTP]()
#==========================
# Extra state
request = {}
status = null
hasError = undefined
transiting = undefined
response = undefined
#==========================
# Private API
#read results from real xhr into response
readHead = ->
# Accessing attributes on an aborted xhr object will
# throw an 'c00c023f error' in IE9 and lower, don't touch it.
response.status = status or xhr.status
response.statusText = xhr.statusText unless status is ABORTED and msie < 10
if status isnt ABORTED
for key, val of convertHeaders xhr.getAllResponseHeaders()
unless response.headers[key]
name = key.toLowerCase()
response.headers[name] = val
return
readBody = ->
#https://xhr.spec.whatwg.org/
if !xhr.responseType or xhr.responseType is "text"
response.text = xhr.responseText
response.data = xhr.responseText
else if xhr.responseType is "document"
response.xml = xhr.responseXML
response.data = xhr.responseXML
else
response.data = xhr.response
#new in some browsers
if "responseURL" of xhr
response.finalUrl = xhr.responseURL
return
#write response into facade xhr
writeHead = ->
facade.status = response.status
facade.statusText = response.statusText
return
writeBody = ->
if 'text' of response
facade.responseText = response.text
if 'xml' of response
facade.responseXML = response.xml
if 'data' of response
facade.response = response.data
if 'finalUrl' of response
facade.responseURL = response.finalUrl
return
#ensure ready state 0 through 4 is handled
emitReadyState = (n) ->
while n > currentState and currentState < 4
facade[READY_STATE] = ++currentState
# make fake events for libraries that actually check the type on
# the event object
if currentState is 1
facade[FIRE] "loadstart", {}
if currentState is 2
writeHead()
if currentState is 4
writeHead()
writeBody()
facade[FIRE] "readystatechange", {}
#delay final events incase of error
if currentState is 4
setTimeout emitFinal, 0
return
emitFinal = ->
unless hasError
facade[FIRE] "load", {}
facade[FIRE] "loadend", {}
if hasError
facade[READY_STATE] = 0
return
#control facade ready state
currentState = 0
setReadyState = (n) ->
#emit events until readyState reaches 4
if n isnt 4
emitReadyState(n)
return
#before emitting 4, run all 'after' hooks in sequence
hooks = xhook.listeners AFTER
process = ->
unless hooks.length
return emitReadyState(4)
hook = hooks.shift()
if hook.length is 2
hook request, response
process()
else if hook.length is 3 and request.async
hook request, response, process
else
process()
process()
return
#==========================
# Facade XHR
facade = request.xhr = EventEmitter()
#==========================
# Handle the underlying ready state
xhr.onreadystatechange = (event) ->
#pull status and headers
try
if xhr[READY_STATE] is 2
readHead()
#pull response data
if xhr[READY_STATE] is 4
transiting = false
readHead()
readBody()
setReadyState xhr[READY_STATE]
return
#mark this xhr as errored
hasErrorHandler = ->
hasError = true
return
facade[ON] 'error', hasErrorHandler
facade[ON] 'timeout', hasErrorHandler
facade[ON] 'abort', hasErrorHandler
# progress means we're current downloading...
facade[ON] 'progress', ->
#progress events are followed by readystatechange for some reason...
if currentState < 3
setReadyState 3
else
facade[FIRE] "readystatechange", {} #TODO fake an XHR event
return
# initialise 'withCredentials' on facade xhr in browsers with it
# or if explicitly told to do so
if 'withCredentials' of xhr or xhook.addWithCredentials
facade.withCredentials = false
facade.status = 0
# initialise all possible event handlers
for event in COMMON_EVENTS.concat(UPLOAD_EVENTS)
facade["on#{event}"] = null
facade.open = (method, url, async, user, pass) ->
# Initailize empty XHR facade
currentState = 0
hasError = false
transiting = false
request.headers = {}
request.headerNames = {}
request.status = 0
response = {}
response.headers = {}
request.method = method
request.url = url
request.async = async isnt false
request.user = user
request.pass = pass
# openned facade xhr (not real xhr)
setReadyState 1
return
facade.send = (body) ->
#read xhr settings before hooking
for k in ['type', 'timeout', 'withCredentials']
modk = if k is "type" then "responseType" else k
request[k] = facade[modk] if modk of facade
request.body = body
send = ->
#proxy all events from real xhr to facade
proxyEvents COMMON_EVENTS, xhr, facade
proxyEvents COMMON_EVENTS.concat(UPLOAD_EVENTS), xhr.upload, facade.upload if facade.upload
#prepare request all at once
transiting = true
#perform open
xhr.open request.method, request.url, request.async, request.user, request.pass
#write xhr settings
for k in ['type', 'timeout', 'withCredentials']
modk = if k is "type" then "responseType" else k
xhr[modk] = request[k] if k of request
#insert headers
for header, value of request.headers
if header
xhr.setRequestHeader header, value
#extract real formdata
if request.body instanceof XHookFormData
request.body = request.body.fd
#real send!
xhr.send request.body
return
hooks = xhook.listeners BEFORE
#process hooks sequentially
process = ->
unless hooks.length
return send()
#go to next hook OR optionally provide response
done = (userResponse) ->
#break chain - provide dummy response (readyState 4)
if typeof userResponse is 'object' and
(typeof userResponse.status is 'number' or
typeof response.status is 'number')
mergeObjects userResponse, response
unless 'data' in userResponse
userResponse.data = userResponse.response or userResponse.text
setReadyState 4
return
#continue processing until no hooks left
process()
return
#specifically provide headers (readyState 2)
done.head = (userResponse) ->
mergeObjects userResponse, response
setReadyState 2
#specifically provide partial text (responseText readyState 3)
done.progress = (userResponse) ->
mergeObjects userResponse, response
setReadyState 3
hook = hooks.shift()
#async or sync?
if hook.length is 1
done hook request
else if hook.length is 2 and request.async
#async handlers must use an async xhr
hook request, done
else
#skip async hook on sync requests
done()
#kick off
process()
return
facade.abort = ->
status = ABORTED;
if transiting
xhr.abort() #this will emit an 'abort' for us
else
facade[FIRE] 'abort', {}
return
facade.setRequestHeader = (header, value) ->
#the first header set is used for all future case-alternatives of 'name'
lName = header?.toLowerCase()
name = request.headerNames[lName] = request.headerNames[lName] || header
#append header to any previous values
if request.headers[name]
value = request.headers[name] + ', ' + value
request.headers[name] = value
return
facade.getResponseHeader = (header) ->
name = header?.toLowerCase()
response.headers[name]
facade.getAllResponseHeaders = ->
convertHeaders response.headers
#proxy call only when supported
if xhr.overrideMimeType
facade.overrideMimeType = ->
xhr.overrideMimeType.apply xhr, arguments
#create emitter when supported
if xhr.upload
facade.upload = request.upload = EventEmitter()
return facade
#publicise (amd+commonjs+window)
if typeof define is "function" and define.amd
define "xhook", [], -> xhook
else
(@exports or @).xhook = xhook
| 189205 | #for compression
document = window.document
BEFORE = 'before'
AFTER = 'after'
READY_STATE = 'readyState'
ON = 'addEventListener'
OFF = 'removeEventListener'
FIRE = 'dispatchEvent'
XMLHTTP = 'XMLHttpRequest'
FormData = 'FormData'
UPLOAD_EVENTS = ['load', 'loadend', 'loadstart']
COMMON_EVENTS = ['progress', 'abort', 'error', 'timeout']
#parse IE version
msie = parseInt((/msie (\d+)/.exec((navigator.userAgent).toLowerCase()) or [])[1])
msie = parseInt((/trident\/.*; rv:(\d+)/.exec((navigator.userAgent).toLowerCase()) or [])[1]) if isNaN(msie)
#if required, add 'indexOf' method to Array
Array::indexOf or= (item) ->
for x, i in this
return i if x is item
return -1
slice = (o,n) -> Array::slice.call o,n
depricatedProp = (p) ->
return p in ["returnValue","totalSize","position"]
mergeObjects = (src, dst) ->
for k,v of src
continue if depricatedProp k
try dst[k] = src[k]
return dst
#proxy events from one emitter to another
proxyEvents = (events, src, dst) ->
p = (event) -> (e) ->
clone = {}
#copies event, with dst emitter inplace of src
for k of e
continue if depricatedProp k
val = e[k]
clone[k] = if val is src then dst else val
#emits out the dst
dst[FIRE] event, clone
#dont proxy manual events
for event in events
if dst._has event
src["on#{event}"] = p(event)
return
#create fake event
fakeEvent = (type) ->
if document.createEventObject?
msieEventObject = document.createEventObject()
msieEventObject.type = type
msieEventObject
else
# on some platforms like android 4.1.2 and safari on windows, it appears
# that new Event is not allowed
try new Event(type)
catch then {type}
#tiny event emitter
EventEmitter = (nodeStyle) ->
#private
events = {}
listeners = (event) ->
events[event] or []
#public
emitter = {}
emitter[ON] = (event, callback, i) ->
events[event] = listeners event
return if events[event].indexOf(callback) >= 0
i = if i is `undefined` then events[event].length else i
events[event].splice i, 0, callback
return
emitter[OFF] = (event, callback) ->
#remove all
if event is `undefined`
events = {}
return
#remove all of type event
if callback is `undefined`
events[event] = []
#remove particular handler
i = listeners(event).indexOf callback
return if i is -1
listeners(event).splice i, 1
return
emitter[FIRE] = ->
args = slice arguments
event = args.shift()
unless nodeStyle
args[0] = mergeObjects args[0], fakeEvent event
legacylistener = emitter["on#{event}"]
if legacylistener
legacylistener.apply emitter, args
for listener, i in listeners(event).concat(listeners("*"))
listener.apply emitter, args
return
emitter._has = (event) ->
return !!(events[event] or emitter["on#{event}"])
#add extra aliases
if nodeStyle
emitter.listeners = (event) ->
slice listeners event
emitter.on = emitter[ON]
emitter.off = emitter[OFF]
emitter.fire = emitter[FIRE]
emitter.once = (e, fn) ->
fire = ->
emitter.off e, fire
fn.apply null, arguments
emitter.on e, fire
emitter.destroy = ->
events = {}
emitter
#use event emitter to store hooks
xhook = EventEmitter(true)
xhook.EventEmitter = EventEmitter
xhook[BEFORE] = (handler, i) ->
if handler.length < 1 or handler.length > 2
throw "invalid hook"
xhook[ON] BEFORE, handler, i
xhook[AFTER] = (handler, i) ->
if handler.length < 2 or handler.length > 3
throw "invalid hook"
xhook[ON] AFTER, handler, i
xhook.enable = ->
window[XMLHTTP] = XHookHttpRequest
window[FormData] = XHookFormData if NativeFormData
return
xhook.disable = ->
window[XMLHTTP] = xhook[XMLHTTP]
window[FormData] = NativeFormData if NativeFormData
return
#helper
convertHeaders = xhook.headers = (h, dest = {}) ->
switch typeof h
when "object"
headers = []
for k,v of h
name = k.toLowerCase()
headers.push "#{name}:\t#{v}"
return headers.join '\n'
when "string"
headers = h.split '\n'
for header in headers
if /([^:]+):\s*(.+)/.test(header)
name = RegExp.$1?.toLowerCase()
value = RegExp.$2
dest[name] ?= value
return dest
return
#patch FormData
# we can do this safely because all XHR
# is hooked, so we can ensure the real FormData
# object is used on send
NativeFormData = window[FormData]
XHookFormData = (form) ->
@fd = if form then new NativeFormData(form) else new NativeFormData()
@form = form
entries = []
Object.defineProperty @, 'entries', get: ->
#extract form entries
fentries = unless form then [] else
slice(form.querySelectorAll("input,select")).filter((e) ->
return e.type not in ['checkbox','radio'] or e.checked
).map((e) ->
[e.name, if e.type is "file" then e.files else e.value]
)
#combine with js entries
return fentries.concat entries
@append = =>
args = slice arguments
entries.push args
@fd.append.apply @fd, args
return
if NativeFormData
#expose native formdata as xhook.FormData incase its needed
xhook[FormData] = NativeFormData
window[FormData] = XHookFormData
#patch XHR
NativeXMLHttp = window[XMLHTTP]
xhook[XMLHTTP] = NativeXMLHttp
XHookHttpRequest = window[XMLHTTP] = ->
ABORTED = -1
xhr = new xhook[XMLHTTP]()
#==========================
# Extra state
request = {}
status = null
hasError = undefined
transiting = undefined
response = undefined
#==========================
# Private API
#read results from real xhr into response
readHead = ->
# Accessing attributes on an aborted xhr object will
# throw an 'c00c023f error' in IE9 and lower, don't touch it.
response.status = status or xhr.status
response.statusText = xhr.statusText unless status is ABORTED and msie < 10
if status isnt ABORTED
for key, val of convertHeaders xhr.getAllResponseHeaders()
unless response.headers[key]
name = key.toLowerCase()
response.headers[name] = val
return
readBody = ->
#https://xhr.spec.whatwg.org/
if !xhr.responseType or xhr.responseType is "text"
response.text = xhr.responseText
response.data = xhr.responseText
else if xhr.responseType is "document"
response.xml = xhr.responseXML
response.data = xhr.responseXML
else
response.data = xhr.response
#new in some browsers
if "responseURL" of xhr
response.finalUrl = xhr.responseURL
return
#write response into facade xhr
writeHead = ->
facade.status = response.status
facade.statusText = response.statusText
return
writeBody = ->
if 'text' of response
facade.responseText = response.text
if 'xml' of response
facade.responseXML = response.xml
if 'data' of response
facade.response = response.data
if 'finalUrl' of response
facade.responseURL = response.finalUrl
return
#ensure ready state 0 through 4 is handled
emitReadyState = (n) ->
while n > currentState and currentState < 4
facade[READY_STATE] = ++currentState
# make fake events for libraries that actually check the type on
# the event object
if currentState is 1
facade[FIRE] "loadstart", {}
if currentState is 2
writeHead()
if currentState is 4
writeHead()
writeBody()
facade[FIRE] "readystatechange", {}
#delay final events incase of error
if currentState is 4
setTimeout emitFinal, 0
return
emitFinal = ->
unless hasError
facade[FIRE] "load", {}
facade[FIRE] "loadend", {}
if hasError
facade[READY_STATE] = 0
return
#control facade ready state
currentState = 0
setReadyState = (n) ->
#emit events until readyState reaches 4
if n isnt 4
emitReadyState(n)
return
#before emitting 4, run all 'after' hooks in sequence
hooks = xhook.listeners AFTER
process = ->
unless hooks.length
return emitReadyState(4)
hook = hooks.shift()
if hook.length is 2
hook request, response
process()
else if hook.length is 3 and request.async
hook request, response, process
else
process()
process()
return
#==========================
# Facade XHR
facade = request.xhr = EventEmitter()
#==========================
# Handle the underlying ready state
xhr.onreadystatechange = (event) ->
#pull status and headers
try
if xhr[READY_STATE] is 2
readHead()
#pull response data
if xhr[READY_STATE] is 4
transiting = false
readHead()
readBody()
setReadyState xhr[READY_STATE]
return
#mark this xhr as errored
hasErrorHandler = ->
hasError = true
return
facade[ON] 'error', hasErrorHandler
facade[ON] 'timeout', hasErrorHandler
facade[ON] 'abort', hasErrorHandler
# progress means we're current downloading...
facade[ON] 'progress', ->
#progress events are followed by readystatechange for some reason...
if currentState < 3
setReadyState 3
else
facade[FIRE] "readystatechange", {} #TODO fake an XHR event
return
# initialise 'withCredentials' on facade xhr in browsers with it
# or if explicitly told to do so
if 'withCredentials' of xhr or xhook.addWithCredentials
facade.withCredentials = false
facade.status = 0
# initialise all possible event handlers
for event in COMMON_EVENTS.concat(UPLOAD_EVENTS)
facade["on#{event}"] = null
facade.open = (method, url, async, user, pass) ->
# Initailize empty XHR facade
currentState = 0
hasError = false
transiting = false
request.headers = {}
request.headerNames = {}
request.status = 0
response = {}
response.headers = {}
request.method = method
request.url = url
request.async = async isnt false
request.user = user
request.pass = <PASSWORD>
# openned facade xhr (not real xhr)
setReadyState 1
return
facade.send = (body) ->
#read xhr settings before hooking
for k in ['type', 'timeout', 'withCredentials']
modk = if k is "type" then "responseType" else k
request[k] = facade[modk] if modk of facade
request.body = body
send = ->
#proxy all events from real xhr to facade
proxyEvents COMMON_EVENTS, xhr, facade
proxyEvents COMMON_EVENTS.concat(UPLOAD_EVENTS), xhr.upload, facade.upload if facade.upload
#prepare request all at once
transiting = true
#perform open
xhr.open request.method, request.url, request.async, request.user, request.pass
#write xhr settings
for k in ['type', 'timeout', 'withCredentials']
modk = if k is "type" then "responseType" else k
xhr[modk] = request[k] if k of request
#insert headers
for header, value of request.headers
if header
xhr.setRequestHeader header, value
#extract real formdata
if request.body instanceof XHookFormData
request.body = request.body.fd
#real send!
xhr.send request.body
return
hooks = xhook.listeners BEFORE
#process hooks sequentially
process = ->
unless hooks.length
return send()
#go to next hook OR optionally provide response
done = (userResponse) ->
#break chain - provide dummy response (readyState 4)
if typeof userResponse is 'object' and
(typeof userResponse.status is 'number' or
typeof response.status is 'number')
mergeObjects userResponse, response
unless 'data' in userResponse
userResponse.data = userResponse.response or userResponse.text
setReadyState 4
return
#continue processing until no hooks left
process()
return
#specifically provide headers (readyState 2)
done.head = (userResponse) ->
mergeObjects userResponse, response
setReadyState 2
#specifically provide partial text (responseText readyState 3)
done.progress = (userResponse) ->
mergeObjects userResponse, response
setReadyState 3
hook = hooks.shift()
#async or sync?
if hook.length is 1
done hook request
else if hook.length is 2 and request.async
#async handlers must use an async xhr
hook request, done
else
#skip async hook on sync requests
done()
#kick off
process()
return
facade.abort = ->
status = ABORTED;
if transiting
xhr.abort() #this will emit an 'abort' for us
else
facade[FIRE] 'abort', {}
return
facade.setRequestHeader = (header, value) ->
#the first header set is used for all future case-alternatives of 'name'
lName = header?.toLowerCase()
name = request.headerNames[lName] = request.headerNames[lName] || header
#append header to any previous values
if request.headers[name]
value = request.headers[name] + ', ' + value
request.headers[name] = value
return
facade.getResponseHeader = (header) ->
name = header?.toLowerCase()
response.headers[name]
facade.getAllResponseHeaders = ->
convertHeaders response.headers
#proxy call only when supported
if xhr.overrideMimeType
facade.overrideMimeType = ->
xhr.overrideMimeType.apply xhr, arguments
#create emitter when supported
if xhr.upload
facade.upload = request.upload = EventEmitter()
return facade
#publicise (amd+commonjs+window)
if typeof define is "function" and define.amd
define "xhook", [], -> xhook
else
(@exports or @).xhook = xhook
| true | #for compression
document = window.document
BEFORE = 'before'
AFTER = 'after'
READY_STATE = 'readyState'
ON = 'addEventListener'
OFF = 'removeEventListener'
FIRE = 'dispatchEvent'
XMLHTTP = 'XMLHttpRequest'
FormData = 'FormData'
UPLOAD_EVENTS = ['load', 'loadend', 'loadstart']
COMMON_EVENTS = ['progress', 'abort', 'error', 'timeout']
#parse IE version
msie = parseInt((/msie (\d+)/.exec((navigator.userAgent).toLowerCase()) or [])[1])
msie = parseInt((/trident\/.*; rv:(\d+)/.exec((navigator.userAgent).toLowerCase()) or [])[1]) if isNaN(msie)
#if required, add 'indexOf' method to Array
Array::indexOf or= (item) ->
for x, i in this
return i if x is item
return -1
slice = (o,n) -> Array::slice.call o,n
depricatedProp = (p) ->
return p in ["returnValue","totalSize","position"]
mergeObjects = (src, dst) ->
for k,v of src
continue if depricatedProp k
try dst[k] = src[k]
return dst
#proxy events from one emitter to another
proxyEvents = (events, src, dst) ->
p = (event) -> (e) ->
clone = {}
#copies event, with dst emitter inplace of src
for k of e
continue if depricatedProp k
val = e[k]
clone[k] = if val is src then dst else val
#emits out the dst
dst[FIRE] event, clone
#dont proxy manual events
for event in events
if dst._has event
src["on#{event}"] = p(event)
return
#create fake event
fakeEvent = (type) ->
if document.createEventObject?
msieEventObject = document.createEventObject()
msieEventObject.type = type
msieEventObject
else
# on some platforms like android 4.1.2 and safari on windows, it appears
# that new Event is not allowed
try new Event(type)
catch then {type}
#tiny event emitter
EventEmitter = (nodeStyle) ->
#private
events = {}
listeners = (event) ->
events[event] or []
#public
emitter = {}
emitter[ON] = (event, callback, i) ->
events[event] = listeners event
return if events[event].indexOf(callback) >= 0
i = if i is `undefined` then events[event].length else i
events[event].splice i, 0, callback
return
emitter[OFF] = (event, callback) ->
#remove all
if event is `undefined`
events = {}
return
#remove all of type event
if callback is `undefined`
events[event] = []
#remove particular handler
i = listeners(event).indexOf callback
return if i is -1
listeners(event).splice i, 1
return
emitter[FIRE] = ->
args = slice arguments
event = args.shift()
unless nodeStyle
args[0] = mergeObjects args[0], fakeEvent event
legacylistener = emitter["on#{event}"]
if legacylistener
legacylistener.apply emitter, args
for listener, i in listeners(event).concat(listeners("*"))
listener.apply emitter, args
return
emitter._has = (event) ->
return !!(events[event] or emitter["on#{event}"])
#add extra aliases
if nodeStyle
emitter.listeners = (event) ->
slice listeners event
emitter.on = emitter[ON]
emitter.off = emitter[OFF]
emitter.fire = emitter[FIRE]
emitter.once = (e, fn) ->
fire = ->
emitter.off e, fire
fn.apply null, arguments
emitter.on e, fire
emitter.destroy = ->
events = {}
emitter
#use event emitter to store hooks
xhook = EventEmitter(true)
xhook.EventEmitter = EventEmitter
xhook[BEFORE] = (handler, i) ->
if handler.length < 1 or handler.length > 2
throw "invalid hook"
xhook[ON] BEFORE, handler, i
xhook[AFTER] = (handler, i) ->
if handler.length < 2 or handler.length > 3
throw "invalid hook"
xhook[ON] AFTER, handler, i
xhook.enable = ->
window[XMLHTTP] = XHookHttpRequest
window[FormData] = XHookFormData if NativeFormData
return
xhook.disable = ->
window[XMLHTTP] = xhook[XMLHTTP]
window[FormData] = NativeFormData if NativeFormData
return
#helper
convertHeaders = xhook.headers = (h, dest = {}) ->
switch typeof h
when "object"
headers = []
for k,v of h
name = k.toLowerCase()
headers.push "#{name}:\t#{v}"
return headers.join '\n'
when "string"
headers = h.split '\n'
for header in headers
if /([^:]+):\s*(.+)/.test(header)
name = RegExp.$1?.toLowerCase()
value = RegExp.$2
dest[name] ?= value
return dest
return
#patch FormData
# we can do this safely because all XHR
# is hooked, so we can ensure the real FormData
# object is used on send
NativeFormData = window[FormData]
XHookFormData = (form) ->
@fd = if form then new NativeFormData(form) else new NativeFormData()
@form = form
entries = []
Object.defineProperty @, 'entries', get: ->
#extract form entries
fentries = unless form then [] else
slice(form.querySelectorAll("input,select")).filter((e) ->
return e.type not in ['checkbox','radio'] or e.checked
).map((e) ->
[e.name, if e.type is "file" then e.files else e.value]
)
#combine with js entries
return fentries.concat entries
@append = =>
args = slice arguments
entries.push args
@fd.append.apply @fd, args
return
if NativeFormData
#expose native formdata as xhook.FormData incase its needed
xhook[FormData] = NativeFormData
window[FormData] = XHookFormData
#patch XHR
NativeXMLHttp = window[XMLHTTP]
xhook[XMLHTTP] = NativeXMLHttp
XHookHttpRequest = window[XMLHTTP] = ->
ABORTED = -1
xhr = new xhook[XMLHTTP]()
#==========================
# Extra state
request = {}
status = null
hasError = undefined
transiting = undefined
response = undefined
#==========================
# Private API
#read results from real xhr into response
readHead = ->
# Accessing attributes on an aborted xhr object will
# throw an 'c00c023f error' in IE9 and lower, don't touch it.
response.status = status or xhr.status
response.statusText = xhr.statusText unless status is ABORTED and msie < 10
if status isnt ABORTED
for key, val of convertHeaders xhr.getAllResponseHeaders()
unless response.headers[key]
name = key.toLowerCase()
response.headers[name] = val
return
readBody = ->
#https://xhr.spec.whatwg.org/
if !xhr.responseType or xhr.responseType is "text"
response.text = xhr.responseText
response.data = xhr.responseText
else if xhr.responseType is "document"
response.xml = xhr.responseXML
response.data = xhr.responseXML
else
response.data = xhr.response
#new in some browsers
if "responseURL" of xhr
response.finalUrl = xhr.responseURL
return
#write response into facade xhr
writeHead = ->
facade.status = response.status
facade.statusText = response.statusText
return
writeBody = ->
if 'text' of response
facade.responseText = response.text
if 'xml' of response
facade.responseXML = response.xml
if 'data' of response
facade.response = response.data
if 'finalUrl' of response
facade.responseURL = response.finalUrl
return
#ensure ready state 0 through 4 is handled
emitReadyState = (n) ->
while n > currentState and currentState < 4
facade[READY_STATE] = ++currentState
# make fake events for libraries that actually check the type on
# the event object
if currentState is 1
facade[FIRE] "loadstart", {}
if currentState is 2
writeHead()
if currentState is 4
writeHead()
writeBody()
facade[FIRE] "readystatechange", {}
#delay final events incase of error
if currentState is 4
setTimeout emitFinal, 0
return
emitFinal = ->
unless hasError
facade[FIRE] "load", {}
facade[FIRE] "loadend", {}
if hasError
facade[READY_STATE] = 0
return
#control facade ready state
currentState = 0
setReadyState = (n) ->
#emit events until readyState reaches 4
if n isnt 4
emitReadyState(n)
return
#before emitting 4, run all 'after' hooks in sequence
hooks = xhook.listeners AFTER
process = ->
unless hooks.length
return emitReadyState(4)
hook = hooks.shift()
if hook.length is 2
hook request, response
process()
else if hook.length is 3 and request.async
hook request, response, process
else
process()
process()
return
#==========================
# Facade XHR
facade = request.xhr = EventEmitter()
#==========================
# Handle the underlying ready state
xhr.onreadystatechange = (event) ->
#pull status and headers
try
if xhr[READY_STATE] is 2
readHead()
#pull response data
if xhr[READY_STATE] is 4
transiting = false
readHead()
readBody()
setReadyState xhr[READY_STATE]
return
#mark this xhr as errored
hasErrorHandler = ->
hasError = true
return
facade[ON] 'error', hasErrorHandler
facade[ON] 'timeout', hasErrorHandler
facade[ON] 'abort', hasErrorHandler
# progress means we're current downloading...
facade[ON] 'progress', ->
#progress events are followed by readystatechange for some reason...
if currentState < 3
setReadyState 3
else
facade[FIRE] "readystatechange", {} #TODO fake an XHR event
return
# initialise 'withCredentials' on facade xhr in browsers with it
# or if explicitly told to do so
if 'withCredentials' of xhr or xhook.addWithCredentials
facade.withCredentials = false
facade.status = 0
# initialise all possible event handlers
for event in COMMON_EVENTS.concat(UPLOAD_EVENTS)
facade["on#{event}"] = null
facade.open = (method, url, async, user, pass) ->
# Initailize empty XHR facade
currentState = 0
hasError = false
transiting = false
request.headers = {}
request.headerNames = {}
request.status = 0
response = {}
response.headers = {}
request.method = method
request.url = url
request.async = async isnt false
request.user = user
request.pass = PI:PASSWORD:<PASSWORD>END_PI
# openned facade xhr (not real xhr)
setReadyState 1
return
facade.send = (body) ->
#read xhr settings before hooking
for k in ['type', 'timeout', 'withCredentials']
modk = if k is "type" then "responseType" else k
request[k] = facade[modk] if modk of facade
request.body = body
send = ->
#proxy all events from real xhr to facade
proxyEvents COMMON_EVENTS, xhr, facade
proxyEvents COMMON_EVENTS.concat(UPLOAD_EVENTS), xhr.upload, facade.upload if facade.upload
#prepare request all at once
transiting = true
#perform open
xhr.open request.method, request.url, request.async, request.user, request.pass
#write xhr settings
for k in ['type', 'timeout', 'withCredentials']
modk = if k is "type" then "responseType" else k
xhr[modk] = request[k] if k of request
#insert headers
for header, value of request.headers
if header
xhr.setRequestHeader header, value
#extract real formdata
if request.body instanceof XHookFormData
request.body = request.body.fd
#real send!
xhr.send request.body
return
hooks = xhook.listeners BEFORE
#process hooks sequentially
process = ->
unless hooks.length
return send()
#go to next hook OR optionally provide response
done = (userResponse) ->
#break chain - provide dummy response (readyState 4)
if typeof userResponse is 'object' and
(typeof userResponse.status is 'number' or
typeof response.status is 'number')
mergeObjects userResponse, response
unless 'data' in userResponse
userResponse.data = userResponse.response or userResponse.text
setReadyState 4
return
#continue processing until no hooks left
process()
return
#specifically provide headers (readyState 2)
done.head = (userResponse) ->
mergeObjects userResponse, response
setReadyState 2
#specifically provide partial text (responseText readyState 3)
done.progress = (userResponse) ->
mergeObjects userResponse, response
setReadyState 3
hook = hooks.shift()
#async or sync?
if hook.length is 1
done hook request
else if hook.length is 2 and request.async
#async handlers must use an async xhr
hook request, done
else
#skip async hook on sync requests
done()
#kick off
process()
return
facade.abort = ->
status = ABORTED;
if transiting
xhr.abort() #this will emit an 'abort' for us
else
facade[FIRE] 'abort', {}
return
facade.setRequestHeader = (header, value) ->
#the first header set is used for all future case-alternatives of 'name'
lName = header?.toLowerCase()
name = request.headerNames[lName] = request.headerNames[lName] || header
#append header to any previous values
if request.headers[name]
value = request.headers[name] + ', ' + value
request.headers[name] = value
return
facade.getResponseHeader = (header) ->
name = header?.toLowerCase()
response.headers[name]
facade.getAllResponseHeaders = ->
convertHeaders response.headers
#proxy call only when supported
if xhr.overrideMimeType
facade.overrideMimeType = ->
xhr.overrideMimeType.apply xhr, arguments
#create emitter when supported
if xhr.upload
facade.upload = request.upload = EventEmitter()
return facade
#publicise (amd+commonjs+window)
if typeof define is "function" and define.amd
define "xhook", [], -> xhook
else
(@exports or @).xhook = xhook
|
[
{
"context": "eator: '561ca7b4ea8b1ab77d6a1efe'\n fileKey: '1107ff00571d2cf89eebbd0ddabbdeb38fb0'\n fileName: 'ic_favorite_task.png'\n fil",
"end": 371,
"score": 0.9997406005859375,
"start": 335,
"tag": "KEY",
"value": "1107ff00571d2cf89eebbd0ddabbdeb38fb0"
},
{
"conte... | talk-api2x/test/schemas/story.coffee | ikingye/talk-os | 3,084 | should = require 'should'
_ = require 'lodash'
Promise = require 'bluebird'
app = require '../app'
limbo = require 'limbo'
{prepare, cleanup} = app
{
StoryModel
} = limbo.use 'talk'
describe 'Schemas#Story', ->
it 'should create a story with file', (done) ->
data =
creator: '561ca7b4ea8b1ab77d6a1efe'
fileKey: '1107ff00571d2cf89eebbd0ddabbdeb38fb0'
fileName: 'ic_favorite_task.png'
fileType: 'png'
fileSize: 2986
fileCategory: 'image'
other: 'unnecessary property'
story = new StoryModel
category: 'file'
data: data
story.data.should.have.properties 'fileKey'
story.should.not.have.properties 'other'
story.data.downloadUrl.should.containEql data.fileKey
# Update data properties
_data = _.clone data
_data.fileKey = '2107ff00571d2cf89eebbd0ddabbdeb38fb0'
story.data = _data
story.data.should.have.properties 'fileKey'
story.data.downloadUrl.should.containEql _data.fileKey
# Save story to database
$story1 = story.$save()
$story2 = $story1.then (story1) ->
StoryModel.findOneAsync _id: story1._id
.then (story2) ->
story2.data.downloadUrl.should.containEql _data.fileKey
story2.should.not.have.properties 'other'
Promise.all [$story1, $story2]
.nodeify done
after cleanup
| 211860 | should = require 'should'
_ = require 'lodash'
Promise = require 'bluebird'
app = require '../app'
limbo = require 'limbo'
{prepare, cleanup} = app
{
StoryModel
} = limbo.use 'talk'
describe 'Schemas#Story', ->
it 'should create a story with file', (done) ->
data =
creator: '561ca7b4ea8b1ab77d6a1efe'
fileKey: '<KEY>'
fileName: 'ic_favorite_task.png'
fileType: 'png'
fileSize: 2986
fileCategory: 'image'
other: 'unnecessary property'
story = new StoryModel
category: 'file'
data: data
story.data.should.have.properties 'fileKey'
story.should.not.have.properties 'other'
story.data.downloadUrl.should.containEql data.fileKey
# Update data properties
_data = _.clone data
_data.fileKey = '<KEY>'
story.data = _data
story.data.should.have.properties 'fileKey'
story.data.downloadUrl.should.containEql _data.fileKey
# Save story to database
$story1 = story.$save()
$story2 = $story1.then (story1) ->
StoryModel.findOneAsync _id: story1._id
.then (story2) ->
story2.data.downloadUrl.should.containEql _data.fileKey
story2.should.not.have.properties 'other'
Promise.all [$story1, $story2]
.nodeify done
after cleanup
| true | should = require 'should'
_ = require 'lodash'
Promise = require 'bluebird'
app = require '../app'
limbo = require 'limbo'
{prepare, cleanup} = app
{
StoryModel
} = limbo.use 'talk'
describe 'Schemas#Story', ->
it 'should create a story with file', (done) ->
data =
creator: '561ca7b4ea8b1ab77d6a1efe'
fileKey: 'PI:KEY:<KEY>END_PI'
fileName: 'ic_favorite_task.png'
fileType: 'png'
fileSize: 2986
fileCategory: 'image'
other: 'unnecessary property'
story = new StoryModel
category: 'file'
data: data
story.data.should.have.properties 'fileKey'
story.should.not.have.properties 'other'
story.data.downloadUrl.should.containEql data.fileKey
# Update data properties
_data = _.clone data
_data.fileKey = 'PI:KEY:<KEY>END_PI'
story.data = _data
story.data.should.have.properties 'fileKey'
story.data.downloadUrl.should.containEql _data.fileKey
# Save story to database
$story1 = story.$save()
$story2 = $story1.then (story1) ->
StoryModel.findOneAsync _id: story1._id
.then (story2) ->
story2.data.downloadUrl.should.containEql _data.fileKey
story2.should.not.have.properties 'other'
Promise.all [$story1, $story2]
.nodeify done
after cleanup
|
[
{
"context": "r useless escapes in strings and regexes\n# @author Onur Temizkan\n###\n\n'use strict'\n\n#-----------------------------",
"end": 92,
"score": 0.9998741149902344,
"start": 79,
"tag": "NAME",
"value": "Onur Temizkan"
},
{
"context": "ring.raw\"foo = /[\\\\/]/\"\n\n # ... | src/tests/rules/no-useless-escape.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Look for useless escapes in strings and regexes
# @author Onur Temizkan
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
### eslint-disable ###
rule = require '../../rules/no-useless-escape'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
### eslint-disable coffee/no-template-curly-in-string, coffee/no-unnecessary-double-quotes ###
ruleTester.run 'no-useless-escape', rule,
valid: [
'foo = /\\./'
'foo = ///\\.///'
'foo = ///#{a}\\.///'
'foo = /\\//g'
'foo = /""/'
"foo = /''/"
'foo = /([A-Z])\\t+/g'
'foo = /([A-Z])\\n+/g'
'foo = /([A-Z])\\v+/g'
'foo = /\\D/'
'foo = /\\W/'
'foo = /\\w/'
'foo = /\\B/'
'foo = /\\\\/g'
'foo = /\\w\\$\\*\\./'
'foo = /\\^\\+\\./'
'foo = /\\|\\}\\{\\./'
'foo = /]\\[\\(\\)\\//'
'foo = "\\x123"'
'foo = "\\u00a9"'
'foo = "\\""'
'foo = "xs\\u2111"'
'foo = "foo \\\\ bar"'
'foo = "\\t"'
'foo = "foo \\b bar"'
"foo = '\\n'"
"foo = 'foo \\r bar'"
"foo = '\\v'"
"foo = '\\f'"
"foo = '\\\n'"
"foo = '\\\r\n'"
,
code: '<foo attr="\\d"/>'
,
code: '<div> Testing: \\ </div>'
,
code: '<div> Testing: \ </div>'
,
code: "<foo attr='\\d'></foo>"
,
code: '<> Testing: \\ </>'
,
code: '<> Testing: \ </>'
,
code: 'foo = "\\x123"'
,
code: 'foo = "\\u00a9"'
,
code: 'foo = "xs\\u2111"'
,
code: 'foo = "foo \\\\ bar"'
,
code: 'foo = "\\t"'
,
code: 'foo = "foo \\b bar"'
,
code: 'foo = "\\n"'
,
code: 'foo = "foo \\r bar"'
,
code: 'foo = "\\v"'
,
code: 'foo = "\\f"'
,
code: 'foo = "\\\n"'
,
code: 'foo = "\\\r\n"'
,
code: 'foo = "#{foo} \\x123"'
,
code: 'foo = "#{foo} \\u00a9"'
,
code: 'foo = "#{foo} xs\\u2111"'
,
code: 'foo = "#{foo} \\\\ #{bar}"'
,
code: 'foo = "#{foo} \\b #{bar}"'
,
code: 'foo = "#{foo}\\t"'
,
code: 'foo = "#{foo}\\n"'
,
code: 'foo = "#{foo}\\r"'
,
code: 'foo = "#{foo}\\v"'
,
code: 'foo = "#{foo}\\f"'
,
code: 'foo = "#{foo}\\\n"'
,
code: 'foo = "#{foo}\\\r\n"'
,
code: 'foo = "\\""'
,
code: 'foo = "\\"#{foo}\\""'
,
code: 'foo = "\\#{{#{foo}"'
,
code: 'foo = "#\\{{#{foo}"'
,
code: 'foo = String.raw"\\."'
,
code: 'foo = myFunc"\\."'
,
String.raw"foo = /[\d]/"
String.raw"foo = /[a\-b]/"
String.raw"foo = /foo\?/"
String.raw"foo = /example\.com/"
String.raw"foo = /foo\|bar/"
String.raw"foo = /\^bar/"
String.raw"foo = /[\^bar]/"
String.raw"foo = /\(bar\)/"
String.raw"foo = /[[\]]/" # A character class containing '[' and ']'
String.raw"foo = /[[]\./" # A character class containing '[', followed by a '.' character
String.raw"foo = /[\]\]]/" # A (redundant) character class containing ']'
String.raw"foo = /\[abc]/" # Matches the literal string '[abc]'
String.raw"foo = /\[foo\.bar]/" # Matches the literal string '[foo.bar]'
String.raw"foo = /vi/m"
String.raw"foo = /\B/"
String.raw"foo = /[\\/]/"
# https://github.com/eslint/eslint/issues/7472
String.raw"foo = /\0/" # null character
'foo = /\\1/' # \x01 character (octal literal)
'foo = /(a)\\1/' # backreference
'foo = /(a)\\12/' # backreference
'foo = /[\\0]/' # null character in character class
"foo = 'foo \\\u2028 bar'"
"foo = 'foo \\\u2029 bar'"
# https://github.com/eslint/eslint/issues/7789
String.raw"/]/"
String.raw"/\]/"
String.raw"/\]/u"
String.raw"foo = /foo\]/"
String.raw"foo = /[[]\]/" # A character class containing '[', followed by a ']' character
String.raw"foo = /\[foo\.bar\]/"
# ES2018
String.raw"foo = /(?<a>)\k<a>/"
String.raw"foo = /(\\?<a>)/"
String.raw"foo = /\p{ASCII}/u"
String.raw"foo = /\P{ASCII}/u"
String.raw"foo = /[\p{ASCII}]/u"
String.raw"foo = /[\P{ASCII}]/u"
'''
foo = """
\\"\\"\\"a\\"\\"\\"
"""
'''
"""
foo = '''
\\'\\'\\'a\\'\\'\\'
'''
"""
'''
"""""surrounded by two quotes"\\""""
'''
'''
/// [\\s] ///
'''
'''
/// #{a}[\\s] ///
'''
'''
"\\#{b}"
'''
'''
"#\\{b}"
'''
'''
/// \\#{b} ///
'''
'''
/// #\\{b} ///
'''
]
invalid: [
code: 'foo = /\\#/'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: 'foo = /\\;/'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\;.'
type: 'Literal'
]
,
code: 'foo = "\\\'"'
errors: [
line: 1
column: 8
message: "Unnecessary escape character: \\'."
type: 'Literal'
]
,
code: 'foo = "\\#/"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: 'foo = "\\`"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
]
,
code: 'foo = "\\a"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\a.'
type: 'Literal'
]
,
code: 'foo = "\\B"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\B.'
type: 'Literal'
]
,
code: 'foo = "\\@"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\@.'
type: 'Literal'
]
,
code: 'foo = "foo \\a bar"'
errors: [
line: 1
column: 12
message: 'Unnecessary escape character: \\a.'
type: 'Literal'
]
,
code: "foo = '\\\"'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\".'
type: 'Literal'
]
,
code: "foo = '\\#'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: "foo = '\\$'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\$.'
type: 'Literal'
]
,
code: "foo = '\\p'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\p.'
type: 'Literal'
]
,
code: "foo = '\\p\\a\\@'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\p.'
type: 'Literal'
,
line: 1
column: 10
message: 'Unnecessary escape character: \\a.'
type: 'Literal'
,
line: 1
column: 12
message: 'Unnecessary escape character: \\@.'
type: 'Literal'
]
,
code: '<foo attr={"\\d"}/>'
errors: [
line: 1
column: 13
message: 'Unnecessary escape character: \\d.'
type: 'Literal'
]
,
code: "foo = '\\`'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
]
,
code: 'foo = "\\\'"'
errors: [
line: 1
column: 8
message: "Unnecessary escape character: \\'."
type: 'Literal'
]
,
code: '''
foo = '\\`foo\\`'
'''
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
,
line: 1
column: 13
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
]
,
code: '''
foo = '\\"foo\\"'
'''
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\".'
type: 'Literal'
,
line: 1
column: 13
message: 'Unnecessary escape character: \\".'
type: 'Literal'
]
,
code: 'foo = "\\\'#{foo}\\\'"'
errors: [
line: 1
column: 8
message: "Unnecessary escape character: \\'."
type: 'TemplateElement'
,
line: 1
column: 16
message: "Unnecessary escape character: \\'."
type: 'TemplateElement'
]
,
code: "foo = '\\ '"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\ .'
type: 'Literal'
]
,
code: 'foo = /\\ /'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\ .'
type: 'Literal'
]
,
code: 'foo = "\\${{#{foo}"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\$.'
type: 'TemplateElement'
]
,
code: 'foo = "\\#a#{foo}"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'TemplateElement'
]
,
code: 'foo = "a\\{{#{foo}"'
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\{.'
type: 'TemplateElement'
]
,
code: String.raw"foo = /[ab\-]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[\-ab]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[ab\?]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\?.'
type: 'Literal'
]
,
code: String.raw"foo = /[ab\.]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\..'
type: 'Literal'
]
,
code: String.raw"foo = /[a\|b]/"
errors: [
line: 1
column: 10
message: 'Unnecessary escape character: \\|.'
type: 'Literal'
]
,
code: String.raw"foo = /\-/"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[\-]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[ab\$]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\$.'
type: 'Literal'
]
,
code: String.raw"foo = /[\(paren]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\(.'
type: 'Literal'
]
,
code: String.raw"foo = /[\[]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\[.'
type: 'Literal'
]
,
# ,
# code: String.raw"foo = /[\/]/" # A character class containing '/'
# errors: [
# line: 1
# column: 9
# message: 'Unnecessary escape character: \\/.'
# type: 'Literal'
# ]
code: String.raw"foo = /[\B]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\B.'
type: 'Literal'
]
,
code: String.raw"foo = /[a][\-b]/"
errors: [
line: 1
column: 12
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /\-[]/"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[a\^]/"
errors: [
line: 1
column: 10
message: 'Unnecessary escape character: \\^.'
type: 'Literal'
]
,
code: '"multiline template\nliteral with useless \\escape"'
errors: [
line: 2
column: 22
message: 'Unnecessary escape character: \\e.'
type: 'Literal'
]
,
# ,
# code: '"\\a"""'
# errors: [
# line: 1
# column: 2
# message: 'Unnecessary escape character: \\a.'
# type: 'TemplateElement'
# ]
code: """
foo = '''
\\"
'''
"""
errors: [
line: 2
column: 3
message: 'Unnecessary escape character: \\".'
type: 'TemplateElement'
]
,
code: """
foo = '''
\\'
'''
"""
errors: [
line: 2
column: 3
message: "Unnecessary escape character: \\'."
type: 'TemplateElement'
]
,
code: '''
foo = """
\\"
"""
'''
errors: [
line: 2
column: 3
message: 'Unnecessary escape character: \\".'
type: 'TemplateElement'
]
,
code: '''
'\\#{b}'
'''
errors: [
line: 1
column: 2
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: '''
/\\#{b}/
'''
errors: [
line: 1
column: 2
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
# ,
# code: '''
# ok ///\\\u2028///.test '\\u2028'
# ok ///\\"///.test '"'
# '''
# errors: [
# line: 2
# # column: 8
# message: 'Unnecessary escape character: \\".'
# type: 'Literal'
# ]
]
| 42188 | ###*
# @fileoverview Look for useless escapes in strings and regexes
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
### eslint-disable ###
rule = require '../../rules/no-useless-escape'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
### eslint-disable coffee/no-template-curly-in-string, coffee/no-unnecessary-double-quotes ###
ruleTester.run 'no-useless-escape', rule,
valid: [
'foo = /\\./'
'foo = ///\\.///'
'foo = ///#{a}\\.///'
'foo = /\\//g'
'foo = /""/'
"foo = /''/"
'foo = /([A-Z])\\t+/g'
'foo = /([A-Z])\\n+/g'
'foo = /([A-Z])\\v+/g'
'foo = /\\D/'
'foo = /\\W/'
'foo = /\\w/'
'foo = /\\B/'
'foo = /\\\\/g'
'foo = /\\w\\$\\*\\./'
'foo = /\\^\\+\\./'
'foo = /\\|\\}\\{\\./'
'foo = /]\\[\\(\\)\\//'
'foo = "\\x123"'
'foo = "\\u00a9"'
'foo = "\\""'
'foo = "xs\\u2111"'
'foo = "foo \\\\ bar"'
'foo = "\\t"'
'foo = "foo \\b bar"'
"foo = '\\n'"
"foo = 'foo \\r bar'"
"foo = '\\v'"
"foo = '\\f'"
"foo = '\\\n'"
"foo = '\\\r\n'"
,
code: '<foo attr="\\d"/>'
,
code: '<div> Testing: \\ </div>'
,
code: '<div> Testing: \ </div>'
,
code: "<foo attr='\\d'></foo>"
,
code: '<> Testing: \\ </>'
,
code: '<> Testing: \ </>'
,
code: 'foo = "\\x123"'
,
code: 'foo = "\\u00a9"'
,
code: 'foo = "xs\\u2111"'
,
code: 'foo = "foo \\\\ bar"'
,
code: 'foo = "\\t"'
,
code: 'foo = "foo \\b bar"'
,
code: 'foo = "\\n"'
,
code: 'foo = "foo \\r bar"'
,
code: 'foo = "\\v"'
,
code: 'foo = "\\f"'
,
code: 'foo = "\\\n"'
,
code: 'foo = "\\\r\n"'
,
code: 'foo = "#{foo} \\x123"'
,
code: 'foo = "#{foo} \\u00a9"'
,
code: 'foo = "#{foo} xs\\u2111"'
,
code: 'foo = "#{foo} \\\\ #{bar}"'
,
code: 'foo = "#{foo} \\b #{bar}"'
,
code: 'foo = "#{foo}\\t"'
,
code: 'foo = "#{foo}\\n"'
,
code: 'foo = "#{foo}\\r"'
,
code: 'foo = "#{foo}\\v"'
,
code: 'foo = "#{foo}\\f"'
,
code: 'foo = "#{foo}\\\n"'
,
code: 'foo = "#{foo}\\\r\n"'
,
code: 'foo = "\\""'
,
code: 'foo = "\\"#{foo}\\""'
,
code: 'foo = "\\#{{#{foo}"'
,
code: 'foo = "#\\{{#{foo}"'
,
code: 'foo = String.raw"\\."'
,
code: 'foo = myFunc"\\."'
,
String.raw"foo = /[\d]/"
String.raw"foo = /[a\-b]/"
String.raw"foo = /foo\?/"
String.raw"foo = /example\.com/"
String.raw"foo = /foo\|bar/"
String.raw"foo = /\^bar/"
String.raw"foo = /[\^bar]/"
String.raw"foo = /\(bar\)/"
String.raw"foo = /[[\]]/" # A character class containing '[' and ']'
String.raw"foo = /[[]\./" # A character class containing '[', followed by a '.' character
String.raw"foo = /[\]\]]/" # A (redundant) character class containing ']'
String.raw"foo = /\[abc]/" # Matches the literal string '[abc]'
String.raw"foo = /\[foo\.bar]/" # Matches the literal string '[foo.bar]'
String.raw"foo = /vi/m"
String.raw"foo = /\B/"
String.raw"foo = /[\\/]/"
# https://github.com/eslint/eslint/issues/7472
String.raw"foo = /\0/" # null character
'foo = /\\1/' # \x01 character (octal literal)
'foo = /(a)\\1/' # backreference
'foo = /(a)\\12/' # backreference
'foo = /[\\0]/' # null character in character class
"foo = 'foo \\\u2028 bar'"
"foo = 'foo \\\u2029 bar'"
# https://github.com/eslint/eslint/issues/7789
String.raw"/]/"
String.raw"/\]/"
String.raw"/\]/u"
String.raw"foo = /foo\]/"
String.raw"foo = /[[]\]/" # A character class containing '[', followed by a ']' character
String.raw"foo = /\[foo\.bar\]/"
# ES2018
String.raw"foo = /(?<a>)\k<a>/"
String.raw"foo = /(\\?<a>)/"
String.raw"foo = /\p{ASCII}/u"
String.raw"foo = /\P{ASCII}/u"
String.raw"foo = /[\p{ASCII}]/u"
String.raw"foo = /[\P{ASCII}]/u"
'''
foo = """
\\"\\"\\"a\\"\\"\\"
"""
'''
"""
foo = '''
\\'\\'\\'a\\'\\'\\'
'''
"""
'''
"""""surrounded by two quotes"\\""""
'''
'''
/// [\\s] ///
'''
'''
/// #{a}[\\s] ///
'''
'''
"\\#{b}"
'''
'''
"#\\{b}"
'''
'''
/// \\#{b} ///
'''
'''
/// #\\{b} ///
'''
]
invalid: [
code: 'foo = /\\#/'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: 'foo = /\\;/'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\;.'
type: 'Literal'
]
,
code: 'foo = "\\\'"'
errors: [
line: 1
column: 8
message: "Unnecessary escape character: \\'."
type: 'Literal'
]
,
code: 'foo = "\\#/"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: 'foo = "\\`"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
]
,
code: 'foo = "\\a"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\a.'
type: 'Literal'
]
,
code: 'foo = "\\B"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\B.'
type: 'Literal'
]
,
code: 'foo = "\\@"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\@.'
type: 'Literal'
]
,
code: 'foo = "foo \\a bar"'
errors: [
line: 1
column: 12
message: 'Unnecessary escape character: \\a.'
type: 'Literal'
]
,
code: "foo = '\\\"'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\".'
type: 'Literal'
]
,
code: "foo = '\\#'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: "foo = '\\$'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\$.'
type: 'Literal'
]
,
code: "foo = '\\p'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\p.'
type: 'Literal'
]
,
code: "foo = '\\p\\a\\@'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\p.'
type: 'Literal'
,
line: 1
column: 10
message: 'Unnecessary escape character: \\a.'
type: 'Literal'
,
line: 1
column: 12
message: 'Unnecessary escape character: \\@.'
type: 'Literal'
]
,
code: '<foo attr={"\\d"}/>'
errors: [
line: 1
column: 13
message: 'Unnecessary escape character: \\d.'
type: 'Literal'
]
,
code: "foo = '\\`'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
]
,
code: 'foo = "\\\'"'
errors: [
line: 1
column: 8
message: "Unnecessary escape character: \\'."
type: 'Literal'
]
,
code: '''
foo = '\\`foo\\`'
'''
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
,
line: 1
column: 13
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
]
,
code: '''
foo = '\\"foo\\"'
'''
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\".'
type: 'Literal'
,
line: 1
column: 13
message: 'Unnecessary escape character: \\".'
type: 'Literal'
]
,
code: 'foo = "\\\'#{foo}\\\'"'
errors: [
line: 1
column: 8
message: "Unnecessary escape character: \\'."
type: 'TemplateElement'
,
line: 1
column: 16
message: "Unnecessary escape character: \\'."
type: 'TemplateElement'
]
,
code: "foo = '\\ '"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\ .'
type: 'Literal'
]
,
code: 'foo = /\\ /'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\ .'
type: 'Literal'
]
,
code: 'foo = "\\${{#{foo}"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\$.'
type: 'TemplateElement'
]
,
code: 'foo = "\\#a#{foo}"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'TemplateElement'
]
,
code: 'foo = "a\\{{#{foo}"'
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\{.'
type: 'TemplateElement'
]
,
code: String.raw"foo = /[ab\-]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[\-ab]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[ab\?]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\?.'
type: 'Literal'
]
,
code: String.raw"foo = /[ab\.]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\..'
type: 'Literal'
]
,
code: String.raw"foo = /[a\|b]/"
errors: [
line: 1
column: 10
message: 'Unnecessary escape character: \\|.'
type: 'Literal'
]
,
code: String.raw"foo = /\-/"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[\-]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[ab\$]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\$.'
type: 'Literal'
]
,
code: String.raw"foo = /[\(paren]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\(.'
type: 'Literal'
]
,
code: String.raw"foo = /[\[]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\[.'
type: 'Literal'
]
,
# ,
# code: String.raw"foo = /[\/]/" # A character class containing '/'
# errors: [
# line: 1
# column: 9
# message: 'Unnecessary escape character: \\/.'
# type: 'Literal'
# ]
code: String.raw"foo = /[\B]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\B.'
type: 'Literal'
]
,
code: String.raw"foo = /[a][\-b]/"
errors: [
line: 1
column: 12
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /\-[]/"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[a\^]/"
errors: [
line: 1
column: 10
message: 'Unnecessary escape character: \\^.'
type: 'Literal'
]
,
code: '"multiline template\nliteral with useless \\escape"'
errors: [
line: 2
column: 22
message: 'Unnecessary escape character: \\e.'
type: 'Literal'
]
,
# ,
# code: '"\\a"""'
# errors: [
# line: 1
# column: 2
# message: 'Unnecessary escape character: \\a.'
# type: 'TemplateElement'
# ]
code: """
foo = '''
\\"
'''
"""
errors: [
line: 2
column: 3
message: 'Unnecessary escape character: \\".'
type: 'TemplateElement'
]
,
code: """
foo = '''
\\'
'''
"""
errors: [
line: 2
column: 3
message: "Unnecessary escape character: \\'."
type: 'TemplateElement'
]
,
code: '''
foo = """
\\"
"""
'''
errors: [
line: 2
column: 3
message: 'Unnecessary escape character: \\".'
type: 'TemplateElement'
]
,
code: '''
'\\#{b}'
'''
errors: [
line: 1
column: 2
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: '''
/\\#{b}/
'''
errors: [
line: 1
column: 2
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
# ,
# code: '''
# ok ///\\\u2028///.test '\\u2028'
# ok ///\\"///.test '"'
# '''
# errors: [
# line: 2
# # column: 8
# message: 'Unnecessary escape character: \\".'
# type: 'Literal'
# ]
]
| true | ###*
# @fileoverview Look for useless escapes in strings and regexes
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
### eslint-disable ###
rule = require '../../rules/no-useless-escape'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
### eslint-disable coffee/no-template-curly-in-string, coffee/no-unnecessary-double-quotes ###
ruleTester.run 'no-useless-escape', rule,
valid: [
'foo = /\\./'
'foo = ///\\.///'
'foo = ///#{a}\\.///'
'foo = /\\//g'
'foo = /""/'
"foo = /''/"
'foo = /([A-Z])\\t+/g'
'foo = /([A-Z])\\n+/g'
'foo = /([A-Z])\\v+/g'
'foo = /\\D/'
'foo = /\\W/'
'foo = /\\w/'
'foo = /\\B/'
'foo = /\\\\/g'
'foo = /\\w\\$\\*\\./'
'foo = /\\^\\+\\./'
'foo = /\\|\\}\\{\\./'
'foo = /]\\[\\(\\)\\//'
'foo = "\\x123"'
'foo = "\\u00a9"'
'foo = "\\""'
'foo = "xs\\u2111"'
'foo = "foo \\\\ bar"'
'foo = "\\t"'
'foo = "foo \\b bar"'
"foo = '\\n'"
"foo = 'foo \\r bar'"
"foo = '\\v'"
"foo = '\\f'"
"foo = '\\\n'"
"foo = '\\\r\n'"
,
code: '<foo attr="\\d"/>'
,
code: '<div> Testing: \\ </div>'
,
code: '<div> Testing: \ </div>'
,
code: "<foo attr='\\d'></foo>"
,
code: '<> Testing: \\ </>'
,
code: '<> Testing: \ </>'
,
code: 'foo = "\\x123"'
,
code: 'foo = "\\u00a9"'
,
code: 'foo = "xs\\u2111"'
,
code: 'foo = "foo \\\\ bar"'
,
code: 'foo = "\\t"'
,
code: 'foo = "foo \\b bar"'
,
code: 'foo = "\\n"'
,
code: 'foo = "foo \\r bar"'
,
code: 'foo = "\\v"'
,
code: 'foo = "\\f"'
,
code: 'foo = "\\\n"'
,
code: 'foo = "\\\r\n"'
,
code: 'foo = "#{foo} \\x123"'
,
code: 'foo = "#{foo} \\u00a9"'
,
code: 'foo = "#{foo} xs\\u2111"'
,
code: 'foo = "#{foo} \\\\ #{bar}"'
,
code: 'foo = "#{foo} \\b #{bar}"'
,
code: 'foo = "#{foo}\\t"'
,
code: 'foo = "#{foo}\\n"'
,
code: 'foo = "#{foo}\\r"'
,
code: 'foo = "#{foo}\\v"'
,
code: 'foo = "#{foo}\\f"'
,
code: 'foo = "#{foo}\\\n"'
,
code: 'foo = "#{foo}\\\r\n"'
,
code: 'foo = "\\""'
,
code: 'foo = "\\"#{foo}\\""'
,
code: 'foo = "\\#{{#{foo}"'
,
code: 'foo = "#\\{{#{foo}"'
,
code: 'foo = String.raw"\\."'
,
code: 'foo = myFunc"\\."'
,
String.raw"foo = /[\d]/"
String.raw"foo = /[a\-b]/"
String.raw"foo = /foo\?/"
String.raw"foo = /example\.com/"
String.raw"foo = /foo\|bar/"
String.raw"foo = /\^bar/"
String.raw"foo = /[\^bar]/"
String.raw"foo = /\(bar\)/"
String.raw"foo = /[[\]]/" # A character class containing '[' and ']'
String.raw"foo = /[[]\./" # A character class containing '[', followed by a '.' character
String.raw"foo = /[\]\]]/" # A (redundant) character class containing ']'
String.raw"foo = /\[abc]/" # Matches the literal string '[abc]'
String.raw"foo = /\[foo\.bar]/" # Matches the literal string '[foo.bar]'
String.raw"foo = /vi/m"
String.raw"foo = /\B/"
String.raw"foo = /[\\/]/"
# https://github.com/eslint/eslint/issues/7472
String.raw"foo = /\0/" # null character
'foo = /\\1/' # \x01 character (octal literal)
'foo = /(a)\\1/' # backreference
'foo = /(a)\\12/' # backreference
'foo = /[\\0]/' # null character in character class
"foo = 'foo \\\u2028 bar'"
"foo = 'foo \\\u2029 bar'"
# https://github.com/eslint/eslint/issues/7789
String.raw"/]/"
String.raw"/\]/"
String.raw"/\]/u"
String.raw"foo = /foo\]/"
String.raw"foo = /[[]\]/" # A character class containing '[', followed by a ']' character
String.raw"foo = /\[foo\.bar\]/"
# ES2018
String.raw"foo = /(?<a>)\k<a>/"
String.raw"foo = /(\\?<a>)/"
String.raw"foo = /\p{ASCII}/u"
String.raw"foo = /\P{ASCII}/u"
String.raw"foo = /[\p{ASCII}]/u"
String.raw"foo = /[\P{ASCII}]/u"
'''
foo = """
\\"\\"\\"a\\"\\"\\"
"""
'''
"""
foo = '''
\\'\\'\\'a\\'\\'\\'
'''
"""
'''
"""""surrounded by two quotes"\\""""
'''
'''
/// [\\s] ///
'''
'''
/// #{a}[\\s] ///
'''
'''
"\\#{b}"
'''
'''
"#\\{b}"
'''
'''
/// \\#{b} ///
'''
'''
/// #\\{b} ///
'''
]
invalid: [
code: 'foo = /\\#/'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: 'foo = /\\;/'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\;.'
type: 'Literal'
]
,
code: 'foo = "\\\'"'
errors: [
line: 1
column: 8
message: "Unnecessary escape character: \\'."
type: 'Literal'
]
,
code: 'foo = "\\#/"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: 'foo = "\\`"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
]
,
code: 'foo = "\\a"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\a.'
type: 'Literal'
]
,
code: 'foo = "\\B"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\B.'
type: 'Literal'
]
,
code: 'foo = "\\@"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\@.'
type: 'Literal'
]
,
code: 'foo = "foo \\a bar"'
errors: [
line: 1
column: 12
message: 'Unnecessary escape character: \\a.'
type: 'Literal'
]
,
code: "foo = '\\\"'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\".'
type: 'Literal'
]
,
code: "foo = '\\#'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: "foo = '\\$'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\$.'
type: 'Literal'
]
,
code: "foo = '\\p'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\p.'
type: 'Literal'
]
,
code: "foo = '\\p\\a\\@'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\p.'
type: 'Literal'
,
line: 1
column: 10
message: 'Unnecessary escape character: \\a.'
type: 'Literal'
,
line: 1
column: 12
message: 'Unnecessary escape character: \\@.'
type: 'Literal'
]
,
code: '<foo attr={"\\d"}/>'
errors: [
line: 1
column: 13
message: 'Unnecessary escape character: \\d.'
type: 'Literal'
]
,
code: "foo = '\\`'"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
]
,
code: 'foo = "\\\'"'
errors: [
line: 1
column: 8
message: "Unnecessary escape character: \\'."
type: 'Literal'
]
,
code: '''
foo = '\\`foo\\`'
'''
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
,
line: 1
column: 13
message: 'Unnecessary escape character: \\`.'
type: 'Literal'
]
,
code: '''
foo = '\\"foo\\"'
'''
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\".'
type: 'Literal'
,
line: 1
column: 13
message: 'Unnecessary escape character: \\".'
type: 'Literal'
]
,
code: 'foo = "\\\'#{foo}\\\'"'
errors: [
line: 1
column: 8
message: "Unnecessary escape character: \\'."
type: 'TemplateElement'
,
line: 1
column: 16
message: "Unnecessary escape character: \\'."
type: 'TemplateElement'
]
,
code: "foo = '\\ '"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\ .'
type: 'Literal'
]
,
code: 'foo = /\\ /'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\ .'
type: 'Literal'
]
,
code: 'foo = "\\${{#{foo}"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\$.'
type: 'TemplateElement'
]
,
code: 'foo = "\\#a#{foo}"'
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\#.'
type: 'TemplateElement'
]
,
code: 'foo = "a\\{{#{foo}"'
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\{.'
type: 'TemplateElement'
]
,
code: String.raw"foo = /[ab\-]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[\-ab]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[ab\?]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\?.'
type: 'Literal'
]
,
code: String.raw"foo = /[ab\.]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\..'
type: 'Literal'
]
,
code: String.raw"foo = /[a\|b]/"
errors: [
line: 1
column: 10
message: 'Unnecessary escape character: \\|.'
type: 'Literal'
]
,
code: String.raw"foo = /\-/"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[\-]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[ab\$]/"
errors: [
line: 1
column: 11
message: 'Unnecessary escape character: \\$.'
type: 'Literal'
]
,
code: String.raw"foo = /[\(paren]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\(.'
type: 'Literal'
]
,
code: String.raw"foo = /[\[]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\[.'
type: 'Literal'
]
,
# ,
# code: String.raw"foo = /[\/]/" # A character class containing '/'
# errors: [
# line: 1
# column: 9
# message: 'Unnecessary escape character: \\/.'
# type: 'Literal'
# ]
code: String.raw"foo = /[\B]/"
errors: [
line: 1
column: 9
message: 'Unnecessary escape character: \\B.'
type: 'Literal'
]
,
code: String.raw"foo = /[a][\-b]/"
errors: [
line: 1
column: 12
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /\-[]/"
errors: [
line: 1
column: 8
message: 'Unnecessary escape character: \\-.'
type: 'Literal'
]
,
code: String.raw"foo = /[a\^]/"
errors: [
line: 1
column: 10
message: 'Unnecessary escape character: \\^.'
type: 'Literal'
]
,
code: '"multiline template\nliteral with useless \\escape"'
errors: [
line: 2
column: 22
message: 'Unnecessary escape character: \\e.'
type: 'Literal'
]
,
# ,
# code: '"\\a"""'
# errors: [
# line: 1
# column: 2
# message: 'Unnecessary escape character: \\a.'
# type: 'TemplateElement'
# ]
code: """
foo = '''
\\"
'''
"""
errors: [
line: 2
column: 3
message: 'Unnecessary escape character: \\".'
type: 'TemplateElement'
]
,
code: """
foo = '''
\\'
'''
"""
errors: [
line: 2
column: 3
message: "Unnecessary escape character: \\'."
type: 'TemplateElement'
]
,
code: '''
foo = """
\\"
"""
'''
errors: [
line: 2
column: 3
message: 'Unnecessary escape character: \\".'
type: 'TemplateElement'
]
,
code: '''
'\\#{b}'
'''
errors: [
line: 1
column: 2
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
,
code: '''
/\\#{b}/
'''
errors: [
line: 1
column: 2
message: 'Unnecessary escape character: \\#.'
type: 'Literal'
]
# ,
# code: '''
# ok ///\\\u2028///.test '\\u2028'
# ok ///\\"///.test '"'
# '''
# errors: [
# line: 2
# # column: 8
# message: 'Unnecessary escape character: \\".'
# type: 'Literal'
# ]
]
|
[
{
"context": "e(_pool)\r\n note.number = number\r\n note.key = _key[number]\r\n note.destinationY = -_height + _fall",
"end": 4422,
"score": 0.7705748081207275,
"start": 4418,
"tag": "KEY",
"value": "_key"
},
{
"context": "l)\r\n note.number = number\r\n note.key = _ke... | js/main.coffee | bokuweb/app.flavabeats | 7 | class @Game
_endTime = 90
_game = null
_status = "stop"
_score =
board : null
val : 0
_note = null
_loadCallback = null
_endCallback = null
_startCallback = null
_hasLoaded = false
_log =
key : []
timing : []
constructor : -> enchant()
start : (music, loadCallback, startCallback, endCallback)->
_loadCallback = loadCallback
_startCallback = startCallback
_endCallback = endCallback
_game = new Core 980, 600
_game.fps = 60
_game.preload g_resouces...
_game.preload music.src, music.img
_game.start()
_game.onload = ->
_endTime = music.endTime
_game.music = _game.assets[music.src]
_score.board = new Score(
game : _game
offsetX : 20
offsetY : 360
url : g_res.score
num : 6
width: 36
height: 49.7
)
_score.board.init()
_score.val = 0
_note = new Note _game, music.note, _judgeEndCallback
_note.init()
_game.rootScene.addEventListener "enterframe", ->
if _status is "playing"
_note.create()
_endGameIfTimeOver()
_loadCallback()
_hasLoaded = true
_mainLoop = ->
if _status is "playing"
_note.create()
_endGameIfTimeOver()
_judgeEndCallback = (judge)->
if judge is "Great" then _score.val += 100000 / _note.getNum()
else if judge is "Good" then _score.val += 70000 / _note.getNum()
if _score.val > 100000 then _score.val = 100000
_score.board.update Math.ceil(_score.val)
_endGameIfTimeOver = ->
music = _game.music
if music.currentTime >= _endTime or music.duration <= music.currentTime
if music.volume - 0.005 < 0 then music.volume = 0 else music.volume -= 0.005
if music.volume <= 0
music.volume = 1
music.currentTime = 0
music.stop()
_status = "stop"
console.log _log.key
console.log _log.timing
_endCallback(Math.ceil(_score.val), _log)
# keydown event detected
document.addEventListener "keydown", (e)->
music = _game.music
if _status is "stop"
if _hasLoaded
if e.keyCode is 13
_startCallback()
_status = "playing"
setTimeout ()->
music.play()
, 1000
else if _status = "playing" then code = _note.seek(e.keyCode)
if 0 <= code <= 4
_log.key.push code
_log.timing.push _game.music.currentTime
class Note
NOTE_MARGIN_RIGHT = 20
NOTE_OFFSET_X = 480
JUDGE_LABEL_X = 500
JUDGE_LABEL_Y = 280
_game = null
_pool = []
_fallDist = 550
_width = 64
_height = 64
_index = 0
_group = null
_timing = []
_key = []
_speed = 0
_cb = null
_threshold =
great : 0.15
good : 0.3
constructor : (game, params, cb)->
_game = game
_timing = params.timing
_key = params.key
_speed = params.speed
_cb = cb
init : ->
_group = new Group()
_index = 0
_renderDist()
_preAllocate()
_game.rootScene.addChild(_group)
create : ->
if _timing[_index]?
if _game.music.currentTime > (_timing[_index] - (_fallDist / _speed)) then _gen(_index++)
seek : (keyCode)->
switch keyCode
when 90 then code = 0 # Z
when 88 then code = 1 # X
when 67 then code = 2 # C
when 86 then code = 3 # V
when 66 then code = 4 # B
else code = null
for value in _group.childNodes
if value.key is code
if -1 < value.timing - _game.music.currentTime < 1
value.clear = true
value.clearTime = _game.music.currentTime
break
return code
getNum : -> _timing.length
_renderDist = ->
for i in [0...5]
noteDist = new Sprite(_width, _height)
noteDist.y = -_height + _fallDist
noteDist.opacity = 0.6
noteDist.x = i * (_width + NOTE_MARGIN_RIGHT) + NOTE_OFFSET_X
noteDist.image = _game.assets[g_res.noteDist]
_game.rootScene.addChild(noteDist)
return
_preAllocate = ->
for v in _timing
note = new Sprite(_width, _height)
note.image = _game.assets[g_res.note]
GameSys.poolSprite(_pool, note)
return
_gen = (number)->
note = GameSys.getSprite(_pool)
note.number = number
note.key = _key[number]
note.destinationY = -_height + _fallDist
note.y = -_height
note.x = note.key * (note.width + NOTE_MARGIN_RIGHT) + NOTE_OFFSET_X
note.frame = 0
note.timing = _timing[number]
note.clear = false
note.opacity = 1
note.scale = 1
note.tl.clear()
note.tl.setTimeBased()
note.tl.scaleTo(1, 1, 0)
note.hasClearAnimationStarted = false
_group.addChild(note)
note.addEventListener "enterframe", _schedule
_schedule = ->
music = _game.music
@y = @destinationY - ((@timing - music.currentTime)*_speed)
@y = @destinationY if @y > @destinationY
if @oldtime?
@rotate((music.currentTime - @oldtime) * 500)
@oldtime = music.currentTime
if _timing[@number] - music.currentTime < -0.3 and not @clear
@tl.clear()
@tl.fadeOut(100).then ()-> _group.removeChild(@)
if @clear and not @hasClearAnimationStarted
@tl.clear()
@tl.scaleTo(1.5, 1.5, 200).and().fadeOut(200).then ()-> _group.removeChild(@)
diffTime = _timing[@number] - @clearTime
judgement = _judge(diffTime)
@hasClearAnimationStarted = true
_judge = (diffTime)->
if -_threshold.great < diffTime < _threshold.great then judge = "Great"
else if -_threshold.good < diffTime < _threshold.good then judge = "Good"
else judge = "Bad"
judgeLabel = new Label(judge)
judgeLabel.x = JUDGE_LABEL_X
judgeLabel.y = JUDGE_LABEL_Y
judgeLabel.font = "bold 32px 'Quicksand'"
_game.rootScene.addChild(judgeLabel)
judgeLabel.tl.setTimeBased()
judgeLabel.tl.fadeOut(500).and().moveY(240, 500).then ()-> _game.rootScene.removeChild(judgeLabel)
_cb(judge)
class Score
_group = null
_real = 0
_display = 0
constructor : (parms)->
for name, value of parms
@[name] = value
init : ->
i = 0
_group = new Group()
while i < @num
score = new Sprite(@width, @height)
score.image = @game.assets[@url]
score.frame = i
score.x = @offsetX + score.width * i
score.y = @offsetY
_group.addChild(score)
i++
@game.rootScene.addChild(_group)
@update 0
update : (score)->
base = Math.pow(10, @num - 1)
for value in _group.childNodes
value.frame = ~~(score / base)
score = score % base
base = base / 10
class GameSys
@getSprite : (pool)->
for value, i in pool
unless value.active
value.active = true
return value
console.log "error sprite pool empty"
return false
@poolSprite : (pool, sprite)->
pool.push(sprite)
sprite.active = false
if sprite.addEventListener
sprite.addEventListener "removed", ()->
@clearEventListener "enterframe"
@active = false
| 160118 | class @Game
_endTime = 90
_game = null
_status = "stop"
_score =
board : null
val : 0
_note = null
_loadCallback = null
_endCallback = null
_startCallback = null
_hasLoaded = false
_log =
key : []
timing : []
constructor : -> enchant()
start : (music, loadCallback, startCallback, endCallback)->
_loadCallback = loadCallback
_startCallback = startCallback
_endCallback = endCallback
_game = new Core 980, 600
_game.fps = 60
_game.preload g_resouces...
_game.preload music.src, music.img
_game.start()
_game.onload = ->
_endTime = music.endTime
_game.music = _game.assets[music.src]
_score.board = new Score(
game : _game
offsetX : 20
offsetY : 360
url : g_res.score
num : 6
width: 36
height: 49.7
)
_score.board.init()
_score.val = 0
_note = new Note _game, music.note, _judgeEndCallback
_note.init()
_game.rootScene.addEventListener "enterframe", ->
if _status is "playing"
_note.create()
_endGameIfTimeOver()
_loadCallback()
_hasLoaded = true
_mainLoop = ->
if _status is "playing"
_note.create()
_endGameIfTimeOver()
_judgeEndCallback = (judge)->
if judge is "Great" then _score.val += 100000 / _note.getNum()
else if judge is "Good" then _score.val += 70000 / _note.getNum()
if _score.val > 100000 then _score.val = 100000
_score.board.update Math.ceil(_score.val)
_endGameIfTimeOver = ->
music = _game.music
if music.currentTime >= _endTime or music.duration <= music.currentTime
if music.volume - 0.005 < 0 then music.volume = 0 else music.volume -= 0.005
if music.volume <= 0
music.volume = 1
music.currentTime = 0
music.stop()
_status = "stop"
console.log _log.key
console.log _log.timing
_endCallback(Math.ceil(_score.val), _log)
# keydown event detected
document.addEventListener "keydown", (e)->
music = _game.music
if _status is "stop"
if _hasLoaded
if e.keyCode is 13
_startCallback()
_status = "playing"
setTimeout ()->
music.play()
, 1000
else if _status = "playing" then code = _note.seek(e.keyCode)
if 0 <= code <= 4
_log.key.push code
_log.timing.push _game.music.currentTime
class Note
NOTE_MARGIN_RIGHT = 20
NOTE_OFFSET_X = 480
JUDGE_LABEL_X = 500
JUDGE_LABEL_Y = 280
_game = null
_pool = []
_fallDist = 550
_width = 64
_height = 64
_index = 0
_group = null
_timing = []
_key = []
_speed = 0
_cb = null
_threshold =
great : 0.15
good : 0.3
constructor : (game, params, cb)->
_game = game
_timing = params.timing
_key = params.key
_speed = params.speed
_cb = cb
init : ->
_group = new Group()
_index = 0
_renderDist()
_preAllocate()
_game.rootScene.addChild(_group)
create : ->
if _timing[_index]?
if _game.music.currentTime > (_timing[_index] - (_fallDist / _speed)) then _gen(_index++)
seek : (keyCode)->
switch keyCode
when 90 then code = 0 # Z
when 88 then code = 1 # X
when 67 then code = 2 # C
when 86 then code = 3 # V
when 66 then code = 4 # B
else code = null
for value in _group.childNodes
if value.key is code
if -1 < value.timing - _game.music.currentTime < 1
value.clear = true
value.clearTime = _game.music.currentTime
break
return code
getNum : -> _timing.length
_renderDist = ->
for i in [0...5]
noteDist = new Sprite(_width, _height)
noteDist.y = -_height + _fallDist
noteDist.opacity = 0.6
noteDist.x = i * (_width + NOTE_MARGIN_RIGHT) + NOTE_OFFSET_X
noteDist.image = _game.assets[g_res.noteDist]
_game.rootScene.addChild(noteDist)
return
_preAllocate = ->
for v in _timing
note = new Sprite(_width, _height)
note.image = _game.assets[g_res.note]
GameSys.poolSprite(_pool, note)
return
_gen = (number)->
note = GameSys.getSprite(_pool)
note.number = number
note.key = <KEY>[<KEY>
note.destinationY = -_height + _fallDist
note.y = -_height
note.x = note.key * (note.width + NOTE_MARGIN_RIGHT) + NOTE_OFFSET_X
note.frame = 0
note.timing = _timing[number]
note.clear = false
note.opacity = 1
note.scale = 1
note.tl.clear()
note.tl.setTimeBased()
note.tl.scaleTo(1, 1, 0)
note.hasClearAnimationStarted = false
_group.addChild(note)
note.addEventListener "enterframe", _schedule
_schedule = ->
music = _game.music
@y = @destinationY - ((@timing - music.currentTime)*_speed)
@y = @destinationY if @y > @destinationY
if @oldtime?
@rotate((music.currentTime - @oldtime) * 500)
@oldtime = music.currentTime
if _timing[@number] - music.currentTime < -0.3 and not @clear
@tl.clear()
@tl.fadeOut(100).then ()-> _group.removeChild(@)
if @clear and not @hasClearAnimationStarted
@tl.clear()
@tl.scaleTo(1.5, 1.5, 200).and().fadeOut(200).then ()-> _group.removeChild(@)
diffTime = _timing[@number] - @clearTime
judgement = _judge(diffTime)
@hasClearAnimationStarted = true
_judge = (diffTime)->
if -_threshold.great < diffTime < _threshold.great then judge = "Great"
else if -_threshold.good < diffTime < _threshold.good then judge = "Good"
else judge = "Bad"
judgeLabel = new Label(judge)
judgeLabel.x = JUDGE_LABEL_X
judgeLabel.y = JUDGE_LABEL_Y
judgeLabel.font = "bold 32px 'Quicksand'"
_game.rootScene.addChild(judgeLabel)
judgeLabel.tl.setTimeBased()
judgeLabel.tl.fadeOut(500).and().moveY(240, 500).then ()-> _game.rootScene.removeChild(judgeLabel)
_cb(judge)
class Score
_group = null
_real = 0
_display = 0
constructor : (parms)->
for name, value of parms
@[name] = value
init : ->
i = 0
_group = new Group()
while i < @num
score = new Sprite(@width, @height)
score.image = @game.assets[@url]
score.frame = i
score.x = @offsetX + score.width * i
score.y = @offsetY
_group.addChild(score)
i++
@game.rootScene.addChild(_group)
@update 0
update : (score)->
base = Math.pow(10, @num - 1)
for value in _group.childNodes
value.frame = ~~(score / base)
score = score % base
base = base / 10
class GameSys
@getSprite : (pool)->
for value, i in pool
unless value.active
value.active = true
return value
console.log "error sprite pool empty"
return false
@poolSprite : (pool, sprite)->
pool.push(sprite)
sprite.active = false
if sprite.addEventListener
sprite.addEventListener "removed", ()->
@clearEventListener "enterframe"
@active = false
| true | class @Game
_endTime = 90
_game = null
_status = "stop"
_score =
board : null
val : 0
_note = null
_loadCallback = null
_endCallback = null
_startCallback = null
_hasLoaded = false
_log =
key : []
timing : []
constructor : -> enchant()
start : (music, loadCallback, startCallback, endCallback)->
_loadCallback = loadCallback
_startCallback = startCallback
_endCallback = endCallback
_game = new Core 980, 600
_game.fps = 60
_game.preload g_resouces...
_game.preload music.src, music.img
_game.start()
_game.onload = ->
_endTime = music.endTime
_game.music = _game.assets[music.src]
_score.board = new Score(
game : _game
offsetX : 20
offsetY : 360
url : g_res.score
num : 6
width: 36
height: 49.7
)
_score.board.init()
_score.val = 0
_note = new Note _game, music.note, _judgeEndCallback
_note.init()
_game.rootScene.addEventListener "enterframe", ->
if _status is "playing"
_note.create()
_endGameIfTimeOver()
_loadCallback()
_hasLoaded = true
_mainLoop = ->
if _status is "playing"
_note.create()
_endGameIfTimeOver()
_judgeEndCallback = (judge)->
if judge is "Great" then _score.val += 100000 / _note.getNum()
else if judge is "Good" then _score.val += 70000 / _note.getNum()
if _score.val > 100000 then _score.val = 100000
_score.board.update Math.ceil(_score.val)
_endGameIfTimeOver = ->
music = _game.music
if music.currentTime >= _endTime or music.duration <= music.currentTime
if music.volume - 0.005 < 0 then music.volume = 0 else music.volume -= 0.005
if music.volume <= 0
music.volume = 1
music.currentTime = 0
music.stop()
_status = "stop"
console.log _log.key
console.log _log.timing
_endCallback(Math.ceil(_score.val), _log)
# keydown event detected
document.addEventListener "keydown", (e)->
music = _game.music
if _status is "stop"
if _hasLoaded
if e.keyCode is 13
_startCallback()
_status = "playing"
setTimeout ()->
music.play()
, 1000
else if _status = "playing" then code = _note.seek(e.keyCode)
if 0 <= code <= 4
_log.key.push code
_log.timing.push _game.music.currentTime
class Note
NOTE_MARGIN_RIGHT = 20
NOTE_OFFSET_X = 480
JUDGE_LABEL_X = 500
JUDGE_LABEL_Y = 280
_game = null
_pool = []
_fallDist = 550
_width = 64
_height = 64
_index = 0
_group = null
_timing = []
_key = []
_speed = 0
_cb = null
_threshold =
great : 0.15
good : 0.3
constructor : (game, params, cb)->
_game = game
_timing = params.timing
_key = params.key
_speed = params.speed
_cb = cb
init : ->
_group = new Group()
_index = 0
_renderDist()
_preAllocate()
_game.rootScene.addChild(_group)
create : ->
if _timing[_index]?
if _game.music.currentTime > (_timing[_index] - (_fallDist / _speed)) then _gen(_index++)
seek : (keyCode)->
switch keyCode
when 90 then code = 0 # Z
when 88 then code = 1 # X
when 67 then code = 2 # C
when 86 then code = 3 # V
when 66 then code = 4 # B
else code = null
for value in _group.childNodes
if value.key is code
if -1 < value.timing - _game.music.currentTime < 1
value.clear = true
value.clearTime = _game.music.currentTime
break
return code
getNum : -> _timing.length
_renderDist = ->
for i in [0...5]
noteDist = new Sprite(_width, _height)
noteDist.y = -_height + _fallDist
noteDist.opacity = 0.6
noteDist.x = i * (_width + NOTE_MARGIN_RIGHT) + NOTE_OFFSET_X
noteDist.image = _game.assets[g_res.noteDist]
_game.rootScene.addChild(noteDist)
return
_preAllocate = ->
for v in _timing
note = new Sprite(_width, _height)
note.image = _game.assets[g_res.note]
GameSys.poolSprite(_pool, note)
return
_gen = (number)->
note = GameSys.getSprite(_pool)
note.number = number
note.key = PI:KEY:<KEY>END_PI[PI:KEY:<KEY>END_PI
note.destinationY = -_height + _fallDist
note.y = -_height
note.x = note.key * (note.width + NOTE_MARGIN_RIGHT) + NOTE_OFFSET_X
note.frame = 0
note.timing = _timing[number]
note.clear = false
note.opacity = 1
note.scale = 1
note.tl.clear()
note.tl.setTimeBased()
note.tl.scaleTo(1, 1, 0)
note.hasClearAnimationStarted = false
_group.addChild(note)
note.addEventListener "enterframe", _schedule
_schedule = ->
music = _game.music
@y = @destinationY - ((@timing - music.currentTime)*_speed)
@y = @destinationY if @y > @destinationY
if @oldtime?
@rotate((music.currentTime - @oldtime) * 500)
@oldtime = music.currentTime
if _timing[@number] - music.currentTime < -0.3 and not @clear
@tl.clear()
@tl.fadeOut(100).then ()-> _group.removeChild(@)
if @clear and not @hasClearAnimationStarted
@tl.clear()
@tl.scaleTo(1.5, 1.5, 200).and().fadeOut(200).then ()-> _group.removeChild(@)
diffTime = _timing[@number] - @clearTime
judgement = _judge(diffTime)
@hasClearAnimationStarted = true
_judge = (diffTime)->
if -_threshold.great < diffTime < _threshold.great then judge = "Great"
else if -_threshold.good < diffTime < _threshold.good then judge = "Good"
else judge = "Bad"
judgeLabel = new Label(judge)
judgeLabel.x = JUDGE_LABEL_X
judgeLabel.y = JUDGE_LABEL_Y
judgeLabel.font = "bold 32px 'Quicksand'"
_game.rootScene.addChild(judgeLabel)
judgeLabel.tl.setTimeBased()
judgeLabel.tl.fadeOut(500).and().moveY(240, 500).then ()-> _game.rootScene.removeChild(judgeLabel)
_cb(judge)
class Score
_group = null
_real = 0
_display = 0
constructor : (parms)->
for name, value of parms
@[name] = value
init : ->
i = 0
_group = new Group()
while i < @num
score = new Sprite(@width, @height)
score.image = @game.assets[@url]
score.frame = i
score.x = @offsetX + score.width * i
score.y = @offsetY
_group.addChild(score)
i++
@game.rootScene.addChild(_group)
@update 0
update : (score)->
base = Math.pow(10, @num - 1)
for value in _group.childNodes
value.frame = ~~(score / base)
score = score % base
base = base / 10
class GameSys
@getSprite : (pool)->
for value, i in pool
unless value.active
value.active = true
return value
console.log "error sprite pool empty"
return false
@poolSprite : (pool, sprite)->
pool.push(sprite)
sprite.active = false
if sprite.addEventListener
sprite.addEventListener "removed", ()->
@clearEventListener "enterframe"
@active = false
|
[
{
"context": ".account-picker .compose-from').trim(), 'DoveCot <me@cozytest.cc>', 'Account selected'\n else\n ",
"end": 1288,
"score": 0.9998947978019714,
"start": 1274,
"tag": "EMAIL",
"value": "me@cozytest.cc"
},
{
"context": ".account-picker .compose-from').tri... | client/tests/casper/full/draft.coffee | cozy-labs/emails | 58 | if global?
require = patchRequire global.require
else
require = patchRequire this.require
require.globals.casper = casper
init = require(fs.workingDirectory + "/client/tests/casper/common").init
utils = require "utils.js"
initSettings = ->
casper.evaluate ->
settings =
"composeInHTML": true
"composeOnTop": false
"displayConversation": true
"displayPreview":true
"layoutStyle":"three"
"messageConfirmDelete":false
window.cozyMails.setSetting settings
casper.test.begin 'Test draft', (test) ->
init casper
messageID = ''
messageSubject = "My draft subject #{new Date().toUTCString()}"
casper.start casper.cozy.startUrl, ->
test.comment "Compose Draft"
casper.waitForSelector "aside[role=menubar][aria-expanded=true]"
casper.then ->
test.comment "Compose Account"
casper.click ".compose-action"
casper.waitForSelector ".form-compose .rt-editor", ->
casper.waitWhileSelector '.composeToolbox .button-spinner', ->
if casper.exists '.compose-from [data-value="dovecot-ID"]'
test.assertEquals casper.fetchText('.account-picker .compose-from').trim(), 'DoveCot <me@cozytest.cc>', 'Account selected'
else
casper.click '.account-picker .caret'
casper.waitUntilVisible '.account-picker .dropdown-menu', ->
test.pass 'Account picker displayed'
casper.click '.account-picker .dropdown-menu [data-value="dovecot-ID"]', ->
casper.waitForSelector '.compose-from [data-value="dovecot-ID"]', ->
test.assertEquals casper.fetchText('.account-picker .compose-from').trim(), 'DoveCot <me@cozytest.cc>', 'Account selected'
casper.then ->
test.comment "Compose message"
casper.click '.form-compose .compose-toggle-cc'
casper.click '.form-compose .compose-toggle-bcc'
casper.fillSelectors 'form',
"#compose-subject": messageSubject,
casper.sendKeys "#compose-bcc", "bcc@cozy.io,",
casper.sendKeys "#compose-cc", "cc@cozy.io,",
casper.sendKeys "#compose-to", "to@cozy.io,"
casper.evaluate ->
editor = document.querySelector('.rt-editor')
editor.innerHTML = "<div><em>Hello,</em><br>Join us now and share the software</div>"
evt = document.createEvent 'HTMLEvents'
evt.initEvent 'input', true, true
editor.dispatchEvent evt
casper.click '.composeToolbox .btn-save'
casper.waitForSelector '.composeToolbox .button-spinner', ->
casper.waitWhileSelector '.composeToolbox .button-spinner', ->
message = casper.evaluate ->
window.cozyMails.getCurrentMessage()
messageID = message.id
test.pass "Message '#{message.subject}' is saved: #{messageID}"
casper.then ->
test.comment "Leave compose"
#initSettings()
casper.cozy.selectAccount "DoveCot", 'Draft', ->
casper.waitUntilVisible '.modal-dialog', ->
confirm = casper.fetchText('.modal-body').trim()
test.assertEquals confirm, "Message not sent, keep the draft?", "Confirmation dialog"
casper.click ".modal-dialog .btn.modal-close"
casper.waitWhileVisible '.modal-dialog'
casper.then ->
test.comment "Edit draft"
#initSettings()
casper.cozy.selectMessage "DoveCot", "Draft", messageSubject, messageID, ->
casper.waitForSelector ".form-compose .rt-editor", ->
test.assertExists '.form-compose', 'Compose form is displayed'
values = casper.getFormValues('.form-compose')
test.assertEquals casper.fetchText(".compose-bcc .address-tag"), "bcc@cozy.io", "Bcc dests"
test.assertEquals casper.fetchText(".compose-cc .address-tag"), "cc@cozy.io", "Cc dests"
test.assertEquals casper.fetchText(".compose-to .address-tag"), "to@cozy.io", "To dests"
test.assertEquals values["compose-subject"], messageSubject, "Subject"
test.assertEquals casper.fetchText('.rt-editor'), "\nHello,Join us now and share the software", "message HTML"
message = casper.evaluate ->
return window.cozyMails.getCurrentMessage()
test.assertEquals message.text, "_Hello,_\nJoin us now and share the software", "messageText"
casper.click '.composeToolbox .btn-delete'
casper.waitUntilVisible '.modal-dialog', ->
confirm = casper.fetchText('.modal-body').trim()
test.assertEquals confirm, "Do you really want to delete message “#{messageSubject}”?", "Confirmation dialog"
casper.click ".modal-dialog .btn.modal-action"
casper.waitWhileSelector ".form-compose h3[data-message-id=#{messageID}]", ->
test.pass 'Compose closed'
if casper.getEngine() is 'slimer'
# delete doesn't work in PhantomJs
casper.waitWhileSelector "li.message[data-message-id='#{messageID}']", ->
test.pass "message deleted"
casper.reload ->
test.assertDoesntExist "li.message[data-message-id='#{messageID}']", "message really deleted"
casper.run ->
test.done()
| 174622 | if global?
require = patchRequire global.require
else
require = patchRequire this.require
require.globals.casper = casper
init = require(fs.workingDirectory + "/client/tests/casper/common").init
utils = require "utils.js"
initSettings = ->
casper.evaluate ->
settings =
"composeInHTML": true
"composeOnTop": false
"displayConversation": true
"displayPreview":true
"layoutStyle":"three"
"messageConfirmDelete":false
window.cozyMails.setSetting settings
casper.test.begin 'Test draft', (test) ->
init casper
messageID = ''
messageSubject = "My draft subject #{new Date().toUTCString()}"
casper.start casper.cozy.startUrl, ->
test.comment "Compose Draft"
casper.waitForSelector "aside[role=menubar][aria-expanded=true]"
casper.then ->
test.comment "Compose Account"
casper.click ".compose-action"
casper.waitForSelector ".form-compose .rt-editor", ->
casper.waitWhileSelector '.composeToolbox .button-spinner', ->
if casper.exists '.compose-from [data-value="dovecot-ID"]'
test.assertEquals casper.fetchText('.account-picker .compose-from').trim(), 'DoveCot <<EMAIL>>', 'Account selected'
else
casper.click '.account-picker .caret'
casper.waitUntilVisible '.account-picker .dropdown-menu', ->
test.pass 'Account picker displayed'
casper.click '.account-picker .dropdown-menu [data-value="dovecot-ID"]', ->
casper.waitForSelector '.compose-from [data-value="dovecot-ID"]', ->
test.assertEquals casper.fetchText('.account-picker .compose-from').trim(), 'DoveCot <<EMAIL>>', 'Account selected'
casper.then ->
test.comment "Compose message"
casper.click '.form-compose .compose-toggle-cc'
casper.click '.form-compose .compose-toggle-bcc'
casper.fillSelectors 'form',
"#compose-subject": messageSubject,
casper.sendKeys "#compose-bcc", "<EMAIL>,",
casper.sendKeys "#compose-cc", "<EMAIL>,",
casper.sendKeys "#compose-to", "<EMAIL>,"
casper.evaluate ->
editor = document.querySelector('.rt-editor')
editor.innerHTML = "<div><em>Hello,</em><br>Join us now and share the software</div>"
evt = document.createEvent 'HTMLEvents'
evt.initEvent 'input', true, true
editor.dispatchEvent evt
casper.click '.composeToolbox .btn-save'
casper.waitForSelector '.composeToolbox .button-spinner', ->
casper.waitWhileSelector '.composeToolbox .button-spinner', ->
message = casper.evaluate ->
window.cozyMails.getCurrentMessage()
messageID = message.id
test.pass "Message '#{message.subject}' is saved: #{messageID}"
casper.then ->
test.comment "Leave compose"
#initSettings()
casper.cozy.selectAccount "DoveCot", 'Draft', ->
casper.waitUntilVisible '.modal-dialog', ->
confirm = casper.fetchText('.modal-body').trim()
test.assertEquals confirm, "Message not sent, keep the draft?", "Confirmation dialog"
casper.click ".modal-dialog .btn.modal-close"
casper.waitWhileVisible '.modal-dialog'
casper.then ->
test.comment "Edit draft"
#initSettings()
casper.cozy.selectMessage "DoveCot", "Draft", messageSubject, messageID, ->
casper.waitForSelector ".form-compose .rt-editor", ->
test.assertExists '.form-compose', 'Compose form is displayed'
values = casper.getFormValues('.form-compose')
test.assertEquals casper.fetchText(".compose-bcc .address-tag"), "<EMAIL>", "Bcc dests"
test.assertEquals casper.fetchText(".compose-cc .address-tag"), "<EMAIL>", "Cc dests"
test.assertEquals casper.fetchText(".compose-to .address-tag"), "to<EMAIL>", "To dests"
test.assertEquals values["compose-subject"], messageSubject, "Subject"
test.assertEquals casper.fetchText('.rt-editor'), "\nHello,Join us now and share the software", "message HTML"
message = casper.evaluate ->
return window.cozyMails.getCurrentMessage()
test.assertEquals message.text, "_Hello,_\nJoin us now and share the software", "messageText"
casper.click '.composeToolbox .btn-delete'
casper.waitUntilVisible '.modal-dialog', ->
confirm = casper.fetchText('.modal-body').trim()
test.assertEquals confirm, "Do you really want to delete message “#{messageSubject}”?", "Confirmation dialog"
casper.click ".modal-dialog .btn.modal-action"
casper.waitWhileSelector ".form-compose h3[data-message-id=#{messageID}]", ->
test.pass 'Compose closed'
if casper.getEngine() is 'slimer'
# delete doesn't work in PhantomJs
casper.waitWhileSelector "li.message[data-message-id='#{messageID}']", ->
test.pass "message deleted"
casper.reload ->
test.assertDoesntExist "li.message[data-message-id='#{messageID}']", "message really deleted"
casper.run ->
test.done()
| true | if global?
require = patchRequire global.require
else
require = patchRequire this.require
require.globals.casper = casper
init = require(fs.workingDirectory + "/client/tests/casper/common").init
utils = require "utils.js"
initSettings = ->
casper.evaluate ->
settings =
"composeInHTML": true
"composeOnTop": false
"displayConversation": true
"displayPreview":true
"layoutStyle":"three"
"messageConfirmDelete":false
window.cozyMails.setSetting settings
casper.test.begin 'Test draft', (test) ->
init casper
messageID = ''
messageSubject = "My draft subject #{new Date().toUTCString()}"
casper.start casper.cozy.startUrl, ->
test.comment "Compose Draft"
casper.waitForSelector "aside[role=menubar][aria-expanded=true]"
casper.then ->
test.comment "Compose Account"
casper.click ".compose-action"
casper.waitForSelector ".form-compose .rt-editor", ->
casper.waitWhileSelector '.composeToolbox .button-spinner', ->
if casper.exists '.compose-from [data-value="dovecot-ID"]'
test.assertEquals casper.fetchText('.account-picker .compose-from').trim(), 'DoveCot <PI:EMAIL:<EMAIL>END_PI>', 'Account selected'
else
casper.click '.account-picker .caret'
casper.waitUntilVisible '.account-picker .dropdown-menu', ->
test.pass 'Account picker displayed'
casper.click '.account-picker .dropdown-menu [data-value="dovecot-ID"]', ->
casper.waitForSelector '.compose-from [data-value="dovecot-ID"]', ->
test.assertEquals casper.fetchText('.account-picker .compose-from').trim(), 'DoveCot <PI:EMAIL:<EMAIL>END_PI>', 'Account selected'
casper.then ->
test.comment "Compose message"
casper.click '.form-compose .compose-toggle-cc'
casper.click '.form-compose .compose-toggle-bcc'
casper.fillSelectors 'form',
"#compose-subject": messageSubject,
casper.sendKeys "#compose-bcc", "PI:EMAIL:<EMAIL>END_PI,",
casper.sendKeys "#compose-cc", "PI:EMAIL:<EMAIL>END_PI,",
casper.sendKeys "#compose-to", "PI:EMAIL:<EMAIL>END_PI,"
casper.evaluate ->
editor = document.querySelector('.rt-editor')
editor.innerHTML = "<div><em>Hello,</em><br>Join us now and share the software</div>"
evt = document.createEvent 'HTMLEvents'
evt.initEvent 'input', true, true
editor.dispatchEvent evt
casper.click '.composeToolbox .btn-save'
casper.waitForSelector '.composeToolbox .button-spinner', ->
casper.waitWhileSelector '.composeToolbox .button-spinner', ->
message = casper.evaluate ->
window.cozyMails.getCurrentMessage()
messageID = message.id
test.pass "Message '#{message.subject}' is saved: #{messageID}"
casper.then ->
test.comment "Leave compose"
#initSettings()
casper.cozy.selectAccount "DoveCot", 'Draft', ->
casper.waitUntilVisible '.modal-dialog', ->
confirm = casper.fetchText('.modal-body').trim()
test.assertEquals confirm, "Message not sent, keep the draft?", "Confirmation dialog"
casper.click ".modal-dialog .btn.modal-close"
casper.waitWhileVisible '.modal-dialog'
casper.then ->
test.comment "Edit draft"
#initSettings()
casper.cozy.selectMessage "DoveCot", "Draft", messageSubject, messageID, ->
casper.waitForSelector ".form-compose .rt-editor", ->
test.assertExists '.form-compose', 'Compose form is displayed'
values = casper.getFormValues('.form-compose')
test.assertEquals casper.fetchText(".compose-bcc .address-tag"), "PI:EMAIL:<EMAIL>END_PI", "Bcc dests"
test.assertEquals casper.fetchText(".compose-cc .address-tag"), "PI:EMAIL:<EMAIL>END_PI", "Cc dests"
test.assertEquals casper.fetchText(".compose-to .address-tag"), "toPI:EMAIL:<EMAIL>END_PI", "To dests"
test.assertEquals values["compose-subject"], messageSubject, "Subject"
test.assertEquals casper.fetchText('.rt-editor'), "\nHello,Join us now and share the software", "message HTML"
message = casper.evaluate ->
return window.cozyMails.getCurrentMessage()
test.assertEquals message.text, "_Hello,_\nJoin us now and share the software", "messageText"
casper.click '.composeToolbox .btn-delete'
casper.waitUntilVisible '.modal-dialog', ->
confirm = casper.fetchText('.modal-body').trim()
test.assertEquals confirm, "Do you really want to delete message “#{messageSubject}”?", "Confirmation dialog"
casper.click ".modal-dialog .btn.modal-action"
casper.waitWhileSelector ".form-compose h3[data-message-id=#{messageID}]", ->
test.pass 'Compose closed'
if casper.getEngine() is 'slimer'
# delete doesn't work in PhantomJs
casper.waitWhileSelector "li.message[data-message-id='#{messageID}']", ->
test.pass "message deleted"
casper.reload ->
test.assertDoesntExist "li.message[data-message-id='#{messageID}']", "message really deleted"
casper.run ->
test.done()
|
[
{
"context": "###################################\n#\n# Created by Markus\n#\n###############################################",
"end": 77,
"score": 0.9988744258880615,
"start": 71,
"tag": "NAME",
"value": "Markus"
}
] | server/methods/post.coffee | agottschalk10/worklearn | 0 | #######################################################
#
# Created by Markus
#
#######################################################
################################################################
Meteor.methods
add_post: (template_id, parent_id, group_name, index) ->
user = Meteor.user()
if not user
throw new Meteor.Error('Not permitted.')
if !Roles.userIsInRole(user._id, 'editor')
throw new Meteor.Error('Not permitted.')
post =
index: index
parent_id: parent_id
template_id: template_id
single_parent: false
group_name: group_name
visible_to: "editor"
id = store_document_unprotected collection, post
msg = "Post added: " + JSON.stringify post, null, 2
log_event msg, event_create, event_info
return id
| 155892 | #######################################################
#
# Created by <NAME>
#
#######################################################
################################################################
Meteor.methods
add_post: (template_id, parent_id, group_name, index) ->
user = Meteor.user()
if not user
throw new Meteor.Error('Not permitted.')
if !Roles.userIsInRole(user._id, 'editor')
throw new Meteor.Error('Not permitted.')
post =
index: index
parent_id: parent_id
template_id: template_id
single_parent: false
group_name: group_name
visible_to: "editor"
id = store_document_unprotected collection, post
msg = "Post added: " + JSON.stringify post, null, 2
log_event msg, event_create, event_info
return id
| true | #######################################################
#
# Created by PI:NAME:<NAME>END_PI
#
#######################################################
################################################################
Meteor.methods
add_post: (template_id, parent_id, group_name, index) ->
user = Meteor.user()
if not user
throw new Meteor.Error('Not permitted.')
if !Roles.userIsInRole(user._id, 'editor')
throw new Meteor.Error('Not permitted.')
post =
index: index
parent_id: parent_id
template_id: template_id
single_parent: false
group_name: group_name
visible_to: "editor"
id = store_document_unprotected collection, post
msg = "Post added: " + JSON.stringify post, null, 2
log_event msg, event_create, event_info
return id
|
[
{
"context": "--------------\n# Copyright Joe Drago 2018.\n# Distributed under the Boost Softw",
"end": 123,
"score": 0.9998282194137573,
"start": 114,
"tag": "NAME",
"value": "Joe Drago"
}
] | lib/templates/src/coffee/SummaryView.coffee | TEAMCHINA/colorist | 0 | # ---------------------------------------------------------------------------
# Copyright Joe Drago 2018.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# ---------------------------------------------------------------------------
React = require 'react'
DOM = require 'react-dom'
RaisedButton = require('material-ui/RaisedButton').default
tags = require './tags'
utils = require './utils'
{el, div, table, tr, td, tbody} = require './tags'
TopBar = require './TopBar'
section = (key, elements) ->
return table {
key: "section_table_#{key}"
style:
fontFamily: 'monospace'
}, [
tbody {
key: "section_tbody_#{key}"
}, elements
]
heading = (title) ->
return tr {
key: "heading_tr_#{title}"
}, [
td {
key: "heading_td_#{title}"
colSpan: 3
style:
fontWeight: 900
fontSize: '1.4em'
borderBottom: '1px solid black'
}, title
]
pair = (indent, key, value) ->
colon = if value then ":" else ""
return tr {
key: "pair_tr_#{key}"
}, [
td {
key: "pair_key_#{key}"
style:
fontWeight: 900
paddingLeft: indent * 20
}, key
td {
key: "pair_colon_#{key}"
style:
fontWeight: 900
}, colon
td {
key: "pair_value_#{key}"
}, value
]
class SummaryView extends React.Component
@defaultProps:
app: null
constructor: (props) ->
super props
render: ->
elements = []
D = COLORIST_DATA
elements.push section "basic", [
heading "Basic info"
pair 0, "Filename", D.filename
pair 0, "Dimensions", "#{D.width}x#{D.height}"
pair 0, "Bit Depth", "#{D.depth}-bits per channel"
pair 0, "ICC Profile", ""
pair 1, "Description", D.icc.description
pair 1, "Primaries", ""
pair 2, "Red", "#{utils.fr(D.icc.primaries[0], 4)}, #{utils.fr(D.icc.primaries[1], 4)}"
pair 2, "Green", "#{utils.fr(D.icc.primaries[2], 4)}, #{utils.fr(D.icc.primaries[3], 4)}"
pair 2, "Blue", "#{utils.fr(D.icc.primaries[4], 4)}, #{utils.fr(D.icc.primaries[5], 4)}"
pair 1, "White Point", "#{utils.fr(D.icc.primaries[6], 4)}, #{utils.fr(D.icc.primaries[7], 4)}"
pair 1, "Max Luminance", "#{D.icc.luminance} nits"
pair 0, "sRGB Overranging (300)", ""
pair 1, "Total Pixels", "#{D.srgb300.pixelCount}"
pair 1, "Total HDR Pixels", "#{D.srgb300.hdrPixelCount} (#{utils.fr(100 * D.srgb300.hdrPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 2, "Overbright Pixels", "#{D.srgb300.overbrightPixelCount} (#{utils.fr(100 * D.srgb300.overbrightPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 2, "Out of Gamut Pixels", "#{D.srgb300.outOfGamutPixelCount} (#{utils.fr(100 * D.srgb300.outOfGamutPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 2, "Both OB and OOG", "#{D.srgb300.bothPixelCount} (#{utils.fr(100 * D.srgb300.bothPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 1, "Brightest Pixel", "#{utils.fr(D.srgb300.brightestPixelNits, 1)} nits"
pair 2, "Coord", "(#{D.srgb300.brightestPixelX}, #{D.srgb300.brightestPixelY})"
]
elements.push el RaisedButton, {
key: "button.pixels"
style:
margin: 12
label: "View pixels"
primary: true
onClick: =>
@props.app.redirect('#pixels')
}
# elements.push el RaisedButton, {
# key: "button.srgb100"
# style:
# margin: 12
# label: "View SRGB Highlight (100 nits)"
# primary: true
# onClick: =>
# @props.app.redirect('#srgb100')
# }
elements.push el RaisedButton, {
key: "button.srgb300"
style:
margin: 12
label: "View SRGB Highlight (300 nits)"
primary: true
onClick: =>
@props.app.redirect('#srgb300')
}
outerElements = []
outerElements.push el TopBar, {
key: "TopBar"
title: "Summary"
app: @props.app
}
outerElements.push div {
key: "outermargin"
style:
margin: '20px'
}, elements
return outerElements
module.exports = SummaryView
| 15218 | # ---------------------------------------------------------------------------
# Copyright <NAME> 2018.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# ---------------------------------------------------------------------------
React = require 'react'
DOM = require 'react-dom'
RaisedButton = require('material-ui/RaisedButton').default
tags = require './tags'
utils = require './utils'
{el, div, table, tr, td, tbody} = require './tags'
TopBar = require './TopBar'
section = (key, elements) ->
return table {
key: "section_table_#{key}"
style:
fontFamily: 'monospace'
}, [
tbody {
key: "section_tbody_#{key}"
}, elements
]
heading = (title) ->
return tr {
key: "heading_tr_#{title}"
}, [
td {
key: "heading_td_#{title}"
colSpan: 3
style:
fontWeight: 900
fontSize: '1.4em'
borderBottom: '1px solid black'
}, title
]
pair = (indent, key, value) ->
colon = if value then ":" else ""
return tr {
key: "pair_tr_#{key}"
}, [
td {
key: "pair_key_#{key}"
style:
fontWeight: 900
paddingLeft: indent * 20
}, key
td {
key: "pair_colon_#{key}"
style:
fontWeight: 900
}, colon
td {
key: "pair_value_#{key}"
}, value
]
class SummaryView extends React.Component
@defaultProps:
app: null
constructor: (props) ->
super props
render: ->
elements = []
D = COLORIST_DATA
elements.push section "basic", [
heading "Basic info"
pair 0, "Filename", D.filename
pair 0, "Dimensions", "#{D.width}x#{D.height}"
pair 0, "Bit Depth", "#{D.depth}-bits per channel"
pair 0, "ICC Profile", ""
pair 1, "Description", D.icc.description
pair 1, "Primaries", ""
pair 2, "Red", "#{utils.fr(D.icc.primaries[0], 4)}, #{utils.fr(D.icc.primaries[1], 4)}"
pair 2, "Green", "#{utils.fr(D.icc.primaries[2], 4)}, #{utils.fr(D.icc.primaries[3], 4)}"
pair 2, "Blue", "#{utils.fr(D.icc.primaries[4], 4)}, #{utils.fr(D.icc.primaries[5], 4)}"
pair 1, "White Point", "#{utils.fr(D.icc.primaries[6], 4)}, #{utils.fr(D.icc.primaries[7], 4)}"
pair 1, "Max Luminance", "#{D.icc.luminance} nits"
pair 0, "sRGB Overranging (300)", ""
pair 1, "Total Pixels", "#{D.srgb300.pixelCount}"
pair 1, "Total HDR Pixels", "#{D.srgb300.hdrPixelCount} (#{utils.fr(100 * D.srgb300.hdrPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 2, "Overbright Pixels", "#{D.srgb300.overbrightPixelCount} (#{utils.fr(100 * D.srgb300.overbrightPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 2, "Out of Gamut Pixels", "#{D.srgb300.outOfGamutPixelCount} (#{utils.fr(100 * D.srgb300.outOfGamutPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 2, "Both OB and OOG", "#{D.srgb300.bothPixelCount} (#{utils.fr(100 * D.srgb300.bothPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 1, "Brightest Pixel", "#{utils.fr(D.srgb300.brightestPixelNits, 1)} nits"
pair 2, "Coord", "(#{D.srgb300.brightestPixelX}, #{D.srgb300.brightestPixelY})"
]
elements.push el RaisedButton, {
key: "button.pixels"
style:
margin: 12
label: "View pixels"
primary: true
onClick: =>
@props.app.redirect('#pixels')
}
# elements.push el RaisedButton, {
# key: "button.srgb100"
# style:
# margin: 12
# label: "View SRGB Highlight (100 nits)"
# primary: true
# onClick: =>
# @props.app.redirect('#srgb100')
# }
elements.push el RaisedButton, {
key: "button.srgb300"
style:
margin: 12
label: "View SRGB Highlight (300 nits)"
primary: true
onClick: =>
@props.app.redirect('#srgb300')
}
outerElements = []
outerElements.push el TopBar, {
key: "TopBar"
title: "Summary"
app: @props.app
}
outerElements.push div {
key: "outermargin"
style:
margin: '20px'
}, elements
return outerElements
module.exports = SummaryView
| true | # ---------------------------------------------------------------------------
# Copyright PI:NAME:<NAME>END_PI 2018.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# ---------------------------------------------------------------------------
React = require 'react'
DOM = require 'react-dom'
RaisedButton = require('material-ui/RaisedButton').default
tags = require './tags'
utils = require './utils'
{el, div, table, tr, td, tbody} = require './tags'
TopBar = require './TopBar'
section = (key, elements) ->
return table {
key: "section_table_#{key}"
style:
fontFamily: 'monospace'
}, [
tbody {
key: "section_tbody_#{key}"
}, elements
]
heading = (title) ->
return tr {
key: "heading_tr_#{title}"
}, [
td {
key: "heading_td_#{title}"
colSpan: 3
style:
fontWeight: 900
fontSize: '1.4em'
borderBottom: '1px solid black'
}, title
]
pair = (indent, key, value) ->
colon = if value then ":" else ""
return tr {
key: "pair_tr_#{key}"
}, [
td {
key: "pair_key_#{key}"
style:
fontWeight: 900
paddingLeft: indent * 20
}, key
td {
key: "pair_colon_#{key}"
style:
fontWeight: 900
}, colon
td {
key: "pair_value_#{key}"
}, value
]
class SummaryView extends React.Component
@defaultProps:
app: null
constructor: (props) ->
super props
render: ->
elements = []
D = COLORIST_DATA
elements.push section "basic", [
heading "Basic info"
pair 0, "Filename", D.filename
pair 0, "Dimensions", "#{D.width}x#{D.height}"
pair 0, "Bit Depth", "#{D.depth}-bits per channel"
pair 0, "ICC Profile", ""
pair 1, "Description", D.icc.description
pair 1, "Primaries", ""
pair 2, "Red", "#{utils.fr(D.icc.primaries[0], 4)}, #{utils.fr(D.icc.primaries[1], 4)}"
pair 2, "Green", "#{utils.fr(D.icc.primaries[2], 4)}, #{utils.fr(D.icc.primaries[3], 4)}"
pair 2, "Blue", "#{utils.fr(D.icc.primaries[4], 4)}, #{utils.fr(D.icc.primaries[5], 4)}"
pair 1, "White Point", "#{utils.fr(D.icc.primaries[6], 4)}, #{utils.fr(D.icc.primaries[7], 4)}"
pair 1, "Max Luminance", "#{D.icc.luminance} nits"
pair 0, "sRGB Overranging (300)", ""
pair 1, "Total Pixels", "#{D.srgb300.pixelCount}"
pair 1, "Total HDR Pixels", "#{D.srgb300.hdrPixelCount} (#{utils.fr(100 * D.srgb300.hdrPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 2, "Overbright Pixels", "#{D.srgb300.overbrightPixelCount} (#{utils.fr(100 * D.srgb300.overbrightPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 2, "Out of Gamut Pixels", "#{D.srgb300.outOfGamutPixelCount} (#{utils.fr(100 * D.srgb300.outOfGamutPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 2, "Both OB and OOG", "#{D.srgb300.bothPixelCount} (#{utils.fr(100 * D.srgb300.bothPixelCount / D.srgb300.pixelCount, 2)}%)"
pair 1, "Brightest Pixel", "#{utils.fr(D.srgb300.brightestPixelNits, 1)} nits"
pair 2, "Coord", "(#{D.srgb300.brightestPixelX}, #{D.srgb300.brightestPixelY})"
]
elements.push el RaisedButton, {
key: "button.pixels"
style:
margin: 12
label: "View pixels"
primary: true
onClick: =>
@props.app.redirect('#pixels')
}
# elements.push el RaisedButton, {
# key: "button.srgb100"
# style:
# margin: 12
# label: "View SRGB Highlight (100 nits)"
# primary: true
# onClick: =>
# @props.app.redirect('#srgb100')
# }
elements.push el RaisedButton, {
key: "button.srgb300"
style:
margin: 12
label: "View SRGB Highlight (300 nits)"
primary: true
onClick: =>
@props.app.redirect('#srgb300')
}
outerElements = []
outerElements.push el TopBar, {
key: "TopBar"
title: "Summary"
app: @props.app
}
outerElements.push div {
key: "outermargin"
style:
margin: '20px'
}, elements
return outerElements
module.exports = SummaryView
|
[
{
"context": "[0]).toEqual([\"a.pretty.ns.key1\", \"a.pretty.ns.key2\"])\n expect(obj.cb).toHaveBeenCalledWith(key1: ",
"end": 3101,
"score": 0.5639996528625488,
"start": 3100,
"tag": "KEY",
"value": "2"
}
] | app/spec/utils/storage/store_spec.coffee | romanornr/ledger-wallet-crw | 173 | describe "Store", ->
store = null
obj =
cb: ->
beforeEach ->
store = new ledger.storage.Store("a.pretty.ns")
it "transform key to namespaced key", ->
expect(store._to_ns_key("key")).toBe("a.pretty.ns.key")
it "transform keys to namespaced keys", ->
expect(store._to_ns_keys(["key1", "key2"])).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
it "transform namespaced key to key", ->
expect(store._from_ns_key("a.pretty.ns.key")).toBe("key")
it "transform namespaced keys to keys", ->
expect(store._from_ns_keys(["a.pretty.ns.key1", "a.pretty.ns.key2"])).toEqual(["key1", "key2"])
it "filter namespaced keys", ->
expect(store._from_ns_keys(["a.pretty.ns.key1", "an.other.ns.key2"])).toEqual(["key1"])
it "preprocess key should namespace key", ->
expect(store._preprocessKey("key")).toBe("a.pretty.ns.key")
it "preprocess keys should preprocess each key", ->
expect(store._preprocessKeys(["key1", "key2"])).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
it "preprocess value should stringify to JSON", ->
expect(store._preprocessValue([1,2,3])).toBe("[1,2,3]")
it "preprocess items should preprocess keys and values", ->
expect(store._preprocessItems(key: [1,2,3])).toEqual("a.pretty.ns.key":"[1,2,3]")
it "filter falsy keys and function values during items preprocess", ->
expect(store._preprocessItems(key: 42, "": 1, undefined: 2, null: 3)).toEqual("a.pretty.ns.key":"42")
it "deprocess key should slice namespace", ->
expect(store._deprocessKey("a.pretty.ns.key")).toBe("key")
it "deprocess keys should deprocess each key", ->
expect(store._deprocessKeys(["a.pretty.ns.key1", "a.pretty.ns.key2"])).toEqual(["key1", "key2"])
it "deprocess keys should skip bad keys", ->
expect(store._deprocessKeys(["a.pretty.ns.key1", "a.pretty.ns.key2"])).toEqual(["key1", "key2"])
it "deprocess value should parse JSON", ->
expect(store._deprocessValue("[1,2,3]")).toEqual([1,2,3])
it "deprocess items should deprocess keys and values", ->
expect(store._deprocessItems("a.pretty.ns.key":"[1,2,3]")).toEqual(key: [1,2,3])
it "calls _raw_set with preprocessed items on set", ->
spyOn(store, '_raw_set').and.callFake((raw_items, cb)-> cb())
spyOn(obj, 'cb')
store.set({key: 42}, obj.cb)
expect(store._raw_set.calls.count()).toBe(1)
expect(store._raw_set.calls.argsFor(0)[0]).toEqual("a.pretty.ns.key":"42")
expect(obj.cb).toHaveBeenCalled()
it "#get calls _raw_get with preprocessed keys", ->
spy = spyOn(store, '_raw_get').and.callFake (raw_keys, cb) -> cb("a.pretty.ns.key":"42")
spyOn(obj, 'cb')
store.get("key", obj.cb)
expect(store._raw_get.calls.count()).toBe(1)
expect(store._raw_get.calls.argsFor(0)[0]).toEqual(["a.pretty.ns.key"])
expect(obj.cb).toHaveBeenCalledWith(key: 42)
spy.and.callFake (raw_keys, cb) -> cb("a.pretty.ns.key1":"1", "a.pretty.ns.key2":"2")
store.get(["key1", "key2"], obj.cb)
expect(store._raw_get.calls.argsFor(1)[0]).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
expect(obj.cb).toHaveBeenCalledWith(key1: 1, key2: 2)
it "#keys calls _raw_keys", ->
spyOn(store, '_raw_keys').and.callFake (cb)-> cb(["a.pretty.ns.key1", "a.pretty.ns.key2"])
spyOn(obj, 'cb')
store.keys(obj.cb)
expect(store._raw_keys).toHaveBeenCalled()
expect(obj.cb).toHaveBeenCalledWith(["key1", "key2"])
it "#keys filter bad keys", ->
spyOn(store, '_raw_keys').and.callFake (cb)-> cb(["a.pretty.ns.key1", "a.other.ns.key2"])
spyOn(obj, 'cb')
store.keys(obj.cb)
expect(store._raw_keys).toHaveBeenCalled()
expect(obj.cb).toHaveBeenCalledWith(["key1"])
it "#remove calls _raw_remove with preprocessed keys", ->
spy = spyOn(store, '_raw_remove').and.callFake (raw_keys, cb)-> cb("a.pretty.ns.key":"42")
spyOn(obj, 'cb')
store.remove("key", obj.cb)
expect(store._raw_remove.calls.count()).toBe(1)
expect(store._raw_remove.calls.argsFor(0)[0]).toEqual(["a.pretty.ns.key"])
expect(obj.cb).toHaveBeenCalledWith(key: 42)
spy.and.callFake (raw_keys, cb)-> cb("a.pretty.ns.key1":"1", "a.pretty.ns.key2":"2")
store.remove(["key1", "key2"], obj.cb)
expect(store._raw_remove.calls.argsFor(1)[0]).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
expect(obj.cb).toHaveBeenCalledWith(key1: 1, key2: 2)
it "#clear calls _raw_keys and _raw_remove", ->
spyOn(store, '_raw_keys').and.callFake (cb)-> cb(["a.pretty.ns.key1", "a.pretty.ns.key2"])
spyOn(store, '_raw_remove').and.callFake (raw_keys, cb)-> cb("a.pretty.ns.key1":"1", "a.pretty.ns.key2":"2")
spyOn(obj, 'cb')
store.clear(obj.cb)
expect(store._raw_keys).toHaveBeenCalled()
expect(store._raw_remove.calls.count()).toBe(1)
expect(store._raw_remove.calls.argsFor(0)[0]).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
expect(obj.cb).toHaveBeenCalledWith(key1: 1, key2: 2)
| 63648 | describe "Store", ->
store = null
obj =
cb: ->
beforeEach ->
store = new ledger.storage.Store("a.pretty.ns")
it "transform key to namespaced key", ->
expect(store._to_ns_key("key")).toBe("a.pretty.ns.key")
it "transform keys to namespaced keys", ->
expect(store._to_ns_keys(["key1", "key2"])).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
it "transform namespaced key to key", ->
expect(store._from_ns_key("a.pretty.ns.key")).toBe("key")
it "transform namespaced keys to keys", ->
expect(store._from_ns_keys(["a.pretty.ns.key1", "a.pretty.ns.key2"])).toEqual(["key1", "key2"])
it "filter namespaced keys", ->
expect(store._from_ns_keys(["a.pretty.ns.key1", "an.other.ns.key2"])).toEqual(["key1"])
it "preprocess key should namespace key", ->
expect(store._preprocessKey("key")).toBe("a.pretty.ns.key")
it "preprocess keys should preprocess each key", ->
expect(store._preprocessKeys(["key1", "key2"])).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
it "preprocess value should stringify to JSON", ->
expect(store._preprocessValue([1,2,3])).toBe("[1,2,3]")
it "preprocess items should preprocess keys and values", ->
expect(store._preprocessItems(key: [1,2,3])).toEqual("a.pretty.ns.key":"[1,2,3]")
it "filter falsy keys and function values during items preprocess", ->
expect(store._preprocessItems(key: 42, "": 1, undefined: 2, null: 3)).toEqual("a.pretty.ns.key":"42")
it "deprocess key should slice namespace", ->
expect(store._deprocessKey("a.pretty.ns.key")).toBe("key")
it "deprocess keys should deprocess each key", ->
expect(store._deprocessKeys(["a.pretty.ns.key1", "a.pretty.ns.key2"])).toEqual(["key1", "key2"])
it "deprocess keys should skip bad keys", ->
expect(store._deprocessKeys(["a.pretty.ns.key1", "a.pretty.ns.key2"])).toEqual(["key1", "key2"])
it "deprocess value should parse JSON", ->
expect(store._deprocessValue("[1,2,3]")).toEqual([1,2,3])
it "deprocess items should deprocess keys and values", ->
expect(store._deprocessItems("a.pretty.ns.key":"[1,2,3]")).toEqual(key: [1,2,3])
it "calls _raw_set with preprocessed items on set", ->
spyOn(store, '_raw_set').and.callFake((raw_items, cb)-> cb())
spyOn(obj, 'cb')
store.set({key: 42}, obj.cb)
expect(store._raw_set.calls.count()).toBe(1)
expect(store._raw_set.calls.argsFor(0)[0]).toEqual("a.pretty.ns.key":"42")
expect(obj.cb).toHaveBeenCalled()
it "#get calls _raw_get with preprocessed keys", ->
spy = spyOn(store, '_raw_get').and.callFake (raw_keys, cb) -> cb("a.pretty.ns.key":"42")
spyOn(obj, 'cb')
store.get("key", obj.cb)
expect(store._raw_get.calls.count()).toBe(1)
expect(store._raw_get.calls.argsFor(0)[0]).toEqual(["a.pretty.ns.key"])
expect(obj.cb).toHaveBeenCalledWith(key: 42)
spy.and.callFake (raw_keys, cb) -> cb("a.pretty.ns.key1":"1", "a.pretty.ns.key2":"2")
store.get(["key1", "key2"], obj.cb)
expect(store._raw_get.calls.argsFor(1)[0]).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key<KEY>"])
expect(obj.cb).toHaveBeenCalledWith(key1: 1, key2: 2)
it "#keys calls _raw_keys", ->
spyOn(store, '_raw_keys').and.callFake (cb)-> cb(["a.pretty.ns.key1", "a.pretty.ns.key2"])
spyOn(obj, 'cb')
store.keys(obj.cb)
expect(store._raw_keys).toHaveBeenCalled()
expect(obj.cb).toHaveBeenCalledWith(["key1", "key2"])
it "#keys filter bad keys", ->
spyOn(store, '_raw_keys').and.callFake (cb)-> cb(["a.pretty.ns.key1", "a.other.ns.key2"])
spyOn(obj, 'cb')
store.keys(obj.cb)
expect(store._raw_keys).toHaveBeenCalled()
expect(obj.cb).toHaveBeenCalledWith(["key1"])
it "#remove calls _raw_remove with preprocessed keys", ->
spy = spyOn(store, '_raw_remove').and.callFake (raw_keys, cb)-> cb("a.pretty.ns.key":"42")
spyOn(obj, 'cb')
store.remove("key", obj.cb)
expect(store._raw_remove.calls.count()).toBe(1)
expect(store._raw_remove.calls.argsFor(0)[0]).toEqual(["a.pretty.ns.key"])
expect(obj.cb).toHaveBeenCalledWith(key: 42)
spy.and.callFake (raw_keys, cb)-> cb("a.pretty.ns.key1":"1", "a.pretty.ns.key2":"2")
store.remove(["key1", "key2"], obj.cb)
expect(store._raw_remove.calls.argsFor(1)[0]).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
expect(obj.cb).toHaveBeenCalledWith(key1: 1, key2: 2)
it "#clear calls _raw_keys and _raw_remove", ->
spyOn(store, '_raw_keys').and.callFake (cb)-> cb(["a.pretty.ns.key1", "a.pretty.ns.key2"])
spyOn(store, '_raw_remove').and.callFake (raw_keys, cb)-> cb("a.pretty.ns.key1":"1", "a.pretty.ns.key2":"2")
spyOn(obj, 'cb')
store.clear(obj.cb)
expect(store._raw_keys).toHaveBeenCalled()
expect(store._raw_remove.calls.count()).toBe(1)
expect(store._raw_remove.calls.argsFor(0)[0]).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
expect(obj.cb).toHaveBeenCalledWith(key1: 1, key2: 2)
| true | describe "Store", ->
store = null
obj =
cb: ->
beforeEach ->
store = new ledger.storage.Store("a.pretty.ns")
it "transform key to namespaced key", ->
expect(store._to_ns_key("key")).toBe("a.pretty.ns.key")
it "transform keys to namespaced keys", ->
expect(store._to_ns_keys(["key1", "key2"])).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
it "transform namespaced key to key", ->
expect(store._from_ns_key("a.pretty.ns.key")).toBe("key")
it "transform namespaced keys to keys", ->
expect(store._from_ns_keys(["a.pretty.ns.key1", "a.pretty.ns.key2"])).toEqual(["key1", "key2"])
it "filter namespaced keys", ->
expect(store._from_ns_keys(["a.pretty.ns.key1", "an.other.ns.key2"])).toEqual(["key1"])
it "preprocess key should namespace key", ->
expect(store._preprocessKey("key")).toBe("a.pretty.ns.key")
it "preprocess keys should preprocess each key", ->
expect(store._preprocessKeys(["key1", "key2"])).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
it "preprocess value should stringify to JSON", ->
expect(store._preprocessValue([1,2,3])).toBe("[1,2,3]")
it "preprocess items should preprocess keys and values", ->
expect(store._preprocessItems(key: [1,2,3])).toEqual("a.pretty.ns.key":"[1,2,3]")
it "filter falsy keys and function values during items preprocess", ->
expect(store._preprocessItems(key: 42, "": 1, undefined: 2, null: 3)).toEqual("a.pretty.ns.key":"42")
it "deprocess key should slice namespace", ->
expect(store._deprocessKey("a.pretty.ns.key")).toBe("key")
it "deprocess keys should deprocess each key", ->
expect(store._deprocessKeys(["a.pretty.ns.key1", "a.pretty.ns.key2"])).toEqual(["key1", "key2"])
it "deprocess keys should skip bad keys", ->
expect(store._deprocessKeys(["a.pretty.ns.key1", "a.pretty.ns.key2"])).toEqual(["key1", "key2"])
it "deprocess value should parse JSON", ->
expect(store._deprocessValue("[1,2,3]")).toEqual([1,2,3])
it "deprocess items should deprocess keys and values", ->
expect(store._deprocessItems("a.pretty.ns.key":"[1,2,3]")).toEqual(key: [1,2,3])
it "calls _raw_set with preprocessed items on set", ->
spyOn(store, '_raw_set').and.callFake((raw_items, cb)-> cb())
spyOn(obj, 'cb')
store.set({key: 42}, obj.cb)
expect(store._raw_set.calls.count()).toBe(1)
expect(store._raw_set.calls.argsFor(0)[0]).toEqual("a.pretty.ns.key":"42")
expect(obj.cb).toHaveBeenCalled()
it "#get calls _raw_get with preprocessed keys", ->
spy = spyOn(store, '_raw_get').and.callFake (raw_keys, cb) -> cb("a.pretty.ns.key":"42")
spyOn(obj, 'cb')
store.get("key", obj.cb)
expect(store._raw_get.calls.count()).toBe(1)
expect(store._raw_get.calls.argsFor(0)[0]).toEqual(["a.pretty.ns.key"])
expect(obj.cb).toHaveBeenCalledWith(key: 42)
spy.and.callFake (raw_keys, cb) -> cb("a.pretty.ns.key1":"1", "a.pretty.ns.key2":"2")
store.get(["key1", "key2"], obj.cb)
expect(store._raw_get.calls.argsFor(1)[0]).toEqual(["a.pretty.ns.key1", "a.pretty.ns.keyPI:KEY:<KEY>END_PI"])
expect(obj.cb).toHaveBeenCalledWith(key1: 1, key2: 2)
it "#keys calls _raw_keys", ->
spyOn(store, '_raw_keys').and.callFake (cb)-> cb(["a.pretty.ns.key1", "a.pretty.ns.key2"])
spyOn(obj, 'cb')
store.keys(obj.cb)
expect(store._raw_keys).toHaveBeenCalled()
expect(obj.cb).toHaveBeenCalledWith(["key1", "key2"])
it "#keys filter bad keys", ->
spyOn(store, '_raw_keys').and.callFake (cb)-> cb(["a.pretty.ns.key1", "a.other.ns.key2"])
spyOn(obj, 'cb')
store.keys(obj.cb)
expect(store._raw_keys).toHaveBeenCalled()
expect(obj.cb).toHaveBeenCalledWith(["key1"])
it "#remove calls _raw_remove with preprocessed keys", ->
spy = spyOn(store, '_raw_remove').and.callFake (raw_keys, cb)-> cb("a.pretty.ns.key":"42")
spyOn(obj, 'cb')
store.remove("key", obj.cb)
expect(store._raw_remove.calls.count()).toBe(1)
expect(store._raw_remove.calls.argsFor(0)[0]).toEqual(["a.pretty.ns.key"])
expect(obj.cb).toHaveBeenCalledWith(key: 42)
spy.and.callFake (raw_keys, cb)-> cb("a.pretty.ns.key1":"1", "a.pretty.ns.key2":"2")
store.remove(["key1", "key2"], obj.cb)
expect(store._raw_remove.calls.argsFor(1)[0]).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
expect(obj.cb).toHaveBeenCalledWith(key1: 1, key2: 2)
it "#clear calls _raw_keys and _raw_remove", ->
spyOn(store, '_raw_keys').and.callFake (cb)-> cb(["a.pretty.ns.key1", "a.pretty.ns.key2"])
spyOn(store, '_raw_remove').and.callFake (raw_keys, cb)-> cb("a.pretty.ns.key1":"1", "a.pretty.ns.key2":"2")
spyOn(obj, 'cb')
store.clear(obj.cb)
expect(store._raw_keys).toHaveBeenCalled()
expect(store._raw_remove.calls.count()).toBe(1)
expect(store._raw_remove.calls.argsFor(0)[0]).toEqual(["a.pretty.ns.key1", "a.pretty.ns.key2"])
expect(obj.cb).toHaveBeenCalledWith(key1: 1, key2: 2)
|
[
{
"context": "ribe 'Infector', ->\n\n class Person\n name: -> 'FooBar'\n\n class PrefixInfector extends Infector\n inf",
"end": 152,
"score": 0.9380234479904175,
"start": 146,
"tag": "NAME",
"value": "FooBar"
}
] | test/helpers/infector_spec.coffee | kabisa/maji-extras | 0 | _ = require('underscore')
Infector = require('helpers/infector')
memo = require('memo-is')
describe 'Infector', ->
class Person
name: -> 'FooBar'
class PrefixInfector extends Infector
infectModel: (modelClass) ->
_.extend(modelClass::,
nameWithPrefix: ->
"Lt. #{@nameWithoutPrefix()}"
)
@aliasMethodChain(modelClass, 'name', 'Prefix')
modelClass
class SuffixInfector extends Infector
infectModel: (modelClass) ->
_.extend(modelClass::,
nameWithSuffix: ->
"#{@nameWithoutSuffix()} Jr."
)
@aliasMethodChain(modelClass, 'name', 'Suffix')
modelClass
modelClass = memo().is -> Person
beforeEach ->
@model = new (modelClass())()
afterEach ->
Person.desinfect?()
describe 'the basic model', ->
it 'returns a simple name', ->
expect(@model.name()).to.eql 'FooBar'
describe 'using prefix infector', ->
modelClass.is ->
(new PrefixInfector).infectModel(Person)
it 'adds a prefix by default', ->
expect(@model.name()).to.eql 'Lt. FooBar'
it 'can still call the original method', ->
expect(@model.nameWithoutPrefix()).to.eql 'FooBar'
context 'after desinfection', ->
it 'restores the original methods', ->
Person.desinfect()
expect(@model.name()).to.eql 'FooBar'
describe 'using suffix infector', ->
modelClass.is ->
(new SuffixInfector).infectModel(Person)
it 'adds a suffix by default', ->
expect(@model.name()).to.eql 'FooBar Jr.'
describe 'using suffix and prefix infector', ->
modelClass.is ->
(new SuffixInfector).infectModel(Person)
(new PrefixInfector).infectModel(Person)
it 'adds a suffix and prefix by default', ->
expect(@model.name()).to.eql 'Lt. FooBar Jr.'
| 169343 | _ = require('underscore')
Infector = require('helpers/infector')
memo = require('memo-is')
describe 'Infector', ->
class Person
name: -> '<NAME>'
class PrefixInfector extends Infector
infectModel: (modelClass) ->
_.extend(modelClass::,
nameWithPrefix: ->
"Lt. #{@nameWithoutPrefix()}"
)
@aliasMethodChain(modelClass, 'name', 'Prefix')
modelClass
class SuffixInfector extends Infector
infectModel: (modelClass) ->
_.extend(modelClass::,
nameWithSuffix: ->
"#{@nameWithoutSuffix()} Jr."
)
@aliasMethodChain(modelClass, 'name', 'Suffix')
modelClass
modelClass = memo().is -> Person
beforeEach ->
@model = new (modelClass())()
afterEach ->
Person.desinfect?()
describe 'the basic model', ->
it 'returns a simple name', ->
expect(@model.name()).to.eql 'FooBar'
describe 'using prefix infector', ->
modelClass.is ->
(new PrefixInfector).infectModel(Person)
it 'adds a prefix by default', ->
expect(@model.name()).to.eql 'Lt. FooBar'
it 'can still call the original method', ->
expect(@model.nameWithoutPrefix()).to.eql 'FooBar'
context 'after desinfection', ->
it 'restores the original methods', ->
Person.desinfect()
expect(@model.name()).to.eql 'FooBar'
describe 'using suffix infector', ->
modelClass.is ->
(new SuffixInfector).infectModel(Person)
it 'adds a suffix by default', ->
expect(@model.name()).to.eql 'FooBar Jr.'
describe 'using suffix and prefix infector', ->
modelClass.is ->
(new SuffixInfector).infectModel(Person)
(new PrefixInfector).infectModel(Person)
it 'adds a suffix and prefix by default', ->
expect(@model.name()).to.eql 'Lt. FooBar Jr.'
| true | _ = require('underscore')
Infector = require('helpers/infector')
memo = require('memo-is')
describe 'Infector', ->
class Person
name: -> 'PI:NAME:<NAME>END_PI'
class PrefixInfector extends Infector
infectModel: (modelClass) ->
_.extend(modelClass::,
nameWithPrefix: ->
"Lt. #{@nameWithoutPrefix()}"
)
@aliasMethodChain(modelClass, 'name', 'Prefix')
modelClass
class SuffixInfector extends Infector
infectModel: (modelClass) ->
_.extend(modelClass::,
nameWithSuffix: ->
"#{@nameWithoutSuffix()} Jr."
)
@aliasMethodChain(modelClass, 'name', 'Suffix')
modelClass
modelClass = memo().is -> Person
beforeEach ->
@model = new (modelClass())()
afterEach ->
Person.desinfect?()
describe 'the basic model', ->
it 'returns a simple name', ->
expect(@model.name()).to.eql 'FooBar'
describe 'using prefix infector', ->
modelClass.is ->
(new PrefixInfector).infectModel(Person)
it 'adds a prefix by default', ->
expect(@model.name()).to.eql 'Lt. FooBar'
it 'can still call the original method', ->
expect(@model.nameWithoutPrefix()).to.eql 'FooBar'
context 'after desinfection', ->
it 'restores the original methods', ->
Person.desinfect()
expect(@model.name()).to.eql 'FooBar'
describe 'using suffix infector', ->
modelClass.is ->
(new SuffixInfector).infectModel(Person)
it 'adds a suffix by default', ->
expect(@model.name()).to.eql 'FooBar Jr.'
describe 'using suffix and prefix infector', ->
modelClass.is ->
(new SuffixInfector).infectModel(Person)
(new PrefixInfector).infectModel(Person)
it 'adds a suffix and prefix by default', ->
expect(@model.name()).to.eql 'Lt. FooBar Jr.'
|
[
{
"context": "es highscore to local storage', ->\n # key = 'test-score-keeper'\n # keeper.enableSaving key\n # keeper.a",
"end": 1742,
"score": 0.9928348660469055,
"start": 1725,
"tag": "KEY",
"value": "test-score-keeper"
}
] | test/score-keeper-spec.coffee | giladgray/rocket-engine | 1 | chai = require 'chai'
expect = chai.expect
ScoreKeeper = require '../src/utils/score-keeper.coffee'
describe 'ScoreKeeper', ->
keeper = null
beforeEach ->
keeper = new ScoreKeeper
it 'can be created', ->
expect(keeper).to.exist
it 'can be created with initial high score', ->
s = new ScoreKeeper(10)
expect(s).to.exist
expect(s.highScore).to.equal 10
describe 'events proxy', ->
it 'provides on, once, and off', ->
expect(keeper.on).to.be.a.function
expect(keeper.off).to.be.a.function
expect(keeper.once).to.be.a.function
describe '#addPoints', ->
it 'adds points to score', ->
keeper.addPoints(10)
expect(keeper.score).to.equal 10
it 'emits \'score\' event with total and new points', (done) ->
keeper.on 'score', (total, pts) ->
expect(total).to.equal 10
expect(pts).to.equal 10
done()
expect(keeper.addPoints 10).to.be.true
it 'updates high score', ->
keeper.addPoints(10)
expect(keeper.highScore).to.equal 10
it 'emits \'highscore\' event with new highscore', -> (done) ->
keeper.on 'highscore', (record) ->
expect(record).to.equal 100
done()
keeper.addPoints 100
describe '#reset', ->
it 'resets score to zero', ->
keeper.addPoints 10
keeper.reset()
expect(keeper.score).to.equal 0
it 'emits \'score\' event with total 0 and negative old score', (done) ->
keeper.addPoints 12
keeper.on 'score', (total, pts) ->
expect(total).to.equal 0
expect(pts).to.equal -12
done()
keeper.reset()
# describe '#enableSaving', ->
# it 'saves highscore to local storage', ->
# key = 'test-score-keeper'
# keeper.enableSaving key
# keeper.addScore 200
# expect(localStorage.getItem key).to.equal 200
describe 'example: score, reset, smaller score', ->
game = ->
keeper.addPoints 10
keeper.addPoints 4
keeper.reset()
keeper.addPoints 12
it 'has appropriate final state', ->
game()
expect(keeper.score).to.equal 12
expect(keeper.highScore).to.equal 14
it 'emits \'score\' events for each step', ->
scores = []
points = []
keeper.on 'score', (total, pts) ->
scores.push total
points.push pts
game()
expect(scores).to.deep.equal [10, 14, 0, 12]
expect(points).to.deep.equal [10, 4, -14, 12]
it 'emits two \'highscore\' events for first two adds', ->
highscores = []
keeper.on 'highscore', (record) -> highscores.push record
game()
expect(highscores).to.deep.equal [10, 14]
| 130475 | chai = require 'chai'
expect = chai.expect
ScoreKeeper = require '../src/utils/score-keeper.coffee'
describe 'ScoreKeeper', ->
keeper = null
beforeEach ->
keeper = new ScoreKeeper
it 'can be created', ->
expect(keeper).to.exist
it 'can be created with initial high score', ->
s = new ScoreKeeper(10)
expect(s).to.exist
expect(s.highScore).to.equal 10
describe 'events proxy', ->
it 'provides on, once, and off', ->
expect(keeper.on).to.be.a.function
expect(keeper.off).to.be.a.function
expect(keeper.once).to.be.a.function
describe '#addPoints', ->
it 'adds points to score', ->
keeper.addPoints(10)
expect(keeper.score).to.equal 10
it 'emits \'score\' event with total and new points', (done) ->
keeper.on 'score', (total, pts) ->
expect(total).to.equal 10
expect(pts).to.equal 10
done()
expect(keeper.addPoints 10).to.be.true
it 'updates high score', ->
keeper.addPoints(10)
expect(keeper.highScore).to.equal 10
it 'emits \'highscore\' event with new highscore', -> (done) ->
keeper.on 'highscore', (record) ->
expect(record).to.equal 100
done()
keeper.addPoints 100
describe '#reset', ->
it 'resets score to zero', ->
keeper.addPoints 10
keeper.reset()
expect(keeper.score).to.equal 0
it 'emits \'score\' event with total 0 and negative old score', (done) ->
keeper.addPoints 12
keeper.on 'score', (total, pts) ->
expect(total).to.equal 0
expect(pts).to.equal -12
done()
keeper.reset()
# describe '#enableSaving', ->
# it 'saves highscore to local storage', ->
# key = '<KEY>'
# keeper.enableSaving key
# keeper.addScore 200
# expect(localStorage.getItem key).to.equal 200
describe 'example: score, reset, smaller score', ->
game = ->
keeper.addPoints 10
keeper.addPoints 4
keeper.reset()
keeper.addPoints 12
it 'has appropriate final state', ->
game()
expect(keeper.score).to.equal 12
expect(keeper.highScore).to.equal 14
it 'emits \'score\' events for each step', ->
scores = []
points = []
keeper.on 'score', (total, pts) ->
scores.push total
points.push pts
game()
expect(scores).to.deep.equal [10, 14, 0, 12]
expect(points).to.deep.equal [10, 4, -14, 12]
it 'emits two \'highscore\' events for first two adds', ->
highscores = []
keeper.on 'highscore', (record) -> highscores.push record
game()
expect(highscores).to.deep.equal [10, 14]
| true | chai = require 'chai'
expect = chai.expect
ScoreKeeper = require '../src/utils/score-keeper.coffee'
describe 'ScoreKeeper', ->
keeper = null
beforeEach ->
keeper = new ScoreKeeper
it 'can be created', ->
expect(keeper).to.exist
it 'can be created with initial high score', ->
s = new ScoreKeeper(10)
expect(s).to.exist
expect(s.highScore).to.equal 10
describe 'events proxy', ->
it 'provides on, once, and off', ->
expect(keeper.on).to.be.a.function
expect(keeper.off).to.be.a.function
expect(keeper.once).to.be.a.function
describe '#addPoints', ->
it 'adds points to score', ->
keeper.addPoints(10)
expect(keeper.score).to.equal 10
it 'emits \'score\' event with total and new points', (done) ->
keeper.on 'score', (total, pts) ->
expect(total).to.equal 10
expect(pts).to.equal 10
done()
expect(keeper.addPoints 10).to.be.true
it 'updates high score', ->
keeper.addPoints(10)
expect(keeper.highScore).to.equal 10
it 'emits \'highscore\' event with new highscore', -> (done) ->
keeper.on 'highscore', (record) ->
expect(record).to.equal 100
done()
keeper.addPoints 100
describe '#reset', ->
it 'resets score to zero', ->
keeper.addPoints 10
keeper.reset()
expect(keeper.score).to.equal 0
it 'emits \'score\' event with total 0 and negative old score', (done) ->
keeper.addPoints 12
keeper.on 'score', (total, pts) ->
expect(total).to.equal 0
expect(pts).to.equal -12
done()
keeper.reset()
# describe '#enableSaving', ->
# it 'saves highscore to local storage', ->
# key = 'PI:KEY:<KEY>END_PI'
# keeper.enableSaving key
# keeper.addScore 200
# expect(localStorage.getItem key).to.equal 200
describe 'example: score, reset, smaller score', ->
game = ->
keeper.addPoints 10
keeper.addPoints 4
keeper.reset()
keeper.addPoints 12
it 'has appropriate final state', ->
game()
expect(keeper.score).to.equal 12
expect(keeper.highScore).to.equal 14
it 'emits \'score\' events for each step', ->
scores = []
points = []
keeper.on 'score', (total, pts) ->
scores.push total
points.push pts
game()
expect(scores).to.deep.equal [10, 14, 0, 12]
expect(points).to.deep.equal [10, 4, -14, 12]
it 'emits two \'highscore\' events for first two adds', ->
highscores = []
keeper.on 'highscore', (record) -> highscores.push record
game()
expect(highscores).to.deep.equal [10, 14]
|
[
{
"context": "r: etFormatter },\n { id: 'participant', name: 'Participant', formatter: pFormatter, width: 200 },\n { id: ",
"end": 2154,
"score": 0.7266793251037598,
"start": 2143,
"tag": "NAME",
"value": "Participant"
}
] | app/assets/javascripts/views/event_search_results_grid.coffee | NUBIC/ncs_navigator_pancakes | 0 | #= require views/search_results_grid
# ----------------------------------------------------------------------------
# FORMATTERS AND SORTING
# ----------------------------------------------------------------------------
# Data collector formatter.
dcFormatter = (row, cell, value, columnDef, dataContext) ->
value.join(', ')
# Event disposition formatter.
edFormatter = (row, cell, value, columnDef, dataContext) ->
value['disposition']
# Event type formatter.
etFormatter = (row, cell, value, columnDef, dataContext) ->
value['display_text']
# Link extractor.
linksFor = (rel, links) ->
link['href'] for link in links when link['rel'] == rel
# Participant formatter.
guard = (v) ->
if v.toString().trim().length == 0
'(empty)'
else
v
pFormatter = (row, cell, value, columnDef, dataContext) ->
links = linksFor 'participant', dataContext['links']
html = """
<span class="name">#{guard dataContext['participant_first_name']}</span>
<span class="name">#{guard dataContext['participant_last_name']}</span>
<span class="participant-id">#{dataContext['participant_id']}</span>
"""
if links[0]
html = "<a href=\"#{links[0]}\">#{html}</a>"
html
# Sort helpers.
fields = ['participant_first_name', 'participant_last_name', 'scheduled_date']
cmp = (a, b) ->
if a < b
-1
else if a > b
1
else
0
comparer = (a, b) ->
for field in fields
res = cmp(a[field], b[field])
if res != 0
return res
0
# ----------------------------------------------------------------------------
# GRID
# ----------------------------------------------------------------------------
Pancakes.EventSearchResultsGrid = Pancakes.SearchResultsGrid.extend
options:
autoHeight: true
forceFitColumns: true
columns: [
{ id: 'data_collectors', name: 'Data collectors', field: 'data_collector_usernames', formatter: dcFormatter },
{ id: 'disposition', name: 'Disposition', field: 'disposition_code', formatter: edFormatter },
{ id: 'event_type', name: 'Event type', field: 'event_type', formatter: etFormatter },
{ id: 'participant', name: 'Participant', formatter: pFormatter, width: 200 },
{ id: 'scheduled_date', name: 'Scheduled date', field: 'scheduled_date' }
]
groupOnContentChange: (->
view = @get 'view'
content = @get 'content'
if view && content
view.setGrouping([{ getter: 'group', formatter: (g) -> "Location: #{g.value}" }])
).observes('content', 'view')
# The underlying DataView and GroupItemMetadataProvider have a couple of
# requirements:
#
# 1. The DataView requires that each row's id property contain a unique ID.
# 2. The grouping provider requires a top-level grouping member.
#
# This observer builds both.
rebuildIndices: (->
view = @get 'view'
content = @get 'content'
if view && content
data = content['event_searches']
_.each data, (o) ->
o['id'] = _.uniqueId()
o['group'] = o['pancakes.location']['name']
view.setItems data
view.sort comparer, true
).observes('content', 'view')
# vim:ts=2:sw=2:et:tw=78
| 92620 | #= require views/search_results_grid
# ----------------------------------------------------------------------------
# FORMATTERS AND SORTING
# ----------------------------------------------------------------------------
# Data collector formatter.
dcFormatter = (row, cell, value, columnDef, dataContext) ->
value.join(', ')
# Event disposition formatter.
edFormatter = (row, cell, value, columnDef, dataContext) ->
value['disposition']
# Event type formatter.
etFormatter = (row, cell, value, columnDef, dataContext) ->
value['display_text']
# Link extractor.
linksFor = (rel, links) ->
link['href'] for link in links when link['rel'] == rel
# Participant formatter.
guard = (v) ->
if v.toString().trim().length == 0
'(empty)'
else
v
pFormatter = (row, cell, value, columnDef, dataContext) ->
links = linksFor 'participant', dataContext['links']
html = """
<span class="name">#{guard dataContext['participant_first_name']}</span>
<span class="name">#{guard dataContext['participant_last_name']}</span>
<span class="participant-id">#{dataContext['participant_id']}</span>
"""
if links[0]
html = "<a href=\"#{links[0]}\">#{html}</a>"
html
# Sort helpers.
fields = ['participant_first_name', 'participant_last_name', 'scheduled_date']
cmp = (a, b) ->
if a < b
-1
else if a > b
1
else
0
comparer = (a, b) ->
for field in fields
res = cmp(a[field], b[field])
if res != 0
return res
0
# ----------------------------------------------------------------------------
# GRID
# ----------------------------------------------------------------------------
Pancakes.EventSearchResultsGrid = Pancakes.SearchResultsGrid.extend
options:
autoHeight: true
forceFitColumns: true
columns: [
{ id: 'data_collectors', name: 'Data collectors', field: 'data_collector_usernames', formatter: dcFormatter },
{ id: 'disposition', name: 'Disposition', field: 'disposition_code', formatter: edFormatter },
{ id: 'event_type', name: 'Event type', field: 'event_type', formatter: etFormatter },
{ id: 'participant', name: '<NAME>', formatter: pFormatter, width: 200 },
{ id: 'scheduled_date', name: 'Scheduled date', field: 'scheduled_date' }
]
groupOnContentChange: (->
view = @get 'view'
content = @get 'content'
if view && content
view.setGrouping([{ getter: 'group', formatter: (g) -> "Location: #{g.value}" }])
).observes('content', 'view')
# The underlying DataView and GroupItemMetadataProvider have a couple of
# requirements:
#
# 1. The DataView requires that each row's id property contain a unique ID.
# 2. The grouping provider requires a top-level grouping member.
#
# This observer builds both.
rebuildIndices: (->
view = @get 'view'
content = @get 'content'
if view && content
data = content['event_searches']
_.each data, (o) ->
o['id'] = _.uniqueId()
o['group'] = o['pancakes.location']['name']
view.setItems data
view.sort comparer, true
).observes('content', 'view')
# vim:ts=2:sw=2:et:tw=78
| true | #= require views/search_results_grid
# ----------------------------------------------------------------------------
# FORMATTERS AND SORTING
# ----------------------------------------------------------------------------
# Data collector formatter.
dcFormatter = (row, cell, value, columnDef, dataContext) ->
value.join(', ')
# Event disposition formatter.
edFormatter = (row, cell, value, columnDef, dataContext) ->
value['disposition']
# Event type formatter.
etFormatter = (row, cell, value, columnDef, dataContext) ->
value['display_text']
# Link extractor.
linksFor = (rel, links) ->
link['href'] for link in links when link['rel'] == rel
# Participant formatter.
guard = (v) ->
if v.toString().trim().length == 0
'(empty)'
else
v
pFormatter = (row, cell, value, columnDef, dataContext) ->
links = linksFor 'participant', dataContext['links']
html = """
<span class="name">#{guard dataContext['participant_first_name']}</span>
<span class="name">#{guard dataContext['participant_last_name']}</span>
<span class="participant-id">#{dataContext['participant_id']}</span>
"""
if links[0]
html = "<a href=\"#{links[0]}\">#{html}</a>"
html
# Sort helpers.
fields = ['participant_first_name', 'participant_last_name', 'scheduled_date']
cmp = (a, b) ->
if a < b
-1
else if a > b
1
else
0
comparer = (a, b) ->
for field in fields
res = cmp(a[field], b[field])
if res != 0
return res
0
# ----------------------------------------------------------------------------
# GRID
# ----------------------------------------------------------------------------
Pancakes.EventSearchResultsGrid = Pancakes.SearchResultsGrid.extend
options:
autoHeight: true
forceFitColumns: true
columns: [
{ id: 'data_collectors', name: 'Data collectors', field: 'data_collector_usernames', formatter: dcFormatter },
{ id: 'disposition', name: 'Disposition', field: 'disposition_code', formatter: edFormatter },
{ id: 'event_type', name: 'Event type', field: 'event_type', formatter: etFormatter },
{ id: 'participant', name: 'PI:NAME:<NAME>END_PI', formatter: pFormatter, width: 200 },
{ id: 'scheduled_date', name: 'Scheduled date', field: 'scheduled_date' }
]
groupOnContentChange: (->
view = @get 'view'
content = @get 'content'
if view && content
view.setGrouping([{ getter: 'group', formatter: (g) -> "Location: #{g.value}" }])
).observes('content', 'view')
# The underlying DataView and GroupItemMetadataProvider have a couple of
# requirements:
#
# 1. The DataView requires that each row's id property contain a unique ID.
# 2. The grouping provider requires a top-level grouping member.
#
# This observer builds both.
rebuildIndices: (->
view = @get 'view'
content = @get 'content'
if view && content
data = content['event_searches']
_.each data, (o) ->
o['id'] = _.uniqueId()
o['group'] = o['pancakes.location']['name']
view.setItems data
view.sort comparer, true
).observes('content', 'view')
# vim:ts=2:sw=2:et:tw=78
|
[
{
"context": "pe:\"ModifierSurviveDamageWatch\"\n\n\n\t@modifierName:\"Survive Damage Watch\"\n\t@description: \"Survive Damage\"",
"end": 230,
"score": 0.7235717177391052,
"start": 227,
"tag": "NAME",
"value": "Sur"
}
] | app/sdk/modifiers/modifierSurviveDamageWatch.coffee | willroberts/duelyst | 5 | Modifier = require './modifier'
DamageAction = require 'app/sdk/actions/damageAction'
class ModifierSurviveDamageWatch extends Modifier
type:"ModifierSurviveDamageWatch"
@type:"ModifierSurviveDamageWatch"
@modifierName:"Survive Damage Watch"
@description: "Survive Damage"
activeInHand: false
activeInDeck: false
activeInSignatureCards: false
activeOnBoard: true
fxResource: ["FX.Modifiers.ModifierSurviveDamageWatch"]
onAfterCleanupAction: (e) ->
super(e)
action = e.action
# watch for this card taking damage > 0 AND surviving the damage
if action instanceof DamageAction and action.getTarget() is @getCard() and action.getTotalDamageAmount() > 0
@onSurviveDamage(action)
onSurviveDamage: (action) ->
# override me in sub classes to implement special behavior
module.exports = ModifierSurviveDamageWatch
| 202975 | Modifier = require './modifier'
DamageAction = require 'app/sdk/actions/damageAction'
class ModifierSurviveDamageWatch extends Modifier
type:"ModifierSurviveDamageWatch"
@type:"ModifierSurviveDamageWatch"
@modifierName:"<NAME>vive Damage Watch"
@description: "Survive Damage"
activeInHand: false
activeInDeck: false
activeInSignatureCards: false
activeOnBoard: true
fxResource: ["FX.Modifiers.ModifierSurviveDamageWatch"]
onAfterCleanupAction: (e) ->
super(e)
action = e.action
# watch for this card taking damage > 0 AND surviving the damage
if action instanceof DamageAction and action.getTarget() is @getCard() and action.getTotalDamageAmount() > 0
@onSurviveDamage(action)
onSurviveDamage: (action) ->
# override me in sub classes to implement special behavior
module.exports = ModifierSurviveDamageWatch
| true | Modifier = require './modifier'
DamageAction = require 'app/sdk/actions/damageAction'
class ModifierSurviveDamageWatch extends Modifier
type:"ModifierSurviveDamageWatch"
@type:"ModifierSurviveDamageWatch"
@modifierName:"PI:NAME:<NAME>END_PIvive Damage Watch"
@description: "Survive Damage"
activeInHand: false
activeInDeck: false
activeInSignatureCards: false
activeOnBoard: true
fxResource: ["FX.Modifiers.ModifierSurviveDamageWatch"]
onAfterCleanupAction: (e) ->
super(e)
action = e.action
# watch for this card taking damage > 0 AND surviving the damage
if action instanceof DamageAction and action.getTarget() is @getCard() and action.getTotalDamageAmount() > 0
@onSurviveDamage(action)
onSurviveDamage: (action) ->
# override me in sub classes to implement special behavior
module.exports = ModifierSurviveDamageWatch
|
[
{
"context": "en?\n config.headers.Authorization = \"Basic #{window.btoa(\"token:\" + $rootScope.user.token)}\"\n config or",
"end": 400,
"score": 0.836371898651123,
"start": 389,
"tag": "KEY",
"value": "window.btoa"
},
{
"context": "facebook.com/{{user.id}}/picture\"\n ... | src/diary/site/static/coffee/diary.app.coffee | hoest/online-dagboek | 1 | "use strict"
###
AngurlarJS App
###
@diary = angular.module "diary", ["ngRoute", "ngResource", "hc.commonmark"]
###
Authenticate interceptor
###
diary.factory "diaryAuthenticate", ["$q", "$location", "$rootScope", ($q, $location, $rootScope) ->
request: (config) ->
config.headers = config.headers or {}
if $rootScope.user?.token?
config.headers.Authorization = "Basic #{window.btoa("token:" + $rootScope.user.token)}"
config or $q.when(config)
requestError: (rejection) ->
$q.reject(rejection)
response: (response) ->
response or $q.when(response)
responseError: (rejection) ->
if rejection?.status? and rejection.status is 401
$location.path("/login")
$q.reject(rejection)
]
diary.config ["$httpProvider", ($httpProvider) ->
$httpProvider.interceptors.push "diaryAuthenticate"
]
###
Disable some $compile stuff: debugInfo
###
diary.config ["$compileProvider", ($compileProvider) ->
$compileProvider.debugInfoEnabled false
]
###
$locationProvider settings
###
diary.config ["$locationProvider", ($locationProvider) ->
$locationProvider.html5Mode
"enabled": true
"requireBase": true
$locationProvider.hashPrefix("!")
]
###
Routes
###
diary.config ["$routeProvider", ($routeProvider) ->
$routeProvider
.when "/diary/:diary_id?",
controller: "diaryController"
template: """<div data-ng-if="user.token">
<article class="post" data-ng-repeat="post in posts track by post.id">
<header>
<h1>{{post.title}}</h1>
<time datetime="{{post.date}}">{{post.date|date:'fullDate'}}</time>
</header>
<section data-common-mark="post.body"></section>
<aside data-ng-if="post.pictures.length != 0">
<div class="image" data-ng-repeat="pic in post.pictures track by pic.id">
<a data-ng-href="{{pic.file_url}}">
<img data-ng-src="{{pic.thumb_url}}" alt="{{pic.title}}" title="{{pic.title}}" />
</a>
</div>
</aside>
</article>
<p data-ng-hide="hideMore">
<a href data-ng-click="loadMore();">Laad meer...</a>
</p>
</div>"""
]
###
Diary controller
###
diary.controller "diaryController", ["$scope", "$rootScope", "$routeParams", "$resource", ($scope, $rootScope, $routeParams, $resource) ->
$scope.posts = []
$scope.hideMore = false
$scope.user = $rootScope.user
page = 1
$scope.loadMore = () ->
Posts = $resource("/api/v1/diaries/#{$routeParams.diary_id}/posts/#{page}")
Posts.get (data) ->
if data.posts.length > 0
$scope.posts = $scope.posts.concat data.posts
else
$scope.hideMore = true
page += 1
$scope.loadMore()
]
###
Navigation
###
diary.directive "diaryNavigation", ->
restrict: "A"
template: """<ul>
<li><a href="/site/">Home</a></li>
<li data-ng-if="user.token">Dagboeken<subitems data-diary-list /></li>
<li><a href="/site/over-deze-site">Over deze site</a></li>
</ul>"""
###
Content
###
diary.directive "diaryContent", ["$rootScope", "$resource", ($rootScope, $resource) ->
link: (scope, element, attr) ->
scope.user = $rootScope.user
restrict: "A"
template: """<div>
<div data-ng-if="user.token">
<p>Welkom {{user.first_name}} ({{user.id}})</p>
<div data-facebook-picture></div>
<div data-ng-view></div>
</div>
<div data-ng-hide="user.token">
<p>Je dient in te loggen met behulp van je Facebook-account.</p>
</div>
</div>"""
]
diary.directive "diaryList", ["$resource", "$location", ($resource, $location) ->
link: (scope, element, attr) ->
Diaries = $resource("/api/v1/diaries")
scope.diaries = []
Diaries.get (data) ->
scope.diaries = data.diaries
restrict: "A"
replace: true
template: """<ul>
<li data-ng-repeat="diary in diaries track by diary.id">
<a href="/site/diary/{{diary.id}}">{{diary.title}}</a>
</li>
</ul>"""
]
###
Footer
###
diary.directive "diaryFooter", ->
template: """<p>© 2014 - <a href="http://www.online-dagboek.nl">www.online-dagboek.nl</a></p>"""
###
Facebook picture
###
diary.directive "facebookPicture", ["$rootScope", ($rootScope) ->
link: (scope, element, attr) ->
scope.user = $rootScope.user
restrict: "A"
template: """<div class="facebook-picture" data-ng-if="user.token">
<a data-ng-href="//www.facebook.com/{{user.id}}">
<img data-ng-src="//graph.facebook.com/{{user.id}}/picture"
alt="Profielfoto van {{user.first_name}}"
title="Profielfoto van {{user.first_name}}" />
</a>
</div>"""
]
###
ngApp bootstrap
###
angular.element(document).ready ->
angular.bootstrap document, ["diary"],
ngStrictDi: true
| 94380 | "use strict"
###
AngurlarJS App
###
@diary = angular.module "diary", ["ngRoute", "ngResource", "hc.commonmark"]
###
Authenticate interceptor
###
diary.factory "diaryAuthenticate", ["$q", "$location", "$rootScope", ($q, $location, $rootScope) ->
request: (config) ->
config.headers = config.headers or {}
if $rootScope.user?.token?
config.headers.Authorization = "Basic #{<KEY>("token:" + $rootScope.user.token)}"
config or $q.when(config)
requestError: (rejection) ->
$q.reject(rejection)
response: (response) ->
response or $q.when(response)
responseError: (rejection) ->
if rejection?.status? and rejection.status is 401
$location.path("/login")
$q.reject(rejection)
]
diary.config ["$httpProvider", ($httpProvider) ->
$httpProvider.interceptors.push "diaryAuthenticate"
]
###
Disable some $compile stuff: debugInfo
###
diary.config ["$compileProvider", ($compileProvider) ->
$compileProvider.debugInfoEnabled false
]
###
$locationProvider settings
###
diary.config ["$locationProvider", ($locationProvider) ->
$locationProvider.html5Mode
"enabled": true
"requireBase": true
$locationProvider.hashPrefix("!")
]
###
Routes
###
diary.config ["$routeProvider", ($routeProvider) ->
$routeProvider
.when "/diary/:diary_id?",
controller: "diaryController"
template: """<div data-ng-if="user.token">
<article class="post" data-ng-repeat="post in posts track by post.id">
<header>
<h1>{{post.title}}</h1>
<time datetime="{{post.date}}">{{post.date|date:'fullDate'}}</time>
</header>
<section data-common-mark="post.body"></section>
<aside data-ng-if="post.pictures.length != 0">
<div class="image" data-ng-repeat="pic in post.pictures track by pic.id">
<a data-ng-href="{{pic.file_url}}">
<img data-ng-src="{{pic.thumb_url}}" alt="{{pic.title}}" title="{{pic.title}}" />
</a>
</div>
</aside>
</article>
<p data-ng-hide="hideMore">
<a href data-ng-click="loadMore();">Laad meer...</a>
</p>
</div>"""
]
###
Diary controller
###
diary.controller "diaryController", ["$scope", "$rootScope", "$routeParams", "$resource", ($scope, $rootScope, $routeParams, $resource) ->
$scope.posts = []
$scope.hideMore = false
$scope.user = $rootScope.user
page = 1
$scope.loadMore = () ->
Posts = $resource("/api/v1/diaries/#{$routeParams.diary_id}/posts/#{page}")
Posts.get (data) ->
if data.posts.length > 0
$scope.posts = $scope.posts.concat data.posts
else
$scope.hideMore = true
page += 1
$scope.loadMore()
]
###
Navigation
###
diary.directive "diaryNavigation", ->
restrict: "A"
template: """<ul>
<li><a href="/site/">Home</a></li>
<li data-ng-if="user.token">Dagboeken<subitems data-diary-list /></li>
<li><a href="/site/over-deze-site">Over deze site</a></li>
</ul>"""
###
Content
###
diary.directive "diaryContent", ["$rootScope", "$resource", ($rootScope, $resource) ->
link: (scope, element, attr) ->
scope.user = $rootScope.user
restrict: "A"
template: """<div>
<div data-ng-if="user.token">
<p>Welkom {{user.first_name}} ({{user.id}})</p>
<div data-facebook-picture></div>
<div data-ng-view></div>
</div>
<div data-ng-hide="user.token">
<p>Je dient in te loggen met behulp van je Facebook-account.</p>
</div>
</div>"""
]
diary.directive "diaryList", ["$resource", "$location", ($resource, $location) ->
link: (scope, element, attr) ->
Diaries = $resource("/api/v1/diaries")
scope.diaries = []
Diaries.get (data) ->
scope.diaries = data.diaries
restrict: "A"
replace: true
template: """<ul>
<li data-ng-repeat="diary in diaries track by diary.id">
<a href="/site/diary/{{diary.id}}">{{diary.title}}</a>
</li>
</ul>"""
]
###
Footer
###
diary.directive "diaryFooter", ->
template: """<p>© 2014 - <a href="http://www.online-dagboek.nl">www.online-dagboek.nl</a></p>"""
###
Facebook picture
###
diary.directive "facebookPicture", ["$rootScope", ($rootScope) ->
link: (scope, element, attr) ->
scope.user = $rootScope.user
restrict: "A"
template: """<div class="facebook-picture" data-ng-if="user.token">
<a data-ng-href="//www.facebook.com/{{user.id}}">
<img data-ng-src="//graph.facebook.com/{{user.id}}/picture"
alt="<NAME> {{user.first_name}}"
title="<NAME> {{user.first_name}}" />
</a>
</div>"""
]
###
ngApp bootstrap
###
angular.element(document).ready ->
angular.bootstrap document, ["diary"],
ngStrictDi: true
| true | "use strict"
###
AngurlarJS App
###
@diary = angular.module "diary", ["ngRoute", "ngResource", "hc.commonmark"]
###
Authenticate interceptor
###
diary.factory "diaryAuthenticate", ["$q", "$location", "$rootScope", ($q, $location, $rootScope) ->
request: (config) ->
config.headers = config.headers or {}
if $rootScope.user?.token?
config.headers.Authorization = "Basic #{PI:KEY:<KEY>END_PI("token:" + $rootScope.user.token)}"
config or $q.when(config)
requestError: (rejection) ->
$q.reject(rejection)
response: (response) ->
response or $q.when(response)
responseError: (rejection) ->
if rejection?.status? and rejection.status is 401
$location.path("/login")
$q.reject(rejection)
]
diary.config ["$httpProvider", ($httpProvider) ->
$httpProvider.interceptors.push "diaryAuthenticate"
]
###
Disable some $compile stuff: debugInfo
###
diary.config ["$compileProvider", ($compileProvider) ->
$compileProvider.debugInfoEnabled false
]
###
$locationProvider settings
###
diary.config ["$locationProvider", ($locationProvider) ->
$locationProvider.html5Mode
"enabled": true
"requireBase": true
$locationProvider.hashPrefix("!")
]
###
Routes
###
diary.config ["$routeProvider", ($routeProvider) ->
$routeProvider
.when "/diary/:diary_id?",
controller: "diaryController"
template: """<div data-ng-if="user.token">
<article class="post" data-ng-repeat="post in posts track by post.id">
<header>
<h1>{{post.title}}</h1>
<time datetime="{{post.date}}">{{post.date|date:'fullDate'}}</time>
</header>
<section data-common-mark="post.body"></section>
<aside data-ng-if="post.pictures.length != 0">
<div class="image" data-ng-repeat="pic in post.pictures track by pic.id">
<a data-ng-href="{{pic.file_url}}">
<img data-ng-src="{{pic.thumb_url}}" alt="{{pic.title}}" title="{{pic.title}}" />
</a>
</div>
</aside>
</article>
<p data-ng-hide="hideMore">
<a href data-ng-click="loadMore();">Laad meer...</a>
</p>
</div>"""
]
###
Diary controller
###
diary.controller "diaryController", ["$scope", "$rootScope", "$routeParams", "$resource", ($scope, $rootScope, $routeParams, $resource) ->
$scope.posts = []
$scope.hideMore = false
$scope.user = $rootScope.user
page = 1
$scope.loadMore = () ->
Posts = $resource("/api/v1/diaries/#{$routeParams.diary_id}/posts/#{page}")
Posts.get (data) ->
if data.posts.length > 0
$scope.posts = $scope.posts.concat data.posts
else
$scope.hideMore = true
page += 1
$scope.loadMore()
]
###
Navigation
###
diary.directive "diaryNavigation", ->
restrict: "A"
template: """<ul>
<li><a href="/site/">Home</a></li>
<li data-ng-if="user.token">Dagboeken<subitems data-diary-list /></li>
<li><a href="/site/over-deze-site">Over deze site</a></li>
</ul>"""
###
Content
###
diary.directive "diaryContent", ["$rootScope", "$resource", ($rootScope, $resource) ->
link: (scope, element, attr) ->
scope.user = $rootScope.user
restrict: "A"
template: """<div>
<div data-ng-if="user.token">
<p>Welkom {{user.first_name}} ({{user.id}})</p>
<div data-facebook-picture></div>
<div data-ng-view></div>
</div>
<div data-ng-hide="user.token">
<p>Je dient in te loggen met behulp van je Facebook-account.</p>
</div>
</div>"""
]
diary.directive "diaryList", ["$resource", "$location", ($resource, $location) ->
link: (scope, element, attr) ->
Diaries = $resource("/api/v1/diaries")
scope.diaries = []
Diaries.get (data) ->
scope.diaries = data.diaries
restrict: "A"
replace: true
template: """<ul>
<li data-ng-repeat="diary in diaries track by diary.id">
<a href="/site/diary/{{diary.id}}">{{diary.title}}</a>
</li>
</ul>"""
]
###
Footer
###
diary.directive "diaryFooter", ->
template: """<p>© 2014 - <a href="http://www.online-dagboek.nl">www.online-dagboek.nl</a></p>"""
###
Facebook picture
###
diary.directive "facebookPicture", ["$rootScope", ($rootScope) ->
link: (scope, element, attr) ->
scope.user = $rootScope.user
restrict: "A"
template: """<div class="facebook-picture" data-ng-if="user.token">
<a data-ng-href="//www.facebook.com/{{user.id}}">
<img data-ng-src="//graph.facebook.com/{{user.id}}/picture"
alt="PI:NAME:<NAME>END_PI {{user.first_name}}"
title="PI:NAME:<NAME>END_PI {{user.first_name}}" />
</a>
</div>"""
]
###
ngApp bootstrap
###
angular.element(document).ready ->
angular.bootstrap document, ["diary"],
ngStrictDi: true
|
[
{
"context": " command = new Command({\n project: '/home/fabian/.atom/packages/build-tools/spec/fixtures'\n n",
"end": 227,
"score": 0.9979881048202515,
"start": 221,
"tag": "USERNAME",
"value": "fabian"
},
{
"context": "/packages/build-tools/spec/fixtures'\n name: ... | spec/modifier-env-spec.coffee | fstiewitz/build-tools-cpp | 3 | Env = require '../lib/modifier/env'
Command = require '../lib/provider/command'
describe 'Command Modifier - Environment Variables', ->
command = null
beforeEach ->
command = new Command({
project: '/home/fabian/.atom/packages/build-tools/spec/fixtures'
name: 'Test'
command: 'echo Hello World'
wd: '.'
env: {}
modifier:
env:
TEST1: 'Hello'
PWD: '/'
stdout:
highlighting: 'nh'
stderr:
highlighting: 'nh'
output:
console:
close_success: false
version: 1
})
command.getSpawnInfo()
Env.preSplit command
it 'returns valid data', ->
expect(command.env['TEST1']).toBe 'Hello'
expect(command.env['PWD']).toBe '/'
| 121545 | Env = require '../lib/modifier/env'
Command = require '../lib/provider/command'
describe 'Command Modifier - Environment Variables', ->
command = null
beforeEach ->
command = new Command({
project: '/home/fabian/.atom/packages/build-tools/spec/fixtures'
name: '<NAME>'
command: 'echo Hello World'
wd: '.'
env: {}
modifier:
env:
TEST1: 'Hello'
PWD: '/'
stdout:
highlighting: 'nh'
stderr:
highlighting: 'nh'
output:
console:
close_success: false
version: 1
})
command.getSpawnInfo()
Env.preSplit command
it 'returns valid data', ->
expect(command.env['TEST1']).toBe 'Hello'
expect(command.env['PWD']).toBe '/'
| true | Env = require '../lib/modifier/env'
Command = require '../lib/provider/command'
describe 'Command Modifier - Environment Variables', ->
command = null
beforeEach ->
command = new Command({
project: '/home/fabian/.atom/packages/build-tools/spec/fixtures'
name: 'PI:NAME:<NAME>END_PI'
command: 'echo Hello World'
wd: '.'
env: {}
modifier:
env:
TEST1: 'Hello'
PWD: '/'
stdout:
highlighting: 'nh'
stderr:
highlighting: 'nh'
output:
console:
close_success: false
version: 1
})
command.getSpawnInfo()
Env.preSplit command
it 'returns valid data', ->
expect(command.env['TEST1']).toBe 'Hello'
expect(command.env['PWD']).toBe '/'
|
[
{
"context": "rt des Verteidigers um 1 (Minimum 0).\"\"\"\n \"Garven Dreis\":\n text: \"\"\"Wenn du einen Fokusmarker ",
"end": 7049,
"score": 0.9926570057868958,
"start": 7037,
"tag": "NAME",
"value": "Garven Dreis"
},
{
"context": "dich nicht zum Ziel bestimmen ka... | coffeescripts/cards-de.coffee | michigun/xwing | 0 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.de = 'Deutsch'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations.Deutsch =
action:
"Barrel Roll": "Fassrolle"
"Boost": "Schub"
"Evade": "Ausweichen"
"Focus": "Fokussierung"
"Target Lock": "Zielerfassung"
"Recover": "Aufladen"
"Reinforce": "Verstärken"
"Jam": "Störsignal"
"Coordinate": "Koordination"
"Cloak": "Tarnen"
slot:
"Astromech": "Astromech"
"Bomb": "Bombe"
"Cannon": "Kanonen"
"Crew": "Crew"
"Elite": "Elite"
"Missile": "Raketen"
"System": "System"
"Torpedo": "Torpedo"
"Turret": "Geschützturm"
"Cargo": "Fracht"
"Hardpoint": "Hardpoint"
"Team": "Team"
"Illicit": "illegales"
"Salvaged Astromech": "geborgener Astromech"
sources: # needed?
"Core": "Grundspiel"
"A-Wing Expansion Pack": "A-Wing Erweiterung"
"B-Wing Expansion Pack": "B-Wing Erweiterung"
"X-Wing Expansion Pack": "X-Wing Erweiterung"
"Y-Wing Expansion Pack": "Y-Wing Erweiterung"
"Millennium Falcon Expansion Pack": "Millenium Falke Erweiterung"
"HWK-290 Expansion Pack": "HWK-290 Erweiterung"
"TIE Fighter Expansion Pack": "TIE-Fighter Erweiterung"
"TIE Interceptor Expansion Pack": "TIE-Abfangjäger Erweiterung"
"TIE Bomber Expansion Pack": "TIE-Bomber Erweiterung"
"TIE Advanced Expansion Pack": "TIE-Advanced Erweiterung"
"Lambda-Class Shuttle Expansion Pack": "Raumfähre der Lambda-Klasse Erweiterung"
"Slave I Expansion Pack": "Sklave I Erweiterung"
"Imperial Aces Expansion Pack": "Fliegerasse des Imperiums Erweiterung"
"Rebel Transport Expansion Pack": "Rebellentransporter Erweiterung"
"Z-95 Headhunter Expansion Pack": "Z-95-Kopfjäger Erweiterung"
"TIE Defender Expansion Pack": "TIE-Jagdbomber Erweiterung"
"E-Wing Expansion Pack": "E-Wing Erweiterung"
"TIE Phantom Expansion Pack": "TIE-Phantom Erweiterung"
"Tantive IV Expansion Pack": "Tantive IV Erweiterung"
"Rebel Aces Expansion Pack": "Fliegerasse der Rebellenallianz Erweiterung"
"YT-2400 Freighter Expansion Pack": "YT-2400-Frachter Erweiterung"
"VT-49 Decimator Expansion Pack": "VT-49 Decimator Erweiterung"
"StarViper Expansion Pack": "SternenViper Erweiterung"
"M3-A Interceptor Expansion Pack": "M3-A Abfangjäger Erweiterung"
"IG-2000 Expansion Pack": "IG-2000 Erweiterung"
"Most Wanted Expansion Pack": "Abschaum und Kriminelle Erweiterung"
"Imperial Raider Expansion Pack": "Imperial Raider Expansion Pack"
ui:
shipSelectorPlaceholder: "Wähle ein Schiff"
pilotSelectorPlaceholder: "Wähle einen Piloten"
upgradePlaceholder: (translator, language, slot) ->
"kein #{translator language, 'slot', slot} Upgrade"
modificationPlaceholder: "keine Modifikation"
titlePlaceholder: "kein Titel"
upgradeHeader: (translator, language, slot) ->
"#{translator language, 'slot', slot} Upgrade"
unreleased: "unveröffentlicht"
epic: "Episch"
limited: "limitiert"
byCSSSelector:
'.translate.sort-cards-by': 'Sortiere Karten per'
'.xwing-card-browser option[value="name"]': 'Name'
'.xwing-card-browser option[value="source"]': 'Quelle'
'.xwing-card-browser option[value="type-by-points"]': 'Typ (Punkte)'
'.xwing-card-browser option[value="type-by-name"]': 'Typ (Name)'
'.xwing-card-browser .translate.select-a-card': 'Wähle eine Karte aus der Liste.'
'.xwing-card-browser .info-range td': 'Reichweite'
# Info well
'.info-well .info-ship td.info-header': 'Schiff'
'.info-well .info-skill td.info-header': 'Pilotenwert'
'.info-well .info-actions td.info-header': 'Aktionen'
'.info-well .info-upgrades td.info-header': 'Aufwertungen'
'.info-well .info-range td.info-header': 'Reichweite'
# Squadron edit buttons
'.clear-squad' : 'Neues Squad'
'.save-list' : 'Speichern'
'.save-list-as' : 'Speichern als…'
'.delete-list' : 'Löschen'
'.backend-list-my-squads' : 'Squad laden'
'.view-as-text' : '<span class="hidden-phone"><i class="icon-print"></i> Drucken/Anzeigen als </span>Text'
'.randomize' : 'Zufallsliste!'
'.randomize-options' : 'Zufallslistenoptionen…'
# Print/View modal
'.bbcode-list' : 'Kopiere den BBCode von unten und füge ihn in deine Forenposts ein.<textarea></textarea>'
'.vertical-space-checkbox' : """Platz für Schadenskarten und Upgrades im Druck berücksichtigen. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Ausdrucken in farbe. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="icon-print"></i> Print'
# Randomizer options
'.do-randomize' : 'Zufall!'
# Top tab bar
'#empireTab' : 'Galaktisches Imperium'
'#rebelTab' : 'Rebellen Allianz'
'#scumTab' : 'Abschaum und Kriminelle'
'#browserTab' : 'Karten Browser'
'#aboutTab' : 'Über'
singular:
'pilots': 'Pilot'
'modifications': 'Modifikation'
'titles': 'Titel'
types:
'Pilot': 'Pilot'
'Modification': 'Modifikation'
'Title': 'Titel'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders.Deutsch = () ->
exportObj.cardLanguage = 'Deutsch'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
# Move TIE Interceptor to TIE-Abfangjäger
exportObj.renameShip 'TIE Interceptor', 'TIE-Abfangjäger'
# Move Z-95 Headhunter to Z-95-Kopfjäger
exportObj.renameShip 'Z-95 Headhunter', 'Z-95-Kopfjäger'
# Move TIE Defender to TIE-Jagdbomber
exportObj.renameShip 'TIE Defender', 'TIE-Jagdbomber'
# Move Lambda-Class Shuttle to Raumfähre der Lambda-Klasse
exportObj.renameShip 'Lambda-Class Shuttle', 'Raumfähre der Lambda-Klasse'
# Move GR-75 Medium Transport to Medium-Transporter GR-75
exportObj.renameShip 'GR-75 Medium Transport', 'Medium-Transporter GR-75'
# Move CR90 Corvette (Fore) to CR90-Korvette (Bug)
exportObj.renameShip 'CR90 Corvette (Fore)', 'CR90-Korvette (Bug)'
# Move CR90 Corvette (Aft) to CR90-Korvette (Heck)
exportObj.renameShip 'CR90 Corvette (Aft)', 'CR90-Korvette (Heck)'
# Move M3-A Interceptor to M3-A Abfangjäger
exportObj.renameShip 'M3-A Interceptor', 'M3-A Abfangjäger'
pilot_translations =
"Wedge Antilles":
text: """Wenn du angreifst, sinkt der Wendigkeitswert des Verteidigers um 1 (Minimum 0)."""
"Garven Dreis":
text: """Wenn du einen Fokusmarker ausgibst, darfst du ihn auf ein anderes freundliches Schiff in Reichweite 1-2 legen (anstatt ihn abzulegen)."""
"Red Squadron Pilot":
name: "Pilot der Rot-Staffel"
"Rookie Pilot":
name: "Anfängerpilot"
"Biggs Darklighter":
text: """Andere freundliche Schiffe in Reichweite 1 dürfen nur dann angegriffen werden, wenn der Angreifer dich nicht zum Ziel bestimmen kann."""
"Luke Skywalker":
text: """Wenn du verteidigst, kannst du 1 deiner %FOCUS% in ein %EVADE% ändern."""
"Gray Squadron Pilot":
name: "Pilot der Grau-Staffel"
'"Dutch" Vander':
text: """Wähle ein anderes freundliches Schiff in Reichweite 1-2, nachdem du eine Zielerfassung durchgeführt hast. Das gewählte Schiff darf sofort ebenfalls eine Zielerfassung durchführen."""
"Horton Salm":
text: """Wenn du ein Ziel in Reichweite 2-3 angreifst, darfst du beliebig viele Leerseiten neu würfeln."""
"Gold Squadron Pilot":
name: "Pilot der Gold-Staffel"
"Academy Pilot":
name: "Pilot der Akademie"
"Obsidian Squadron Pilot":
name: "Pilot der Obsidian-Staffel"
"Black Squadron Pilot":
name: "Pilot der Schwarz-Staffel"
'"Winged Gundark"':
name: '"Geflügelter Gundark"'
text: """Wenn du ein Ziel in Reichweite 1 angreifst, darfst du eines deiner %HIT% in ein %CRIT% ändern."""
'"Night Beast"':
name: '"Nachtbestie"'
text: """Nachdem du ein grünes Manöver ausgeführt hast, darfst du als freie Aktion eine Fokussierung durchführen."""
'"Backstabber"':
text: """Wenn du bei deinem Angriff nicht im Feuerwinkel des Verteidigers bist, erhältst du 1 zusätzlichen Angriffswürfel."""
'"Dark Curse"':
text: """Wenn du verteidigst, können angreifende Schiffe keine Fokusmarker ausgeben oder Angriffswürfel neu würfeln."""
'"Mauler Mithel"':
text: """Wirf 1 zusätzlichen Angriffswürfel, wenn du ein Ziel in Reichweite 1 angreifst."""
'"Howlrunner"':
name: '"Kreischläufer"'
text: """Wenn ein anderes freundliches Schiff in Reichweite 1 mit seinen Primärwaffen angreift, darf es 1 Angriffswürfel neu würfeln."""
"Maarek Stele":
text: """Wenn ein Verteidiger durch deinen Angriff eine offene Schadenskarte erhalten würde, ziehst du stattdessen 3 Schadenskarten, wählst eine davon zum Austeilen und legst die restlichen ab."""
"Tempest Squadron Pilot":
name: "Pilot der Tornado-Staffel"
"Storm Squadron Pilot":
name: "Pilot der Storm-Staffel"
"Darth Vader":
text: """Im Schritt "Aktionen durchführen" darfst du 2 Aktionen durchführen."""
"Alpha Squadron Pilot":
name: "Pilot der Alpha-Staffel"
ship: "TIE-Abfangjäger"
"Avenger Squadron Pilot":
name: "Pilot der Avenger-Staffel"
ship: "TIE-Abfangjäger"
"Saber Squadron Pilot":
name: "Pilot der Saber-Staffel"
ship: "TIE-Abfangjäger"
"\"Fel's Wrath\"":
ship: "TIE-Abfangjäger"
text: """Wenn die Summe deiner Schadenskarten deinen Hüllenwert erreicht oder übersteigt, wirst du nicht sofort zerstört, sondern erst am Ende der Kampfphase."""
"Turr Phennir":
ship: "TIE-Abfangjäger"
text: """Nachdem du angegriffen hast, darfst du eine freie Aktion Schub oder Fassrolle durchführen."""
"Soontir Fel":
ship: "TIE-Abfangjäger"
text: """Immer wenn du einen Stressmarker erhältst, darfst du deinem Schiff auch einen Fokusmarker geben."""
"Tycho Celchu":
text: """Du darfst auch dann Aktionen durchführen, wenn du Stressmarker hast."""
"Arvel Crynyd":
text: """Wenn du angreifst, darfst du auch auf feindliche Schiffe zielen, deren Basen du berührst (vorausgesetzt sie sind innerhalb deines Feuerwinkels)."""
"Green Squadron Pilot":
name: "Pilot der Grün-Staffel"
"Prototype Pilot":
name: "Testpilot"
"Outer Rim Smuggler":
name: "Schmuggler aus dem Outer Rim"
"Chewbacca":
text: """Wenn du eine offene Schadenskarte erhältst, wird sie sofort umgedreht (ohne dass ihr Kartentext in Kraft tritt)."""
"Lando Calrissian":
text: """Wähle nach dem Ausführen eines grünen Manövers ein anderes freundliches Schiff in Reichweite 1. Dieses Schiff darf eine freie Aktion aus seiner Aktionsleiste durchführen."""
"Han Solo":
text: """Wenn du angreifst, darfst du all deine Würfel neu würfeln. Tust du dies, musst du so viele Würfel wie möglich neu würfeln."""
"Kath Scarlet":
text: """Wenn du angreifst und der Verteidiger mindestens 1 %CRIT% negiert, erhält er 1 Stressmarker."""
"Boba Fett":
text: """Sobald du ein Drehmanöver (%BANKLEFT% oder %BANKRIGHT%) aufdeckst, darfst du das Drehmanöver mit gleicher eschwindigkeit, aber anderer Richtung, auf deinem Rad nachträglich einstellen."""
"Krassis Trelix":
text: """Wenn du mit einer Sekundärwaffe angreifst, darfst du 1 Angriffswürfel neu würfeln."""
"Bounty Hunter":
name: "Kopfgeldjäger"
"Ten Numb":
text: """Wenn du angreifst, kann 1 deiner %CRIT% von Verteidigungswürfeln nicht negiert werden."""
"Ibtisam":
text: """Beim Angreifen oder Verteidigen darfst du 1 deiner Würfel neu würfeln, sofern du mindestens 1 Stressmarker hast."""
"Dagger Squadron Pilot":
name: "Pilot der Dagger-Staffel"
"Blue Squadron Pilot":
name: "Pilot der Blauen Staffel"
"Rebel Operative":
name: "Rebellenagent"
"Roark Garnet":
text: '''Wähle zu Beginn der Kampfphase 1 anderes freundliches Schiff in Reichweite 1-3. Bis zum Ende der Phase wird dieses Schiff behandelt, als hätte es einen Pilotenwert von 12.'''
"Kyle Katarn":
text: """Zu Beginn der Kampfphase darfst du einem anderen freundlichen Schiff in Reichweite 1-3 einen deiner Fokusmarker geben."""
"Jan Ors":
text: """Wenn ein anderes freundliches Schiff in Reichweite 1-3 angreift und du keine Stressmarker hast, darfst du 1 Stressmarker nehmen, damit dieses Schiff 1 zusätzlichen Angriffswürfel erhält."""
"Scimitar Squadron Pilot":
name: "Pilot der Scimitar-Staffel"
"Gamma Squadron Pilot":
name: "Pilot der Gamma-Staffel"
"Captain Jonus":
text: """Wenn ein anderes freundliches Schiff in Reichweite 1 mit einer Sekundärwaffe angreift, darf es bis zu 2 Angriffswürfel neu würfeln."""
"Major Rhymer":
text: """Beim Angreifen mit einer Sekundärwaffe darfst du die Reichweite der Waffe um 1 erhöhen oder verringern, bis zu einer Reichweite von 1-3."""
"Captain Kagi":
ship: "Raumfähre der Lambda-Klasse"
text: """Wenn ein feindliches Schiff eine Zielerfassung durchführt, muss es wenn möglich dich als Ziel erfassen."""
"Colonel Jendon":
ship: "Raumfähre der Lambda-Klasse"
text: """Zu Beginn der Kampfphase darfst du 1 deiner blauen Zielerfassungsmarker auf ein freundliches Schiff in Reichweite 1 legen, das noch keinen blauen Zielerfassungsmarker hat."""
"Captain Yorr":
ship: "Raumfähre der Lambda-Klasse"
text: """Wenn ein anderes freundliches Schiff in Reichweite 1-2 einen Stressmarker erhalten würde und du 2 oder weniger Stressmarker hast, darfst du statt ihm diesen Marker nehmen."""
"Omicron Group Pilot":
ship: "Raumfähre der Lambda-Klasse"
name: "Pilot der Omikron-Gruppe"
"Lieutenant Lorrir":
ship: "TIE-Abfangjäger"
text: """Wenn du die Aktion Fassrolle ausführst, kannst du 1 Stressmarker erhalten, um die (%BANKLEFT% 1) oder (%BANKRIGHT% 1) Manöverschablone anstatt der (%STRAIGHT% 1) Manöverschablone zu benutzen."""
"Royal Guard Pilot":
ship: "TIE-Abfangjäger"
name: "Pilot der Roten Garde"
"Tetran Cowall":
ship: "TIE-Abfangjäger"
text: """Immer wenn du ein %UTURN% Manöver aufdeckst, kannst du das Manöver mit einer Geschwindigkeit von "1," "3," oder "5" ausführen."""
"Kir Kanos":
ship: "TIE-Abfangjäger"
text: """Wenn du ein Ziel in Reichweite 2-3 angreifst, darfst du einen Ausweichmarker ausgeben, um 1 %HIT% zu deinem Wurf hinzuzufügen."""
"Carnor Jax":
ship: "TIE-Abfangjäger"
text: """Feindliche Schiffe in Reichweite 1 können weder Fokussierung und Ausweichen Aktionen durchführen noch Ausweichmarker und Fokusmarker ausgeben."""
"GR-75 Medium Transport":
ship: "Medium-Transporter GR-75"
name: "Medium-Transporter GR-75"
"Bandit Squadron Pilot":
ship: "Z-95-Kopfjäger"
name: "Pilot der Bandit-Staffel"
"Tala Squadron Pilot":
ship: "Z-95-Kopfjäger"
name: "Pilot der Tala-Staffel"
"Lieutenant Blount":
ship: "Z-95-Kopfjäger"
name: "Lieutenant Blount"
text: """Wenn du angreifst, triffst du immer, selbst wenn das verteidigende Schiff keinen Schaden nimmt."""
"Airen Cracken":
ship: "Z-95-Kopfjäger"
name: "Airen Cracken"
text: """Nachdem du angegriffen hast, darfst du ein anderes freundliches Schiff in Reichweite 1 wählen. Dieses Schiff darf 1 freie Aktion durchführen."""
"Delta Squadron Pilot":
ship: "TIE-Jagdbomber"
name: "Pilot der Delta-Staffel"
"Onyx Squadron Pilot":
ship: "TIE-Jagdbomber"
name: "Pilot der Onyx-Staffel"
"Colonel Vessery":
ship: "TIE-Jagdbomber"
text: """Wenn du angreifst und der Verteidiger bereits einen roten Zielerfassungsmarker hat, darfst du ihn unmittelbar nach dem Angriffswurf in die Zielerfassung nehmen."""
"Rexler Brath":
ship: "TIE-Jagdbomber"
text: """Nachdem du angegriffen und damit dem Verteidiger mindestens 1 Schadenskarte zugeteilt hast, kannst du einen Fokusmarker ausgeben, um die soeben zugeteilten Schadenskarten aufzudecken."""
"Knave Squadron Pilot":
name: "Pilot der Schurken-Staffel"
"Blackmoon Squadron Pilot":
name: "Pilot der Schwarzmond-Staffel"
"Etahn A'baht":
text: """Sobald ein feindliches Schiff in Reichweite 1–3 und innerhalb deines Feuerwinkels verteidigt, darf der Angreifer 1 %HIT% seiner in ein %CRIT% ändern."""
"Corran Horn":
text: """Zu Beginn der Endphase kannst du einen Angriff durchführen. Tust du das, darfst du in der nächsten Runde nicht angreifen."""
"Sigma Squadron Pilot":
name: "Pilot der Sigma-Staffel"
"Shadow Squadron Pilot":
name: "Pilot der Schatten-Staffel"
'"Echo"':
name: '"Echo"'
text: """Wenn du dich enttarnst, musst du statt der (%STRAIGHT% 2)-Manöverschablone die (%BANKRIGHT% 2)- oder (%BANKLEFT% 2)-Schablone verwenden."""
'"Whisper"':
name: '"Geflüster"'
text: """Nachdem du mit einem Angriff getroffen hast, darfst du deinem Schiff 1 Fokusmarker geben."""
"CR90 Corvette (Fore)":
name: "CR90-Korvette (Bug)"
ship: "CR90-Korvette (Bug)"
text: """Wenn du mit deinen Primärwaffen angreifst, kannst du 1 Energie ausgeben, um 1 zusätzlichen Angriffswürfel zu bekommen"""
"CR90 Corvette (Aft)":
name: "CR90-Korvette (Heck)"
ship: "CR90-Korvette (Heck)"
"Wes Janson":
text: """Nachdem du einen Angriff durchgeführt hast, darfst du 1 Fokus-, Ausweich- oder blauen Zielerfassungsmarker vom Verteidiger entfernen."""
"Jek Porkins":
text: """Wenn du einen Stressmarker erhälst, darfst du ihn entfernen und 1 Angriffswürfel werfen. Bei %HIT% bekommt dein Schiff 1 verdeckte Schadenskarte."""
'"Hobbie" Klivian':
text: """Wenn du ein Schiff in die Zielerfassung nimmst oder einen Zielerfassungsmarker ausgibst, kannst du 1 Stressmarker von deinem Schiff entfernen."""
"Tarn Mison":
text: """Wenn ein feindliches Schiff einen Angriff gegen dich ansagt, kannst du dieses Schiff in die Zielerfassung nehmen."""
"Jake Farrell":
text: """Nachdem du die Aktion Fokussierung durchgeführt oder einen Fokusmarker erhalten hast, darfst du als freie Aktion einen Schub oder eine Fassrolle durchführen."""
"Gemmer Sojan":
name: "Gemmer Sojan"
text: """Solange du in Reichweite 1 zu mindestens einem feindlichen Schiff bist, steigt dein Wendigkeitswert um 1."""
"Keyan Farlander":
text: """Beim Angreifen darfst du 1 Stressmarker entfernen, um alle deine %FOCUS% in %HIT% zu ändern."""
"Nera Dantels":
text: """Mit %TORPEDO%-Sekundärwaffen kannst du auch feindliche Schiffe außerhalb deines Feuerwinkels angreifen."""
# "CR90 Corvette (Crippled Aft)":
# name: "CR90-Korvette (Heck-Lahmgelegt)"
# ship: "CR90-Korvette (Heck)"
# text: """Folgende Manöver darfst du weder wählen noch ausführen: (%STRAIGHT% 4), (%BANKLEFT% 2), or (%BANKRIGHT% 2) ."""
# "CR90 Corvette (Crippled Fore)":
# name: "CR90-Korvette (Bug-Lahmgelegt)"
# ship: "CR90-Korvette (Bug)"
"Wild Space Fringer":
name: "Grenzgänger aus dem Wilden Raum"
"Dash Rendar":
text: """Du darfst in der Aktivierungsphase und beim Durchführen von Aktionen Hindernisse ignorieren."""
'"Leebo"':
text: """Immer wenn du eine offene Schadenskarte erhältst, ziehst du 1 weitere Schadenskarte. Wähle 1, die abgehandelt wird, und lege die andere ab."""
"Eaden Vrill":
text: """Wirf 1 zusätzlichen Angriffswürfel, wenn du mit den Primärwaffen auf ein Schiff mit Stressmarker schießt."""
"Patrol Leader":
name: "Patrouillenführer"
"Rear Admiral Chiraneau":
name: "Konteradmiral Chiraneau"
text: """Wenn du ein Ziel in Reichweite 1-2 angreifst, kannst du ein %FOCUS% in ein %CRIT% ändern."""
"Commander Kenkirk":
text: """Wenn du keine Schilde und mindestens 1 Schadenskarte hast, steigt deine Wendigkeit um 1."""
"Captain Oicunn":
text: """Nach dem Ausführen eines Manövers nimmt jedes feindliche Schiff, das du berührst, 1 Schaden."""
"Prince Xizor":
name: "Prinz Xizor"
text: """Sobald du verteidigst, darf ein freundliches Schiff in Reichweite 1 ein nicht-negiertes %HIT% oder %CRIT% an deiner Stelle nehmen."""
"Guri":
text: """Wenn du zu Beginn der Kampfphase in Reichweite 1 zu einem feindlichen Schiff bist, darfst du 1 Fokusmarker auf dein Schiff legen."""
"Black Sun Vigo":
name: "Vigo der Schwarzen Sonne"
"Black Sun Enforcer":
name: "Vollstrecker der Schwarzen Sonne"
"Serissu":
ship: "M3-A Abfangjäger"
text: """Sobald ein anderes freundliches Schiff in Reichweite 1 verteidigt, darf es 1 Verteidigungswürfel neu würfeln."""
"Laetin A'shera":
ship: "M3-A Abfangjäger"
text: """Nachdem du gegen einen Angriff verteidigt hast und falls der Angriff nicht getroffen hat, darfst du deinem Schiff 1 Ausweichmarker zuordnen."""
"Tansarii Point Veteran":
ship: "M3-A Abfangjäger"
name: "Veteran von Tansarii Point"
"Cartel Spacer":
ship: "M3-A Abfangjäger"
name: "Raumfahrer des Kartells"
"IG-88A":
text: """Nachdem du einen Angriff durchgeführt hast, der den Verteidiger zerstört, darfst du 1 Schild wiederaufladen."""
"IG-88B":
text: """Ein Mal pro Runde darfst du, nachdem du mit einem Angriff verfehlt hast, einen weiteren Angriff mit einer ausgerüsteten %CANNON%-Sekundärwaffe durchführen."""
"IG-88C":
text: """Nachdem du die Aktion Schub durchgeführt hast, darfst du eine freie Aktion Ausweichen durchführen."""
"IG-88D":
text: """Du darfst die Manöver (%SLOOPLEFT% 3) oder (%SLOOPRIGHT% 3) auch mit den entsprechenden Schablonen für Wendemanöver (%TURNLEFT% 3) bzw. (%TURNRIGHT% 3) ausführen."""
"Boba Fett (Scum)":
name: "Boba Fett (Abschaum)"
text: """Sobald du angreifst oder verteidigst, darfst du für jedes feindliche Schiff in Reichweite 1 einen deiner Würfel neu würfeln."""
"Kath Scarlet (Scum)":
name: "Kath Scarlet (Abschaum)"
text: """Sobald du ein Schiff innerhalb deines Zusatz-Feuerwinkels angreifst, erhältst du 1 zusätzlichen Angriffswürfel."""
"Emon Azzameen":
text: """Sobald du eine Bombe legst, darfst du auch die Schablone [%TURNLEFT% 3], [%STRAIGHT% 3] oder [%TURNRIGHT% 3] anstatt der [%STRAIGHT% 1]-Schablone verwenden."""
"Mandalorian Mercenary":
name: "Mandalorianischer Söldner"
"Kavil":
text: """Sobald du ein Schiff außerhalb deines Feuerwinkels angreifst, erhältst du 1 zusätzlichen Angriffswürfel."""
"Drea Renthal":
text: """Nachdem du einen Zielerfassungsmarker ausgegeben hast, darfst du 1 Stressmarker nehmen, um ein Schiff in die Zielerfassung zu nehmen."""
"Syndicate Thug":
name: "Verbrecher des Syndikats"
"Hired Gun":
name: "Söldner"
"Dace Bonearm":
text: """Sobald ein feindliches Schiff in Reichweite 1-3 mindestens 1 Ionenmarker erhält und falls du keinen Stressmarker hast, darfst du 1 Stressmarker nehmen, damit das Schiff 1 Schaden nimmt."""
"Palob Godalhi":
text: """Zu Beginn der Kampfphase darfst du 1 Fokus- oder Ausweichmarker von einem feindlichen Schiff in Reichweite 1-2 entfernen und dir selbst zuordnen."""
"Torkil Mux":
text: """Wähle am Ende der Aktivierungsphase 1 feindliches Schiff in Reichweite 1-2. Bis zum Ende der Kampfphase wird der Pilotenwert des Schiffs als "0" behandelt."""
"Spice Runner":
name: "Spiceschmuggler"
"N'Dru Suhlak":
ship: "Z-95-Kopfjäger"
text: """Sobald du angreifst, erhälst du 1 zusätzlichen Angriffswürfel, falls keine anderen freundlichen Schiffe in Reichweite 1-2 zu dir sind."""
"Kaa'To Leeachos":
ship: "Z-95-Kopfjäger"
text: """Zu Beginn der Kampfphase darfst du 1 Fokus- oder Ausweichmarker von einem anderem freundlichen Schiff in Reichweite 1-2 entfernen und dir selbst zuordnen."""
"Binayre Pirate":
ship: "Z-95-Kopfjäger"
name: "Binayre-Pilot"
"Black Sun Soldier":
ship: "Z-95-Kopfjäger"
name: "Kampfpilot der Schwarzen Sonne"
"Commander Alozen":
text: """At the start of the Combat phase, you may acquire a target lock on an enemy ship at Range 1."""
"Raider-class Corvette (Fore)":
text: """Once per round, ??? perform a primary ??? attack, you may spend 2 e??? perform another primary wea???"""
"Juno Eclipse":
text: """When you reveal your maneuver, you may increase or decrease its speed by 1 (to a minimum of 1)."""
"Zertik Strom":
text: """Enemy ships at Range 1 cannot add their range combat bonus when attacking."""
"Lieutenant Colzet":
text: """At the start of the End phase, you may spend a target lock you have on an enemy ship to flip 1 random facedown Damage card assigned to it faceup."""
"Latts Razzi":
text: """When a friendly ship declares an attack, you may spend a target lock you have on the defender to reduce its agility by 1 for that attack."""
"Graz the Hunter":
text: """When defending, if the attacker is inside your firing arc, roll 1 additional defense die."""
"Esege Tuketu":
text: """When another friendly ship at Range 1-2 is attacking, it may treat your focus tokens as its own."""
'"Redline"':
text: """You may maintain 2 target locks on the same ship. When you acquire a target lock, you may acquire a second lock on that ship."""
'"Deathrain"':
text: """When dropping a bomb, you may use the front guides of your ship. After dropping a bomb, you may perform a free barrel roll action."""
"Moralo Eval":
text: """You can perform %CANNON% secondary attacks against ships inside your auxiliary firing arc."""
'Gozanti-class Cruiser':
text: """After you execute a maneuver, you may deploy up to 2 attached ships."""
'"Scourge"':
text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die."""
"The Inquisitor":
text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1."""
"Zuckuss":
text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die."""
"Dengar":
text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship."""
upgrade_translations =
"Ion Cannon Turret":
name: "Ionengeschütz"
text: """<strong>Angriff:</strong> Greife 1 Schiff an (es muss nicht in deinem Feuerwinkel sein).<br /><br />Wenn der Angriff trifft, nimmt das verteidigende Schiff 1 Schaden und erhält 1 Ionenmarker. Dann werden alle übrigen Würfelergebnisse negiert."""
"Proton Torpedoes":
name: "Protonen-Torpedos"
text: """<strong>Angriff (Zielerfassung):</strong>Gib eine Zielerfassung aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst eines deiner %FOCUS% in ein %CRIT% ändern."""
"R2 Astromech":
name: "R2 Astromechdroide"
text: """Du darfst alle Manöver mit Geschwindigkeit 1 und 2 wie grüne Manöver behandeln."""
"R2-D2":
text: """Nachdem du ein grünes Manöver ausgeführt hast, darfst du 1 Schild wiederaufladen (bis maximal zum Schildwert)."""
"R2-F2":
text: """<strong>Aktion:</strong> Erhöhe deinen Wendigkeitswert bis zum Ende der Spielrunde um 1."""
"R5-D8":
text: """<strong>Aktion:</strong> Wirf 1 Verteidigungswürfel.<br /><br />Lege bei %EVADE% oder %FOCUS% 1 deiner verdeckten Schadenskarten ab."""
"R5-K6":
text: """Wirf 1 Verteidigungswürfel nachdem du deine Zielerfassungsmarker ausgegeben hast.<br /><br />Bei %EVADE% nimmst du dasselbe Schiff sofort wieder in die Zielerfassung. Für diesen Angriff kannst du die Zielerfassungsmarker nicht erneut ausgeben."""
"R5 Astromech":
name: "R5 Astromechdroide"
text: """Wähle während der Endphase 1 deiner offnen Schadenskarte mit dem Attribut <strong>Schiff</strong> und drehe sie um."""
"Determination":
name: "Entschlossenheit"
text: """Wenn du eine offene Schadenskarte mit dem Attribut <b>Pilot</b> erhältst, wird diese sofort abgelegt (ohne dass der Kartentext in Kraft tritt)."""
"Swarm Tactics":
name: "Schwarmtaktik"
text: """Du darfst zu Beginn der Kampfphase 1 freundliches Schiff in Reichweite 1 wählen.<br /><br />Bis zum Ende dieser Phase wird das gewählte Schiff so behandelt, als hätte es denselben Pilotenwert wie du."""
"Squad Leader":
name: "Staffelführer"
text: """<strong>Aktion:</strong> Wähle ein Schiff in Reichweite 1-2 mit einem geringeren Pilotenwert als du.<br /><br />Das gewählte Schiff darf sofort 1 freie Aktion durhführen."""
"Expert Handling":
name: "Flugkunst"
text: """<strong>Aktion:</strong> Führe als freie Aktion eine Fassrolle durch. Wenn du kein %BARRELROLL%-Symbol hast, erhältst du 1 Stressmarker.<br /><br />Dann darfst du 1 feindlichen Zielerfassungsmarker von deinem Schiff entfernen."""
"Marksmanship":
name: "Treffsicherheit"
text: """<strong>Aktion:</strong> Wenn du in dieser Runde angreifst, darfst du eines deiner %FOCUS% in ein %CRIT% und alle anderen %FOCUS% in %HIT% ändern."""
"Concussion Missiles":
name: "Erschütterungsraketen"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst eine deiner Leerseiten in ein %HIT% ändern."""
"Cluster Missiles":
name: "Cluster-Raketen"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmaker aus und lege diese Karte ab, um mit dieser Sekundärwaffe <strong>zwei Mal</strong> anzugreifen."""
"Daredevil":
name: "Draufgänger"
text: """<strong>Aktion:</strong> Führe ein weißes (%TURNLEFT% 1) oder (%TURNRIGHT% 1) Manöver aus. Dann erhälst du einen Stresmarker.<br /><br />Wenn du kein %BOOST%-Aktionssymbol hast, musst du dann 2 Angriffswürfel werfen. Du nimmst allen gewürfelten Schaden (%HIT%) und kritischen Schaden (%CRIT%)."""
"Elusiveness":
name: "Schwer zu Treffen"
text: """Wenn du verteidigst, darfst du 1 Stressmarker nehmen, um 1 Angriffswürfel zu wählen. Diesen muss der Angreifer neu würfeln.<br /><br />Du kannst diese Fähigkeit nicht einsetzen, solange du 1 oder mehrere Stressmarker hast."""
"Homing Missiles":
name: "Lenkraketen"
text: """<strong>Angriff (Zielerfassung):</strong> Lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Bei diesem Angriff kann der Verteidiger keine Ausweichmarker ausgeben."""
"Push the Limit":
name: "Bis an die Grenzen"
text: """Einmal pro Runde darfst du nach dem Durchführen einer Aktion eine freie Aktion aus deiner Aktionsleiste durhführen.<br /><br />Dann erhältst du 1 Stressmarker."""
"Deadeye":
name: "Meisterschütze"
text: """Du darfst die Bedingung "Angriff (Zielerfassung):" in "Angriff (Fokussierung):" ändern.<br /><br />Wenn ein Angriff das Ausgeben von Zielerfassungsmarkern erfordert, darfst du stattdessen auch einen Fokusmarker ausgeben."""
"Expose":
name: "Aggressiv"
text: """<strong>Aktion:</strong> Bis zum Ende der Runde steigt dein Primärwaffenwert um 1, dafür sinkt dein Wendigkeitswert um 1."""
"Gunner":
name: "Bordschütze"
text: """Unmittelbar nachdem du mit einem Angriff verfehlt hast, darfst du einen weiteren Angriff mit deiner Primärwaffe durchführen. Danach kannst du in dieser Runde nicht noch einmal angreifen."""
"Ion Cannon":
name: "Ionenkanonen"
text: """<strong>Angriff:</strong> Greife 1 Schiff mit dieser Sekundärwaffe an.<br /><br />Wenn du triffst, nimmt das verteidigende Schiff 1 Schaden und erhält 1 Ionenmarker. Dann werden <b>alle</b> übrigen Würfelergebnisse negiert."""
"Heavy Laser Cannon":
name: "Schwere Laserkanone"
text: """<strong>Attack:</strong> Greife 1 Schiff mit dieser Sekundärwaffe an.<br /><br />Unmittelbar nach dem Angriffswurf musst du alle %CRIT% in %HIT% ändern."""
"Seismic Charges":
name: "Seismische Bomben"
text: """Nach dem Aufdecken deines Manöverrads darfst du diese Karte ablegen um 1 Seismischen Bomben-Marker zu <strong>legen</strong>.<br /><br />Der Marker <strong>detoniert</strong> am Ende der Aktivierungsphase."""
"Mercenary Copilot":
name: "Angeheuerter Kopilot"
text: """Wenn du ein Ziel in Reichweite 3 angreifst, darfst du eines deiner %HIT% in ein %CRIT% ändern."""
"Assault Missiles":
name: "Angriffsraketen"
text: """Angriff (Zielerfassung): Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Wenn du triffst, nimmt jedes andere Schiff in Reichweite 1 des verteidigenden Schiffs 1 Schaden."""
"Veteran Instincts":
name: "Veteraneninstinkte"
text: """Dein Pilotenwert steigt um 2."""
"Proximity Mines":
name: "Annährungsminen"
text: """<strong>Aktion:</strong> Lege diese Karte ab, um 1 Annährungsminen-Marker zu <strong>legen</strong>.<br /><br />Der Marker <strong>detoniert</strong>, sobald sich die Basis eines Schiffs oder die Manöverschablone mit dem Marker überschneidet."""
"Weapons Engineer":
name: "Waffen-Techniker"
text: """Du darfst 2 verschiedene Schiffe gleichzeitig in der Zielerfassung haben (maximal 1 Zielerfassung pro feindlichem Schiff).<br /><br />Sobald du eine Zielerfassung durchführst, darfst du zwei verschiedene Schiffe als Ziele erfassen."""
"Draw Their Fire":
name: "Das Feuer auf mich ziehen"
text: """Wenn ein freundliches Schiff in Reichweite 1 durch einen Angriff getroffen wird, darfst du anstelle dieses Schiffs den Schaden für 1 nicht-negiertes %CRIT% auf dich nehmen."""
"Luke Skywalker":
text: """%DE_REBELONLY%%LINEBREAK%Unmittelbar nachdem du mit einem Angriff verfehlt hast, darfst du einen weiteren Angriff mit deiner Primärwaffe durchführen. Du darfst ein %FOCUS% in ein %HIT% ändern. Danach kannst du in dieser Runde nicht noch einmal angreifen."""
"Nien Nunb":
text: """%DE_REBELONLY%%LINEBREAK%Du darfst alle %STRAIGHT%-Manöver wie grüne Manöver behandeln."""
"Chewbacca":
name: "Chewbacca (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Wenn du eine Schadenskarte erhältst, darfst du sie sofort ablegen und 1 Schild wiederaufladen.<br /><br />Danach wird diese Aufwertungskarte abgelegt."""
"Advanced Proton Torpedoes":
name: "Verstärkte Protonen-Torpedos"
text: """<strong>Angriff (Zielerfassung):</strong> Gib eine Zielerfassung aus und lege diese Karte ab um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst bis zu 3 deiner Leerseiten in %FOCUS% ändern."""
"Autoblaster":
name: "Repertierblaster"
text: """<strong>Angriff:</strong> Greife 1 Schiff mit dieser Sekundärwaffe an.<br /><br />Deine %HIT% können von Verteidigungswürfeln nicht negiert werden.<br /><br />Der Verteidiger darf %CRIT% negieren, bevor alle %HIT% negiert wurden."""
"Fire-Control System":
name: "Feuerkontrollsystem"
text: """Nachdem du angegriffen hast, darfst du eine Zielerfassung auf den Verteidiger durchführen."""
"Blaster Turret":
name: "Blastergeschütz"
text: """<strong>Angriff (Fokussierung):</strong> Gib 1 Fokusmarker aus, um 1 Schiff mit dieser Sekundärwaffe anzugreifen (es muss nicht in deinem Feuerwinkel sein)."""
"Recon Specialist":
name: "Aufklärungs-Experte"
text: """Wenn du die Aktion Fokussieren durchführst, lege 1 zusätzlichen Fokusmarker neben dein Schiff."""
"Saboteur":
text: """<strong>Aktion:</strong> Wähle 1 feindliches Schiff in Reichweite 1 und wirf 1 Angriffswürfel. Bei %HIT% oder %CRIT%, wähle 1 zufällige verdeckte Schadenskarte des Schiffs, decke sie auf und handle sie ab."""
"Intelligence Agent":
name: "Geheimagent"
text: """Wähle zu Beginn der Aktivierungsphase 1 feindliches Schiff in Reichweite 1-2. Du darfst dir das ausgewählte Manöver dieses Schiffs ansehen."""
"Proton Bombs":
name: "Protonenbomben"
text: """Nach dem Aufdecken deines Manöverrads darfst du diese Karte ablegen um 1 Protonenbomben-Marker zu <strong>legen</strong>.<br /><br />Der Marker <strong>detoniert</strong> am Ende der Aktivierungsphase."""
"Adrenaline Rush":
name: "Adrenalinschub"
text: """Wenn du ein rotes Manöver aufdeckst, darfst du diese Karte ablegen, um das Manöver bis zum Ende der Aktivierungsphase wie ein weißes Manöver zu behandeln."""
"Advanced Sensors":
name: "Verbesserte Sensoren"
text: """Unmittelbar vor dem Aufdecken deines Manövers darfst du 1 freie Aktion durchführen.<br /><br />Wenn du diese Fähigkeit nutzt, musst du den Schritt "Aktion durchführen" in dieser Runde überspringen."""
"Sensor Jammer":
name: "Störsender"
text: """Beim Verteidigen darfst du eines der %HIT% des Angreifers in ein %FOCUS% ändern.<br /><br />Der Angreifer darf den veränderten Würfel nicht neu würfeln."""
"Darth Vader":
name: "Darth Vader (Crew)"
text: """%DE_IMPERIALONLY%%LINEBREAK%Nachdem du ein feindliches Schiff angegriffen hast, darfst du 2 Schaden nehmen, damit dieses Schiff 1 kritischen Schaden nimmt."""
"Rebel Captive":
name: "Gefangener Rebell"
text: """%DE_IMPERIALONLY%%LINEBREAK%Ein Mal pro Runde erhält das erste Schiff, das einen Angriff gegen dich ansagt, sofort 1 Stressmarker."""
"Flight Instructor":
name: "Fluglehrer"
text: """Beim Verteidigen darfst du 1 deiner %FOCUS% neu würfeln. Hat der Angreifer einen Pilotenwert von 2 oder weniger, darfst du stattdessen 1 deiner Leerseiten neu würfeln."""
"Navigator":
name: "Navigator"
text: """Nach dem Aufdecken deines Manöverrads darfst du das Rad auf ein anderes Manöver mit gleicher Flugrichtung drehen.<br /><br />Wenn du bereits Stressmarker hast, darfst du es nicht auf ein rotes Manöver drehen."""
"Opportunist":
name: "Opportunist"
text: """Wenn du angreifst und der Verteidiger keine Fokusmarker oder Ausweichmarker hat, kannst du einen Stressmarker nehmen, um einen zusätzlichen Angriffswürfel zu erhalten.<br /><br />Du kannst diese Fähigkeit nicht nutzen, wenn du einen Stressmarker hast."""
"Comms Booster":
name: "Kommunikationsverstärker"
text: """<strong>Energie:</strong> Gib 1 Energie aus, um sämtliche Stressmarker von einem freundlichen Schiff in Reichweite 1-3 zu entfernen. Dann erhält jenes Schiff 1 Fokusmarker."""
"Slicer Tools":
name: "Hackersoftware"
text: """<strong>Aktion:</strong> Wähle 1 oder mehrere feindliche Schiffe mit Stressmarker in Reichweite 1-3. Bei jedem gewählten Schiff kannst du 1 Energie ausgeben, damit es 1 Schaden nimmt."""
"Shield Projector":
name: "Schildprojektor"
text: """Wenn ein feindliches Schiff in der Kampfphase an die Reihe kommt, kannst du 3 Energie ausgeben, um das Schiff bis zum Ende der Phase dazu zu zwingen dich anzugreifen, falls möglich."""
"Ion Pulse Missiles":
name: "Ionenpuls-Raketen"
text: """<strong>Angriff (Zielerfassung):</strong> Lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Wenn du triffst, nimmt das verteidigende Schiff 1 Schaden und erhält 2 Ionenmarker. Dann werden <strong>alle<strong> übrigen Würfelergebnisse negiert."""
"Wingman":
name: "Flügelmann"
text: """Entferne zu Beginn der Kampfphase 1 Stressmarker von einem anderen freundlichen Schiff in Reichweite 1."""
"Decoy":
name: "Täuschziel"
text: """Zu Beginn der Kampfphase darfst du 1 freundliches Schiff in Reichweite 1-2 wählen. Bis zum Ende der Phase tauscht du mit diesem Schiff den Pilotenwert."""
"Outmaneuver":
name: "Ausmanövrieren"
text: """Wenn du ein Schiff innerhalb deines Feuerwinkels angreifst und selbst nicht im Feuerwinkel dieses Schiffs bist, wird seine Wendigkeit um 1 reduziert (Minimum 0)"""
"Predator":
name: "Jagdinstinkt"
text: """Wenn du angreifst, darfst du 1 Angriffswürfel neu würfeln. Ist der Pilotenwert des Verteidigers2 oder niedriger, darfst du stattdessen bis zu 2 Angriffswürfel neu würfeln."""
"Flechette Torpedoes":
name: "Flechet-Torpedos"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Nachdem du angegriffen hast, bekommt der Verteidiger 1 Stressmarker, sofern sein Hüllenwert 4 oder weniger beträgt."""
"R7 Astromech":
name: "R7-Astromech-Droide"
text: """Ein Mal pro Runde kannst du beim Verteidigen gegen den Angriff eines Schiffs, das du in Zielerfassung hast, die Zielerfassungsmarker ausgeben, um beliebige (oder alle) Angriffswürfel zu wählen. Diese muss der Angreifer neu würfeln."""
"R7-T1":
name: "R7-T1"
text: """<strong>Aktion:</strong> Wähle ein feindliches Schiff in Reichweite 1-2. Wenn du im Feuerwinkel dieses Schiffs bist, kannst du es in die Zielerfassung nehmen. Dann darfst du als freie Aktion einen Schub durchführen."""
"Tactician":
name: "Taktiker"
text: """Nachdem du ein Schiff in Reichweite 2 und innerhalb deines Feuerwinkels angegriffen hast, erhält es 1 Stressmarker."""
"R2-D2 (Crew)":
name: "R2-D2 (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Wenn du am Ende der Endphase keine Schilde hast, darfst du 1 Schild wieder aufladen und 1 Angriffswürfel werfen. Bei %HIT% musst du 1 deiner verdeckten Schadenskarten (zufällig gewählt) umdrehen und abhandeln."""
"C-3PO":
name: "C-3PO"
text: """%DE_REBELONLY%%LINEBREAK%Einmal pro Runde darfst du, bevor du 1 oder mehrere Verteidigungswürfel wirfst, laut raten, wie viele %EVADE% du würfeln wirst. Wenn du richtig geraten hast (bevor die Ergebnisse modifiziert werden), wird 1 %EVADE% hinzugefügt."""
"Single Turbolasers":
name: "Einzelne Turbolasers"
text: """<strong>Angriff (Energie):</strong> gib 2 Energie von dieser Karte aus, um mit dieser Sekundärwaffe anzugreifen. Der Verteidiger verwendet zum Verteidigen seinen doppelten Wendigkeitswert. Du darfst 1 deiner %FOCUS% in ein %HIT% ändern."""
"Quad Laser Cannons":
name: "Vierlings-Laserkanone"
text: """<strong>Angriff (Energie):</strong> Gib 1 Energie von dieser Karte aus, um mit dieser Sekundärwaffe anzugreifen. Wenn der Angriff verfehlt, kannst du sofort 1 Energie von dieser Karte ausgeben, um den Angriff zu wiederholen."""
"Tibanna Gas Supplies":
name: "Tibanna-Gas-Vorräte"
text: """<strong>Energie:</strong> Du kannst diese Karte ablegen, um 3 Energie zu erzeugen."""
"Ionization Reactor":
name: "Ionenreaktor"
text: """<strong>Energie:</strong> Gib 5 Energie von dieser Karte aus und lege sie ab, damit jedes andere Schiff in Reichweite 1 einen Schaden nimmt und einen Ionenmarker bekommt."""
"Engine Booster":
name: "Nachbrenner"
text: """Unmittelbar bevor du dein Manöverrad aufdeckst, kannst du 1 Energie ausgeben, um ein weißes (%STRAIGHT% 1)-Manöver auszuführen. Wenn es dadurch zur Überschneidung mit einem anderen Schiff käme, darfst du diese Fähigkeit nicht nutzen."""
"R3-A2":
name: "R3-A2"
text: """Nachdem du das Ziel deines Angriffs angesagt hast, darfst du, wenn der Verteidiger in deinem Feuerwinkel ist, 1 Stressmarker nehmen, damit der Verteidiger auch 1 Stressmarker bekommt."""
"R2-D6":
name: "R2-D6"
text: """Deine Aufwertungsleiste bekommt ein %ELITE%-Symbol.<br /><br />Du kannst diese Aufwertung nicht ausrüsten, wenn du bereits ein %ELITE%-Symbol hast oder dein Pilotenwert 2 oder weniger beträgt."""
"Enhanced Scopes":
name: "Verbessertes Radar"
text: """Behandle in der Aktivierungsphase deinen Pilotenwert als "0"."""
"Chardaan Refit":
name: "Chardaan-Nachrüstung"
text: """Diese Karte hat negative Kommandopunktekosten."""
"Proton Rockets":
name: "Protonenraketen"
text: """<strong>Angriff (Fokussierung):</strong> Lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst so viele zusätzliche Angriffswürfel werfen, wie du Wendigkeit hast (maximal 3 zusätzliche Würfel)."""
"Kyle Katarn":
name: "Kyle Katarn (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Nachdem du einen Stressmarker von deinem Schiff entfernt hast, darfst du deinem Schiff einen Fokusmarker geben."""
"Jan Ors":
name: "Jan Ors (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Ein Mal pro runde darfst du einem freundlichem Schiff in Reichweite 1-3, das gerade die Aktion Fokussierung durchführt oder einen Fokusmarker erhalten würde, stattdessen einen Ausweichmarker geben."""
"Toryn Farr":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%<strong>Aktion:</strong> Gib X Energie aus, um X feindliche Schiffe in Reichweite 1-2 zu wählen. Sämtliche Fokus-, Ausweich- und blauen Zielerfassungsmarker dieser Schiffe werden entfernt."""
# TODO Check card formatting
"R4-D6":
text: """Wenn du von einem Angriff getroffen wirst und es mindestens 3 nicht negierte %HIT% gibt, darfst du so viele %HIT% wählen und negieren, bis es nur noch 2 sind. Für jedes auf diese Weise negierte %HIT% bekommst du 1 Stressmarker."""
"R5-P9":
text: """Am Ende der Kampfphase kannst du 1 deiner Fokusmarker ausgeben, um 1 Schild wiederaufzuladen (bis maximal zum Schildwert)."""
"WED-15 Repair Droid":
name: "WED-15 Reparaturdroide"
text: """%DE_HUGESHIPONLY%%LINEBREAK%<strong>Aktion:</strong> gib 1 Energie aus, um 1 deiner verdeckten Schadenskarten abzulegen oder gib 3 Energie aus, um 1 deiner offenen Schadenskarten abzulegen."""
"Carlist Rieekan":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%Zu Beginn der Aktivierungsphase kannst du diese Karte ablegen, damit bis zum Ende der Phase der Pilotenwert aller freundlichen Schiffe 12 beträgt."""
"Jan Dodonna":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%Wenn ein anderes freundliches Schiff in Reichweite 1 angreift, darf es 1 seiner gewürfelten %HIT% in ein %CRIT% ändern."""
"Expanded Cargo Hold":
name: "Erweiterter Ladebereich"
text: """Ein Mal pro Runde darfst du, wenn du eine offene Schadenskarte erhältst, frei wählen, ob du sie vom Schadensstapel Bug oder Heck ziehen willst."""
ship: "Medium-Transporter GR-75"
"Backup Shield Generator":
name: "Sekundärer Schildgenerator"
text: """Am Ende jeder Runde kannst du 1 Energie ausgeben, um 1 Schild wiederaufzuladen (bis maximal zum Schildwert)."""
"EM Emitter":
name: "EM-Emitter"
text: """Wenn du bei einem Angriff die Schussbahn versperrst, bekommst der Verteidiger 3 zusätzliche Verteidigungswürfel (anstatt 1)."""
"Frequency Jammer":
name: "Störsender (Fracht)"
text: """Wenn du die Aktion Störsignal durchführst, wähle 1 feindliches Schiff ohne Stressmarker in Reichweite 1 des vom Störsignal betroffenen Schiffs. Das gewählte Schiff erhält 1 Stressmarker."""
"Han Solo":
name: "Han Solo (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Wenn du angreifst und den Verteidiger in Zielerfassung hast, kannst du diese Zielerfassung ausgeben, um all deine gewürfelten %FOCUS% in %HIT% zu ändern."""
"Leia Organa":
text: """%DE_REBELONLY%%LINEBREAK%Zu Beginn der Aktivierungsphase kannst du diese Karte ablegen, damit alle freundlichen Schiffe, die ein rotes Manöver aufdecken, dieses bis zum Ende der Phase wie ein weißes Manöver behandeln dürfen."""
"Targeting Coordinator":
text: """<strong>Energy:</strong> You may spend 1 energy to choose 1 friendly ship at Range 1-2. Acquire a target lock, then assign the blue target lock token to the chosen ship."""
"Raymus Antilles":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%Wähle zu Beginn der Aktivierungsphase 1 feindliches Schiff in Reichweite 1-3. Du kannst dir das gewählte Manöver dieses Schiffes ansehen. Wenn es weiß ist, bekommt dieses Schiff 1 Stressmarker."""
"Gunnery Team":
name: "Bordschützenteam"
text: """Einmal pro Runde kannst du beim Angreifen mit einer Sekundärwaffe 1 Energie ausgeben, um 1 gewürfelte Leerseite in ein %HIT% zu ändern."""
"Sensor Team":
name: "Sensortechnikerteam"
text: """Du kannst feindliche Schiffe in Reichweite 1-5 in die Zielerfassung nehmen (anstatt in Reichweite 1-3)."""
"Engineering Team":
name: "Ingenieurteam"
text: """Wenn du in der Aktivierungsphase ein %STRAIGHT% Manöver aufdeckst, bekommst du im Schritt "Energie gewinnen" 1 zusätzlichen Energiemarker."""
"Lando Calrissian":
name: "Lando Calrissian (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%<strong>Aktion:</strong> Wirf 2 Verteidigungswürfel. Dein Schiff bekommt 1 Fokusmarker für jedes %FOCUS% und 1 Ausweichmarker für jedes %EVADE%."""
"Mara Jade":
text: """%DE_IMPERIALONLY%%LINEBREAK%Am Ende der Kampfphase erhält jedes feindliche Schiff in Reichweite 1, das keine Stressmarker hat, einen Stressmarker."""
"Fleet Officer":
name: "Flottenoffizier"
text: """%DE_IMPERIALONLY%%LINEBREAK%<strong>Aktion:</strong> Wähle bis zu 2 freundliche Schiffe in Reichweite 1-2 und gib ihnen je 1 Fokusmarker. Dann erhältst du 1 Stressmarker."""
"Targeting Coordinator":
name: "Zielkoordinator"
text: """<strong>Energie:</strong> Du kannst 1 Energie ausgeben, um 1 freundliches Schiff in Reichweite1-2 zu wählen. Nimm dann ein Schiff in die Zielerfassung und gibt den blauen Zielerfassungsmarker dem gewählten Schiff."""
"Lone Wolf":
name: "Einsamer Wolf"
text: """Wenn keine freundlichen Schiffe in Reichweite 1-2 sind, darfst du beim Angreifen und Verteidigen 1 gewürfelte Leerseite neu würfeln."""
"Stay On Target":
name: "Am Ziel bleiben"
text: """Nach dem Aufdecken des Manöverrads darfst du ein anderes Manöver mit gleicher Geschwindigkeit auf deinem Rad einstellen.<br /><br />Dieses Manöver wird wie ein rotes Manöver behandelt."""
"Dash Rendar":
name: "Dash Rendar (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Du darfst auch angreifen während du dich mit einem Hindernis überschneidest.<br /><br />Deine Schussbahn kann nicht versperrt werden."""
'"Leebo"':
name: '"Leebo" (Crew)'
text: """%DE_REBELONLY%%LINEBREAK%<strong>Aktion:</strong> Führe als freie Aktion einen Schub durch. Dann erhältst du 1 Ionenmarker."""
"Ruthlessness":
name: "Erbarmungslos"
text: """%DE_IMPERIALONLY%%LINEBREAK%Nachdem du mit einem Angriff getroffen hast, <strong>musst</strong> du 1 anderes Schiff in Reichweite 1 des Verteidigers (außer dir selbst) wählen. Das Schiff nimmt 1 Schaden."""
"Intimidation":
name: "Furchteinflössend"
text: """Die Wendigkeit feindlicher Schiffe sinkt um 1, solange du sie berührst."""
"Ysanne Isard":
text: """%DE_IMPERIALONLY%%LINEBREAK%Wenn du zu Beginn der Kampfphase keine Schilde und mindestens 1 Schadenskarte hast, darfst du als freie Aktion ausweichen."""
"Moff Jerjerrod":
text: """%DE_IMPERIALONLY%%LINEBREAK%Wenn du eine offene Schadenskarte erhältst, kannst du diese Aufwertungskarte oder eine andere %CREW%-Aufwertung ablegen, um die Schadenskarte umzudrehen (ohne dass der Kartentext in Kraft tritt)."""
"Ion Torpedoes":
name: "Ionentorpedos"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Triffst du, erhalten alle Schiffe in Reichweite 1 des Verteidigers und der Verteidiger selbst je 1 Ionenmarker."""
"Bodyguard":
name: "Leibwache"
text: """%DE_SCUMONLY%%LINEBREAK%Zu Beginn der Kampfphase darfst du einen Fokusmarker ausgeben um ein freundliches Schiff in Reichweite 1 zu wählen, dessen Pilotenwert höher ist als deiner. Bis zum Ende der Runde steigt sein Wendigkeitswert um 1."""
"Calculation":
name: "Berechnung"
text: """Sobald du angreifst, darfst du einen Fokusmarker ausgeben, um 1 deiner %FOCUS% in ein %CRIT% zu ändern."""
"Accuracy Corrector":
name: "Zielvisor"
text: """Sobald du angreifst, darfst du alle deine Würfelergebnisse negieren. Dann darfst du 2 %HIT% hinzufügen.%LINEBREAK%Deine Würfel können während dieses Angriffs nicht noch einmal modifiziert werden."""
"Inertial Dampeners":
name: "Trägheitsdämpfer"
text: """Sobald du dein Manöverraf aufdeckst, darfst du diese Karte ablegen, um [0%STOP%]-Manöver auszuführen. Dann erhältst du 1 Stressmarker."""
"Flechette Cannon":
name: "Flechettekanonen"
text: """<strong>Angriff:</strong> Greife 1 Schiffe an.%LINEBREAK%Wenn dieser Angriff trifft, nimmt das verteidigende Schiff 1 Schaden und erhält 1 Stressmarker (falls es noch keinen hat.) Dann werden <strong>alle</strong> Würfelergebnisse negiert."""
'"Mangler" Cannon':
name: '"Mangler"-Kanonen'
text: """<strong>Angriff:</strong> Greife 1 Schiff an.%LINEBREAK%Sobald du angreifst, darfst du 1 deiner %HIT% in ein %CRIT% ändern."""
"Dead Man's Switch":
name: "Totmannschalter"
text: """Sobald du zerstörst wirst, nimmt jedes Schiff in Reichweite 1 einen Schaden."""
"Feedback Array":
name: "Rückkopplungsfeld"
text: """In der Kampfphase darfst du statt einen Angriff durchzuführen 1 Ionenmarker und 1 Schaden nehmen, um eine feindliches Schiff in Reichweite 1 zu wählen. Das gewählte Schiff nimmt 1 Schaden."""
'"Hot Shot" Blaster':
text: """<strong>Angriff:</strong> Lege diese Karte ab, um 1 Schiff (auch außerhalb deines Feuerwinkels) anzugreifen."""
"Greedo":
text: """%DE_SCUMONLY%%LINEBREAK%In jeder Runde wird bei deinem ersten Angriff und deiner ersten Verteidigung die erste Schadenskarte offen zugeteilt."""
"Salvaged Astromech":
name: "Abgewrackter Astromechdroide"
text: """Sobald du eine Schadenskarte mit dem Attribut <strong>Schiff</strong> erhälst, darfst du sie sofort ablegen (bevor ihr Effekt abgehandelt wird).%LINEBREAK%Danach wird diese Aufwertungskarte abgelegt."""
"Bomb Loadout":
name: "Bombenladung"
text: """<span class="card-restriction">Nur für Y-Wing.</span>%LINEBREAK%Füge deiner Aufwertungsleiste das %BOMB%-Symbol hinzu."""
'"Genius"':
name: '"Genie"'
text: """Wenn du eine Bombe ausgerüstet hast, die vor dem Aufdecken deines Manövers gelegt werden kann, darfst du sie stattdessen auch <strong>nach</strong> Ausführung des Manövers legen."""
"Unhinged Astromech":
name: "Ausgeklinkter Astromech-Droide"
text: """Du darfst alle Manöver mit Geschwindigkeit 3 wie grüne Manöver behandeln."""
"R4-B11":
text: """Sobald du angreifst, darfst du, falls du den Verteidiger in der Zielerfassung hast, den Zielerfassungsmarker ausgeben, um einen oder alle Verteidigungswürfel zu wählen. Diese muss der Verteidiger neu würfeln."""
"Autoblaster Turret":
name: "Autoblastergeschütz"
text: """<strong>Angriff:</strong> Greife 1 Schiff (auch außerhalb deines Feuerwinkels) an. %LINEBREAK%Deine %HIT% können von Verteidigungswürfeln nicht negiert werden. Der Verteidiger darf %CRIT% vor %HIT% negieren."""
"R4 Agromech":
name: "R4-Agromech-Droide"
text: """Sobald du angreifst, darfst du, nachdem du einen Fokusmarker ausgegeben hast, den Verteidiger in die Zielerfassung nehmen."""
"K4 Security Droid":
name: "K4-Sicherheitsdroide"
text: """%DE_SCUMONLY%%LINEBREAK%Nachdem du ein grünes Manöver ausgeführt hast, darfst du ein Schiff in die Zielerfassung nehmen."""
"Outlaw Tech":
name: "Gesetzloser Techniker"
text: """%DE_SCUMONLY%%LINEBREAK%Nachdem du ein rotes Manöver ausgeführt hast, darfst du deinem Schiff 1 Fokusmarker zuweisen."""
"Advanced Targeting Computer":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%When attacking with your primary weapon, if you have a target lock on the defender, you may add 1 %CRIT% result to your roll. If you do, you cannot spend target locks during this attack."""
"Ion Cannon Battery":
text: """<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack. If this attack hits, the defender suffers 1 critical damage and receives 1 ion token. Then cancel <strong>all<strong> dice results."""
"Emperor Palpatine":
text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again."""
"Bossk":
text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender."""
"Lightning Reflexes":
text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180°. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step."""
"Twin Laser Turret":
text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results."""
"Plasma Torpedoes":
text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender."""
"Ion Bombs":
text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token."""
"Conner Net":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token."""
"Bombardier":
text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template."""
"Cluster Mines":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token."""
'Crack Shot':
text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.'''
"Advanced Homing Missiles":
text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results."""
'Agent Kallus':
text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.'''
'XX-23 S-Thread Tracers':
text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results."""
"Tractor Beam":
text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results."""
"Cloaking Device":
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token."""
modification_translations =
"Stealth Device":
name: "Tarnvorrichtung"
text: """Dein Wendigkeitswert steigt um 1. Lege diese Karte ab, wenn du von einem Angriff getroffen wirst."""
"Shield Upgrade":
name: "Verbesserte Schilde"
text: """Dein Schildwert steigt um 1."""
"Engine Upgrade":
name: "Verbessertes Triebwerk"
text: """Füge deiner Aktionsleiste ein %BOOST%-Symbol hinzu."""
"Anti-Pursuit Lasers":
name: "Kurzstreckenlaser"
text: """%DE_LARGESHIPONLY%%LINEBREAK%Nachdem ein feindliches Schiff ein Manöver ausgeführt hat, das zur Überschneidung mit deinem Schiff führt, wirf 1 Angriffswürfel. Bei %HIT% oder %CRIT% nimmt das feindliche Schiff 1 Schaden."""
"Targeting Computer":
name: "Zielerfassungssystem"
text: """Deine Aktionsleiste erhält das %TARGETLOCK%-Symbol."""
"Hull Upgrade":
name: "Verbesserte Hülle"
text: """Erhöhe deinen Hüllenwert um 1."""
"Munitions Failsafe":
name: "Ausfallsichere Munition"
text: """Wenn du mit einer Sekundärwaffe angreifst, deren Kartentext besagt, dass sie zum Angriff abgelegt werden muss, legst du sie nur ab, falls du triffst."""
"Stygium Particle Accelerator":
name: "Stygium-Teilchen-Beschleuniger"
text: """immer wenn du dich enttarnst oder die Aktion Tarnen durchführst, darfst du als freie Aktion ausweichen."""
"Advanced Cloaking Device":
name: "Verbesserte Tarnvorrichtung"
text: """Nachdem du angegriffen hast, darfst du dich als freie Aktion tarnen."""
"Combat Retrofit":
name: "Umrüstung für den Kampfeinsatz"
ship: "Medium-Transporter GR-75"
text: """Erhöhe deinen Hüllenwert um 2 und deinen Schildwert um 1."""
"B-Wing/E2":
text: """Füge deiner Aufwertungsleiste das %CREW%-Symbol hinzu."""
"Countermeasures":
name: "Gegenmassnahmen"
text: """%DE_LARGESHIPONLY%%LINEBREAK%Zu Beginn der Kampfphase kannst du diese Karte ablegen, um deine Wendigkeit bis zum Ende der Runde um 1 zu erhöhen. Dann darfst du 1 feindliche Zielerfassung von deinem Schiff entfernen."""
"Experimental Interface":
name: "Experimentelles Interface"
text: """Ein Mal pro Runde darfst du nach dem Durchführen einer Aktion 1 ausgerüstete Aufwertungskarte mit dem Stichwort "<strong>Aktion:</strong>" benutzen (dies zählt als freie Aktion). Dann erhältst du 1 Stressmarker."""
"Tactical Jammer":
name: "Taktischer Störsender"
text: """%DE_LARGESHIPONLY%%LINEBREAK%Dein Schiff kann die feindliche Schussbahn versperren."""
"Autothrusters":
name: "Automatische Schubdüsen"
text: """Sobald du verteidigst und jenseits von Reichweite 2 oder außerhalb des Feuerwinkels des Angreifers bist, darfst du 1 deiner Leerseiten in ein %EVADE% ändern. Du darfst diese Karte nur ausrüsten, wenn du das %BOOST%-Aktionssymbol hast."""
"Twin Ion Engine Mk. II":
text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers."""
"Maneuvering Fins":
text: """When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed."""
"Ion Projector":
text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token."""
title_translations =
"Slave I":
name: "Sklave I"
text: """<span class="card-restriction">Nur für Firespray-31.</span>%LINEBREAK%Füge deiner Aktionsleiste ein %TORPEDO%-Symbol hinzu."""
"Millennium Falcon":
name: "Millennium Falke"
text: """<span class="card-restriction">Nur für YT-1300.</span>%LINEBREAK%Füge deiner Aktionsleiste ein %EVADE%-Symbol hinzu."""
"Moldy Crow":
text: """<span class="card-restriction">Nur für HWK-290.</span>%LINEBREAK%In der Endphase werden von diesem Schiff keine unbenutzen Fokusmarker entfernt."""
"ST-321":
ship: "Raumfähre der Lambda-Klasse"
text: """<span class="card-restriction">Nur für Raumfähren der Lamda-Klasse.</span>%LINEBREAK%Wenn du eine Zielerfassung durchführst, darfst du ein beliebiges feindliches Schiff auf der Spielfläche als Ziel erfassen."""
"Royal Guard TIE":
name: "TIE der Roten Garde"
ship: "TIE-Abfangjäger"
text: """<span class="card-restriction">Nur für TIE-Abfangjäger.</span>%LINEBREAK%Du kannst bis zu 2 verschiedene Modifikationen verwenden (statt einer).<br /><br />Du kannst diese Karte nicht verwenden, wenn der Pilotenwert "4" oder kleiner ist."""
"Dodonna's Pride":
name: "Dodonnas Stolz"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">Nur für CR90-Korvette (Bug).</span>%LINEBREAK%Wenn du die Aktion Koordination durchführst, kannst du 2 freundliche Schiffe wählen (anstatt 1). Jedes dieser Schiffe darf 1 freie Aktion durchführen."""
"A-Wing Test Pilot":
name: "Erfahrener Testpilot"
text: """<span class="card-restriction">Nur für A-Wing.</span>%LINEBREAK%Füge deiner Aufwertungsleiste 1 %ELITE%-Symbol hinzu.<br /><br />Du darfst jede %ELITE%-Aufwertung nur ein Mal ausrüsten. Du kannst diese Karte nicht verwenden, wenn dein Pilotenwert "1" oder niedriger ist."""
"Tantive IV":
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">Nur für CR90-Korvette (Bug).</span>%LINEBREAK%Die Aufwertungsleiste deiner Bugsektion erhält 1 zusätzliches %CREW% und 1 zusätzliches %TEAM% ."""
"Bright Hope":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">Nur für Medium-Transporter GR-75.</span>%LINEBREAK%Wenn neben deiner Bugsektion ein Verstärkungsmarker liegt, fügt er 2 %EVADE% hinzu (anstatt 1)."""
"Quantum Storm":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">Nur für Medium-Transporter GR-75.</span>%LINEBREAK%Wenn du zu Beginn der Endphase 1 Energiemarker oder weniger hast, gewinnst du 1 Energiemarker."""
"Dutyfree":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">Nur für Medium-Transporter GR-75.</span>%LINEBREAK%Bei der Aktion Störsignal kannst du ein feindliches Schiff in Reichweite 1-3 (statt 1-2) wählen."""
"Jaina's Light":
name: "Jainas Licht"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">Nur für CR90-Korvette (Bug).</span>%LINEBREAK%Wenn du verteidigst, darfst du einmal pro Angriff eine soeben erhaltene, offene Schadenskarte ablegen und dafür eine neue offene Schadenskarte ziehen."""
"Outrider":
text: """<span class="card-restriction">Nur für YT-2400.</span>%LINEBREAK%Solange du eine %CANNON%-Aufwertung ausgerüstet hast, kannst du deine Primärwaffen <strong>nicht</strong> verwenden. Dafür darfst du mit %CANNON%-Sekundärwaffen auch Ziele außerhalb deines Feuerwinkels angreifen."""
"Dauntless":
text: """<span class="card-restriction">Nur für VT-49 Decimator.</span>%LINEBREAK%Nach dem Ausführen eines Manövers, das zur Überschneidung mit einem anderen Schiff geführt hat, darfst du 1 freie Aktion durchführen. Dann erhältst du 1 Stressmarker."""
"Virago":
text: """<span class="card-restriction">Nur für SternenViper.</span>%LINEBREAK%Füge deiner Aufwertungsleiste ein %SYSTEM%- und ein %ILLICIT%-Symbol hinzu.%LINEBREAK%Du kannst diese Karte nicht ausrüsten, wenn dein Pilotenwert "3" oder niedriger ist."""
'"Heavy Scyk" Interceptor (Cannon)':
ship: "M3-A Abfangjäger"
name: '"Schwerer Scyk"-Abfangjäger (Kannone)'
text: """<span class="card-restriction">Nur für M3-A-Abfangjäger.</span>%LINEBREAK%Füge deiner Aufwertungsleiste eines der folgenden Symbole hinzu: %CANNON%, %TORPEDO%, oder %MISSILE%."""
'"Heavy Scyk" Interceptor (Torpedo)':
ship: "M3-A Abfangjäger"
name: '"Schwerer Scyk"-Abfangjäger (Torpedo)'
text: """<span class="card-restriction">Nur für M3-A-Abfangjäger.</span>%LINEBREAK%Füge deiner Aufwertungsleiste eines der folgenden Symbole hinzu: %CANNON%, %TORPEDO%, oder %MISSILE%."""
'"Heavy Scyk" Interceptor (Missile)':
ship: "M3-A Abfangjäger"
name: '"Schwerer Scyk"-Abfangjäger (Rakete)'
text: """<span class="card-restriction">Nur für M3-A-Abfangjäger.</span>%LINEBREAK%Füge deiner Aufwertungsleiste eines der folgenden Symbole hinzu: %CANNON%, %TORPEDO%, oder %MISSILE%."""
"IG-2000":
text: """<span class="card-restriction">Nur für Aggressor.</span>%LINEBREAK%Du bekommst die Pilotenfähigkeiten aller anderen freundlichen Schiffe mit der Aufwertungskarte <em>IG-2000</em> (zusätzlich zu deiner eigenen Pilotenfähigkeit)."""
"BTL-A4 Y-Wing":
name: "BTL-A4-Y-Wing"
text: """<span class="card-restriction">Nur für Y-Wing.</span>%LINEBREAK%Du darfst Schiffe außerhalb deines Feuerwinkels nicht angreifen. Nachdem du einen Angriff mit deinen Primärwaffen durchgeführt hast, darfst du sofort einen weiteren Angriff mit einer %TURRET%-Sekundärwaffe durchführen."""
"Andrasta":
text: """<span class="card-restriction">Nur für Firespray-31.</span>%LINEBREAK%Füge deiner Aufwertungsleiste zwei weitere %BOMB%-Symbole hinzu."""
"TIE/x1":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% upgrade icon.%LINEBREAK%If you equip a %SYSTEM% upgrade, its squad point cost is reduced by 4 (to a minimum of 0)."""
"Ghost":
text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides."""
"Phantom":
text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round."""
"TIE/v1":
text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action."""
"Mist Hunter":
text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal)."""
"Punishing One":
text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1."""
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations
| 181305 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.de = 'Deutsch'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations.Deutsch =
action:
"Barrel Roll": "Fassrolle"
"Boost": "Schub"
"Evade": "Ausweichen"
"Focus": "Fokussierung"
"Target Lock": "Zielerfassung"
"Recover": "Aufladen"
"Reinforce": "Verstärken"
"Jam": "Störsignal"
"Coordinate": "Koordination"
"Cloak": "Tarnen"
slot:
"Astromech": "Astromech"
"Bomb": "Bombe"
"Cannon": "Kanonen"
"Crew": "Crew"
"Elite": "Elite"
"Missile": "Raketen"
"System": "System"
"Torpedo": "Torpedo"
"Turret": "Geschützturm"
"Cargo": "Fracht"
"Hardpoint": "Hardpoint"
"Team": "Team"
"Illicit": "illegales"
"Salvaged Astromech": "geborgener Astromech"
sources: # needed?
"Core": "Grundspiel"
"A-Wing Expansion Pack": "A-Wing Erweiterung"
"B-Wing Expansion Pack": "B-Wing Erweiterung"
"X-Wing Expansion Pack": "X-Wing Erweiterung"
"Y-Wing Expansion Pack": "Y-Wing Erweiterung"
"Millennium Falcon Expansion Pack": "Millenium Falke Erweiterung"
"HWK-290 Expansion Pack": "HWK-290 Erweiterung"
"TIE Fighter Expansion Pack": "TIE-Fighter Erweiterung"
"TIE Interceptor Expansion Pack": "TIE-Abfangjäger Erweiterung"
"TIE Bomber Expansion Pack": "TIE-Bomber Erweiterung"
"TIE Advanced Expansion Pack": "TIE-Advanced Erweiterung"
"Lambda-Class Shuttle Expansion Pack": "Raumfähre der Lambda-Klasse Erweiterung"
"Slave I Expansion Pack": "Sklave I Erweiterung"
"Imperial Aces Expansion Pack": "Fliegerasse des Imperiums Erweiterung"
"Rebel Transport Expansion Pack": "Rebellentransporter Erweiterung"
"Z-95 Headhunter Expansion Pack": "Z-95-Kopfjäger Erweiterung"
"TIE Defender Expansion Pack": "TIE-Jagdbomber Erweiterung"
"E-Wing Expansion Pack": "E-Wing Erweiterung"
"TIE Phantom Expansion Pack": "TIE-Phantom Erweiterung"
"Tantive IV Expansion Pack": "Tantive IV Erweiterung"
"Rebel Aces Expansion Pack": "Fliegerasse der Rebellenallianz Erweiterung"
"YT-2400 Freighter Expansion Pack": "YT-2400-Frachter Erweiterung"
"VT-49 Decimator Expansion Pack": "VT-49 Decimator Erweiterung"
"StarViper Expansion Pack": "SternenViper Erweiterung"
"M3-A Interceptor Expansion Pack": "M3-A Abfangjäger Erweiterung"
"IG-2000 Expansion Pack": "IG-2000 Erweiterung"
"Most Wanted Expansion Pack": "Abschaum und Kriminelle Erweiterung"
"Imperial Raider Expansion Pack": "Imperial Raider Expansion Pack"
ui:
shipSelectorPlaceholder: "Wähle ein Schiff"
pilotSelectorPlaceholder: "Wähle einen Piloten"
upgradePlaceholder: (translator, language, slot) ->
"kein #{translator language, 'slot', slot} Upgrade"
modificationPlaceholder: "keine Modifikation"
titlePlaceholder: "kein Titel"
upgradeHeader: (translator, language, slot) ->
"#{translator language, 'slot', slot} Upgrade"
unreleased: "unveröffentlicht"
epic: "Episch"
limited: "limitiert"
byCSSSelector:
'.translate.sort-cards-by': 'Sortiere Karten per'
'.xwing-card-browser option[value="name"]': 'Name'
'.xwing-card-browser option[value="source"]': 'Quelle'
'.xwing-card-browser option[value="type-by-points"]': 'Typ (Punkte)'
'.xwing-card-browser option[value="type-by-name"]': 'Typ (Name)'
'.xwing-card-browser .translate.select-a-card': 'Wähle eine Karte aus der Liste.'
'.xwing-card-browser .info-range td': 'Reichweite'
# Info well
'.info-well .info-ship td.info-header': 'Schiff'
'.info-well .info-skill td.info-header': 'Pilotenwert'
'.info-well .info-actions td.info-header': 'Aktionen'
'.info-well .info-upgrades td.info-header': 'Aufwertungen'
'.info-well .info-range td.info-header': 'Reichweite'
# Squadron edit buttons
'.clear-squad' : 'Neues Squad'
'.save-list' : 'Speichern'
'.save-list-as' : 'Speichern als…'
'.delete-list' : 'Löschen'
'.backend-list-my-squads' : 'Squad laden'
'.view-as-text' : '<span class="hidden-phone"><i class="icon-print"></i> Drucken/Anzeigen als </span>Text'
'.randomize' : 'Zufallsliste!'
'.randomize-options' : 'Zufallslistenoptionen…'
# Print/View modal
'.bbcode-list' : 'Kopiere den BBCode von unten und füge ihn in deine Forenposts ein.<textarea></textarea>'
'.vertical-space-checkbox' : """Platz für Schadenskarten und Upgrades im Druck berücksichtigen. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Ausdrucken in farbe. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="icon-print"></i> Print'
# Randomizer options
'.do-randomize' : 'Zufall!'
# Top tab bar
'#empireTab' : 'Galaktisches Imperium'
'#rebelTab' : 'Rebellen Allianz'
'#scumTab' : 'Abschaum und Kriminelle'
'#browserTab' : 'Karten Browser'
'#aboutTab' : 'Über'
singular:
'pilots': 'Pilot'
'modifications': 'Modifikation'
'titles': 'Titel'
types:
'Pilot': 'Pilot'
'Modification': 'Modifikation'
'Title': 'Titel'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders.Deutsch = () ->
exportObj.cardLanguage = 'Deutsch'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
# Move TIE Interceptor to TIE-Abfangjäger
exportObj.renameShip 'TIE Interceptor', 'TIE-Abfangjäger'
# Move Z-95 Headhunter to Z-95-Kopfjäger
exportObj.renameShip 'Z-95 Headhunter', 'Z-95-Kopfjäger'
# Move TIE Defender to TIE-Jagdbomber
exportObj.renameShip 'TIE Defender', 'TIE-Jagdbomber'
# Move Lambda-Class Shuttle to Raumfähre der Lambda-Klasse
exportObj.renameShip 'Lambda-Class Shuttle', 'Raumfähre der Lambda-Klasse'
# Move GR-75 Medium Transport to Medium-Transporter GR-75
exportObj.renameShip 'GR-75 Medium Transport', 'Medium-Transporter GR-75'
# Move CR90 Corvette (Fore) to CR90-Korvette (Bug)
exportObj.renameShip 'CR90 Corvette (Fore)', 'CR90-Korvette (Bug)'
# Move CR90 Corvette (Aft) to CR90-Korvette (Heck)
exportObj.renameShip 'CR90 Corvette (Aft)', 'CR90-Korvette (Heck)'
# Move M3-A Interceptor to M3-A Abfangjäger
exportObj.renameShip 'M3-A Interceptor', 'M3-A Abfangjäger'
pilot_translations =
"Wedge Antilles":
text: """Wenn du angreifst, sinkt der Wendigkeitswert des Verteidigers um 1 (Minimum 0)."""
"<NAME>":
text: """Wenn du einen Fokusmarker ausgibst, darfst du ihn auf ein anderes freundliches Schiff in Reichweite 1-2 legen (anstatt ihn abzulegen)."""
"Red Squadron Pilot":
name: "Pilot der Rot-Staffel"
"Rookie Pilot":
name: "Anfängerpilot"
"Biggs Darklighter":
text: """Andere freundliche Schiffe in Reichweite 1 dürfen nur dann angegriffen werden, wenn der Angreifer dich nicht zum Ziel bestimmen kann."""
"Lu<NAME> Skywalker":
text: """Wenn du verteidigst, kannst du 1 deiner %FOCUS% in ein %EVADE% ändern."""
"Gray Squadron Pilot":
name: "Pilot der Grau-Staffel"
'"Dutch" Vander':
text: """Wähle ein anderes freundliches Schiff in Reichweite 1-2, nachdem du eine Zielerfassung durchgeführt hast. Das gewählte Schiff darf sofort ebenfalls eine Zielerfassung durchführen."""
"<NAME>":
text: """Wenn du ein Ziel in Reichweite 2-3 angreifst, darfst du beliebig viele Leerseiten neu würfeln."""
"Gold Squadron Pilot":
name: "Pilot der Gold-Staffel"
"Academy Pilot":
name: "Pilot der Akademie"
"Obsidian Squadron Pilot":
name: "Pilot der Obsidian-Staffel"
"Black Squadron Pilot":
name: "Pilot der Schwarz-Staffel"
'"<NAME>"':
name: '"<NAME>"'
text: """Wenn du ein Ziel in Reichweite 1 angreifst, darfst du eines deiner %HIT% in ein %CRIT% ändern."""
'"Night Beast"':
name: '"<NAME>"'
text: """Nachdem du ein grünes Manöver ausgeführt hast, darfst du als freie Aktion eine Fokussierung durchführen."""
'"Backstabber"':
text: """Wenn du bei deinem Angriff nicht im Feuerwinkel des Verteidigers bist, erhältst du 1 zusätzlichen Angriffswürfel."""
'"Dark Curse"':
text: """Wenn du verteidigst, können angreifende Schiffe keine Fokusmarker ausgeben oder Angriffswürfel neu würfeln."""
'"<NAME>"':
text: """Wirf 1 zusätzlichen Angriffswürfel, wenn du ein Ziel in Reichweite 1 angreifst."""
'"<NAME>"':
name: '"<NAME>"'
text: """Wenn ein anderes freundliches Schiff in Reichweite 1 mit seinen Primärwaffen angreift, darf es 1 Angriffswürfel neu würfeln."""
"<NAME>":
text: """Wenn ein Verteidiger durch deinen Angriff eine offene Schadenskarte erhalten würde, ziehst du stattdessen 3 Schadenskarten, wählst eine davon zum Austeilen und legst die restlichen ab."""
"Tempest Squadron Pilot":
name: "Pilot der Tornado-Staffel"
"Storm Squadron Pilot":
name: "Pilot der Storm-Staffel"
"<NAME>":
text: """Im Schritt "Aktionen durchführen" darfst du 2 Aktionen durchführen."""
"Alpha Squadron Pilot":
name: "Pilot der Alpha-Staffel"
ship: "TIE-Abfangjäger"
"Avenger Squadron Pilot":
name: "Pilot der Avenger-Staffel"
ship: "TIE-Abfangjäger"
"Saber Squadron Pilot":
name: "Pilot der Saber-Staffel"
ship: "TIE-Abfangjäger"
"\"<NAME>\"":
ship: "TIE-Abfangjäger"
text: """Wenn die Summe deiner Schadenskarten deinen Hüllenwert erreicht oder übersteigt, wirst du nicht sofort zerstört, sondern erst am Ende der Kampfphase."""
"<NAME>":
ship: "TIE-Abfangjäger"
text: """Nachdem du angegriffen hast, darfst du eine freie Aktion Schub oder Fassrolle durchführen."""
"<NAME>":
ship: "TIE-Abfangjäger"
text: """Immer wenn du einen Stressmarker erhältst, darfst du deinem Schiff auch einen Fokusmarker geben."""
"<NAME>":
text: """Du darfst auch dann Aktionen durchführen, wenn du Stressmarker hast."""
"<NAME>":
text: """Wenn du angreifst, darfst du auch auf feindliche Schiffe zielen, deren Basen du berührst (vorausgesetzt sie sind innerhalb deines Feuerwinkels)."""
"Green Squadron Pilot":
name: "Pilot der Grün-Staffel"
"Prototype Pilot":
name: "Testpilot"
"Outer Rim Smuggler":
name: "Schmuggler aus dem Outer Rim"
"<NAME>":
text: """Wenn du eine offene Schadenskarte erhältst, wird sie sofort umgedreht (ohne dass ihr Kartentext in Kraft tritt)."""
"<NAME>":
text: """Wähle nach dem Ausführen eines grünen Manövers ein anderes freundliches Schiff in Reichweite 1. Dieses Schiff darf eine freie Aktion aus seiner Aktionsleiste durchführen."""
"<NAME>":
text: """Wenn du angreifst, darfst du all deine Würfel neu würfeln. Tust du dies, musst du so viele Würfel wie möglich neu würfeln."""
"<NAME>":
text: """Wenn du angreifst und der Verteidiger mindestens 1 %CRIT% negiert, erhält er 1 Stressmarker."""
"<NAME>":
text: """Sobald du ein Drehmanöver (%BANKLEFT% oder %BANKRIGHT%) aufdeckst, darfst du das Drehmanöver mit gleicher eschwindigkeit, aber anderer Richtung, auf deinem Rad nachträglich einstellen."""
"<NAME>":
text: """Wenn du mit einer Sekundärwaffe angreifst, darfst du 1 Angriffswürfel neu würfeln."""
"<NAME>":
name: "<NAME>"
"<NAME>":
text: """Wenn du angreifst, kann 1 deiner %CRIT% von Verteidigungswürfeln nicht negiert werden."""
"<NAME>":
text: """Beim Angreifen oder Verteidigen darfst du 1 deiner Würfel neu würfeln, sofern du mindestens 1 Stressmarker hast."""
"Dagger Squadron Pilot":
name: "Pilot der Dagger-Staffel"
"Blue Squadron Pilot":
name: "Pilot der Blauen Staffel"
"Rebel Operative":
name: "Rebellenagent"
"<NAME>":
text: '''Wähle zu Beginn der Kampfphase 1 anderes freundliches Schiff in Reichweite 1-3. Bis zum Ende der Phase wird dieses Schiff behandelt, als hätte es einen Pilotenwert von 12.'''
"<NAME>":
text: """Zu Beginn der Kampfphase darfst du einem anderen freundlichen Schiff in Reichweite 1-3 einen deiner Fokusmarker geben."""
"<NAME>":
text: """Wenn ein anderes freundliches Schiff in Reichweite 1-3 angreift und du keine Stressmarker hast, darfst du 1 Stressmarker nehmen, damit dieses Schiff 1 zusätzlichen Angriffswürfel erhält."""
"Scimitar Squadron Pilot":
name: "Pilot der Scimitar-Staffel"
"Gamma Squadron Pilot":
name: "Pilot der Gamma-Staffel"
"<NAME>":
text: """Wenn ein anderes freundliches Schiff in Reichweite 1 mit einer Sekundärwaffe angreift, darf es bis zu 2 Angriffswürfel neu würfeln."""
"Major <NAME>hymer":
text: """Beim Angreifen mit einer Sekundärwaffe darfst du die Reichweite der Waffe um 1 erhöhen oder verringern, bis zu einer Reichweite von 1-3."""
"<NAME>":
ship: "Raumfähre der Lambda-Klasse"
text: """Wenn ein feindliches Schiff eine Zielerfassung durchführt, muss es wenn möglich dich als Ziel erfassen."""
"<NAME>":
ship: "Raumfähre der Lambda-Klasse"
text: """Zu Beginn der Kampfphase darfst du 1 deiner blauen Zielerfassungsmarker auf ein freundliches Schiff in Reichweite 1 legen, das noch keinen blauen Zielerfassungsmarker hat."""
"<NAME>":
ship: "Raumfähre der Lambda-Klasse"
text: """Wenn ein anderes freundliches Schiff in Reichweite 1-2 einen Stressmarker erhalten würde und du 2 oder weniger Stressmarker hast, darfst du statt ihm diesen Marker nehmen."""
"Omicron Group Pilot":
ship: "Raumfähre der Lambda-Klasse"
name: "Pilot der Omikron-Gruppe"
"<NAME>":
ship: "TIE-Abfangjäger"
text: """Wenn du die Aktion Fassrolle ausführst, kannst du 1 Stressmarker erhalten, um die (%BANKLEFT% 1) oder (%BANKRIGHT% 1) Manöverschablone anstatt der (%STRAIGHT% 1) Manöverschablone zu benutzen."""
"Royal Guard Pilot":
ship: "TIE-Abfangjäger"
name: "Pilot der Roten Garde"
"<NAME>":
ship: "TIE-Abfangjäger"
text: """Immer wenn du ein %UTURN% Manöver aufdeckst, kannst du das Manöver mit einer Geschwindigkeit von "1," "3," oder "5" ausführen."""
"<NAME>":
ship: "TIE-Abfangjäger"
text: """Wenn du ein Ziel in Reichweite 2-3 angreifst, darfst du einen Ausweichmarker ausgeben, um 1 %HIT% zu deinem Wurf hinzuzufügen."""
"<NAME>":
ship: "TIE-Abfangjäger"
text: """Feindliche Schiffe in Reichweite 1 können weder Fokussierung und Ausweichen Aktionen durchführen noch Ausweichmarker und Fokusmarker ausgeben."""
"GR-75 Medium Transport":
ship: "Medium-Transporter GR-75"
name: "Medium-Transporter GR-75"
"Bandit Squadron Pilot":
ship: "Z-95-Kopfjäger"
name: "Pilot der Bandit-Staffel"
"Tala Squadron Pilot":
ship: "Z-95-Kopfjäger"
name: "Pilot der Tala-Staffel"
"<NAME>":
ship: "Z-95-Kopfjäger"
name: "<NAME>"
text: """Wenn du angreifst, triffst du immer, selbst wenn das verteidigende Schiff keinen Schaden nimmt."""
"<NAME>":
ship: "Z-95-Kopfjäger"
name: "<NAME>"
text: """Nachdem du angegriffen hast, darfst du ein anderes freundliches Schiff in Reichweite 1 wählen. Dieses Schiff darf 1 freie Aktion durchführen."""
"Delta Squadron Pilot":
ship: "TIE-Jagdbomber"
name: "Pilot der Delta-Staffel"
"Onyx Squadron Pilot":
ship: "TIE-Jagdbomber"
name: "Pilot der Onyx-Staffel"
"<NAME>":
ship: "TIE-Jagdbomber"
text: """Wenn du angreifst und der Verteidiger bereits einen roten Zielerfassungsmarker hat, darfst du ihn unmittelbar nach dem Angriffswurf in die Zielerfassung nehmen."""
"<NAME>":
ship: "TIE-Jagdbomber"
text: """Nachdem du angegriffen und damit dem Verteidiger mindestens 1 Schadenskarte zugeteilt hast, kannst du einen Fokusmarker ausgeben, um die soeben zugeteilten Schadenskarten aufzudecken."""
"Knave Squadron Pilot":
name: "Pilot der Schurken-Staffel"
"Blackmoon Squadron Pilot":
name: "Pilot der Schwarzmond-Staffel"
"<NAME>":
text: """Sobald ein feindliches Schiff in Reichweite 1–3 und innerhalb deines Feuerwinkels verteidigt, darf der Angreifer 1 %HIT% seiner in ein %CRIT% ändern."""
"<NAME>":
text: """Zu Beginn der Endphase kannst du einen Angriff durchführen. Tust du das, darfst du in der nächsten Runde nicht angreifen."""
"Sigma Squadron Pilot":
name: "Pilot der Sigma-Staffel"
"Shadow Squadron Pilot":
name: "Pilot der Schatten-Staffel"
'"Echo"':
name: '"Echo"'
text: """Wenn du dich enttarnst, musst du statt der (%STRAIGHT% 2)-Manöverschablone die (%BANKRIGHT% 2)- oder (%BANKLEFT% 2)-Schablone verwenden."""
'"Wh<NAME>"':
name: '"<NAME>"'
text: """Nachdem du mit einem Angriff getroffen hast, darfst du deinem Schiff 1 Fokusmarker geben."""
"CR90 Corvette (Fore)":
name: "CR90-Korvette (Bug)"
ship: "CR90-Korvette (Bug)"
text: """Wenn du mit deinen Primärwaffen angreifst, kannst du 1 Energie ausgeben, um 1 zusätzlichen Angriffswürfel zu bekommen"""
"CR90 Corvette (Aft)":
name: "CR90-Korvette (Heck)"
ship: "CR90-Korvette (Heck)"
"<NAME>":
text: """Nachdem du einen Angriff durchgeführt hast, darfst du 1 Fokus-, Ausweich- oder blauen Zielerfassungsmarker vom Verteidiger entfernen."""
"<NAME>":
text: """Wenn du einen Stressmarker erhälst, darfst du ihn entfernen und 1 Angriffswürfel werfen. Bei %HIT% bekommt dein Schiff 1 verdeckte Schadenskarte."""
'"<NAME>" <NAME>':
text: """Wenn du ein Schiff in die Zielerfassung nimmst oder einen Zielerfassungsmarker ausgibst, kannst du 1 Stressmarker von deinem Schiff entfernen."""
"<NAME>":
text: """Wenn ein feindliches Schiff einen Angriff gegen dich ansagt, kannst du dieses Schiff in die Zielerfassung nehmen."""
"<NAME>":
text: """Nachdem du die Aktion Fokussierung durchgeführt oder einen Fokusmarker erhalten hast, darfst du als freie Aktion einen Schub oder eine Fassrolle durchführen."""
"<NAME>":
name: "<NAME>"
text: """Solange du in Reichweite 1 zu mindestens einem feindlichen Schiff bist, steigt dein Wendigkeitswert um 1."""
"<NAME>":
text: """Beim Angreifen darfst du 1 Stressmarker entfernen, um alle deine %FOCUS% in %HIT% zu ändern."""
"<NAME>":
text: """Mit %TORPEDO%-Sekundärwaffen kannst du auch feindliche Schiffe außerhalb deines Feuerwinkels angreifen."""
# "CR90 Corvette (Crippled Aft)":
# name: "CR90-Korvette (Heck-Lahmgelegt)"
# ship: "CR90-Korvette (Heck)"
# text: """Folgende Manöver darfst du weder wählen noch ausführen: (%STRAIGHT% 4), (%BANKLEFT% 2), or (%BANKRIGHT% 2) ."""
# "CR90 Corvette (Crippled Fore)":
# name: "CR90-Korvette (Bug-Lahmgelegt)"
# ship: "CR90-Korvette (Bug)"
"Wild Space Fringer":
name: "Grenzgänger aus dem Wilden Raum"
"Dash Rendar":
text: """Du darfst in der Aktivierungsphase und beim Durchführen von Aktionen Hindernisse ignorieren."""
'"<NAME>"':
text: """Immer wenn du eine offene Schadenskarte erhältst, ziehst du 1 weitere Schadenskarte. Wähle 1, die abgehandelt wird, und lege die andere ab."""
"<NAME>":
text: """Wirf 1 zusätzlichen Angriffswürfel, wenn du mit den Primärwaffen auf ein Schiff mit Stressmarker schießt."""
"<NAME>":
name: "<NAME>"
"<NAME>":
name: "<NAME>"
text: """Wenn du ein Ziel in Reichweite 1-2 angreifst, kannst du ein %FOCUS% in ein %CRIT% ändern."""
"<NAME>":
text: """Wenn du keine Schilde und mindestens 1 Schadenskarte hast, steigt deine Wendigkeit um 1."""
"<NAME>":
text: """Nach dem Ausführen eines Manövers nimmt jedes feindliche Schiff, das du berührst, 1 Schaden."""
"<NAME>":
name: "<NAME>"
text: """Sobald du verteidigst, darf ein freundliches Schiff in Reichweite 1 ein nicht-negiertes %HIT% oder %CRIT% an deiner Stelle nehmen."""
"<NAME>":
text: """Wenn du zu Beginn der Kampfphase in Reichweite 1 zu einem feindlichen Schiff bist, darfst du 1 Fokusmarker auf dein Schiff legen."""
"Black Sun Vigo":
name: "Vigo der Schwarzen Sonne"
"Black Sun Enforcer":
name: "Vollstrecker der Schwarzen Sonne"
"<NAME>":
ship: "M3-A Abfangjäger"
text: """Sobald ein anderes freundliches Schiff in Reichweite 1 verteidigt, darf es 1 Verteidigungswürfel neu würfeln."""
"<NAME>":
ship: "M3-A Abfangjäger"
text: """Nachdem du gegen einen Angriff verteidigt hast und falls der Angriff nicht getroffen hat, darfst du deinem Schiff 1 Ausweichmarker zuordnen."""
"<NAME>":
ship: "M3-A Abfangjäger"
name: "<NAME>"
"<NAME>":
ship: "M3-A Abfangjäger"
name: "<NAME>"
"IG-88A":
text: """Nachdem du einen Angriff durchgeführt hast, der den Verteidiger zerstört, darfst du 1 Schild wiederaufladen."""
"IG-88B":
text: """Ein Mal pro Runde darfst du, nachdem du mit einem Angriff verfehlt hast, einen weiteren Angriff mit einer ausgerüsteten %CANNON%-Sekundärwaffe durchführen."""
"IG-88C":
text: """Nachdem du die Aktion Schub durchgeführt hast, darfst du eine freie Aktion Ausweichen durchführen."""
"IG-88D":
text: """Du darfst die Manöver (%SLOOPLEFT% 3) oder (%SLOOPRIGHT% 3) auch mit den entsprechenden Schablonen für Wendemanöver (%TURNLEFT% 3) bzw. (%TURNRIGHT% 3) ausführen."""
"<NAME> (Scum)":
name: "<NAME> (Abschaum)"
text: """Sobald du angreifst oder verteidigst, darfst du für jedes feindliche Schiff in Reichweite 1 einen deiner Würfel neu würfeln."""
"<NAME> (Scum)":
name: "<NAME> (Abschaum)"
text: """Sobald du ein Schiff innerhalb deines Zusatz-Feuerwinkels angreifst, erhältst du 1 zusätzlichen Angriffswürfel."""
"<NAME>":
text: """Sobald du eine Bombe legst, darfst du auch die Schablone [%TURNLEFT% 3], [%STRAIGHT% 3] oder [%TURNRIGHT% 3] anstatt der [%STRAIGHT% 1]-Schablone verwenden."""
"<NAME>":
name: "<NAME>"
"<NAME>":
text: """Sobald du ein Schiff außerhalb deines Feuerwinkels angreifst, erhältst du 1 zusätzlichen Angriffswürfel."""
"<NAME>":
text: """Nachdem du einen Zielerfassungsmarker ausgegeben hast, darfst du 1 Stressmarker nehmen, um ein Schiff in die Zielerfassung zu nehmen."""
"<NAME>":
name: "<NAME>brecher des Syndikats"
"<NAME>":
name: "<NAME>"
"<NAME>":
text: """Sobald ein feindliches Schiff in Reichweite 1-3 mindestens 1 Ionenmarker erhält und falls du keinen Stressmarker hast, darfst du 1 Stressmarker nehmen, damit das Schiff 1 Schaden nimmt."""
"<NAME>":
text: """Zu Beginn der Kampfphase darfst du 1 Fokus- oder Ausweichmarker von einem feindlichen Schiff in Reichweite 1-2 entfernen und dir selbst zuordnen."""
"<NAME>":
text: """Wähle am Ende der Aktivierungsphase 1 feindliches Schiff in Reichweite 1-2. Bis zum Ende der Kampfphase wird der Pilotenwert des Schiffs als "0" behandelt."""
"<NAME>":
name: "<NAME>"
"<NAME>":
ship: "Z-95-Kopfjäger"
text: """Sobald du angreifst, erhälst du 1 zusätzlichen Angriffswürfel, falls keine anderen freundlichen Schiffe in Reichweite 1-2 zu dir sind."""
"<NAME>":
ship: "Z-95-Kopfjäger"
text: """Zu Beginn der Kampfphase darfst du 1 Fokus- oder Ausweichmarker von einem anderem freundlichen Schiff in Reichweite 1-2 entfernen und dir selbst zuordnen."""
"<NAME>":
ship: "Z-95-Kopfjäger"
name: "<NAME>"
"Black Sun <NAME>":
ship: "Z-95-Kopfjäger"
name: "Kampfpilot der Schwarzen Sonne"
"<NAME>":
text: """At the start of the Combat phase, you may acquire a target lock on an enemy ship at Range 1."""
"Raider-class Corvette (Fore)":
text: """Once per round, ??? perform a primary ??? attack, you may spend 2 e??? perform another primary wea???"""
"<NAME>":
text: """When you reveal your maneuver, you may increase or decrease its speed by 1 (to a minimum of 1)."""
"<NAME>":
text: """Enemy ships at Range 1 cannot add their range combat bonus when attacking."""
"<NAME>":
text: """At the start of the End phase, you may spend a target lock you have on an enemy ship to flip 1 random facedown Damage card assigned to it faceup."""
"<NAME>":
text: """When a friendly ship declares an attack, you may spend a target lock you have on the defender to reduce its agility by 1 for that attack."""
"<NAME>":
text: """When defending, if the attacker is inside your firing arc, roll 1 additional defense die."""
"<NAME>":
text: """When another friendly ship at Range 1-2 is attacking, it may treat your focus tokens as its own."""
'"Red<NAME>"':
text: """You may maintain 2 target locks on the same ship. When you acquire a target lock, you may acquire a second lock on that ship."""
'"Death<NAME>"':
text: """When dropping a bomb, you may use the front guides of your ship. After dropping a bomb, you may perform a free barrel roll action."""
"Moralo <NAME>":
text: """You can perform %CANNON% secondary attacks against ships inside your auxiliary firing arc."""
'Gozanti-class Cruiser':
text: """After you execute a maneuver, you may deploy up to 2 attached ships."""
'"<NAME>"':
text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die."""
"The In<NAME>itor":
text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1."""
"<NAME>":
text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die."""
"<NAME>":
text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship."""
upgrade_translations =
"Ion Cannon Turret":
name: "<NAME>"
text: """<strong>Angriff:</strong> Greife 1 Schiff an (es muss nicht in deinem Feuerwinkel sein).<br /><br />Wenn der Angriff trifft, nimmt das verteidigende Schiff 1 Schaden und erhält 1 Ionenmarker. Dann werden alle übrigen Würfelergebnisse negiert."""
"<NAME>":
name: "<NAME>"
text: """<strong>Angriff (Zielerfassung):</strong>Gib eine Zielerfassung aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst eines deiner %FOCUS% in ein %CRIT% ändern."""
"R2 Astromech":
name: "R2 Astromechdroide"
text: """Du darfst alle Manöver mit Geschwindigkeit 1 und 2 wie grüne Manöver behandeln."""
"R2-D2":
text: """Nachdem du ein grünes Manöver ausgeführt hast, darfst du 1 Schild wiederaufladen (bis maximal zum Schildwert)."""
"R2-F2":
text: """<strong>Aktion:</strong> Erhöhe deinen Wendigkeitswert bis zum Ende der Spielrunde um 1."""
"R5-D8":
text: """<strong>Aktion:</strong> Wirf 1 Verteidigungswürfel.<br /><br />Lege bei %EVADE% oder %FOCUS% 1 deiner verdeckten Schadenskarten ab."""
"R5-K6":
text: """Wirf 1 Verteidigungswürfel nachdem du deine Zielerfassungsmarker ausgegeben hast.<br /><br />Bei %EVADE% nimmst du dasselbe Schiff sofort wieder in die Zielerfassung. Für diesen Angriff kannst du die Zielerfassungsmarker nicht erneut ausgeben."""
"R5 Astromech":
name: "R5 Astromechdroide"
text: """Wähle während der Endphase 1 deiner offnen Schadenskarte mit dem Attribut <strong>Schiff</strong> und drehe sie um."""
"Determination":
name: "<NAME>"
text: """Wenn du eine offene Schadenskarte mit dem Attribut <b>Pilot</b> erhältst, wird diese sofort abgelegt (ohne dass der Kartentext in Kraft tritt)."""
"Swarm Tactics":
name: "<NAME>"
text: """Du darfst zu Beginn der Kampfphase 1 freundliches Schiff in Reichweite 1 wählen.<br /><br />Bis zum Ende dieser Phase wird das gewählte Schiff so behandelt, als hätte es denselben Pilotenwert wie du."""
"Squad Leader":
name: "<NAME>"
text: """<strong>Aktion:</strong> Wähle ein Schiff in Reichweite 1-2 mit einem geringeren Pilotenwert als du.<br /><br />Das gewählte Schiff darf sofort 1 freie Aktion durhführen."""
"Expert Handling":
name: "<NAME>"
text: """<strong>Aktion:</strong> Führe als freie Aktion eine Fassrolle durch. Wenn du kein %BARRELROLL%-Symbol hast, erhältst du 1 Stressmarker.<br /><br />Dann darfst du 1 feindlichen Zielerfassungsmarker von deinem Schiff entfernen."""
"Marksmanship":
name: "<NAME>"
text: """<strong>Aktion:</strong> Wenn du in dieser Runde angreifst, darfst du eines deiner %FOCUS% in ein %CRIT% und alle anderen %FOCUS% in %HIT% ändern."""
"Concussion Missiles":
name: "<NAME>"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst eine deiner Leerseiten in ein %HIT% ändern."""
"Cluster Missiles":
name: "Cluster-<NAME>"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmaker aus und lege diese Karte ab, um mit dieser Sekundärwaffe <strong>zwei Mal</strong> anzugreifen."""
"<NAME>":
name: "<NAME>"
text: """<strong>Aktion:</strong> Führe ein weißes (%TURNLEFT% 1) oder (%TURNRIGHT% 1) Manöver aus. Dann erhälst du einen Stresmarker.<br /><br />Wenn du kein %BOOST%-Aktionssymbol hast, musst du dann 2 Angriffswürfel werfen. Du nimmst allen gewürfelten Schaden (%HIT%) und kritischen Schaden (%CRIT%)."""
"El<NAME>iveness":
name: "<NAME>"
text: """Wenn du verteidigst, darfst du 1 Stressmarker nehmen, um 1 Angriffswürfel zu wählen. Diesen muss der Angreifer neu würfeln.<br /><br />Du kannst diese Fähigkeit nicht einsetzen, solange du 1 oder mehrere Stressmarker hast."""
"Homing M<NAME>":
name: "<NAME>"
text: """<strong>Angriff (Zielerfassung):</strong> Lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Bei diesem Angriff kann der Verteidiger keine Ausweichmarker ausgeben."""
"Push the Limit":
name: "<NAME> an die Grenzen"
text: """Einmal pro Runde darfst du nach dem Durchführen einer Aktion eine freie Aktion aus deiner Aktionsleiste durhführen.<br /><br />Dann erhältst du 1 Stressmarker."""
"<NAME>":
name: "<NAME>"
text: """Du darfst die Bedingung "Angriff (Zielerfassung):" in "Angriff (Fokussierung):" ändern.<br /><br />Wenn ein Angriff das Ausgeben von Zielerfassungsmarkern erfordert, darfst du stattdessen auch einen Fokusmarker ausgeben."""
"Expose":
name: "<NAME>"
text: """<strong>Aktion:</strong> Bis zum Ende der Runde steigt dein Primärwaffenwert um 1, dafür sinkt dein Wendigkeitswert um 1."""
"<NAME>":
name: "<NAME>"
text: """Unmittelbar nachdem du mit einem Angriff verfehlt hast, darfst du einen weiteren Angriff mit deiner Primärwaffe durchführen. Danach kannst du in dieser Runde nicht noch einmal angreifen."""
"Ion Cannon":
name: "<NAME>"
text: """<strong>Angriff:</strong> Greife 1 Schiff mit dieser Sekundärwaffe an.<br /><br />Wenn du triffst, nimmt das verteidigende Schiff 1 Schaden und erhält 1 Ionenmarker. Dann werden <b>alle</b> übrigen Würfelergebnisse negiert."""
"Heavy Laser Cannon":
name: "<NAME>"
text: """<strong>Attack:</strong> Greife 1 Schiff mit dieser Sekundärwaffe an.<br /><br />Unmittelbar nach dem Angriffswurf musst du alle %CRIT% in %HIT% ändern."""
"Seismic Charges":
name: "<NAME>mische Bomben"
text: """Nach dem Aufdecken deines Manöverrads darfst du diese Karte ablegen um 1 Seismischen Bomben-Marker zu <strong>legen</strong>.<br /><br />Der Marker <strong>detoniert</strong> am Ende der Aktivierungsphase."""
"Mercenary Copilot":
name: "Angeheuerter Kopilot"
text: """Wenn du ein Ziel in Reichweite 3 angreifst, darfst du eines deiner %HIT% in ein %CRIT% ändern."""
"Ass<NAME>":
name: "<NAME>"
text: """Angriff (Zielerfassung): Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Wenn du triffst, nimmt jedes andere Schiff in Reichweite 1 des verteidigenden Schiffs 1 Schaden."""
"Veteran Instincts":
name: "<NAME>"
text: """Dein Pilotenwert steigt um 2."""
"Proximity Mines":
name: "<NAME>"
text: """<strong>Aktion:</strong> Lege diese Karte ab, um 1 Annährungsminen-Marker zu <strong>legen</strong>.<br /><br />Der Marker <strong>detoniert</strong>, sobald sich die Basis eines Schiffs oder die Manöverschablone mit dem Marker überschneidet."""
"Weapons Engineer":
name: "<NAME>"
text: """Du darfst 2 verschiedene Schiffe gleichzeitig in der Zielerfassung haben (maximal 1 Zielerfassung pro feindlichem Schiff).<br /><br />Sobald du eine Zielerfassung durchführst, darfst du zwei verschiedene Schiffe als Ziele erfassen."""
"Draw Their Fire":
name: "Das Feuer auf mich ziehen"
text: """Wenn ein freundliches Schiff in Reichweite 1 durch einen Angriff getroffen wird, darfst du anstelle dieses Schiffs den Schaden für 1 nicht-negiertes %CRIT% auf dich nehmen."""
"<NAME>":
text: """%DE_REBELONLY%%LINEBREAK%Unmittelbar nachdem du mit einem Angriff verfehlt hast, darfst du einen weiteren Angriff mit deiner Primärwaffe durchführen. Du darfst ein %FOCUS% in ein %HIT% ändern. Danach kannst du in dieser Runde nicht noch einmal angreifen."""
"<NAME>":
text: """%DE_REBELONLY%%LINEBREAK%Du darfst alle %STRAIGHT%-Manöver wie grüne Manöver behandeln."""
"Chewbacca":
name: "Chewbacca (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Wenn du eine Schadenskarte erhältst, darfst du sie sofort ablegen und 1 Schild wiederaufladen.<br /><br />Danach wird diese Aufwertungskarte abgelegt."""
"Advanced Proton Torpedoes":
name: "Verstärkte Protonen-Torpedos"
text: """<strong>Angriff (Zielerfassung):</strong> Gib eine Zielerfassung aus und lege diese Karte ab um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst bis zu 3 deiner Leerseiten in %FOCUS% ändern."""
"Autoblaster":
name: "Repertierblaster"
text: """<strong>Angriff:</strong> Greife 1 Schiff mit dieser Sekundärwaffe an.<br /><br />Deine %HIT% können von Verteidigungswürfeln nicht negiert werden.<br /><br />Der Verteidiger darf %CRIT% negieren, bevor alle %HIT% negiert wurden."""
"Fire-Control System":
name: "Feuerkontrollsystem"
text: """Nachdem du angegriffen hast, darfst du eine Zielerfassung auf den Verteidiger durchführen."""
"Blaster Turret":
name: "Blastergeschütz"
text: """<strong>Angriff (Fokussierung):</strong> Gib 1 Fokusmarker aus, um 1 Schiff mit dieser Sekundärwaffe anzugreifen (es muss nicht in deinem Feuerwinkel sein)."""
"Recon Specialist":
name: "<NAME>"
text: """Wenn du die Aktion Fokussieren durchführst, lege 1 zusätzlichen Fokusmarker neben dein Schiff."""
"Saboteur":
text: """<strong>Aktion:</strong> Wähle 1 feindliches Schiff in Reichweite 1 und wirf 1 Angriffswürfel. Bei %HIT% oder %CRIT%, wähle 1 zufällige verdeckte Schadenskarte des Schiffs, decke sie auf und handle sie ab."""
"Intelligence Agent":
name: "<NAME>"
text: """Wähle zu Beginn der Aktivierungsphase 1 feindliches Schiff in Reichweite 1-2. Du darfst dir das ausgewählte Manöver dieses Schiffs ansehen."""
"Pro<NAME>":
name: "<NAME>"
text: """Nach dem Aufdecken deines Manöverrads darfst du diese Karte ablegen um 1 Protonenbomben-Marker zu <strong>legen</strong>.<br /><br />Der Marker <strong>detoniert</strong> am Ende der Aktivierungsphase."""
"<NAME>":
name: "<NAME>"
text: """Wenn du ein rotes Manöver aufdeckst, darfst du diese Karte ablegen, um das Manöver bis zum Ende der Aktivierungsphase wie ein weißes Manöver zu behandeln."""
"Advanced Sensors":
name: "Verbesserte Sensoren"
text: """Unmittelbar vor dem Aufdecken deines Manövers darfst du 1 freie Aktion durchführen.<br /><br />Wenn du diese Fähigkeit nutzt, musst du den Schritt "Aktion durchführen" in dieser Runde überspringen."""
"Sensor <NAME>ammer":
name: "<NAME>"
text: """Beim Verteidigen darfst du eines der %HIT% des Angreifers in ein %FOCUS% ändern.<br /><br />Der Angreifer darf den veränderten Würfel nicht neu würfeln."""
"<NAME>":
name: "<NAME> (<NAME>)"
text: """%DE_IMPERIALONLY%%LINEBREAK%Nachdem du ein feindliches Schiff angegriffen hast, darfst du 2 Schaden nehmen, damit dieses Schiff 1 kritischen Schaden nimmt."""
"Rebel Captive":
name: "<NAME>"
text: """%DE_IMPERIALONLY%%LINEBREAK%Ein Mal pro Runde erhält das erste Schiff, das einen Angriff gegen dich ansagt, sofort 1 Stressmarker."""
"Flight Instructor":
name: "<NAME>"
text: """Beim Verteidigen darfst du 1 deiner %FOCUS% neu würfeln. Hat der Angreifer einen Pilotenwert von 2 oder weniger, darfst du stattdessen 1 deiner Leerseiten neu würfeln."""
"Navigator":
name: "Navigator"
text: """Nach dem Aufdecken deines Manöverrads darfst du das Rad auf ein anderes Manöver mit gleicher Flugrichtung drehen.<br /><br />Wenn du bereits Stressmarker hast, darfst du es nicht auf ein rotes Manöver drehen."""
"Opportunist":
name: "Opportunist"
text: """Wenn du angreifst und der Verteidiger keine Fokusmarker oder Ausweichmarker hat, kannst du einen Stressmarker nehmen, um einen zusätzlichen Angriffswürfel zu erhalten.<br /><br />Du kannst diese Fähigkeit nicht nutzen, wenn du einen Stressmarker hast."""
"Comms Booster":
name: "Kommunikationsverstärker"
text: """<strong>Energie:</strong> Gib 1 Energie aus, um sämtliche Stressmarker von einem freundlichen Schiff in Reichweite 1-3 zu entfernen. Dann erhält jenes Schiff 1 Fokusmarker."""
"Slicer Tools":
name: "Hackersoftware"
text: """<strong>Aktion:</strong> Wähle 1 oder mehrere feindliche Schiffe mit Stressmarker in Reichweite 1-3. Bei jedem gewählten Schiff kannst du 1 Energie ausgeben, damit es 1 Schaden nimmt."""
"Shield Projector":
name: "Schildprojektor"
text: """Wenn ein feindliches Schiff in der Kampfphase an die Reihe kommt, kannst du 3 Energie ausgeben, um das Schiff bis zum Ende der Phase dazu zu zwingen dich anzugreifen, falls möglich."""
"Ion Pulse Missiles":
name: "Ionenpuls-Raketen"
text: """<strong>Angriff (Zielerfassung):</strong> Lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Wenn du triffst, nimmt das verteidigende Schiff 1 Schaden und erhält 2 Ionenmarker. Dann werden <strong>alle<strong> übrigen Würfelergebnisse negiert."""
"<NAME>":
name: "<NAME>"
text: """Entferne zu Beginn der Kampfphase 1 Stressmarker von einem anderen freundlichen Schiff in Reichweite 1."""
"<NAME>":
name: "<NAME>"
text: """Zu Beginn der Kampfphase darfst du 1 freundliches Schiff in Reichweite 1-2 wählen. Bis zum Ende der Phase tauscht du mit diesem Schiff den Pilotenwert."""
"<NAME>":
name: "<NAME>"
text: """Wenn du ein Schiff innerhalb deines Feuerwinkels angreifst und selbst nicht im Feuerwinkel dieses Schiffs bist, wird seine Wendigkeit um 1 reduziert (Minimum 0)"""
"Predator":
name: "<NAME>"
text: """Wenn du angreifst, darfst du 1 Angriffswürfel neu würfeln. Ist der Pilotenwert des Verteidigers2 oder niedriger, darfst du stattdessen bis zu 2 Angriffswürfel neu würfeln."""
"<NAME>":
name: "<NAME>"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Nachdem du angegriffen hast, bekommt der Verteidiger 1 Stressmarker, sofern sein Hüllenwert 4 oder weniger beträgt."""
"R7 Astromech":
name: "R7-Astromech-Droide"
text: """Ein Mal pro Runde kannst du beim Verteidigen gegen den Angriff eines Schiffs, das du in Zielerfassung hast, die Zielerfassungsmarker ausgeben, um beliebige (oder alle) Angriffswürfel zu wählen. Diese muss der Angreifer neu würfeln."""
"R7-T1":
name: "R7-T1"
text: """<strong>Aktion:</strong> Wähle ein feindliches Schiff in Reichweite 1-2. Wenn du im Feuerwinkel dieses Schiffs bist, kannst du es in die Zielerfassung nehmen. Dann darfst du als freie Aktion einen Schub durchführen."""
"Tactician":
name: "<NAME>"
text: """Nachdem du ein Schiff in Reichweite 2 und innerhalb deines Feuerwinkels angegriffen hast, erhält es 1 Stressmarker."""
"R2-D2 (Crew)":
name: "R2-D2 (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Wenn du am Ende der Endphase keine Schilde hast, darfst du 1 Schild wieder aufladen und 1 Angriffswürfel werfen. Bei %HIT% musst du 1 deiner verdeckten Schadenskarten (zufällig gewählt) umdrehen und abhandeln."""
"C-3PO":
name: "C-3PO"
text: """%DE_REBELONLY%%LINEBREAK%Einmal pro Runde darfst du, bevor du 1 oder mehrere Verteidigungswürfel wirfst, laut raten, wie viele %EVADE% du würfeln wirst. Wenn du richtig geraten hast (bevor die Ergebnisse modifiziert werden), wird 1 %EVADE% hinzugefügt."""
"Single Turbolasers":
name: "Einzelne Turbolasers"
text: """<strong>Angriff (Energie):</strong> gib 2 Energie von dieser Karte aus, um mit dieser Sekundärwaffe anzugreifen. Der Verteidiger verwendet zum Verteidigen seinen doppelten Wendigkeitswert. Du darfst 1 deiner %FOCUS% in ein %HIT% ändern."""
"Quad Laser Cannons":
name: "<NAME>lings-L<NAME>kan<NAME>"
text: """<strong>Angriff (Energie):</strong> Gib 1 Energie von dieser Karte aus, um mit dieser Sekundärwaffe anzugreifen. Wenn der Angriff verfehlt, kannst du sofort 1 Energie von dieser Karte ausgeben, um den Angriff zu wiederholen."""
"Tibanna Gas Supplies":
name: "Tibanna-Gas-Vorräte"
text: """<strong>Energie:</strong> Du kannst diese Karte ablegen, um 3 Energie zu erzeugen."""
"Ionization Reactor":
name: "<NAME>"
text: """<strong>Energie:</strong> Gib 5 Energie von dieser Karte aus und lege sie ab, damit jedes andere Schiff in Reichweite 1 einen Schaden nimmt und einen Ionenmarker bekommt."""
"Engine Booster":
name: "<NAME>"
text: """Unmittelbar bevor du dein Manöverrad aufdeckst, kannst du 1 Energie ausgeben, um ein weißes (%STRAIGHT% 1)-Manöver auszuführen. Wenn es dadurch zur Überschneidung mit einem anderen Schiff käme, darfst du diese Fähigkeit nicht nutzen."""
"R3-A2":
name: "R3-A2"
text: """Nachdem du das Ziel deines Angriffs angesagt hast, darfst du, wenn der Verteidiger in deinem Feuerwinkel ist, 1 Stressmarker nehmen, damit der Verteidiger auch 1 Stressmarker bekommt."""
"R2-D6":
name: "R2-D6"
text: """Deine Aufwertungsleiste bekommt ein %ELITE%-Symbol.<br /><br />Du kannst diese Aufwertung nicht ausrüsten, wenn du bereits ein %ELITE%-Symbol hast oder dein Pilotenwert 2 oder weniger beträgt."""
"Enhanced Scopes":
name: "Verbessertes Radar"
text: """Behandle in der Aktivierungsphase deinen Pilotenwert als "0"."""
"Chardaan Refit":
name: "Chardaan-Nachrüstung"
text: """Diese Karte hat negative Kommandopunktekosten."""
"Proton Rockets":
name: "Protonenraketen"
text: """<strong>Angriff (Fokussierung):</strong> Lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst so viele zusätzliche Angriffswürfel werfen, wie du Wendigkeit hast (maximal 3 zusätzliche Würfel)."""
"<NAME>":
name: "<NAME> (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Nachdem du einen Stressmarker von deinem Schiff entfernt hast, darfst du deinem Schiff einen Fokusmarker geben."""
"<NAME>":
name: "<NAME> (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Ein Mal pro runde darfst du einem freundlichem Schiff in Reichweite 1-3, das gerade die Aktion Fokussierung durchführt oder einen Fokusmarker erhalten würde, stattdessen einen Ausweichmarker geben."""
"<NAME>":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%<strong>Aktion:</strong> Gib X Energie aus, um X feindliche Schiffe in Reichweite 1-2 zu wählen. Sämtliche Fokus-, Ausweich- und blauen Zielerfassungsmarker dieser Schiffe werden entfernt."""
# TODO Check card formatting
"R4-D6":
text: """Wenn du von einem Angriff getroffen wirst und es mindestens 3 nicht negierte %HIT% gibt, darfst du so viele %HIT% wählen und negieren, bis es nur noch 2 sind. Für jedes auf diese Weise negierte %HIT% bekommst du 1 Stressmarker."""
"R5-P9":
text: """Am Ende der Kampfphase kannst du 1 deiner Fokusmarker ausgeben, um 1 Schild wiederaufzuladen (bis maximal zum Schildwert)."""
"WED-15 Repair Droid":
name: "WED-15 Reparaturdroide"
text: """%DE_HUGESHIPONLY%%LINEBREAK%<strong>Aktion:</strong> gib 1 Energie aus, um 1 deiner verdeckten Schadenskarten abzulegen oder gib 3 Energie aus, um 1 deiner offenen Schadenskarten abzulegen."""
"<NAME>":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%Zu Beginn der Aktivierungsphase kannst du diese Karte ablegen, damit bis zum Ende der Phase der Pilotenwert aller freundlichen Schiffe 12 beträgt."""
"<NAME>":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%Wenn ein anderes freundliches Schiff in Reichweite 1 angreift, darf es 1 seiner gewürfelten %HIT% in ein %CRIT% ändern."""
"Expanded Cargo Hold":
name: "Erweiterter Ladebereich"
text: """Ein Mal pro Runde darfst du, wenn du eine offene Schadenskarte erhältst, frei wählen, ob du sie vom Schadensstapel Bug oder Heck ziehen willst."""
ship: "Medium-Transporter GR-75"
"Backup Shield Generator":
name: "Sekundärer Schildgenerator"
text: """Am Ende jeder Runde kannst du 1 Energie ausgeben, um 1 Schild wiederaufzuladen (bis maximal zum Schildwert)."""
"EM Emitter":
name: "EM-Emitter"
text: """Wenn du bei einem Angriff die Schussbahn versperrst, bekommst der Verteidiger 3 zusätzliche Verteidigungswürfel (anstatt 1)."""
"Frequency Jammer":
name: "Störsender (Fracht)"
text: """Wenn du die Aktion Störsignal durchführst, wähle 1 feindliches Schiff ohne Stressmarker in Reichweite 1 des vom Störsignal betroffenen Schiffs. Das gewählte Schiff erhält 1 Stressmarker."""
"<NAME>":
name: "<NAME> (Cre<NAME>)"
text: """%DE_REBELONLY%%LINEBREAK%Wenn du angreifst und den Verteidiger in Zielerfassung hast, kannst du diese Zielerfassung ausgeben, um all deine gewürfelten %FOCUS% in %HIT% zu ändern."""
"<NAME>":
text: """%DE_REBELONLY%%LINEBREAK%Zu Beginn der Aktivierungsphase kannst du diese Karte ablegen, damit alle freundlichen Schiffe, die ein rotes Manöver aufdecken, dieses bis zum Ende der Phase wie ein weißes Manöver behandeln dürfen."""
"Targeting Coordinator":
text: """<strong>Energy:</strong> You may spend 1 energy to choose 1 friendly ship at Range 1-2. Acquire a target lock, then assign the blue target lock token to the chosen ship."""
"<NAME>":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%Wähle zu Beginn der Aktivierungsphase 1 feindliches Schiff in Reichweite 1-3. Du kannst dir das gewählte Manöver dieses Schiffes ansehen. Wenn es weiß ist, bekommt dieses Schiff 1 Stressmarker."""
"Gunnery Team":
name: "<NAME>"
text: """Einmal pro Runde kannst du beim Angreifen mit einer Sekundärwaffe 1 Energie ausgeben, um 1 gewürfelte Leerseite in ein %HIT% zu ändern."""
"Sensor Team":
name: "Sensortechnikerteam"
text: """Du kannst feindliche Schiffe in Reichweite 1-5 in die Zielerfassung nehmen (anstatt in Reichweite 1-3)."""
"Engineering Team":
name: "<NAME>"
text: """Wenn du in der Aktivierungsphase ein %STRAIGHT% Manöver aufdeckst, bekommst du im Schritt "Energie gewinnen" 1 zusätzlichen Energiemarker."""
"<NAME>":
name: "<NAME> (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%<strong>Aktion:</strong> Wirf 2 Verteidigungswürfel. Dein Schiff bekommt 1 Fokusmarker für jedes %FOCUS% und 1 Ausweichmarker für jedes %EVADE%."""
"<NAME>":
text: """%DE_IMPERIALONLY%%LINEBREAK%Am Ende der Kampfphase erhält jedes feindliche Schiff in Reichweite 1, das keine Stressmarker hat, einen Stressmarker."""
"Fleet Officer":
name: "<NAME>"
text: """%DE_IMPERIALONLY%%LINEBREAK%<strong>Aktion:</strong> Wähle bis zu 2 freundliche Schiffe in Reichweite 1-2 und gib ihnen je 1 Fokusmarker. Dann erhältst du 1 Stressmarker."""
"Targeting Coordinator":
name: "<NAME>"
text: """<strong>Energie:</strong> Du kannst 1 Energie ausgeben, um 1 freundliches Schiff in Reichweite1-2 zu wählen. Nimm dann ein Schiff in die Zielerfassung und gibt den blauen Zielerfassungsmarker dem gewählten Schiff."""
"Lone Wolf":
name: "<NAME>"
text: """Wenn keine freundlichen Schiffe in Reichweite 1-2 sind, darfst du beim Angreifen und Verteidigen 1 gewürfelte Leerseite neu würfeln."""
"Stay On Target":
name: "<NAME>"
text: """Nach dem Aufdecken des Manöverrads darfst du ein anderes Manöver mit gleicher Geschwindigkeit auf deinem Rad einstellen.<br /><br />Dieses Manöver wird wie ein rotes Manöver behandelt."""
"Dash Rendar":
name: "Dash Rendar (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Du darfst auch angreifen während du dich mit einem Hindernis überschneidest.<br /><br />Deine Schussbahn kann nicht versperrt werden."""
'"Leebo"':
name: '"Leebo" (Crew)'
text: """%DE_REBELONLY%%LINEBREAK%<strong>Aktion:</strong> Führe als freie Aktion einen Schub durch. Dann erhältst du 1 Ionenmarker."""
"Ruthlessness":
name: "<NAME>"
text: """%DE_IMPERIALONLY%%LINEBREAK%Nachdem du mit einem Angriff getroffen hast, <strong>musst</strong> du 1 anderes Schiff in Reichweite 1 des Verteidigers (außer dir selbst) wählen. Das Schiff nimmt 1 Schaden."""
"Int<NAME>idation":
name: "<NAME>"
text: """Die Wendigkeit feindlicher Schiffe sinkt um 1, solange du sie berührst."""
"<NAME>":
text: """%DE_IMPERIALONLY%%LINEBREAK%Wenn du zu Beginn der Kampfphase keine Schilde und mindestens 1 Schadenskarte hast, darfst du als freie Aktion ausweichen."""
"<NAME>":
text: """%DE_IMPERIALONLY%%LINEBREAK%Wenn du eine offene Schadenskarte erhältst, kannst du diese Aufwertungskarte oder eine andere %CREW%-Aufwertung ablegen, um die Schadenskarte umzudrehen (ohne dass der Kartentext in Kraft tritt)."""
"Ion Torpedoes":
name: "Ionentorpedos"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Triffst du, erhalten alle Schiffe in Reichweite 1 des Verteidigers und der Verteidiger selbst je 1 Ionenmarker."""
"Bodyguard":
name: "<NAME>"
text: """%DE_SCUMONLY%%LINEBREAK%Zu Beginn der Kampfphase darfst du einen Fokusmarker ausgeben um ein freundliches Schiff in Reichweite 1 zu wählen, dessen Pilotenwert höher ist als deiner. Bis zum Ende der Runde steigt sein Wendigkeitswert um 1."""
"Calculation":
name: "Berechnung"
text: """Sobald du angreifst, darfst du einen Fokusmarker ausgeben, um 1 deiner %FOCUS% in ein %CRIT% zu ändern."""
"Accuracy Corrector":
name: "<NAME>"
text: """Sobald du angreifst, darfst du alle deine Würfelergebnisse negieren. Dann darfst du 2 %HIT% hinzufügen.%LINEBREAK%Deine Würfel können während dieses Angriffs nicht noch einmal modifiziert werden."""
"Inertial Dampeners":
name: "<NAME>"
text: """Sobald du dein Manöverraf aufdeckst, darfst du diese Karte ablegen, um [0%STOP%]-Manöver auszuführen. Dann erhältst du 1 Stressmarker."""
"<NAME>":
name: "<NAME>"
text: """<strong>Angriff:</strong> Greife 1 Schiffe an.%LINEBREAK%Wenn dieser Angriff trifft, nimmt das verteidigende Schiff 1 Schaden und erhält 1 Stressmarker (falls es noch keinen hat.) Dann werden <strong>alle</strong> Würfelergebnisse negiert."""
'"<NAME>" <NAME>':
name: '"<NAME>"-<NAME>'
text: """<strong>Angriff:</strong> Greife 1 Schiff an.%LINEBREAK%Sobald du angreifst, darfst du 1 deiner %HIT% in ein %CRIT% ändern."""
"Dead Man's Switch":
name: "<NAME>"
text: """Sobald du zerstörst wirst, nimmt jedes Schiff in Reichweite 1 einen Schaden."""
"Feedback Array":
name: "Rückkopplungsfeld"
text: """In der Kampfphase darfst du statt einen Angriff durchzuführen 1 Ionenmarker und 1 Schaden nehmen, um eine feindliches Schiff in Reichweite 1 zu wählen. Das gewählte Schiff nimmt 1 Schaden."""
'"Hot Shot" Blaster':
text: """<strong>Angriff:</strong> Lege diese Karte ab, um 1 Schiff (auch außerhalb deines Feuerwinkels) anzugreifen."""
"Greedo":
text: """%DE_SCUMONLY%%LINEBREAK%In jeder Runde wird bei deinem ersten Angriff und deiner ersten Verteidigung die erste Schadenskarte offen zugeteilt."""
"Salvaged Astromech":
name: "Abgewrackter Astromechdroide"
text: """Sobald du eine Schadenskarte mit dem Attribut <strong>Schiff</strong> erhälst, darfst du sie sofort ablegen (bevor ihr Effekt abgehandelt wird).%LINEBREAK%Danach wird diese Aufwertungskarte abgelegt."""
"Bomb Loadout":
name: "Bombenladung"
text: """<span class="card-restriction">Nur für Y-Wing.</span>%LINEBREAK%Füge deiner Aufwertungsleiste das %BOMB%-Symbol hinzu."""
'"Genius"':
name: '"Genie"'
text: """Wenn du eine Bombe ausgerüstet hast, die vor dem Aufdecken deines Manövers gelegt werden kann, darfst du sie stattdessen auch <strong>nach</strong> Ausführung des Manövers legen."""
"Unhinged Astromech":
name: "Ausgeklinkter Astromech-Droide"
text: """Du darfst alle Manöver mit Geschwindigkeit 3 wie grüne Manöver behandeln."""
"R4-B11":
text: """Sobald du angreifst, darfst du, falls du den Verteidiger in der Zielerfassung hast, den Zielerfassungsmarker ausgeben, um einen oder alle Verteidigungswürfel zu wählen. Diese muss der Verteidiger neu würfeln."""
"Autoblaster Turret":
name: "Autoblastergeschütz"
text: """<strong>Angriff:</strong> Greife 1 Schiff (auch außerhalb deines Feuerwinkels) an. %LINEBREAK%Deine %HIT% können von Verteidigungswürfeln nicht negiert werden. Der Verteidiger darf %CRIT% vor %HIT% negieren."""
"R4 Agromech":
name: "R4-Agromech-Droide"
text: """Sobald du angreifst, darfst du, nachdem du einen Fokusmarker ausgegeben hast, den Verteidiger in die Zielerfassung nehmen."""
"K4 Security Droid":
name: "K4-Sicherheitsdroide"
text: """%DE_SCUMONLY%%LINEBREAK%Nachdem du ein grünes Manöver ausgeführt hast, darfst du ein Schiff in die Zielerfassung nehmen."""
"Outlaw Tech":
name: "Gesetzloser Techniker"
text: """%DE_SCUMONLY%%LINEBREAK%Nachdem du ein rotes Manöver ausgeführt hast, darfst du deinem Schiff 1 Fokusmarker zuweisen."""
"Advanced Targeting Computer":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%When attacking with your primary weapon, if you have a target lock on the defender, you may add 1 %CRIT% result to your roll. If you do, you cannot spend target locks during this attack."""
"Ion Cannon Battery":
text: """<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack. If this attack hits, the defender suffers 1 critical damage and receives 1 ion token. Then cancel <strong>all<strong> dice results."""
"Emperor Palpatine":
text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again."""
"Bossk":
text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender."""
"Lightning Reflexes":
text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180°. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step."""
"Twin Laser Turret":
text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results."""
"Plasma Torpedoes":
text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender."""
"Ion Bombs":
text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token."""
"Conner Net":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token."""
"Bombardier":
text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template."""
"Cluster Mines":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token."""
'Crack Shot':
text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.'''
"Advanced Homing Missiles":
text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results."""
'Agent Kallus':
text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.'''
'XX-23 S-Thread Tracers':
text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results."""
"Tractor Beam":
text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results."""
"Cloaking Device":
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token."""
modification_translations =
"Stealth Device":
name: "Tarnvorrichtung"
text: """Dein Wendigkeitswert steigt um 1. Lege diese Karte ab, wenn du von einem Angriff getroffen wirst."""
"Shield Upgrade":
name: "Verbesserte Schilde"
text: """Dein Schildwert steigt um 1."""
"Engine Upgrade":
name: "Verbessertes Triebwerk"
text: """Füge deiner Aktionsleiste ein %BOOST%-Symbol hinzu."""
"Anti-Pursuit Lasers":
name: "Kurzstreckenlaser"
text: """%DE_LARGESHIPONLY%%LINEBREAK%Nachdem ein feindliches Schiff ein Manöver ausgeführt hat, das zur Überschneidung mit deinem Schiff führt, wirf 1 Angriffswürfel. Bei %HIT% oder %CRIT% nimmt das feindliche Schiff 1 Schaden."""
"Targeting Computer":
name: "Zielerfassungssystem"
text: """Deine Aktionsleiste erhält das %TARGETLOCK%-Symbol."""
"Hull Upgrade":
name: "Verbesserte Hülle"
text: """Erhöhe deinen Hüllenwert um 1."""
"Munitions Failsafe":
name: "Ausfallsichere Munition"
text: """Wenn du mit einer Sekundärwaffe angreifst, deren Kartentext besagt, dass sie zum Angriff abgelegt werden muss, legst du sie nur ab, falls du triffst."""
"Stygium Particle Accelerator":
name: "Stygium-Teilchen-Beschleuniger"
text: """immer wenn du dich enttarnst oder die Aktion Tarnen durchführst, darfst du als freie Aktion ausweichen."""
"Advanced Cloaking Device":
name: "Verbesserte Tarnvorrichtung"
text: """Nachdem du angegriffen hast, darfst du dich als freie Aktion tarnen."""
"Combat Retrofit":
name: "Umrüstung für den Kampfeinsatz"
ship: "Medium-Transporter GR-75"
text: """Erhöhe deinen Hüllenwert um 2 und deinen Schildwert um 1."""
"B-Wing/E2":
text: """Füge deiner Aufwertungsleiste das %CREW%-Symbol hinzu."""
"Countermeasures":
name: "Gegenmassnahmen"
text: """%DE_LARGESHIPONLY%%LINEBREAK%Zu Beginn der Kampfphase kannst du diese Karte ablegen, um deine Wendigkeit bis zum Ende der Runde um 1 zu erhöhen. Dann darfst du 1 feindliche Zielerfassung von deinem Schiff entfernen."""
"Experimental Interface":
name: "Experimentelles Interface"
text: """Ein Mal pro Runde darfst du nach dem Durchführen einer Aktion 1 ausgerüstete Aufwertungskarte mit dem Stichwort "<strong>Aktion:</strong>" benutzen (dies zählt als freie Aktion). Dann erhältst du 1 Stressmarker."""
"Tactical Jammer":
name: "<NAME>"
text: """%DE_LARGESHIPONLY%%LINEBREAK%Dein Schiff kann die feindliche Schussbahn versperren."""
"Autothrusters":
name: "<NAME>"
text: """Sobald du verteidigst und jenseits von Reichweite 2 oder außerhalb des Feuerwinkels des Angreifers bist, darfst du 1 deiner Leerseiten in ein %EVADE% ändern. Du darfst diese Karte nur ausrüsten, wenn du das %BOOST%-Aktionssymbol hast."""
"Twin Ion Engine Mk. II":
text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers."""
"Maneuvering Fins":
text: """When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed."""
"Ion Projector":
text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token."""
title_translations =
"Slave I":
name: "<NAME>"
text: """<span class="card-restriction">Nur für Firespray-31.</span>%LINEBREAK%Füge deiner Aktionsleiste ein %TORPEDO%-Symbol hinzu."""
"<NAME>illennium <NAME>":
name: "<NAME>"
text: """<span class="card-restriction">Nur für YT-1300.</span>%LINEBREAK%Füge deiner Aktionsleiste ein %EVADE%-Symbol hinzu."""
"<NAME>":
text: """<span class="card-restriction">Nur für HWK-290.</span>%LINEBREAK%In der Endphase werden von diesem Schiff keine unbenutzen Fokusmarker entfernt."""
"ST-321":
ship: "Raumfähre der Lambda-Klasse"
text: """<span class="card-restriction">Nur für Raumfähren der Lamda-Klasse.</span>%LINEBREAK%Wenn du eine Zielerfassung durchführst, darfst du ein beliebiges feindliches Schiff auf der Spielfläche als Ziel erfassen."""
"Royal Guard TIE":
name: "TI<NAME>"
ship: "TIE-Abfangjäger"
text: """<span class="card-restriction">Nur für TIE-Abfangjäger.</span>%LINEBREAK%Du kannst bis zu 2 verschiedene Modifikationen verwenden (statt einer).<br /><br />Du kannst diese Karte nicht verwenden, wenn der Pilotenwert "4" oder kleiner ist."""
"Dodon<NAME>'s Pride":
name: "<NAME>"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">Nur für CR90-Korvette (Bug).</span>%LINEBREAK%Wenn du die Aktion Koordination durchführst, kannst du 2 freundliche Schiffe wählen (anstatt 1). Jedes dieser Schiffe darf 1 freie Aktion durchführen."""
"A-Wing Test Pilot":
name: "<NAME>"
text: """<span class="card-restriction">Nur für A-Wing.</span>%LINEBREAK%Füge deiner Aufwertungsleiste 1 %ELITE%-Symbol hinzu.<br /><br />Du darfst jede %ELITE%-Aufwertung nur ein Mal ausrüsten. Du kannst diese Karte nicht verwenden, wenn dein Pilotenwert "1" oder niedriger ist."""
"Tantive IV":
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">Nur für CR90-Korvette (Bug).</span>%LINEBREAK%Die Aufwertungsleiste deiner Bugsektion erhält 1 zusätzliches %CREW% und 1 zusätzliches %TEAM% ."""
"Bright Hope":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">Nur für Medium-Transporter GR-75.</span>%LINEBREAK%Wenn neben deiner Bugsektion ein Verstärkungsmarker liegt, fügt er 2 %EVADE% hinzu (anstatt 1)."""
"Quantum Storm":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">Nur für Medium-Transporter GR-75.</span>%LINEBREAK%Wenn du zu Beginn der Endphase 1 Energiemarker oder weniger hast, gewinnst du 1 Energiemarker."""
"Dutyfree":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">Nur für Medium-Transporter GR-75.</span>%LINEBREAK%Bei der Aktion Störsignal kannst du ein feindliches Schiff in Reichweite 1-3 (statt 1-2) wählen."""
"Jaina's Light":
name: "<NAME>"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">Nur für CR90-Korvette (Bug).</span>%LINEBREAK%Wenn du verteidigst, darfst du einmal pro Angriff eine soeben erhaltene, offene Schadenskarte ablegen und dafür eine neue offene Schadenskarte ziehen."""
"Outrider":
text: """<span class="card-restriction">Nur für YT-2400.</span>%LINEBREAK%Solange du eine %CANNON%-Aufwertung ausgerüstet hast, kannst du deine Primärwaffen <strong>nicht</strong> verwenden. Dafür darfst du mit %CANNON%-Sekundärwaffen auch Ziele außerhalb deines Feuerwinkels angreifen."""
"Dauntless":
text: """<span class="card-restriction">Nur für VT-49 Decimator.</span>%LINEBREAK%Nach dem Ausführen eines Manövers, das zur Überschneidung mit einem anderen Schiff geführt hat, darfst du 1 freie Aktion durchführen. Dann erhältst du 1 Stressmarker."""
"Virago":
text: """<span class="card-restriction">Nur für SternenViper.</span>%LINEBREAK%Füge deiner Aufwertungsleiste ein %SYSTEM%- und ein %ILLICIT%-Symbol hinzu.%LINEBREAK%Du kannst diese Karte nicht ausrüsten, wenn dein Pilotenwert "3" oder niedriger ist."""
'"Heavy Scyk" Interceptor (Cannon)':
ship: "M3-A Abfangjäger"
name: '"<NAME> S<NAME>"-Abfangjäger (Kannone)'
text: """<span class="card-restriction">Nur für M3-A-Abfangjäger.</span>%LINEBREAK%Füge deiner Aufwertungsleiste eines der folgenden Symbole hinzu: %CANNON%, %TORPEDO%, oder %MISSILE%."""
'"Heavy Scyk" Interceptor (Torpedo)':
ship: "M3-A Abfangjäger"
name: '"<NAME> Scyk"-Abfangjäger (Torpedo)'
text: """<span class="card-restriction">Nur für M3-A-Abfangjäger.</span>%LINEBREAK%Füge deiner Aufwertungsleiste eines der folgenden Symbole hinzu: %CANNON%, %TORPEDO%, oder %MISSILE%."""
'"Heavy Scyk" Interceptor (Missile)':
ship: "M3-A Abfangjäger"
name: '"<NAME>er Scyk"-Abfangjäger (Rakete)'
text: """<span class="card-restriction">Nur für M3-A-Abfangjäger.</span>%LINEBREAK%Füge deiner Aufwertungsleiste eines der folgenden Symbole hinzu: %CANNON%, %TORPEDO%, oder %MISSILE%."""
"IG-2000":
text: """<span class="card-restriction">Nur für Aggressor.</span>%LINEBREAK%Du bekommst die Pilotenfähigkeiten aller anderen freundlichen Schiffe mit der Aufwertungskarte <em>IG-2000</em> (zusätzlich zu deiner eigenen Pilotenfähigkeit)."""
"BTL-A4 Y-Wing":
name: "BTL-A4-Y-Wing"
text: """<span class="card-restriction">Nur für Y-Wing.</span>%LINEBREAK%Du darfst Schiffe außerhalb deines Feuerwinkels nicht angreifen. Nachdem du einen Angriff mit deinen Primärwaffen durchgeführt hast, darfst du sofort einen weiteren Angriff mit einer %TURRET%-Sekundärwaffe durchführen."""
"Andrasta":
text: """<span class="card-restriction">Nur für Firespray-31.</span>%LINEBREAK%Füge deiner Aufwertungsleiste zwei weitere %BOMB%-Symbole hinzu."""
"TIE/x1":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% upgrade icon.%LINEBREAK%If you equip a %SYSTEM% upgrade, its squad point cost is reduced by 4 (to a minimum of 0)."""
"Ghost":
text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides."""
"Phantom":
text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round."""
"TIE/v1":
text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action."""
"<NAME>":
text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal)."""
"Punishing One":
text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1."""
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations
| true | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.de = 'Deutsch'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations.Deutsch =
action:
"Barrel Roll": "Fassrolle"
"Boost": "Schub"
"Evade": "Ausweichen"
"Focus": "Fokussierung"
"Target Lock": "Zielerfassung"
"Recover": "Aufladen"
"Reinforce": "Verstärken"
"Jam": "Störsignal"
"Coordinate": "Koordination"
"Cloak": "Tarnen"
slot:
"Astromech": "Astromech"
"Bomb": "Bombe"
"Cannon": "Kanonen"
"Crew": "Crew"
"Elite": "Elite"
"Missile": "Raketen"
"System": "System"
"Torpedo": "Torpedo"
"Turret": "Geschützturm"
"Cargo": "Fracht"
"Hardpoint": "Hardpoint"
"Team": "Team"
"Illicit": "illegales"
"Salvaged Astromech": "geborgener Astromech"
sources: # needed?
"Core": "Grundspiel"
"A-Wing Expansion Pack": "A-Wing Erweiterung"
"B-Wing Expansion Pack": "B-Wing Erweiterung"
"X-Wing Expansion Pack": "X-Wing Erweiterung"
"Y-Wing Expansion Pack": "Y-Wing Erweiterung"
"Millennium Falcon Expansion Pack": "Millenium Falke Erweiterung"
"HWK-290 Expansion Pack": "HWK-290 Erweiterung"
"TIE Fighter Expansion Pack": "TIE-Fighter Erweiterung"
"TIE Interceptor Expansion Pack": "TIE-Abfangjäger Erweiterung"
"TIE Bomber Expansion Pack": "TIE-Bomber Erweiterung"
"TIE Advanced Expansion Pack": "TIE-Advanced Erweiterung"
"Lambda-Class Shuttle Expansion Pack": "Raumfähre der Lambda-Klasse Erweiterung"
"Slave I Expansion Pack": "Sklave I Erweiterung"
"Imperial Aces Expansion Pack": "Fliegerasse des Imperiums Erweiterung"
"Rebel Transport Expansion Pack": "Rebellentransporter Erweiterung"
"Z-95 Headhunter Expansion Pack": "Z-95-Kopfjäger Erweiterung"
"TIE Defender Expansion Pack": "TIE-Jagdbomber Erweiterung"
"E-Wing Expansion Pack": "E-Wing Erweiterung"
"TIE Phantom Expansion Pack": "TIE-Phantom Erweiterung"
"Tantive IV Expansion Pack": "Tantive IV Erweiterung"
"Rebel Aces Expansion Pack": "Fliegerasse der Rebellenallianz Erweiterung"
"YT-2400 Freighter Expansion Pack": "YT-2400-Frachter Erweiterung"
"VT-49 Decimator Expansion Pack": "VT-49 Decimator Erweiterung"
"StarViper Expansion Pack": "SternenViper Erweiterung"
"M3-A Interceptor Expansion Pack": "M3-A Abfangjäger Erweiterung"
"IG-2000 Expansion Pack": "IG-2000 Erweiterung"
"Most Wanted Expansion Pack": "Abschaum und Kriminelle Erweiterung"
"Imperial Raider Expansion Pack": "Imperial Raider Expansion Pack"
ui:
shipSelectorPlaceholder: "Wähle ein Schiff"
pilotSelectorPlaceholder: "Wähle einen Piloten"
upgradePlaceholder: (translator, language, slot) ->
"kein #{translator language, 'slot', slot} Upgrade"
modificationPlaceholder: "keine Modifikation"
titlePlaceholder: "kein Titel"
upgradeHeader: (translator, language, slot) ->
"#{translator language, 'slot', slot} Upgrade"
unreleased: "unveröffentlicht"
epic: "Episch"
limited: "limitiert"
byCSSSelector:
'.translate.sort-cards-by': 'Sortiere Karten per'
'.xwing-card-browser option[value="name"]': 'Name'
'.xwing-card-browser option[value="source"]': 'Quelle'
'.xwing-card-browser option[value="type-by-points"]': 'Typ (Punkte)'
'.xwing-card-browser option[value="type-by-name"]': 'Typ (Name)'
'.xwing-card-browser .translate.select-a-card': 'Wähle eine Karte aus der Liste.'
'.xwing-card-browser .info-range td': 'Reichweite'
# Info well
'.info-well .info-ship td.info-header': 'Schiff'
'.info-well .info-skill td.info-header': 'Pilotenwert'
'.info-well .info-actions td.info-header': 'Aktionen'
'.info-well .info-upgrades td.info-header': 'Aufwertungen'
'.info-well .info-range td.info-header': 'Reichweite'
# Squadron edit buttons
'.clear-squad' : 'Neues Squad'
'.save-list' : 'Speichern'
'.save-list-as' : 'Speichern als…'
'.delete-list' : 'Löschen'
'.backend-list-my-squads' : 'Squad laden'
'.view-as-text' : '<span class="hidden-phone"><i class="icon-print"></i> Drucken/Anzeigen als </span>Text'
'.randomize' : 'Zufallsliste!'
'.randomize-options' : 'Zufallslistenoptionen…'
# Print/View modal
'.bbcode-list' : 'Kopiere den BBCode von unten und füge ihn in deine Forenposts ein.<textarea></textarea>'
'.vertical-space-checkbox' : """Platz für Schadenskarten und Upgrades im Druck berücksichtigen. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Ausdrucken in farbe. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="icon-print"></i> Print'
# Randomizer options
'.do-randomize' : 'Zufall!'
# Top tab bar
'#empireTab' : 'Galaktisches Imperium'
'#rebelTab' : 'Rebellen Allianz'
'#scumTab' : 'Abschaum und Kriminelle'
'#browserTab' : 'Karten Browser'
'#aboutTab' : 'Über'
singular:
'pilots': 'Pilot'
'modifications': 'Modifikation'
'titles': 'Titel'
types:
'Pilot': 'Pilot'
'Modification': 'Modifikation'
'Title': 'Titel'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders.Deutsch = () ->
exportObj.cardLanguage = 'Deutsch'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
# Move TIE Interceptor to TIE-Abfangjäger
exportObj.renameShip 'TIE Interceptor', 'TIE-Abfangjäger'
# Move Z-95 Headhunter to Z-95-Kopfjäger
exportObj.renameShip 'Z-95 Headhunter', 'Z-95-Kopfjäger'
# Move TIE Defender to TIE-Jagdbomber
exportObj.renameShip 'TIE Defender', 'TIE-Jagdbomber'
# Move Lambda-Class Shuttle to Raumfähre der Lambda-Klasse
exportObj.renameShip 'Lambda-Class Shuttle', 'Raumfähre der Lambda-Klasse'
# Move GR-75 Medium Transport to Medium-Transporter GR-75
exportObj.renameShip 'GR-75 Medium Transport', 'Medium-Transporter GR-75'
# Move CR90 Corvette (Fore) to CR90-Korvette (Bug)
exportObj.renameShip 'CR90 Corvette (Fore)', 'CR90-Korvette (Bug)'
# Move CR90 Corvette (Aft) to CR90-Korvette (Heck)
exportObj.renameShip 'CR90 Corvette (Aft)', 'CR90-Korvette (Heck)'
# Move M3-A Interceptor to M3-A Abfangjäger
exportObj.renameShip 'M3-A Interceptor', 'M3-A Abfangjäger'
pilot_translations =
"Wedge Antilles":
text: """Wenn du angreifst, sinkt der Wendigkeitswert des Verteidigers um 1 (Minimum 0)."""
"PI:NAME:<NAME>END_PI":
text: """Wenn du einen Fokusmarker ausgibst, darfst du ihn auf ein anderes freundliches Schiff in Reichweite 1-2 legen (anstatt ihn abzulegen)."""
"Red Squadron Pilot":
name: "Pilot der Rot-Staffel"
"Rookie Pilot":
name: "Anfängerpilot"
"Biggs Darklighter":
text: """Andere freundliche Schiffe in Reichweite 1 dürfen nur dann angegriffen werden, wenn der Angreifer dich nicht zum Ziel bestimmen kann."""
"LuPI:NAME:<NAME>END_PI Skywalker":
text: """Wenn du verteidigst, kannst du 1 deiner %FOCUS% in ein %EVADE% ändern."""
"Gray Squadron Pilot":
name: "Pilot der Grau-Staffel"
'"Dutch" Vander':
text: """Wähle ein anderes freundliches Schiff in Reichweite 1-2, nachdem du eine Zielerfassung durchgeführt hast. Das gewählte Schiff darf sofort ebenfalls eine Zielerfassung durchführen."""
"PI:NAME:<NAME>END_PI":
text: """Wenn du ein Ziel in Reichweite 2-3 angreifst, darfst du beliebig viele Leerseiten neu würfeln."""
"Gold Squadron Pilot":
name: "Pilot der Gold-Staffel"
"Academy Pilot":
name: "Pilot der Akademie"
"Obsidian Squadron Pilot":
name: "Pilot der Obsidian-Staffel"
"Black Squadron Pilot":
name: "Pilot der Schwarz-Staffel"
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Wenn du ein Ziel in Reichweite 1 angreifst, darfst du eines deiner %HIT% in ein %CRIT% ändern."""
'"Night Beast"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Nachdem du ein grünes Manöver ausgeführt hast, darfst du als freie Aktion eine Fokussierung durchführen."""
'"Backstabber"':
text: """Wenn du bei deinem Angriff nicht im Feuerwinkel des Verteidigers bist, erhältst du 1 zusätzlichen Angriffswürfel."""
'"Dark Curse"':
text: """Wenn du verteidigst, können angreifende Schiffe keine Fokusmarker ausgeben oder Angriffswürfel neu würfeln."""
'"PI:NAME:<NAME>END_PI"':
text: """Wirf 1 zusätzlichen Angriffswürfel, wenn du ein Ziel in Reichweite 1 angreifst."""
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Wenn ein anderes freundliches Schiff in Reichweite 1 mit seinen Primärwaffen angreift, darf es 1 Angriffswürfel neu würfeln."""
"PI:NAME:<NAME>END_PI":
text: """Wenn ein Verteidiger durch deinen Angriff eine offene Schadenskarte erhalten würde, ziehst du stattdessen 3 Schadenskarten, wählst eine davon zum Austeilen und legst die restlichen ab."""
"Tempest Squadron Pilot":
name: "Pilot der Tornado-Staffel"
"Storm Squadron Pilot":
name: "Pilot der Storm-Staffel"
"PI:NAME:<NAME>END_PI":
text: """Im Schritt "Aktionen durchführen" darfst du 2 Aktionen durchführen."""
"Alpha Squadron Pilot":
name: "Pilot der Alpha-Staffel"
ship: "TIE-Abfangjäger"
"Avenger Squadron Pilot":
name: "Pilot der Avenger-Staffel"
ship: "TIE-Abfangjäger"
"Saber Squadron Pilot":
name: "Pilot der Saber-Staffel"
ship: "TIE-Abfangjäger"
"\"PI:NAME:<NAME>END_PI\"":
ship: "TIE-Abfangjäger"
text: """Wenn die Summe deiner Schadenskarten deinen Hüllenwert erreicht oder übersteigt, wirst du nicht sofort zerstört, sondern erst am Ende der Kampfphase."""
"PI:NAME:<NAME>END_PI":
ship: "TIE-Abfangjäger"
text: """Nachdem du angegriffen hast, darfst du eine freie Aktion Schub oder Fassrolle durchführen."""
"PI:NAME:<NAME>END_PI":
ship: "TIE-Abfangjäger"
text: """Immer wenn du einen Stressmarker erhältst, darfst du deinem Schiff auch einen Fokusmarker geben."""
"PI:NAME:<NAME>END_PI":
text: """Du darfst auch dann Aktionen durchführen, wenn du Stressmarker hast."""
"PI:NAME:<NAME>END_PI":
text: """Wenn du angreifst, darfst du auch auf feindliche Schiffe zielen, deren Basen du berührst (vorausgesetzt sie sind innerhalb deines Feuerwinkels)."""
"Green Squadron Pilot":
name: "Pilot der Grün-Staffel"
"Prototype Pilot":
name: "Testpilot"
"Outer Rim Smuggler":
name: "Schmuggler aus dem Outer Rim"
"PI:NAME:<NAME>END_PI":
text: """Wenn du eine offene Schadenskarte erhältst, wird sie sofort umgedreht (ohne dass ihr Kartentext in Kraft tritt)."""
"PI:NAME:<NAME>END_PI":
text: """Wähle nach dem Ausführen eines grünen Manövers ein anderes freundliches Schiff in Reichweite 1. Dieses Schiff darf eine freie Aktion aus seiner Aktionsleiste durchführen."""
"PI:NAME:<NAME>END_PI":
text: """Wenn du angreifst, darfst du all deine Würfel neu würfeln. Tust du dies, musst du so viele Würfel wie möglich neu würfeln."""
"PI:NAME:<NAME>END_PI":
text: """Wenn du angreifst und der Verteidiger mindestens 1 %CRIT% negiert, erhält er 1 Stressmarker."""
"PI:NAME:<NAME>END_PI":
text: """Sobald du ein Drehmanöver (%BANKLEFT% oder %BANKRIGHT%) aufdeckst, darfst du das Drehmanöver mit gleicher eschwindigkeit, aber anderer Richtung, auf deinem Rad nachträglich einstellen."""
"PI:NAME:<NAME>END_PI":
text: """Wenn du mit einer Sekundärwaffe angreifst, darfst du 1 Angriffswürfel neu würfeln."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI":
text: """Wenn du angreifst, kann 1 deiner %CRIT% von Verteidigungswürfeln nicht negiert werden."""
"PI:NAME:<NAME>END_PI":
text: """Beim Angreifen oder Verteidigen darfst du 1 deiner Würfel neu würfeln, sofern du mindestens 1 Stressmarker hast."""
"Dagger Squadron Pilot":
name: "Pilot der Dagger-Staffel"
"Blue Squadron Pilot":
name: "Pilot der Blauen Staffel"
"Rebel Operative":
name: "Rebellenagent"
"PI:NAME:<NAME>END_PI":
text: '''Wähle zu Beginn der Kampfphase 1 anderes freundliches Schiff in Reichweite 1-3. Bis zum Ende der Phase wird dieses Schiff behandelt, als hätte es einen Pilotenwert von 12.'''
"PI:NAME:<NAME>END_PI":
text: """Zu Beginn der Kampfphase darfst du einem anderen freundlichen Schiff in Reichweite 1-3 einen deiner Fokusmarker geben."""
"PI:NAME:<NAME>END_PI":
text: """Wenn ein anderes freundliches Schiff in Reichweite 1-3 angreift und du keine Stressmarker hast, darfst du 1 Stressmarker nehmen, damit dieses Schiff 1 zusätzlichen Angriffswürfel erhält."""
"Scimitar Squadron Pilot":
name: "Pilot der Scimitar-Staffel"
"Gamma Squadron Pilot":
name: "Pilot der Gamma-Staffel"
"PI:NAME:<NAME>END_PI":
text: """Wenn ein anderes freundliches Schiff in Reichweite 1 mit einer Sekundärwaffe angreift, darf es bis zu 2 Angriffswürfel neu würfeln."""
"Major PI:NAME:<NAME>END_PIhymer":
text: """Beim Angreifen mit einer Sekundärwaffe darfst du die Reichweite der Waffe um 1 erhöhen oder verringern, bis zu einer Reichweite von 1-3."""
"PI:NAME:<NAME>END_PI":
ship: "Raumfähre der Lambda-Klasse"
text: """Wenn ein feindliches Schiff eine Zielerfassung durchführt, muss es wenn möglich dich als Ziel erfassen."""
"PI:NAME:<NAME>END_PI":
ship: "Raumfähre der Lambda-Klasse"
text: """Zu Beginn der Kampfphase darfst du 1 deiner blauen Zielerfassungsmarker auf ein freundliches Schiff in Reichweite 1 legen, das noch keinen blauen Zielerfassungsmarker hat."""
"PI:NAME:<NAME>END_PI":
ship: "Raumfähre der Lambda-Klasse"
text: """Wenn ein anderes freundliches Schiff in Reichweite 1-2 einen Stressmarker erhalten würde und du 2 oder weniger Stressmarker hast, darfst du statt ihm diesen Marker nehmen."""
"Omicron Group Pilot":
ship: "Raumfähre der Lambda-Klasse"
name: "Pilot der Omikron-Gruppe"
"PI:NAME:<NAME>END_PI":
ship: "TIE-Abfangjäger"
text: """Wenn du die Aktion Fassrolle ausführst, kannst du 1 Stressmarker erhalten, um die (%BANKLEFT% 1) oder (%BANKRIGHT% 1) Manöverschablone anstatt der (%STRAIGHT% 1) Manöverschablone zu benutzen."""
"Royal Guard Pilot":
ship: "TIE-Abfangjäger"
name: "Pilot der Roten Garde"
"PI:NAME:<NAME>END_PI":
ship: "TIE-Abfangjäger"
text: """Immer wenn du ein %UTURN% Manöver aufdeckst, kannst du das Manöver mit einer Geschwindigkeit von "1," "3," oder "5" ausführen."""
"PI:NAME:<NAME>END_PI":
ship: "TIE-Abfangjäger"
text: """Wenn du ein Ziel in Reichweite 2-3 angreifst, darfst du einen Ausweichmarker ausgeben, um 1 %HIT% zu deinem Wurf hinzuzufügen."""
"PI:NAME:<NAME>END_PI":
ship: "TIE-Abfangjäger"
text: """Feindliche Schiffe in Reichweite 1 können weder Fokussierung und Ausweichen Aktionen durchführen noch Ausweichmarker und Fokusmarker ausgeben."""
"GR-75 Medium Transport":
ship: "Medium-Transporter GR-75"
name: "Medium-Transporter GR-75"
"Bandit Squadron Pilot":
ship: "Z-95-Kopfjäger"
name: "Pilot der Bandit-Staffel"
"Tala Squadron Pilot":
ship: "Z-95-Kopfjäger"
name: "Pilot der Tala-Staffel"
"PI:NAME:<NAME>END_PI":
ship: "Z-95-Kopfjäger"
name: "PI:NAME:<NAME>END_PI"
text: """Wenn du angreifst, triffst du immer, selbst wenn das verteidigende Schiff keinen Schaden nimmt."""
"PI:NAME:<NAME>END_PI":
ship: "Z-95-Kopfjäger"
name: "PI:NAME:<NAME>END_PI"
text: """Nachdem du angegriffen hast, darfst du ein anderes freundliches Schiff in Reichweite 1 wählen. Dieses Schiff darf 1 freie Aktion durchführen."""
"Delta Squadron Pilot":
ship: "TIE-Jagdbomber"
name: "Pilot der Delta-Staffel"
"Onyx Squadron Pilot":
ship: "TIE-Jagdbomber"
name: "Pilot der Onyx-Staffel"
"PI:NAME:<NAME>END_PI":
ship: "TIE-Jagdbomber"
text: """Wenn du angreifst und der Verteidiger bereits einen roten Zielerfassungsmarker hat, darfst du ihn unmittelbar nach dem Angriffswurf in die Zielerfassung nehmen."""
"PI:NAME:<NAME>END_PI":
ship: "TIE-Jagdbomber"
text: """Nachdem du angegriffen und damit dem Verteidiger mindestens 1 Schadenskarte zugeteilt hast, kannst du einen Fokusmarker ausgeben, um die soeben zugeteilten Schadenskarten aufzudecken."""
"Knave Squadron Pilot":
name: "Pilot der Schurken-Staffel"
"Blackmoon Squadron Pilot":
name: "Pilot der Schwarzmond-Staffel"
"PI:NAME:<NAME>END_PI":
text: """Sobald ein feindliches Schiff in Reichweite 1–3 und innerhalb deines Feuerwinkels verteidigt, darf der Angreifer 1 %HIT% seiner in ein %CRIT% ändern."""
"PI:NAME:<NAME>END_PI":
text: """Zu Beginn der Endphase kannst du einen Angriff durchführen. Tust du das, darfst du in der nächsten Runde nicht angreifen."""
"Sigma Squadron Pilot":
name: "Pilot der Sigma-Staffel"
"Shadow Squadron Pilot":
name: "Pilot der Schatten-Staffel"
'"Echo"':
name: '"Echo"'
text: """Wenn du dich enttarnst, musst du statt der (%STRAIGHT% 2)-Manöverschablone die (%BANKRIGHT% 2)- oder (%BANKLEFT% 2)-Schablone verwenden."""
'"WhPI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Nachdem du mit einem Angriff getroffen hast, darfst du deinem Schiff 1 Fokusmarker geben."""
"CR90 Corvette (Fore)":
name: "CR90-Korvette (Bug)"
ship: "CR90-Korvette (Bug)"
text: """Wenn du mit deinen Primärwaffen angreifst, kannst du 1 Energie ausgeben, um 1 zusätzlichen Angriffswürfel zu bekommen"""
"CR90 Corvette (Aft)":
name: "CR90-Korvette (Heck)"
ship: "CR90-Korvette (Heck)"
"PI:NAME:<NAME>END_PI":
text: """Nachdem du einen Angriff durchgeführt hast, darfst du 1 Fokus-, Ausweich- oder blauen Zielerfassungsmarker vom Verteidiger entfernen."""
"PI:NAME:<NAME>END_PI":
text: """Wenn du einen Stressmarker erhälst, darfst du ihn entfernen und 1 Angriffswürfel werfen. Bei %HIT% bekommt dein Schiff 1 verdeckte Schadenskarte."""
'"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI':
text: """Wenn du ein Schiff in die Zielerfassung nimmst oder einen Zielerfassungsmarker ausgibst, kannst du 1 Stressmarker von deinem Schiff entfernen."""
"PI:NAME:<NAME>END_PI":
text: """Wenn ein feindliches Schiff einen Angriff gegen dich ansagt, kannst du dieses Schiff in die Zielerfassung nehmen."""
"PI:NAME:<NAME>END_PI":
text: """Nachdem du die Aktion Fokussierung durchgeführt oder einen Fokusmarker erhalten hast, darfst du als freie Aktion einen Schub oder eine Fassrolle durchführen."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Solange du in Reichweite 1 zu mindestens einem feindlichen Schiff bist, steigt dein Wendigkeitswert um 1."""
"PI:NAME:<NAME>END_PI":
text: """Beim Angreifen darfst du 1 Stressmarker entfernen, um alle deine %FOCUS% in %HIT% zu ändern."""
"PI:NAME:<NAME>END_PI":
text: """Mit %TORPEDO%-Sekundärwaffen kannst du auch feindliche Schiffe außerhalb deines Feuerwinkels angreifen."""
# "CR90 Corvette (Crippled Aft)":
# name: "CR90-Korvette (Heck-Lahmgelegt)"
# ship: "CR90-Korvette (Heck)"
# text: """Folgende Manöver darfst du weder wählen noch ausführen: (%STRAIGHT% 4), (%BANKLEFT% 2), or (%BANKRIGHT% 2) ."""
# "CR90 Corvette (Crippled Fore)":
# name: "CR90-Korvette (Bug-Lahmgelegt)"
# ship: "CR90-Korvette (Bug)"
"Wild Space Fringer":
name: "Grenzgänger aus dem Wilden Raum"
"Dash Rendar":
text: """Du darfst in der Aktivierungsphase und beim Durchführen von Aktionen Hindernisse ignorieren."""
'"PI:NAME:<NAME>END_PI"':
text: """Immer wenn du eine offene Schadenskarte erhältst, ziehst du 1 weitere Schadenskarte. Wähle 1, die abgehandelt wird, und lege die andere ab."""
"PI:NAME:<NAME>END_PI":
text: """Wirf 1 zusätzlichen Angriffswürfel, wenn du mit den Primärwaffen auf ein Schiff mit Stressmarker schießt."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Wenn du ein Ziel in Reichweite 1-2 angreifst, kannst du ein %FOCUS% in ein %CRIT% ändern."""
"PI:NAME:<NAME>END_PI":
text: """Wenn du keine Schilde und mindestens 1 Schadenskarte hast, steigt deine Wendigkeit um 1."""
"PI:NAME:<NAME>END_PI":
text: """Nach dem Ausführen eines Manövers nimmt jedes feindliche Schiff, das du berührst, 1 Schaden."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Sobald du verteidigst, darf ein freundliches Schiff in Reichweite 1 ein nicht-negiertes %HIT% oder %CRIT% an deiner Stelle nehmen."""
"PI:NAME:<NAME>END_PI":
text: """Wenn du zu Beginn der Kampfphase in Reichweite 1 zu einem feindlichen Schiff bist, darfst du 1 Fokusmarker auf dein Schiff legen."""
"Black Sun Vigo":
name: "Vigo der Schwarzen Sonne"
"Black Sun Enforcer":
name: "Vollstrecker der Schwarzen Sonne"
"PI:NAME:<NAME>END_PI":
ship: "M3-A Abfangjäger"
text: """Sobald ein anderes freundliches Schiff in Reichweite 1 verteidigt, darf es 1 Verteidigungswürfel neu würfeln."""
"PI:NAME:<NAME>END_PI":
ship: "M3-A Abfangjäger"
text: """Nachdem du gegen einen Angriff verteidigt hast und falls der Angriff nicht getroffen hat, darfst du deinem Schiff 1 Ausweichmarker zuordnen."""
"PI:NAME:<NAME>END_PI":
ship: "M3-A Abfangjäger"
name: "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI":
ship: "M3-A Abfangjäger"
name: "PI:NAME:<NAME>END_PI"
"IG-88A":
text: """Nachdem du einen Angriff durchgeführt hast, der den Verteidiger zerstört, darfst du 1 Schild wiederaufladen."""
"IG-88B":
text: """Ein Mal pro Runde darfst du, nachdem du mit einem Angriff verfehlt hast, einen weiteren Angriff mit einer ausgerüsteten %CANNON%-Sekundärwaffe durchführen."""
"IG-88C":
text: """Nachdem du die Aktion Schub durchgeführt hast, darfst du eine freie Aktion Ausweichen durchführen."""
"IG-88D":
text: """Du darfst die Manöver (%SLOOPLEFT% 3) oder (%SLOOPRIGHT% 3) auch mit den entsprechenden Schablonen für Wendemanöver (%TURNLEFT% 3) bzw. (%TURNRIGHT% 3) ausführen."""
"PI:NAME:<NAME>END_PI (Scum)":
name: "PI:NAME:<NAME>END_PI (Abschaum)"
text: """Sobald du angreifst oder verteidigst, darfst du für jedes feindliche Schiff in Reichweite 1 einen deiner Würfel neu würfeln."""
"PI:NAME:<NAME>END_PI (Scum)":
name: "PI:NAME:<NAME>END_PI (Abschaum)"
text: """Sobald du ein Schiff innerhalb deines Zusatz-Feuerwinkels angreifst, erhältst du 1 zusätzlichen Angriffswürfel."""
"PI:NAME:<NAME>END_PI":
text: """Sobald du eine Bombe legst, darfst du auch die Schablone [%TURNLEFT% 3], [%STRAIGHT% 3] oder [%TURNRIGHT% 3] anstatt der [%STRAIGHT% 1]-Schablone verwenden."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI":
text: """Sobald du ein Schiff außerhalb deines Feuerwinkels angreifst, erhältst du 1 zusätzlichen Angriffswürfel."""
"PI:NAME:<NAME>END_PI":
text: """Nachdem du einen Zielerfassungsmarker ausgegeben hast, darfst du 1 Stressmarker nehmen, um ein Schiff in die Zielerfassung zu nehmen."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PIbrecher des Syndikats"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI":
text: """Sobald ein feindliches Schiff in Reichweite 1-3 mindestens 1 Ionenmarker erhält und falls du keinen Stressmarker hast, darfst du 1 Stressmarker nehmen, damit das Schiff 1 Schaden nimmt."""
"PI:NAME:<NAME>END_PI":
text: """Zu Beginn der Kampfphase darfst du 1 Fokus- oder Ausweichmarker von einem feindlichen Schiff in Reichweite 1-2 entfernen und dir selbst zuordnen."""
"PI:NAME:<NAME>END_PI":
text: """Wähle am Ende der Aktivierungsphase 1 feindliches Schiff in Reichweite 1-2. Bis zum Ende der Kampfphase wird der Pilotenwert des Schiffs als "0" behandelt."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI":
ship: "Z-95-Kopfjäger"
text: """Sobald du angreifst, erhälst du 1 zusätzlichen Angriffswürfel, falls keine anderen freundlichen Schiffe in Reichweite 1-2 zu dir sind."""
"PI:NAME:<NAME>END_PI":
ship: "Z-95-Kopfjäger"
text: """Zu Beginn der Kampfphase darfst du 1 Fokus- oder Ausweichmarker von einem anderem freundlichen Schiff in Reichweite 1-2 entfernen und dir selbst zuordnen."""
"PI:NAME:<NAME>END_PI":
ship: "Z-95-Kopfjäger"
name: "PI:NAME:<NAME>END_PI"
"Black Sun PI:NAME:<NAME>END_PI":
ship: "Z-95-Kopfjäger"
name: "Kampfpilot der Schwarzen Sonne"
"PI:NAME:<NAME>END_PI":
text: """At the start of the Combat phase, you may acquire a target lock on an enemy ship at Range 1."""
"Raider-class Corvette (Fore)":
text: """Once per round, ??? perform a primary ??? attack, you may spend 2 e??? perform another primary wea???"""
"PI:NAME:<NAME>END_PI":
text: """When you reveal your maneuver, you may increase or decrease its speed by 1 (to a minimum of 1)."""
"PI:NAME:<NAME>END_PI":
text: """Enemy ships at Range 1 cannot add their range combat bonus when attacking."""
"PI:NAME:<NAME>END_PI":
text: """At the start of the End phase, you may spend a target lock you have on an enemy ship to flip 1 random facedown Damage card assigned to it faceup."""
"PI:NAME:<NAME>END_PI":
text: """When a friendly ship declares an attack, you may spend a target lock you have on the defender to reduce its agility by 1 for that attack."""
"PI:NAME:<NAME>END_PI":
text: """When defending, if the attacker is inside your firing arc, roll 1 additional defense die."""
"PI:NAME:<NAME>END_PI":
text: """When another friendly ship at Range 1-2 is attacking, it may treat your focus tokens as its own."""
'"RedPI:NAME:<NAME>END_PI"':
text: """You may maintain 2 target locks on the same ship. When you acquire a target lock, you may acquire a second lock on that ship."""
'"DeathPI:NAME:<NAME>END_PI"':
text: """When dropping a bomb, you may use the front guides of your ship. After dropping a bomb, you may perform a free barrel roll action."""
"Moralo PI:NAME:<NAME>END_PI":
text: """You can perform %CANNON% secondary attacks against ships inside your auxiliary firing arc."""
'Gozanti-class Cruiser':
text: """After you execute a maneuver, you may deploy up to 2 attached ships."""
'"PI:NAME:<NAME>END_PI"':
text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die."""
"The InPI:NAME:<NAME>END_PIitor":
text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1."""
"PI:NAME:<NAME>END_PI":
text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die."""
"PI:NAME:<NAME>END_PI":
text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship."""
upgrade_translations =
"Ion Cannon Turret":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Angriff:</strong> Greife 1 Schiff an (es muss nicht in deinem Feuerwinkel sein).<br /><br />Wenn der Angriff trifft, nimmt das verteidigende Schiff 1 Schaden und erhält 1 Ionenmarker. Dann werden alle übrigen Würfelergebnisse negiert."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Angriff (Zielerfassung):</strong>Gib eine Zielerfassung aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst eines deiner %FOCUS% in ein %CRIT% ändern."""
"R2 Astromech":
name: "R2 Astromechdroide"
text: """Du darfst alle Manöver mit Geschwindigkeit 1 und 2 wie grüne Manöver behandeln."""
"R2-D2":
text: """Nachdem du ein grünes Manöver ausgeführt hast, darfst du 1 Schild wiederaufladen (bis maximal zum Schildwert)."""
"R2-F2":
text: """<strong>Aktion:</strong> Erhöhe deinen Wendigkeitswert bis zum Ende der Spielrunde um 1."""
"R5-D8":
text: """<strong>Aktion:</strong> Wirf 1 Verteidigungswürfel.<br /><br />Lege bei %EVADE% oder %FOCUS% 1 deiner verdeckten Schadenskarten ab."""
"R5-K6":
text: """Wirf 1 Verteidigungswürfel nachdem du deine Zielerfassungsmarker ausgegeben hast.<br /><br />Bei %EVADE% nimmst du dasselbe Schiff sofort wieder in die Zielerfassung. Für diesen Angriff kannst du die Zielerfassungsmarker nicht erneut ausgeben."""
"R5 Astromech":
name: "R5 Astromechdroide"
text: """Wähle während der Endphase 1 deiner offnen Schadenskarte mit dem Attribut <strong>Schiff</strong> und drehe sie um."""
"Determination":
name: "PI:NAME:<NAME>END_PI"
text: """Wenn du eine offene Schadenskarte mit dem Attribut <b>Pilot</b> erhältst, wird diese sofort abgelegt (ohne dass der Kartentext in Kraft tritt)."""
"Swarm Tactics":
name: "PI:NAME:<NAME>END_PI"
text: """Du darfst zu Beginn der Kampfphase 1 freundliches Schiff in Reichweite 1 wählen.<br /><br />Bis zum Ende dieser Phase wird das gewählte Schiff so behandelt, als hätte es denselben Pilotenwert wie du."""
"Squad Leader":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Aktion:</strong> Wähle ein Schiff in Reichweite 1-2 mit einem geringeren Pilotenwert als du.<br /><br />Das gewählte Schiff darf sofort 1 freie Aktion durhführen."""
"Expert Handling":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Aktion:</strong> Führe als freie Aktion eine Fassrolle durch. Wenn du kein %BARRELROLL%-Symbol hast, erhältst du 1 Stressmarker.<br /><br />Dann darfst du 1 feindlichen Zielerfassungsmarker von deinem Schiff entfernen."""
"Marksmanship":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Aktion:</strong> Wenn du in dieser Runde angreifst, darfst du eines deiner %FOCUS% in ein %CRIT% und alle anderen %FOCUS% in %HIT% ändern."""
"Concussion Missiles":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst eine deiner Leerseiten in ein %HIT% ändern."""
"Cluster Missiles":
name: "Cluster-PI:NAME:<NAME>END_PI"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmaker aus und lege diese Karte ab, um mit dieser Sekundärwaffe <strong>zwei Mal</strong> anzugreifen."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Aktion:</strong> Führe ein weißes (%TURNLEFT% 1) oder (%TURNRIGHT% 1) Manöver aus. Dann erhälst du einen Stresmarker.<br /><br />Wenn du kein %BOOST%-Aktionssymbol hast, musst du dann 2 Angriffswürfel werfen. Du nimmst allen gewürfelten Schaden (%HIT%) und kritischen Schaden (%CRIT%)."""
"ElPI:NAME:<NAME>END_PIiveness":
name: "PI:NAME:<NAME>END_PI"
text: """Wenn du verteidigst, darfst du 1 Stressmarker nehmen, um 1 Angriffswürfel zu wählen. Diesen muss der Angreifer neu würfeln.<br /><br />Du kannst diese Fähigkeit nicht einsetzen, solange du 1 oder mehrere Stressmarker hast."""
"Homing MPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Angriff (Zielerfassung):</strong> Lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Bei diesem Angriff kann der Verteidiger keine Ausweichmarker ausgeben."""
"Push the Limit":
name: "PI:NAME:<NAME>END_PI an die Grenzen"
text: """Einmal pro Runde darfst du nach dem Durchführen einer Aktion eine freie Aktion aus deiner Aktionsleiste durhführen.<br /><br />Dann erhältst du 1 Stressmarker."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Du darfst die Bedingung "Angriff (Zielerfassung):" in "Angriff (Fokussierung):" ändern.<br /><br />Wenn ein Angriff das Ausgeben von Zielerfassungsmarkern erfordert, darfst du stattdessen auch einen Fokusmarker ausgeben."""
"Expose":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Aktion:</strong> Bis zum Ende der Runde steigt dein Primärwaffenwert um 1, dafür sinkt dein Wendigkeitswert um 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Unmittelbar nachdem du mit einem Angriff verfehlt hast, darfst du einen weiteren Angriff mit deiner Primärwaffe durchführen. Danach kannst du in dieser Runde nicht noch einmal angreifen."""
"Ion Cannon":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Angriff:</strong> Greife 1 Schiff mit dieser Sekundärwaffe an.<br /><br />Wenn du triffst, nimmt das verteidigende Schiff 1 Schaden und erhält 1 Ionenmarker. Dann werden <b>alle</b> übrigen Würfelergebnisse negiert."""
"Heavy Laser Cannon":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Attack:</strong> Greife 1 Schiff mit dieser Sekundärwaffe an.<br /><br />Unmittelbar nach dem Angriffswurf musst du alle %CRIT% in %HIT% ändern."""
"Seismic Charges":
name: "PI:NAME:<NAME>END_PImische Bomben"
text: """Nach dem Aufdecken deines Manöverrads darfst du diese Karte ablegen um 1 Seismischen Bomben-Marker zu <strong>legen</strong>.<br /><br />Der Marker <strong>detoniert</strong> am Ende der Aktivierungsphase."""
"Mercenary Copilot":
name: "Angeheuerter Kopilot"
text: """Wenn du ein Ziel in Reichweite 3 angreifst, darfst du eines deiner %HIT% in ein %CRIT% ändern."""
"AssPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Angriff (Zielerfassung): Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Wenn du triffst, nimmt jedes andere Schiff in Reichweite 1 des verteidigenden Schiffs 1 Schaden."""
"Veteran Instincts":
name: "PI:NAME:<NAME>END_PI"
text: """Dein Pilotenwert steigt um 2."""
"Proximity Mines":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Aktion:</strong> Lege diese Karte ab, um 1 Annährungsminen-Marker zu <strong>legen</strong>.<br /><br />Der Marker <strong>detoniert</strong>, sobald sich die Basis eines Schiffs oder die Manöverschablone mit dem Marker überschneidet."""
"Weapons Engineer":
name: "PI:NAME:<NAME>END_PI"
text: """Du darfst 2 verschiedene Schiffe gleichzeitig in der Zielerfassung haben (maximal 1 Zielerfassung pro feindlichem Schiff).<br /><br />Sobald du eine Zielerfassung durchführst, darfst du zwei verschiedene Schiffe als Ziele erfassen."""
"Draw Their Fire":
name: "Das Feuer auf mich ziehen"
text: """Wenn ein freundliches Schiff in Reichweite 1 durch einen Angriff getroffen wird, darfst du anstelle dieses Schiffs den Schaden für 1 nicht-negiertes %CRIT% auf dich nehmen."""
"PI:NAME:<NAME>END_PI":
text: """%DE_REBELONLY%%LINEBREAK%Unmittelbar nachdem du mit einem Angriff verfehlt hast, darfst du einen weiteren Angriff mit deiner Primärwaffe durchführen. Du darfst ein %FOCUS% in ein %HIT% ändern. Danach kannst du in dieser Runde nicht noch einmal angreifen."""
"PI:NAME:<NAME>END_PI":
text: """%DE_REBELONLY%%LINEBREAK%Du darfst alle %STRAIGHT%-Manöver wie grüne Manöver behandeln."""
"Chewbacca":
name: "Chewbacca (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Wenn du eine Schadenskarte erhältst, darfst du sie sofort ablegen und 1 Schild wiederaufladen.<br /><br />Danach wird diese Aufwertungskarte abgelegt."""
"Advanced Proton Torpedoes":
name: "Verstärkte Protonen-Torpedos"
text: """<strong>Angriff (Zielerfassung):</strong> Gib eine Zielerfassung aus und lege diese Karte ab um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst bis zu 3 deiner Leerseiten in %FOCUS% ändern."""
"Autoblaster":
name: "Repertierblaster"
text: """<strong>Angriff:</strong> Greife 1 Schiff mit dieser Sekundärwaffe an.<br /><br />Deine %HIT% können von Verteidigungswürfeln nicht negiert werden.<br /><br />Der Verteidiger darf %CRIT% negieren, bevor alle %HIT% negiert wurden."""
"Fire-Control System":
name: "Feuerkontrollsystem"
text: """Nachdem du angegriffen hast, darfst du eine Zielerfassung auf den Verteidiger durchführen."""
"Blaster Turret":
name: "Blastergeschütz"
text: """<strong>Angriff (Fokussierung):</strong> Gib 1 Fokusmarker aus, um 1 Schiff mit dieser Sekundärwaffe anzugreifen (es muss nicht in deinem Feuerwinkel sein)."""
"Recon Specialist":
name: "PI:NAME:<NAME>END_PI"
text: """Wenn du die Aktion Fokussieren durchführst, lege 1 zusätzlichen Fokusmarker neben dein Schiff."""
"Saboteur":
text: """<strong>Aktion:</strong> Wähle 1 feindliches Schiff in Reichweite 1 und wirf 1 Angriffswürfel. Bei %HIT% oder %CRIT%, wähle 1 zufällige verdeckte Schadenskarte des Schiffs, decke sie auf und handle sie ab."""
"Intelligence Agent":
name: "PI:NAME:<NAME>END_PI"
text: """Wähle zu Beginn der Aktivierungsphase 1 feindliches Schiff in Reichweite 1-2. Du darfst dir das ausgewählte Manöver dieses Schiffs ansehen."""
"ProPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Nach dem Aufdecken deines Manöverrads darfst du diese Karte ablegen um 1 Protonenbomben-Marker zu <strong>legen</strong>.<br /><br />Der Marker <strong>detoniert</strong> am Ende der Aktivierungsphase."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Wenn du ein rotes Manöver aufdeckst, darfst du diese Karte ablegen, um das Manöver bis zum Ende der Aktivierungsphase wie ein weißes Manöver zu behandeln."""
"Advanced Sensors":
name: "Verbesserte Sensoren"
text: """Unmittelbar vor dem Aufdecken deines Manövers darfst du 1 freie Aktion durchführen.<br /><br />Wenn du diese Fähigkeit nutzt, musst du den Schritt "Aktion durchführen" in dieser Runde überspringen."""
"Sensor PI:NAME:<NAME>END_PIammer":
name: "PI:NAME:<NAME>END_PI"
text: """Beim Verteidigen darfst du eines der %HIT% des Angreifers in ein %FOCUS% ändern.<br /><br />Der Angreifer darf den veränderten Würfel nicht neu würfeln."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)"
text: """%DE_IMPERIALONLY%%LINEBREAK%Nachdem du ein feindliches Schiff angegriffen hast, darfst du 2 Schaden nehmen, damit dieses Schiff 1 kritischen Schaden nimmt."""
"Rebel Captive":
name: "PI:NAME:<NAME>END_PI"
text: """%DE_IMPERIALONLY%%LINEBREAK%Ein Mal pro Runde erhält das erste Schiff, das einen Angriff gegen dich ansagt, sofort 1 Stressmarker."""
"Flight Instructor":
name: "PI:NAME:<NAME>END_PI"
text: """Beim Verteidigen darfst du 1 deiner %FOCUS% neu würfeln. Hat der Angreifer einen Pilotenwert von 2 oder weniger, darfst du stattdessen 1 deiner Leerseiten neu würfeln."""
"Navigator":
name: "Navigator"
text: """Nach dem Aufdecken deines Manöverrads darfst du das Rad auf ein anderes Manöver mit gleicher Flugrichtung drehen.<br /><br />Wenn du bereits Stressmarker hast, darfst du es nicht auf ein rotes Manöver drehen."""
"Opportunist":
name: "Opportunist"
text: """Wenn du angreifst und der Verteidiger keine Fokusmarker oder Ausweichmarker hat, kannst du einen Stressmarker nehmen, um einen zusätzlichen Angriffswürfel zu erhalten.<br /><br />Du kannst diese Fähigkeit nicht nutzen, wenn du einen Stressmarker hast."""
"Comms Booster":
name: "Kommunikationsverstärker"
text: """<strong>Energie:</strong> Gib 1 Energie aus, um sämtliche Stressmarker von einem freundlichen Schiff in Reichweite 1-3 zu entfernen. Dann erhält jenes Schiff 1 Fokusmarker."""
"Slicer Tools":
name: "Hackersoftware"
text: """<strong>Aktion:</strong> Wähle 1 oder mehrere feindliche Schiffe mit Stressmarker in Reichweite 1-3. Bei jedem gewählten Schiff kannst du 1 Energie ausgeben, damit es 1 Schaden nimmt."""
"Shield Projector":
name: "Schildprojektor"
text: """Wenn ein feindliches Schiff in der Kampfphase an die Reihe kommt, kannst du 3 Energie ausgeben, um das Schiff bis zum Ende der Phase dazu zu zwingen dich anzugreifen, falls möglich."""
"Ion Pulse Missiles":
name: "Ionenpuls-Raketen"
text: """<strong>Angriff (Zielerfassung):</strong> Lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Wenn du triffst, nimmt das verteidigende Schiff 1 Schaden und erhält 2 Ionenmarker. Dann werden <strong>alle<strong> übrigen Würfelergebnisse negiert."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Entferne zu Beginn der Kampfphase 1 Stressmarker von einem anderen freundlichen Schiff in Reichweite 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Zu Beginn der Kampfphase darfst du 1 freundliches Schiff in Reichweite 1-2 wählen. Bis zum Ende der Phase tauscht du mit diesem Schiff den Pilotenwert."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Wenn du ein Schiff innerhalb deines Feuerwinkels angreifst und selbst nicht im Feuerwinkel dieses Schiffs bist, wird seine Wendigkeit um 1 reduziert (Minimum 0)"""
"Predator":
name: "PI:NAME:<NAME>END_PI"
text: """Wenn du angreifst, darfst du 1 Angriffswürfel neu würfeln. Ist der Pilotenwert des Verteidigers2 oder niedriger, darfst du stattdessen bis zu 2 Angriffswürfel neu würfeln."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Nachdem du angegriffen hast, bekommt der Verteidiger 1 Stressmarker, sofern sein Hüllenwert 4 oder weniger beträgt."""
"R7 Astromech":
name: "R7-Astromech-Droide"
text: """Ein Mal pro Runde kannst du beim Verteidigen gegen den Angriff eines Schiffs, das du in Zielerfassung hast, die Zielerfassungsmarker ausgeben, um beliebige (oder alle) Angriffswürfel zu wählen. Diese muss der Angreifer neu würfeln."""
"R7-T1":
name: "R7-T1"
text: """<strong>Aktion:</strong> Wähle ein feindliches Schiff in Reichweite 1-2. Wenn du im Feuerwinkel dieses Schiffs bist, kannst du es in die Zielerfassung nehmen. Dann darfst du als freie Aktion einen Schub durchführen."""
"Tactician":
name: "PI:NAME:<NAME>END_PI"
text: """Nachdem du ein Schiff in Reichweite 2 und innerhalb deines Feuerwinkels angegriffen hast, erhält es 1 Stressmarker."""
"R2-D2 (Crew)":
name: "R2-D2 (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Wenn du am Ende der Endphase keine Schilde hast, darfst du 1 Schild wieder aufladen und 1 Angriffswürfel werfen. Bei %HIT% musst du 1 deiner verdeckten Schadenskarten (zufällig gewählt) umdrehen und abhandeln."""
"C-3PO":
name: "C-3PO"
text: """%DE_REBELONLY%%LINEBREAK%Einmal pro Runde darfst du, bevor du 1 oder mehrere Verteidigungswürfel wirfst, laut raten, wie viele %EVADE% du würfeln wirst. Wenn du richtig geraten hast (bevor die Ergebnisse modifiziert werden), wird 1 %EVADE% hinzugefügt."""
"Single Turbolasers":
name: "Einzelne Turbolasers"
text: """<strong>Angriff (Energie):</strong> gib 2 Energie von dieser Karte aus, um mit dieser Sekundärwaffe anzugreifen. Der Verteidiger verwendet zum Verteidigen seinen doppelten Wendigkeitswert. Du darfst 1 deiner %FOCUS% in ein %HIT% ändern."""
"Quad Laser Cannons":
name: "PI:NAME:<NAME>END_PIlings-LPI:NAME:<NAME>END_PIkanPI:NAME:<NAME>END_PI"
text: """<strong>Angriff (Energie):</strong> Gib 1 Energie von dieser Karte aus, um mit dieser Sekundärwaffe anzugreifen. Wenn der Angriff verfehlt, kannst du sofort 1 Energie von dieser Karte ausgeben, um den Angriff zu wiederholen."""
"Tibanna Gas Supplies":
name: "Tibanna-Gas-Vorräte"
text: """<strong>Energie:</strong> Du kannst diese Karte ablegen, um 3 Energie zu erzeugen."""
"Ionization Reactor":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Energie:</strong> Gib 5 Energie von dieser Karte aus und lege sie ab, damit jedes andere Schiff in Reichweite 1 einen Schaden nimmt und einen Ionenmarker bekommt."""
"Engine Booster":
name: "PI:NAME:<NAME>END_PI"
text: """Unmittelbar bevor du dein Manöverrad aufdeckst, kannst du 1 Energie ausgeben, um ein weißes (%STRAIGHT% 1)-Manöver auszuführen. Wenn es dadurch zur Überschneidung mit einem anderen Schiff käme, darfst du diese Fähigkeit nicht nutzen."""
"R3-A2":
name: "R3-A2"
text: """Nachdem du das Ziel deines Angriffs angesagt hast, darfst du, wenn der Verteidiger in deinem Feuerwinkel ist, 1 Stressmarker nehmen, damit der Verteidiger auch 1 Stressmarker bekommt."""
"R2-D6":
name: "R2-D6"
text: """Deine Aufwertungsleiste bekommt ein %ELITE%-Symbol.<br /><br />Du kannst diese Aufwertung nicht ausrüsten, wenn du bereits ein %ELITE%-Symbol hast oder dein Pilotenwert 2 oder weniger beträgt."""
"Enhanced Scopes":
name: "Verbessertes Radar"
text: """Behandle in der Aktivierungsphase deinen Pilotenwert als "0"."""
"Chardaan Refit":
name: "Chardaan-Nachrüstung"
text: """Diese Karte hat negative Kommandopunktekosten."""
"Proton Rockets":
name: "Protonenraketen"
text: """<strong>Angriff (Fokussierung):</strong> Lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Du darfst so viele zusätzliche Angriffswürfel werfen, wie du Wendigkeit hast (maximal 3 zusätzliche Würfel)."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Nachdem du einen Stressmarker von deinem Schiff entfernt hast, darfst du deinem Schiff einen Fokusmarker geben."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Ein Mal pro runde darfst du einem freundlichem Schiff in Reichweite 1-3, das gerade die Aktion Fokussierung durchführt oder einen Fokusmarker erhalten würde, stattdessen einen Ausweichmarker geben."""
"PI:NAME:<NAME>END_PI":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%<strong>Aktion:</strong> Gib X Energie aus, um X feindliche Schiffe in Reichweite 1-2 zu wählen. Sämtliche Fokus-, Ausweich- und blauen Zielerfassungsmarker dieser Schiffe werden entfernt."""
# TODO Check card formatting
"R4-D6":
text: """Wenn du von einem Angriff getroffen wirst und es mindestens 3 nicht negierte %HIT% gibt, darfst du so viele %HIT% wählen und negieren, bis es nur noch 2 sind. Für jedes auf diese Weise negierte %HIT% bekommst du 1 Stressmarker."""
"R5-P9":
text: """Am Ende der Kampfphase kannst du 1 deiner Fokusmarker ausgeben, um 1 Schild wiederaufzuladen (bis maximal zum Schildwert)."""
"WED-15 Repair Droid":
name: "WED-15 Reparaturdroide"
text: """%DE_HUGESHIPONLY%%LINEBREAK%<strong>Aktion:</strong> gib 1 Energie aus, um 1 deiner verdeckten Schadenskarten abzulegen oder gib 3 Energie aus, um 1 deiner offenen Schadenskarten abzulegen."""
"PI:NAME:<NAME>END_PI":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%Zu Beginn der Aktivierungsphase kannst du diese Karte ablegen, damit bis zum Ende der Phase der Pilotenwert aller freundlichen Schiffe 12 beträgt."""
"PI:NAME:<NAME>END_PI":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%Wenn ein anderes freundliches Schiff in Reichweite 1 angreift, darf es 1 seiner gewürfelten %HIT% in ein %CRIT% ändern."""
"Expanded Cargo Hold":
name: "Erweiterter Ladebereich"
text: """Ein Mal pro Runde darfst du, wenn du eine offene Schadenskarte erhältst, frei wählen, ob du sie vom Schadensstapel Bug oder Heck ziehen willst."""
ship: "Medium-Transporter GR-75"
"Backup Shield Generator":
name: "Sekundärer Schildgenerator"
text: """Am Ende jeder Runde kannst du 1 Energie ausgeben, um 1 Schild wiederaufzuladen (bis maximal zum Schildwert)."""
"EM Emitter":
name: "EM-Emitter"
text: """Wenn du bei einem Angriff die Schussbahn versperrst, bekommst der Verteidiger 3 zusätzliche Verteidigungswürfel (anstatt 1)."""
"Frequency Jammer":
name: "Störsender (Fracht)"
text: """Wenn du die Aktion Störsignal durchführst, wähle 1 feindliches Schiff ohne Stressmarker in Reichweite 1 des vom Störsignal betroffenen Schiffs. Das gewählte Schiff erhält 1 Stressmarker."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI (CrePI:NAME:<NAME>END_PI)"
text: """%DE_REBELONLY%%LINEBREAK%Wenn du angreifst und den Verteidiger in Zielerfassung hast, kannst du diese Zielerfassung ausgeben, um all deine gewürfelten %FOCUS% in %HIT% zu ändern."""
"PI:NAME:<NAME>END_PI":
text: """%DE_REBELONLY%%LINEBREAK%Zu Beginn der Aktivierungsphase kannst du diese Karte ablegen, damit alle freundlichen Schiffe, die ein rotes Manöver aufdecken, dieses bis zum Ende der Phase wie ein weißes Manöver behandeln dürfen."""
"Targeting Coordinator":
text: """<strong>Energy:</strong> You may spend 1 energy to choose 1 friendly ship at Range 1-2. Acquire a target lock, then assign the blue target lock token to the chosen ship."""
"PI:NAME:<NAME>END_PI":
text: """%DE_HUGESHIPONLY%%LINEBREAK%%DE_REBELONLY%%LINEBREAK%Wähle zu Beginn der Aktivierungsphase 1 feindliches Schiff in Reichweite 1-3. Du kannst dir das gewählte Manöver dieses Schiffes ansehen. Wenn es weiß ist, bekommt dieses Schiff 1 Stressmarker."""
"Gunnery Team":
name: "PI:NAME:<NAME>END_PI"
text: """Einmal pro Runde kannst du beim Angreifen mit einer Sekundärwaffe 1 Energie ausgeben, um 1 gewürfelte Leerseite in ein %HIT% zu ändern."""
"Sensor Team":
name: "Sensortechnikerteam"
text: """Du kannst feindliche Schiffe in Reichweite 1-5 in die Zielerfassung nehmen (anstatt in Reichweite 1-3)."""
"Engineering Team":
name: "PI:NAME:<NAME>END_PI"
text: """Wenn du in der Aktivierungsphase ein %STRAIGHT% Manöver aufdeckst, bekommst du im Schritt "Energie gewinnen" 1 zusätzlichen Energiemarker."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%<strong>Aktion:</strong> Wirf 2 Verteidigungswürfel. Dein Schiff bekommt 1 Fokusmarker für jedes %FOCUS% und 1 Ausweichmarker für jedes %EVADE%."""
"PI:NAME:<NAME>END_PI":
text: """%DE_IMPERIALONLY%%LINEBREAK%Am Ende der Kampfphase erhält jedes feindliche Schiff in Reichweite 1, das keine Stressmarker hat, einen Stressmarker."""
"Fleet Officer":
name: "PI:NAME:<NAME>END_PI"
text: """%DE_IMPERIALONLY%%LINEBREAK%<strong>Aktion:</strong> Wähle bis zu 2 freundliche Schiffe in Reichweite 1-2 und gib ihnen je 1 Fokusmarker. Dann erhältst du 1 Stressmarker."""
"Targeting Coordinator":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Energie:</strong> Du kannst 1 Energie ausgeben, um 1 freundliches Schiff in Reichweite1-2 zu wählen. Nimm dann ein Schiff in die Zielerfassung und gibt den blauen Zielerfassungsmarker dem gewählten Schiff."""
"Lone Wolf":
name: "PI:NAME:<NAME>END_PI"
text: """Wenn keine freundlichen Schiffe in Reichweite 1-2 sind, darfst du beim Angreifen und Verteidigen 1 gewürfelte Leerseite neu würfeln."""
"Stay On Target":
name: "PI:NAME:<NAME>END_PI"
text: """Nach dem Aufdecken des Manöverrads darfst du ein anderes Manöver mit gleicher Geschwindigkeit auf deinem Rad einstellen.<br /><br />Dieses Manöver wird wie ein rotes Manöver behandelt."""
"Dash Rendar":
name: "Dash Rendar (Crew)"
text: """%DE_REBELONLY%%LINEBREAK%Du darfst auch angreifen während du dich mit einem Hindernis überschneidest.<br /><br />Deine Schussbahn kann nicht versperrt werden."""
'"Leebo"':
name: '"Leebo" (Crew)'
text: """%DE_REBELONLY%%LINEBREAK%<strong>Aktion:</strong> Führe als freie Aktion einen Schub durch. Dann erhältst du 1 Ionenmarker."""
"Ruthlessness":
name: "PI:NAME:<NAME>END_PI"
text: """%DE_IMPERIALONLY%%LINEBREAK%Nachdem du mit einem Angriff getroffen hast, <strong>musst</strong> du 1 anderes Schiff in Reichweite 1 des Verteidigers (außer dir selbst) wählen. Das Schiff nimmt 1 Schaden."""
"IntPI:NAME:<NAME>END_PIidation":
name: "PI:NAME:<NAME>END_PI"
text: """Die Wendigkeit feindlicher Schiffe sinkt um 1, solange du sie berührst."""
"PI:NAME:<NAME>END_PI":
text: """%DE_IMPERIALONLY%%LINEBREAK%Wenn du zu Beginn der Kampfphase keine Schilde und mindestens 1 Schadenskarte hast, darfst du als freie Aktion ausweichen."""
"PI:NAME:<NAME>END_PI":
text: """%DE_IMPERIALONLY%%LINEBREAK%Wenn du eine offene Schadenskarte erhältst, kannst du diese Aufwertungskarte oder eine andere %CREW%-Aufwertung ablegen, um die Schadenskarte umzudrehen (ohne dass der Kartentext in Kraft tritt)."""
"Ion Torpedoes":
name: "Ionentorpedos"
text: """<strong>Angriff (Zielerfassung):</strong> Gib deine Zielerfassungsmarker aus und lege diese Karte ab, um mit dieser Sekundärwaffe anzugreifen.<br /><br />Triffst du, erhalten alle Schiffe in Reichweite 1 des Verteidigers und der Verteidiger selbst je 1 Ionenmarker."""
"Bodyguard":
name: "PI:NAME:<NAME>END_PI"
text: """%DE_SCUMONLY%%LINEBREAK%Zu Beginn der Kampfphase darfst du einen Fokusmarker ausgeben um ein freundliches Schiff in Reichweite 1 zu wählen, dessen Pilotenwert höher ist als deiner. Bis zum Ende der Runde steigt sein Wendigkeitswert um 1."""
"Calculation":
name: "Berechnung"
text: """Sobald du angreifst, darfst du einen Fokusmarker ausgeben, um 1 deiner %FOCUS% in ein %CRIT% zu ändern."""
"Accuracy Corrector":
name: "PI:NAME:<NAME>END_PI"
text: """Sobald du angreifst, darfst du alle deine Würfelergebnisse negieren. Dann darfst du 2 %HIT% hinzufügen.%LINEBREAK%Deine Würfel können während dieses Angriffs nicht noch einmal modifiziert werden."""
"Inertial Dampeners":
name: "PI:NAME:<NAME>END_PI"
text: """Sobald du dein Manöverraf aufdeckst, darfst du diese Karte ablegen, um [0%STOP%]-Manöver auszuführen. Dann erhältst du 1 Stressmarker."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Angriff:</strong> Greife 1 Schiffe an.%LINEBREAK%Wenn dieser Angriff trifft, nimmt das verteidigende Schiff 1 Schaden und erhält 1 Stressmarker (falls es noch keinen hat.) Dann werden <strong>alle</strong> Würfelergebnisse negiert."""
'"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI':
name: '"PI:NAME:<NAME>END_PI"-PI:NAME:<NAME>END_PI'
text: """<strong>Angriff:</strong> Greife 1 Schiff an.%LINEBREAK%Sobald du angreifst, darfst du 1 deiner %HIT% in ein %CRIT% ändern."""
"Dead Man's Switch":
name: "PI:NAME:<NAME>END_PI"
text: """Sobald du zerstörst wirst, nimmt jedes Schiff in Reichweite 1 einen Schaden."""
"Feedback Array":
name: "Rückkopplungsfeld"
text: """In der Kampfphase darfst du statt einen Angriff durchzuführen 1 Ionenmarker und 1 Schaden nehmen, um eine feindliches Schiff in Reichweite 1 zu wählen. Das gewählte Schiff nimmt 1 Schaden."""
'"Hot Shot" Blaster':
text: """<strong>Angriff:</strong> Lege diese Karte ab, um 1 Schiff (auch außerhalb deines Feuerwinkels) anzugreifen."""
"Greedo":
text: """%DE_SCUMONLY%%LINEBREAK%In jeder Runde wird bei deinem ersten Angriff und deiner ersten Verteidigung die erste Schadenskarte offen zugeteilt."""
"Salvaged Astromech":
name: "Abgewrackter Astromechdroide"
text: """Sobald du eine Schadenskarte mit dem Attribut <strong>Schiff</strong> erhälst, darfst du sie sofort ablegen (bevor ihr Effekt abgehandelt wird).%LINEBREAK%Danach wird diese Aufwertungskarte abgelegt."""
"Bomb Loadout":
name: "Bombenladung"
text: """<span class="card-restriction">Nur für Y-Wing.</span>%LINEBREAK%Füge deiner Aufwertungsleiste das %BOMB%-Symbol hinzu."""
'"Genius"':
name: '"Genie"'
text: """Wenn du eine Bombe ausgerüstet hast, die vor dem Aufdecken deines Manövers gelegt werden kann, darfst du sie stattdessen auch <strong>nach</strong> Ausführung des Manövers legen."""
"Unhinged Astromech":
name: "Ausgeklinkter Astromech-Droide"
text: """Du darfst alle Manöver mit Geschwindigkeit 3 wie grüne Manöver behandeln."""
"R4-B11":
text: """Sobald du angreifst, darfst du, falls du den Verteidiger in der Zielerfassung hast, den Zielerfassungsmarker ausgeben, um einen oder alle Verteidigungswürfel zu wählen. Diese muss der Verteidiger neu würfeln."""
"Autoblaster Turret":
name: "Autoblastergeschütz"
text: """<strong>Angriff:</strong> Greife 1 Schiff (auch außerhalb deines Feuerwinkels) an. %LINEBREAK%Deine %HIT% können von Verteidigungswürfeln nicht negiert werden. Der Verteidiger darf %CRIT% vor %HIT% negieren."""
"R4 Agromech":
name: "R4-Agromech-Droide"
text: """Sobald du angreifst, darfst du, nachdem du einen Fokusmarker ausgegeben hast, den Verteidiger in die Zielerfassung nehmen."""
"K4 Security Droid":
name: "K4-Sicherheitsdroide"
text: """%DE_SCUMONLY%%LINEBREAK%Nachdem du ein grünes Manöver ausgeführt hast, darfst du ein Schiff in die Zielerfassung nehmen."""
"Outlaw Tech":
name: "Gesetzloser Techniker"
text: """%DE_SCUMONLY%%LINEBREAK%Nachdem du ein rotes Manöver ausgeführt hast, darfst du deinem Schiff 1 Fokusmarker zuweisen."""
"Advanced Targeting Computer":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%When attacking with your primary weapon, if you have a target lock on the defender, you may add 1 %CRIT% result to your roll. If you do, you cannot spend target locks during this attack."""
"Ion Cannon Battery":
text: """<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack. If this attack hits, the defender suffers 1 critical damage and receives 1 ion token. Then cancel <strong>all<strong> dice results."""
"Emperor Palpatine":
text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again."""
"Bossk":
text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender."""
"Lightning Reflexes":
text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180°. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step."""
"Twin Laser Turret":
text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results."""
"Plasma Torpedoes":
text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender."""
"Ion Bombs":
text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token."""
"Conner Net":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token."""
"Bombardier":
text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template."""
"Cluster Mines":
text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token."""
'Crack Shot':
text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.'''
"Advanced Homing Missiles":
text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results."""
'Agent Kallus':
text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.'''
'XX-23 S-Thread Tracers':
text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results."""
"Tractor Beam":
text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results."""
"Cloaking Device":
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token."""
modification_translations =
"Stealth Device":
name: "Tarnvorrichtung"
text: """Dein Wendigkeitswert steigt um 1. Lege diese Karte ab, wenn du von einem Angriff getroffen wirst."""
"Shield Upgrade":
name: "Verbesserte Schilde"
text: """Dein Schildwert steigt um 1."""
"Engine Upgrade":
name: "Verbessertes Triebwerk"
text: """Füge deiner Aktionsleiste ein %BOOST%-Symbol hinzu."""
"Anti-Pursuit Lasers":
name: "Kurzstreckenlaser"
text: """%DE_LARGESHIPONLY%%LINEBREAK%Nachdem ein feindliches Schiff ein Manöver ausgeführt hat, das zur Überschneidung mit deinem Schiff führt, wirf 1 Angriffswürfel. Bei %HIT% oder %CRIT% nimmt das feindliche Schiff 1 Schaden."""
"Targeting Computer":
name: "Zielerfassungssystem"
text: """Deine Aktionsleiste erhält das %TARGETLOCK%-Symbol."""
"Hull Upgrade":
name: "Verbesserte Hülle"
text: """Erhöhe deinen Hüllenwert um 1."""
"Munitions Failsafe":
name: "Ausfallsichere Munition"
text: """Wenn du mit einer Sekundärwaffe angreifst, deren Kartentext besagt, dass sie zum Angriff abgelegt werden muss, legst du sie nur ab, falls du triffst."""
"Stygium Particle Accelerator":
name: "Stygium-Teilchen-Beschleuniger"
text: """immer wenn du dich enttarnst oder die Aktion Tarnen durchführst, darfst du als freie Aktion ausweichen."""
"Advanced Cloaking Device":
name: "Verbesserte Tarnvorrichtung"
text: """Nachdem du angegriffen hast, darfst du dich als freie Aktion tarnen."""
"Combat Retrofit":
name: "Umrüstung für den Kampfeinsatz"
ship: "Medium-Transporter GR-75"
text: """Erhöhe deinen Hüllenwert um 2 und deinen Schildwert um 1."""
"B-Wing/E2":
text: """Füge deiner Aufwertungsleiste das %CREW%-Symbol hinzu."""
"Countermeasures":
name: "Gegenmassnahmen"
text: """%DE_LARGESHIPONLY%%LINEBREAK%Zu Beginn der Kampfphase kannst du diese Karte ablegen, um deine Wendigkeit bis zum Ende der Runde um 1 zu erhöhen. Dann darfst du 1 feindliche Zielerfassung von deinem Schiff entfernen."""
"Experimental Interface":
name: "Experimentelles Interface"
text: """Ein Mal pro Runde darfst du nach dem Durchführen einer Aktion 1 ausgerüstete Aufwertungskarte mit dem Stichwort "<strong>Aktion:</strong>" benutzen (dies zählt als freie Aktion). Dann erhältst du 1 Stressmarker."""
"Tactical Jammer":
name: "PI:NAME:<NAME>END_PI"
text: """%DE_LARGESHIPONLY%%LINEBREAK%Dein Schiff kann die feindliche Schussbahn versperren."""
"Autothrusters":
name: "PI:NAME:<NAME>END_PI"
text: """Sobald du verteidigst und jenseits von Reichweite 2 oder außerhalb des Feuerwinkels des Angreifers bist, darfst du 1 deiner Leerseiten in ein %EVADE% ändern. Du darfst diese Karte nur ausrüsten, wenn du das %BOOST%-Aktionssymbol hast."""
"Twin Ion Engine Mk. II":
text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers."""
"Maneuvering Fins":
text: """When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed."""
"Ion Projector":
text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token."""
title_translations =
"Slave I":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Nur für Firespray-31.</span>%LINEBREAK%Füge deiner Aktionsleiste ein %TORPEDO%-Symbol hinzu."""
"PI:NAME:<NAME>END_PIillennium PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Nur für YT-1300.</span>%LINEBREAK%Füge deiner Aktionsleiste ein %EVADE%-Symbol hinzu."""
"PI:NAME:<NAME>END_PI":
text: """<span class="card-restriction">Nur für HWK-290.</span>%LINEBREAK%In der Endphase werden von diesem Schiff keine unbenutzen Fokusmarker entfernt."""
"ST-321":
ship: "Raumfähre der Lambda-Klasse"
text: """<span class="card-restriction">Nur für Raumfähren der Lamda-Klasse.</span>%LINEBREAK%Wenn du eine Zielerfassung durchführst, darfst du ein beliebiges feindliches Schiff auf der Spielfläche als Ziel erfassen."""
"Royal Guard TIE":
name: "TIPI:NAME:<NAME>END_PI"
ship: "TIE-Abfangjäger"
text: """<span class="card-restriction">Nur für TIE-Abfangjäger.</span>%LINEBREAK%Du kannst bis zu 2 verschiedene Modifikationen verwenden (statt einer).<br /><br />Du kannst diese Karte nicht verwenden, wenn der Pilotenwert "4" oder kleiner ist."""
"DodonPI:NAME:<NAME>END_PI's Pride":
name: "PI:NAME:<NAME>END_PI"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">Nur für CR90-Korvette (Bug).</span>%LINEBREAK%Wenn du die Aktion Koordination durchführst, kannst du 2 freundliche Schiffe wählen (anstatt 1). Jedes dieser Schiffe darf 1 freie Aktion durchführen."""
"A-Wing Test Pilot":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Nur für A-Wing.</span>%LINEBREAK%Füge deiner Aufwertungsleiste 1 %ELITE%-Symbol hinzu.<br /><br />Du darfst jede %ELITE%-Aufwertung nur ein Mal ausrüsten. Du kannst diese Karte nicht verwenden, wenn dein Pilotenwert "1" oder niedriger ist."""
"Tantive IV":
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">Nur für CR90-Korvette (Bug).</span>%LINEBREAK%Die Aufwertungsleiste deiner Bugsektion erhält 1 zusätzliches %CREW% und 1 zusätzliches %TEAM% ."""
"Bright Hope":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">Nur für Medium-Transporter GR-75.</span>%LINEBREAK%Wenn neben deiner Bugsektion ein Verstärkungsmarker liegt, fügt er 2 %EVADE% hinzu (anstatt 1)."""
"Quantum Storm":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">Nur für Medium-Transporter GR-75.</span>%LINEBREAK%Wenn du zu Beginn der Endphase 1 Energiemarker oder weniger hast, gewinnst du 1 Energiemarker."""
"Dutyfree":
ship: "Medium-Transporter GR-75"
text: """<span class="card-restriction">Nur für Medium-Transporter GR-75.</span>%LINEBREAK%Bei der Aktion Störsignal kannst du ein feindliches Schiff in Reichweite 1-3 (statt 1-2) wählen."""
"Jaina's Light":
name: "PI:NAME:<NAME>END_PI"
ship: "CR90-Korvette (Bug)"
text: """<span class="card-restriction">Nur für CR90-Korvette (Bug).</span>%LINEBREAK%Wenn du verteidigst, darfst du einmal pro Angriff eine soeben erhaltene, offene Schadenskarte ablegen und dafür eine neue offene Schadenskarte ziehen."""
"Outrider":
text: """<span class="card-restriction">Nur für YT-2400.</span>%LINEBREAK%Solange du eine %CANNON%-Aufwertung ausgerüstet hast, kannst du deine Primärwaffen <strong>nicht</strong> verwenden. Dafür darfst du mit %CANNON%-Sekundärwaffen auch Ziele außerhalb deines Feuerwinkels angreifen."""
"Dauntless":
text: """<span class="card-restriction">Nur für VT-49 Decimator.</span>%LINEBREAK%Nach dem Ausführen eines Manövers, das zur Überschneidung mit einem anderen Schiff geführt hat, darfst du 1 freie Aktion durchführen. Dann erhältst du 1 Stressmarker."""
"Virago":
text: """<span class="card-restriction">Nur für SternenViper.</span>%LINEBREAK%Füge deiner Aufwertungsleiste ein %SYSTEM%- und ein %ILLICIT%-Symbol hinzu.%LINEBREAK%Du kannst diese Karte nicht ausrüsten, wenn dein Pilotenwert "3" oder niedriger ist."""
'"Heavy Scyk" Interceptor (Cannon)':
ship: "M3-A Abfangjäger"
name: '"PI:NAME:<NAME>END_PI SPI:NAME:<NAME>END_PI"-Abfangjäger (Kannone)'
text: """<span class="card-restriction">Nur für M3-A-Abfangjäger.</span>%LINEBREAK%Füge deiner Aufwertungsleiste eines der folgenden Symbole hinzu: %CANNON%, %TORPEDO%, oder %MISSILE%."""
'"Heavy Scyk" Interceptor (Torpedo)':
ship: "M3-A Abfangjäger"
name: '"PI:NAME:<NAME>END_PI Scyk"-Abfangjäger (Torpedo)'
text: """<span class="card-restriction">Nur für M3-A-Abfangjäger.</span>%LINEBREAK%Füge deiner Aufwertungsleiste eines der folgenden Symbole hinzu: %CANNON%, %TORPEDO%, oder %MISSILE%."""
'"Heavy Scyk" Interceptor (Missile)':
ship: "M3-A Abfangjäger"
name: '"PI:NAME:<NAME>END_PIer Scyk"-Abfangjäger (Rakete)'
text: """<span class="card-restriction">Nur für M3-A-Abfangjäger.</span>%LINEBREAK%Füge deiner Aufwertungsleiste eines der folgenden Symbole hinzu: %CANNON%, %TORPEDO%, oder %MISSILE%."""
"IG-2000":
text: """<span class="card-restriction">Nur für Aggressor.</span>%LINEBREAK%Du bekommst die Pilotenfähigkeiten aller anderen freundlichen Schiffe mit der Aufwertungskarte <em>IG-2000</em> (zusätzlich zu deiner eigenen Pilotenfähigkeit)."""
"BTL-A4 Y-Wing":
name: "BTL-A4-Y-Wing"
text: """<span class="card-restriction">Nur für Y-Wing.</span>%LINEBREAK%Du darfst Schiffe außerhalb deines Feuerwinkels nicht angreifen. Nachdem du einen Angriff mit deinen Primärwaffen durchgeführt hast, darfst du sofort einen weiteren Angriff mit einer %TURRET%-Sekundärwaffe durchführen."""
"Andrasta":
text: """<span class="card-restriction">Nur für Firespray-31.</span>%LINEBREAK%Füge deiner Aufwertungsleiste zwei weitere %BOMB%-Symbole hinzu."""
"TIE/x1":
text: """<span class="card-restriction">TIE Advanced only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% upgrade icon.%LINEBREAK%If you equip a %SYSTEM% upgrade, its squad point cost is reduced by 4 (to a minimum of 0)."""
"Ghost":
text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides."""
"Phantom":
text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round."""
"TIE/v1":
text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action."""
"PI:NAME:<NAME>END_PI":
text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal)."""
"Punishing One":
text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1."""
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations
|
[
{
"context": "set\", ->\n createUser\n slackUsername: 'bob'\n .then (@user)=>\n @user.newRecord().",
"end": 510,
"score": 0.9926880598068237,
"start": 507,
"tag": "USERNAME",
"value": "bob"
},
{
"context": " getUserByName: (userName)->\n id: \"someI... | test/models/user-tests.coffee | citizencode/swarmbot | 21 | { createUser } = require '../helpers/test-helper'
sinon = require 'sinon'
{ p } = require 'lightsaber'
User = require '../../src/models/user'
KeenioInfo = require '../../src/services/keenio-info.coffee'
describe 'User', ->
describe 'newRecord', ->
it "returns true if slackUsername is NOT set", ->
createUser
slackUsername: null
.then (@user)=>
@user.newRecord().should.eq true
it "returns false if slackUsername is set", ->
createUser
slackUsername: 'bob'
.then (@user)=>
@user.newRecord().should.eq false
describe 'events', ->
context 'when executing an invalid state', ->
it 'resets user state', ->
createUser
state: "some#state"
stateData: {foo: 'bar'}
menu: {foo: 'bar'}
.then (@user)=>
@user.exit()
.then =>
@user.get('state').should.eq User::initialState
@user.get('stateData').should.deep.eq {}
@user.get('menu').should.deep.eq {}
describe '#reset', ->
it 'resets user state, stateData, and menu', ->
createUser
state: "some#state"
stateData: {foo: 'bar'}
menu: {foo: 'bar'}
.then (@user)=>
@user.exit()
.then =>
@user.get('state').should.eq User::initialState
@user.get('stateData').should.deep.eq {}
@user.get('menu').should.deep.eq {}
describe '#setupToReceiveBitcoin', ->
spy = null
beforeEach ->
spy = sinon.spy(KeenioInfo::, 'createUser')
sinon.stub(Date, 'now').returns(123456)
afterEach ->
KeenioInfo::createUser.restore?()
Date.now.restore?()
it 'should mark the user in Keen.io', ->
sendPm = sinon.spy()
App.robot =
messageRoom: -> {}
App.slack =
getUserByName: (userName)->
id: "someId"
real_name: 'some real name'
createUser(name: 'admin', slackUsername: 'adminUserName')
.then (@admin)=>
User.setupToReceiveBitcoin(@admin, 'someGuy', {}, sendPm)
.then =>
assert.fail()
.error =>
spy.should.have.been.called
.then =>
User.findBySlackUsername('someGuy')
.then (someGuy)=>
someGuy.get('state').should.eq 'users#setBtc'
someGuy.get('lastActiveOnSlack').should.eq 123456
someGuy.get('firstSeen').should.eq 123456
someGuy.get('hasInteracted')?.should.eq false
someGuy.get('name').should.eq "slack:someId"
someGuy.get('realName').should.eq 'some real name'
someGuy.get('slackUsername').should.eq "someGuy"
someGuy.get('slackId').should.eq "someId"
| 136734 | { createUser } = require '../helpers/test-helper'
sinon = require 'sinon'
{ p } = require 'lightsaber'
User = require '../../src/models/user'
KeenioInfo = require '../../src/services/keenio-info.coffee'
describe 'User', ->
describe 'newRecord', ->
it "returns true if slackUsername is NOT set", ->
createUser
slackUsername: null
.then (@user)=>
@user.newRecord().should.eq true
it "returns false if slackUsername is set", ->
createUser
slackUsername: 'bob'
.then (@user)=>
@user.newRecord().should.eq false
describe 'events', ->
context 'when executing an invalid state', ->
it 'resets user state', ->
createUser
state: "some#state"
stateData: {foo: 'bar'}
menu: {foo: 'bar'}
.then (@user)=>
@user.exit()
.then =>
@user.get('state').should.eq User::initialState
@user.get('stateData').should.deep.eq {}
@user.get('menu').should.deep.eq {}
describe '#reset', ->
it 'resets user state, stateData, and menu', ->
createUser
state: "some#state"
stateData: {foo: 'bar'}
menu: {foo: 'bar'}
.then (@user)=>
@user.exit()
.then =>
@user.get('state').should.eq User::initialState
@user.get('stateData').should.deep.eq {}
@user.get('menu').should.deep.eq {}
describe '#setupToReceiveBitcoin', ->
spy = null
beforeEach ->
spy = sinon.spy(KeenioInfo::, 'createUser')
sinon.stub(Date, 'now').returns(123456)
afterEach ->
KeenioInfo::createUser.restore?()
Date.now.restore?()
it 'should mark the user in Keen.io', ->
sendPm = sinon.spy()
App.robot =
messageRoom: -> {}
App.slack =
getUserByName: (userName)->
id: "someId"
real_name: '<NAME>'
createUser(name: 'admin', slackUsername: 'adminUserName')
.then (@admin)=>
User.setupToReceiveBitcoin(@admin, 'someGuy', {}, sendPm)
.then =>
assert.fail()
.error =>
spy.should.have.been.called
.then =>
User.findBySlackUsername('someGuy')
.then (someGuy)=>
someGuy.get('state').should.eq 'users#setBtc'
someGuy.get('lastActiveOnSlack').should.eq 123456
someGuy.get('firstSeen').should.eq 123456
someGuy.get('hasInteracted')?.should.eq false
someGuy.get('name').should.eq "slack:someId"
someGuy.get('realName').should.eq 'some real name'
someGuy.get('slackUsername').should.eq "someGuy"
someGuy.get('slackId').should.eq "someId"
| true | { createUser } = require '../helpers/test-helper'
sinon = require 'sinon'
{ p } = require 'lightsaber'
User = require '../../src/models/user'
KeenioInfo = require '../../src/services/keenio-info.coffee'
describe 'User', ->
describe 'newRecord', ->
it "returns true if slackUsername is NOT set", ->
createUser
slackUsername: null
.then (@user)=>
@user.newRecord().should.eq true
it "returns false if slackUsername is set", ->
createUser
slackUsername: 'bob'
.then (@user)=>
@user.newRecord().should.eq false
describe 'events', ->
context 'when executing an invalid state', ->
it 'resets user state', ->
createUser
state: "some#state"
stateData: {foo: 'bar'}
menu: {foo: 'bar'}
.then (@user)=>
@user.exit()
.then =>
@user.get('state').should.eq User::initialState
@user.get('stateData').should.deep.eq {}
@user.get('menu').should.deep.eq {}
describe '#reset', ->
it 'resets user state, stateData, and menu', ->
createUser
state: "some#state"
stateData: {foo: 'bar'}
menu: {foo: 'bar'}
.then (@user)=>
@user.exit()
.then =>
@user.get('state').should.eq User::initialState
@user.get('stateData').should.deep.eq {}
@user.get('menu').should.deep.eq {}
describe '#setupToReceiveBitcoin', ->
spy = null
beforeEach ->
spy = sinon.spy(KeenioInfo::, 'createUser')
sinon.stub(Date, 'now').returns(123456)
afterEach ->
KeenioInfo::createUser.restore?()
Date.now.restore?()
it 'should mark the user in Keen.io', ->
sendPm = sinon.spy()
App.robot =
messageRoom: -> {}
App.slack =
getUserByName: (userName)->
id: "someId"
real_name: 'PI:NAME:<NAME>END_PI'
createUser(name: 'admin', slackUsername: 'adminUserName')
.then (@admin)=>
User.setupToReceiveBitcoin(@admin, 'someGuy', {}, sendPm)
.then =>
assert.fail()
.error =>
spy.should.have.been.called
.then =>
User.findBySlackUsername('someGuy')
.then (someGuy)=>
someGuy.get('state').should.eq 'users#setBtc'
someGuy.get('lastActiveOnSlack').should.eq 123456
someGuy.get('firstSeen').should.eq 123456
someGuy.get('hasInteracted')?.should.eq false
someGuy.get('name').should.eq "slack:someId"
someGuy.get('realName').should.eq 'some real name'
someGuy.get('slackUsername').should.eq "someGuy"
someGuy.get('slackId').should.eq "someId"
|
[
{
"context": "ss: (model) ->\n username = app.whoami.get \"username\"\n if username && username != \"\"\n ",
"end": 799,
"score": 0.9627928733825684,
"start": 791,
"tag": "USERNAME",
"value": "username"
},
{
"context": "dex.jade\"]\n template_data: ->\n ... | fmc/fmc-webui/src/main/webapp/app/controllers/signin_page.coffee | kpelykh/fuse | 1 | ###
Copyright 2010 Red Hat, Inc.
Red Hat licenses this file to you 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.
###
define [
"models/app"
"views/jade"
"controllers/controls/accordion"
], (app, jade) ->
goto_app = ->
app.whoami.fetch
success: (model) ->
username = app.whoami.get "username"
if username && username != ""
app.update_menu()
app.router.navigate "/containers", true
else
app.flash
kind: "error"
title: "Invalid username or password."
class SigninController extends FON.TemplateController
template: jade["signin/index.jade"]
template_data: ->
username: "admin"
elements:
"input[name=\"username\"]": "username"
"input[name=\"password\"]": "password"
"form": "form"
on_render: ->
@username.bind "DOMNodeInsertedIntoDocument", => @username.focus()
@form.submit =>
$.ajax
url: "/rest/system/login"
dataType: "json"
type: "POST"
data:
username: @username.val()
password: @password.val()
success: (data) ->
if data
goto_app()
else
app.flash
kind: "error"
title: "Invalid username or password."
hide_after: 2000
error: (data) ->
app.flash
kind: "error"
title: "Error communicating with the server."
false
app.router.route "/signin", "signin", ->
app.system_state.fetch
success: (model, resp) ->
app.menu []
if (model.get "client_connected")
app.page new SigninController
else
app.router.navigate "/welcome", true
error: (data) ->
app.flash
kind: "error"
title: "Error communicating with the server."
app.router.route "/signout", "signout", ->
$.ajax
url: "/rest/system/logout.json"
dataType: "json"
success: (data) ->
app.menu []
app.page null
app.flash
kind: "info"
title: "Logged out! "
message: "Your session has been closed."
hide_after: 2000
on_close: ->
app.whoami.set
username: null
app.router.navigate "/signin", true
error: (data) ->
app.whoami.fetch()
app.flash
kind: "error"
title: "Error communicating with the server."
SigninController
| 20583 | ###
Copyright 2010 Red Hat, Inc.
Red Hat licenses this file to you 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.
###
define [
"models/app"
"views/jade"
"controllers/controls/accordion"
], (app, jade) ->
goto_app = ->
app.whoami.fetch
success: (model) ->
username = app.whoami.get "username"
if username && username != ""
app.update_menu()
app.router.navigate "/containers", true
else
app.flash
kind: "error"
title: "Invalid username or password."
class SigninController extends FON.TemplateController
template: jade["signin/index.jade"]
template_data: ->
username: "admin"
elements:
"input[name=\"username\"]": "username"
"input[name=\"password\"]": "<PASSWORD>"
"form": "form"
on_render: ->
@username.bind "DOMNodeInsertedIntoDocument", => @username.focus()
@form.submit =>
$.ajax
url: "/rest/system/login"
dataType: "json"
type: "POST"
data:
username: @username.val()
password: @<PASSWORD>.val()
success: (data) ->
if data
goto_app()
else
app.flash
kind: "error"
title: "Invalid username or password."
hide_after: 2000
error: (data) ->
app.flash
kind: "error"
title: "Error communicating with the server."
false
app.router.route "/signin", "signin", ->
app.system_state.fetch
success: (model, resp) ->
app.menu []
if (model.get "client_connected")
app.page new SigninController
else
app.router.navigate "/welcome", true
error: (data) ->
app.flash
kind: "error"
title: "Error communicating with the server."
app.router.route "/signout", "signout", ->
$.ajax
url: "/rest/system/logout.json"
dataType: "json"
success: (data) ->
app.menu []
app.page null
app.flash
kind: "info"
title: "Logged out! "
message: "Your session has been closed."
hide_after: 2000
on_close: ->
app.whoami.set
username: null
app.router.navigate "/signin", true
error: (data) ->
app.whoami.fetch()
app.flash
kind: "error"
title: "Error communicating with the server."
SigninController
| true | ###
Copyright 2010 Red Hat, Inc.
Red Hat licenses this file to you 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.
###
define [
"models/app"
"views/jade"
"controllers/controls/accordion"
], (app, jade) ->
goto_app = ->
app.whoami.fetch
success: (model) ->
username = app.whoami.get "username"
if username && username != ""
app.update_menu()
app.router.navigate "/containers", true
else
app.flash
kind: "error"
title: "Invalid username or password."
class SigninController extends FON.TemplateController
template: jade["signin/index.jade"]
template_data: ->
username: "admin"
elements:
"input[name=\"username\"]": "username"
"input[name=\"password\"]": "PI:PASSWORD:<PASSWORD>END_PI"
"form": "form"
on_render: ->
@username.bind "DOMNodeInsertedIntoDocument", => @username.focus()
@form.submit =>
$.ajax
url: "/rest/system/login"
dataType: "json"
type: "POST"
data:
username: @username.val()
password: @PI:PASSWORD:<PASSWORD>END_PI.val()
success: (data) ->
if data
goto_app()
else
app.flash
kind: "error"
title: "Invalid username or password."
hide_after: 2000
error: (data) ->
app.flash
kind: "error"
title: "Error communicating with the server."
false
app.router.route "/signin", "signin", ->
app.system_state.fetch
success: (model, resp) ->
app.menu []
if (model.get "client_connected")
app.page new SigninController
else
app.router.navigate "/welcome", true
error: (data) ->
app.flash
kind: "error"
title: "Error communicating with the server."
app.router.route "/signout", "signout", ->
$.ajax
url: "/rest/system/logout.json"
dataType: "json"
success: (data) ->
app.menu []
app.page null
app.flash
kind: "info"
title: "Logged out! "
message: "Your session has been closed."
hide_after: 2000
on_close: ->
app.whoami.set
username: null
app.router.navigate "/signin", true
error: (data) ->
app.whoami.fetch()
app.flash
kind: "error"
title: "Error communicating with the server."
SigninController
|
[
{
"context": ", streams[1], (s1, s2) ->\n {'name': s1, 'pass': s2}\n ).subscribe( (x) ->\n $('#login-button').pro",
"end": 408,
"score": 0.8383554220199585,
"start": 406,
"tag": "PASSWORD",
"value": "s2"
}
] | app/assets/javascripts/loginbutton.coffee | adwd/twitterlike | 0 | $ ->
$('#login-button').prop("disabled", true)
# ログインの名前とパスワードの入力イベントをそれぞれ入力文字数のストリームにする
streams = $.map(['#login-name', '#login-password'], (n, i) ->
Rx.Observable.fromEvent($(n), 'input').map( (x) ->
x.target.value.length
)
)
# 名前とパスワードのストリームを一つのオブジェクトのストリームにして
# ボタンのdisabledプロパティに反映
Rx.Observable.combineLatest(streams[0], streams[1], (s1, s2) ->
{'name': s1, 'pass': s2}
).subscribe( (x) ->
$('#login-button').prop("disabled", x.name == 0 || x.pass < 8)
)
| 175393 | $ ->
$('#login-button').prop("disabled", true)
# ログインの名前とパスワードの入力イベントをそれぞれ入力文字数のストリームにする
streams = $.map(['#login-name', '#login-password'], (n, i) ->
Rx.Observable.fromEvent($(n), 'input').map( (x) ->
x.target.value.length
)
)
# 名前とパスワードのストリームを一つのオブジェクトのストリームにして
# ボタンのdisabledプロパティに反映
Rx.Observable.combineLatest(streams[0], streams[1], (s1, s2) ->
{'name': s1, 'pass': <PASSWORD>}
).subscribe( (x) ->
$('#login-button').prop("disabled", x.name == 0 || x.pass < 8)
)
| true | $ ->
$('#login-button').prop("disabled", true)
# ログインの名前とパスワードの入力イベントをそれぞれ入力文字数のストリームにする
streams = $.map(['#login-name', '#login-password'], (n, i) ->
Rx.Observable.fromEvent($(n), 'input').map( (x) ->
x.target.value.length
)
)
# 名前とパスワードのストリームを一つのオブジェクトのストリームにして
# ボタンのdisabledプロパティに反映
Rx.Observable.combineLatest(streams[0], streams[1], (s1, s2) ->
{'name': s1, 'pass': PI:PASSWORD:<PASSWORD>END_PI}
).subscribe( (x) ->
$('#login-button').prop("disabled", x.name == 0 || x.pass < 8)
)
|
[
{
"context": "# contants\nanalyticsWriteKey = 'pDV1EgxAbco4gjPXpJzuOeDyYgtkrmmG'\n\n# imports\n_ = require 'underscore-plus'\n{allowU",
"end": 64,
"score": 0.9993293881416321,
"start": 32,
"tag": "KEY",
"value": "pDV1EgxAbco4gjPXpJzuOeDyYgtkrmmG"
},
{
"context": "because of [Unsafe-E... | lib/tracker.coffee | slavaGanzin/atom-sync-settings | 0 | # contants
analyticsWriteKey = 'pDV1EgxAbco4gjPXpJzuOeDyYgtkrmmG'
# imports
_ = require 'underscore-plus'
{allowUnsafeEval} = require 'loophole'
# Analytics require a special import because of [Unsafe-Eval error](https://github.com/Glavin001/atom-beautify/commit/fbc58a648d3ccd845548d556f3dd1e046075bf04)
Analytics = null
allowUnsafeEval -> Analytics = require 'analytics-node'
# load package.json to include package info in analytics
pkg = require("../package.json")
class Tracker
constructor: (@analyticsUserIdConfigKey, @analyticsEnabledConfigKey) ->
# Setup Analytics
@analytics = new Analytics analyticsWriteKey
# set a unique identifier
if not atom.config.get @analyticsUserIdConfigKey
uuid = require 'node-uuid'
atom.config.set @analyticsUserIdConfigKey, uuid.v4()
# default event properties
@defaultEvent =
userId: atom.config.get @analyticsUserIdConfigKey
properties:
value: 1
version: atom.getVersion()
platform: navigator.platform
category: "Atom-#{atom.getVersion()}/#{pkg.name}-#{pkg.version}"
context:
app:
name: pkg.name
version: pkg.version
userAgent: navigator.userAgent
# identify the user
atom.config.observe @analyticsUserIdConfigKey, (userId) =>
@analytics.identify
userId: userId
@defaultEvent.userId = userId
# cache enabled and watch for changes
@enabled = atom.config.get @analyticsEnabledConfigKey
atom.config.onDidChange @analyticsEnabledConfigKey, ({newValue}) =>
@enabled = newValue
track: (message) ->
return if not @enabled
message = event: message if _.isString(message)
console.debug "tracking #{message.event}"
@analytics.track _.deepExtend(@defaultEvent, message)
trackActivate: ->
@track
event: 'Activate'
properties:
label: pkg.version
trackDeactivate: ->
@track
event: 'Deactivate'
properties:
label: pkg.version
error: (e) ->
@track
event: 'Error'
properties:
error: e
module.exports = Tracker
| 161063 | # contants
analyticsWriteKey = '<KEY>'
# imports
_ = require 'underscore-plus'
{allowUnsafeEval} = require 'loophole'
# Analytics require a special import because of [Unsafe-Eval error](https://github.com/Glavin001/atom-beautify/commit/fbc58a648d3ccd845548d556f3dd1e046075bf04)
Analytics = null
allowUnsafeEval -> Analytics = require 'analytics-node'
# load package.json to include package info in analytics
pkg = require("../package.json")
class Tracker
constructor: (@analyticsUserIdConfigKey, @analyticsEnabledConfigKey) ->
# Setup Analytics
@analytics = new Analytics analyticsWriteKey
# set a unique identifier
if not atom.config.get @analyticsUserIdConfigKey
uuid = require 'node-uuid'
atom.config.set @analyticsUserIdConfigKey, uuid.v4()
# default event properties
@defaultEvent =
userId: atom.config.get @analyticsUserIdConfigKey
properties:
value: 1
version: atom.getVersion()
platform: navigator.platform
category: "Atom-#{atom.getVersion()}/#{pkg.name}-#{pkg.version}"
context:
app:
name: pkg.name
version: pkg.version
userAgent: navigator.userAgent
# identify the user
atom.config.observe @analyticsUserIdConfigKey, (userId) =>
@analytics.identify
userId: userId
@defaultEvent.userId = userId
# cache enabled and watch for changes
@enabled = atom.config.get @analyticsEnabledConfigKey
atom.config.onDidChange @analyticsEnabledConfigKey, ({newValue}) =>
@enabled = newValue
track: (message) ->
return if not @enabled
message = event: message if _.isString(message)
console.debug "tracking #{message.event}"
@analytics.track _.deepExtend(@defaultEvent, message)
trackActivate: ->
@track
event: 'Activate'
properties:
label: pkg.version
trackDeactivate: ->
@track
event: 'Deactivate'
properties:
label: pkg.version
error: (e) ->
@track
event: 'Error'
properties:
error: e
module.exports = Tracker
| true | # contants
analyticsWriteKey = 'PI:KEY:<KEY>END_PI'
# imports
_ = require 'underscore-plus'
{allowUnsafeEval} = require 'loophole'
# Analytics require a special import because of [Unsafe-Eval error](https://github.com/Glavin001/atom-beautify/commit/fbc58a648d3ccd845548d556f3dd1e046075bf04)
Analytics = null
allowUnsafeEval -> Analytics = require 'analytics-node'
# load package.json to include package info in analytics
pkg = require("../package.json")
class Tracker
constructor: (@analyticsUserIdConfigKey, @analyticsEnabledConfigKey) ->
# Setup Analytics
@analytics = new Analytics analyticsWriteKey
# set a unique identifier
if not atom.config.get @analyticsUserIdConfigKey
uuid = require 'node-uuid'
atom.config.set @analyticsUserIdConfigKey, uuid.v4()
# default event properties
@defaultEvent =
userId: atom.config.get @analyticsUserIdConfigKey
properties:
value: 1
version: atom.getVersion()
platform: navigator.platform
category: "Atom-#{atom.getVersion()}/#{pkg.name}-#{pkg.version}"
context:
app:
name: pkg.name
version: pkg.version
userAgent: navigator.userAgent
# identify the user
atom.config.observe @analyticsUserIdConfigKey, (userId) =>
@analytics.identify
userId: userId
@defaultEvent.userId = userId
# cache enabled and watch for changes
@enabled = atom.config.get @analyticsEnabledConfigKey
atom.config.onDidChange @analyticsEnabledConfigKey, ({newValue}) =>
@enabled = newValue
track: (message) ->
return if not @enabled
message = event: message if _.isString(message)
console.debug "tracking #{message.event}"
@analytics.track _.deepExtend(@defaultEvent, message)
trackActivate: ->
@track
event: 'Activate'
properties:
label: pkg.version
trackDeactivate: ->
@track
event: 'Deactivate'
properties:
label: pkg.version
error: (e) ->
@track
event: 'Error'
properties:
error: e
module.exports = Tracker
|
[
{
"context": "rapper around Node.js 'assert' module\n#\n# (C) 2011 Tristan Slominski\n#\nanode = require '../lib/anode'\nnodeassert = req",
"end": 95,
"score": 0.999571681022644,
"start": 78,
"tag": "NAME",
"value": "Tristan Slominski"
}
] | src/assert.coffee | tristanls/anodejs | 3 | #
# assert.coffee : anode wrapper around Node.js 'assert' module
#
# (C) 2011 Tristan Slominski
#
anode = require '../lib/anode'
nodeassert = require 'assert'
nodeutil = require 'util'
#
# helper function to make the assertion failures more meaningful by displaying which
# actor generated the failed assertion
#
processAssertionError = ( @cust, @msg, error ) ->
text = 'AssertionError'
if @cust
__name = if @cust.__name then @cust.__name + '::' else ''
text += ' in: [' + __name + @cust.__uid + ']'
if @msg
msgText = []
for element in @msg
do ( element ) ->
if element instanceof anode.Actor
__label = '['
if element.__name
__label += element.__name + '::'
__label += element.__uid + ']'
msgText.push __label
else
msgText.push element
text += ' on: ' + nodeutil.inspect msgText
console.error text
throw error
assert_beh = anode.beh
'cust, msg, #deepEqual, actual, expected, [message]' : ->
try
nodeassert.deepEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#deepEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #doesNotThrow, block, [error], [message]' : ->
try
nodeassert.doesNotThrow @block, @error, @message
if @cust # ack requested
@send( @, '#doesNotThrow' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #equal, actual, expected, [message]' : ->
try
nodeassert.equal @actual, @expected, @message
if @cust # ack requested
@send( @, '#equal' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #fail, actual, expected, message, operator' : ->
try
nodeassert.fail @actual, @expected, @message, @operator
catch error
processAssertionError @cust, @msg, error
'cust, msg, #ifError, value' : ->
try
nodeassert.ifError @value
if @cust # ack requested
@send( @, '#ifError' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #notDeepEqual, actual, expected, [message]' : ->
try
nodeassert.notDeepEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#notDeepEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #notStrictEqual, actual, expected, [message]' : ->
try
nodeassert.notStrictEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#notStrictEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #notEqual, actual, expected, [message]' : ->
try
nodeassert.notEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#notEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #ok, value, [message]' : ->
try
nodeassert.ok @value, @message
if @cust # ack requested
@send( @, '#ok' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #strictEqual, actual, expected, [message]' : ->
try
nodeassert.strictEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#strictEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #throws, block, [error], [message]' : ->
try
nodeassert.throws @block, @error, @message
if @cust # ack requested
@send( @, '#throws' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, value, message' : ->
try
nodeassert @value, @message
if @cust # ack requested
@send( @ ).to @cust
catch error
processAssertionError @cust, @msg, error
#
# export assert behavior
#
exports.assert_beh = assert_beh | 182498 | #
# assert.coffee : anode wrapper around Node.js 'assert' module
#
# (C) 2011 <NAME>
#
anode = require '../lib/anode'
nodeassert = require 'assert'
nodeutil = require 'util'
#
# helper function to make the assertion failures more meaningful by displaying which
# actor generated the failed assertion
#
processAssertionError = ( @cust, @msg, error ) ->
text = 'AssertionError'
if @cust
__name = if @cust.__name then @cust.__name + '::' else ''
text += ' in: [' + __name + @cust.__uid + ']'
if @msg
msgText = []
for element in @msg
do ( element ) ->
if element instanceof anode.Actor
__label = '['
if element.__name
__label += element.__name + '::'
__label += element.__uid + ']'
msgText.push __label
else
msgText.push element
text += ' on: ' + nodeutil.inspect msgText
console.error text
throw error
assert_beh = anode.beh
'cust, msg, #deepEqual, actual, expected, [message]' : ->
try
nodeassert.deepEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#deepEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #doesNotThrow, block, [error], [message]' : ->
try
nodeassert.doesNotThrow @block, @error, @message
if @cust # ack requested
@send( @, '#doesNotThrow' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #equal, actual, expected, [message]' : ->
try
nodeassert.equal @actual, @expected, @message
if @cust # ack requested
@send( @, '#equal' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #fail, actual, expected, message, operator' : ->
try
nodeassert.fail @actual, @expected, @message, @operator
catch error
processAssertionError @cust, @msg, error
'cust, msg, #ifError, value' : ->
try
nodeassert.ifError @value
if @cust # ack requested
@send( @, '#ifError' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #notDeepEqual, actual, expected, [message]' : ->
try
nodeassert.notDeepEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#notDeepEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #notStrictEqual, actual, expected, [message]' : ->
try
nodeassert.notStrictEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#notStrictEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #notEqual, actual, expected, [message]' : ->
try
nodeassert.notEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#notEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #ok, value, [message]' : ->
try
nodeassert.ok @value, @message
if @cust # ack requested
@send( @, '#ok' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #strictEqual, actual, expected, [message]' : ->
try
nodeassert.strictEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#strictEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #throws, block, [error], [message]' : ->
try
nodeassert.throws @block, @error, @message
if @cust # ack requested
@send( @, '#throws' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, value, message' : ->
try
nodeassert @value, @message
if @cust # ack requested
@send( @ ).to @cust
catch error
processAssertionError @cust, @msg, error
#
# export assert behavior
#
exports.assert_beh = assert_beh | true | #
# assert.coffee : anode wrapper around Node.js 'assert' module
#
# (C) 2011 PI:NAME:<NAME>END_PI
#
anode = require '../lib/anode'
nodeassert = require 'assert'
nodeutil = require 'util'
#
# helper function to make the assertion failures more meaningful by displaying which
# actor generated the failed assertion
#
processAssertionError = ( @cust, @msg, error ) ->
text = 'AssertionError'
if @cust
__name = if @cust.__name then @cust.__name + '::' else ''
text += ' in: [' + __name + @cust.__uid + ']'
if @msg
msgText = []
for element in @msg
do ( element ) ->
if element instanceof anode.Actor
__label = '['
if element.__name
__label += element.__name + '::'
__label += element.__uid + ']'
msgText.push __label
else
msgText.push element
text += ' on: ' + nodeutil.inspect msgText
console.error text
throw error
assert_beh = anode.beh
'cust, msg, #deepEqual, actual, expected, [message]' : ->
try
nodeassert.deepEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#deepEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #doesNotThrow, block, [error], [message]' : ->
try
nodeassert.doesNotThrow @block, @error, @message
if @cust # ack requested
@send( @, '#doesNotThrow' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #equal, actual, expected, [message]' : ->
try
nodeassert.equal @actual, @expected, @message
if @cust # ack requested
@send( @, '#equal' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #fail, actual, expected, message, operator' : ->
try
nodeassert.fail @actual, @expected, @message, @operator
catch error
processAssertionError @cust, @msg, error
'cust, msg, #ifError, value' : ->
try
nodeassert.ifError @value
if @cust # ack requested
@send( @, '#ifError' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #notDeepEqual, actual, expected, [message]' : ->
try
nodeassert.notDeepEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#notDeepEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #notStrictEqual, actual, expected, [message]' : ->
try
nodeassert.notStrictEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#notStrictEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #notEqual, actual, expected, [message]' : ->
try
nodeassert.notEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#notEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #ok, value, [message]' : ->
try
nodeassert.ok @value, @message
if @cust # ack requested
@send( @, '#ok' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #strictEqual, actual, expected, [message]' : ->
try
nodeassert.strictEqual @actual, @expected, @message
if @cust # ack requested
@send( @, '#strictEqual' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, #throws, block, [error], [message]' : ->
try
nodeassert.throws @block, @error, @message
if @cust # ack requested
@send( @, '#throws' ).to @cust
catch error
processAssertionError @cust, @msg, error
'cust, msg, value, message' : ->
try
nodeassert @value, @message
if @cust # ack requested
@send( @ ).to @cust
catch error
processAssertionError @cust, @msg, error
#
# export assert behavior
#
exports.assert_beh = assert_beh |
[
{
"context": "a: [\n id: 1\n age: 30\n name: \"Alf\"\n comment: null\n ,\n id: 2\n ",
"end": 571,
"score": 0.9990970492362976,
"start": 568,
"tag": "NAME",
"value": "Alf"
},
{
"context": "omment: null\n ,\n id: 2\n name: \... | test/mocha/mysql_object.coffee | alinex/node-database | 0 | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
async = require 'async'
database = require '../../src/index'
util= require 'alinex-util'
describe "Mysql object", ->
Driver = require '../../src/driver/mysql'
object2sql = require '../../src/object2sql'
driver = new Driver 'mocha',
server:
type: 'mysql'
example =
person:
struct:
id: 'INT AUTO_INCREMENT PRIMARY KEY'
name: 'VARCHAR(10)'
age: 'INT'
comment: 'VARCHAR(32)'
data: [
id: 1
age: 30
name: "Alf"
comment: null
,
id: 2
name: "Egon"
age: 35
comment: null
]
address:
struct:
id: 'INT AUTO_INCREMENT PRIMARY KEY'
person_id: 'INT'
city: 'VARCHAR(20)'
data: [
id: 1
person_id: 1
city: 'Munich'
,
id: 2
person_id: 1
city: 'New York'
]
before (done) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
queries = []
for table in Object.keys example
fields = Object.keys(example[table].struct).map (e) -> "#{e} #{example[table].struct[e]}"
.join ', '
queries.push "CREATE TABLE #{table} (#{fields})"
for e in example[table].data
queries.push "INSERT INTO #{table} SET " + (
Object.keys(e).map (k) ->
"#{k} = " + switch
when not e[k]?
'NULL'
when typeof e[k] is 'number'
e[k]
else
"'#{e[k]}'"
.join ', '
)
async.eachSeries queries, (sql, cb) ->
db.exec sql, cb
, (err) ->
expect(err, 'error on init data').to.not.exist
db.close done
after (done) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
async.eachSeries Object.keys(example), (table, cb) ->
db.exec "DROP TABLE IF EXISTS #{table}", cb
, (err) ->
expect(err, 'error after drop').to.not.exist
db.close done
list = (obj, data, sql, check, cb) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
expect(object2sql(obj, db), 'sql').to.equal sql
db.list obj, data, (err, res) ->
expect(err, 'server error').to.not.exist
expect(res, 'result').to.deep.equal check
cb()
record = (obj, data, sql, check, cb) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
expect(object2sql(obj, db), 'sql').to.equal sql
db.record obj, data, (err, res) ->
expect(err, 'server error').to.not.exist
expect(res, 'result').to.deep.equal check
cb()
value = (obj, data, sql, check, cb) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
expect(object2sql(obj, db), 'sql').to.equal sql
db.value obj, data, (err, res) ->
expect(err, 'server error').to.not.exist
expect(res, 'result').to.deep.equal check
cb()
describe "SELECT", ->
it "should get all fields", (cb) ->
list
select: '*'
from: '@person'
, null
, "SELECT * FROM `person`;"
, example.person.data
, cb
it "should get all fields from table", (cb) ->
list
select: '@person.*'
from: '@person'
, null
, "SELECT `person`.* FROM `person`;"
, example.person.data
, cb
it "should get multiple fields", (cb) ->
list
select: ['@name', '@age']
from: '@person'
, null
, "SELECT `name`, `age` FROM `person`;"
, example.person.data.map((e) ->
n = {}
for k, v of e
n[k] = v if k in ['name', 'age']
n
)
, cb
it "should get fields with alias", (cb) ->
list
select:
Name: '@name'
Age: '@age'
from: '@person'
, null
, "SELECT `name` AS `Name`, `age` AS `Age` FROM `person`;"
, example.person.data.map((e) ->
n = {}
for k, v of e
n[util.string.ucFirst k] = v if k in ['name', 'age']
n
)
, cb
it "should read multiple tables", (cb) ->
list
select: '*'
from: ['@person', '@address']
, null
, "SELECT * FROM `person`, `address`;"
, (
->
n = []
for a in example.address.data
for p in example.person.data
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
n
)()
, cb
it "should allow table alias", (cb) ->
list
select: '*'
from:
p: '@person'
a: '@address'
, null
, "SELECT * FROM `person` AS `p`, `address` AS `a`;"
, (
->
n = []
for a in example.address.data
for p in example.person.data
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
n
)()
, cb
describe "DISTINCT", ->
it "should get distinct records", (cb) ->
list
select: '@person_id'
distinct: true
from: '@address'
, null
, "SELECT DISTINCT `person_id` FROM `address`;"
, util.array.unique(
example.address.data.map((e) -> e.person_id)
).map((e) -> return {person_id: e})
, cb
describe "functions", ->
it "should support count", (cb) ->
list
select:
$count: '*'
from: '@person'
, null
, "SELECT COUNT(*) FROM `person`;"
, [
'COUNT(*)': example.person.data.length
]
, cb
it "should support count as named", (cb) ->
list
select:
sum:
$count: '*'
from: '@person'
, null
, "SELECT COUNT(*) AS `sum` FROM `person`;"
, [
'sum': example.person.data.length
]
, cb
it "should support eq operator", (cb) ->
list
select:
ok:
age:
$eq: 30
from: '@person'
, null
, "SELECT `age` = 30 AS `ok` FROM `person`;"
, example.person.data.map((e) -> {ok: if e.age is 30 then 1 else 0})
, cb
describe "FROM", ->
it "should use one table", (cb) ->
list
select: '*'
from: '@person'
, null
, "SELECT * FROM `person`;"
, example.person.data
, cb
it "should use multiple tables", (cb) ->
list
select: '*'
from: ['@person', '@address']
, null
, "SELECT * FROM `person`, `address`;"
, (
->
n = []
for a in example.address.data
for p in example.person.data
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
n
)()
, cb
it "should support alias", (cb) ->
list
select: '*'
from:
Person: '@person'
, null
, "SELECT * FROM `person` AS `Person`;"
, example.person.data
, cb
it "should support left join", (cb) ->
list
select: '*'
from:
Person: '@person'
Address:
address:
join: 'left' # left, right, outer, inner
on: # join criteria
person_id: '@Person.id'
, null
, "SELECT * FROM `person` AS `Person` LEFT JOIN `address` AS `Address`
ON `Address`.`person_id` = `Person`.`id`;"
, (
->
n = []
for p in example.person.data
found = false
for a in example.address.data
continue unless a.person_id is p.id
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
found = true
unless found
o = util.clone p
o.comment ?= null # add because missing else
for k of example.address.struct
o[k] = null # add because missing else
n.push o
n
)()
, cb
it "should support join in array", (cb) ->
list
select: '*'
from: [
Person: '@person'
,
Address:
address:
join: 'left' # left, right, outer, inner
on: # join criteria
person_id: '@Person.id'
]
, null
, "SELECT * FROM `person` AS `Person` LEFT JOIN `address` AS `Address` ON `Address`.`person_id` = `Person`.`id`;"
, (
->
n = []
for p in example.person.data
found = false
for a in example.address.data
continue unless a.person_id is p.id
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
found = true
unless found
o = util.clone p
o.comment ?= null # add because missing else
for k of example.address.struct
o[k] = null # add because missing else
n.push o
n
)()
, cb
describe "WHILE", ->
it "should allow conditions", (cb) ->
list
select: '*'
from: '@person'
where:
age: 30
, null
, "SELECT * FROM `person` WHERE `age` = 30;"
, example.person.data.filter((e) -> e.age is 30)
, cb
describe "placeholder", ->
| 75824 | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
async = require 'async'
database = require '../../src/index'
util= require 'alinex-util'
describe "Mysql object", ->
Driver = require '../../src/driver/mysql'
object2sql = require '../../src/object2sql'
driver = new Driver 'mocha',
server:
type: 'mysql'
example =
person:
struct:
id: 'INT AUTO_INCREMENT PRIMARY KEY'
name: 'VARCHAR(10)'
age: 'INT'
comment: 'VARCHAR(32)'
data: [
id: 1
age: 30
name: "<NAME>"
comment: null
,
id: 2
name: "<NAME>"
age: 35
comment: null
]
address:
struct:
id: 'INT AUTO_INCREMENT PRIMARY KEY'
person_id: 'INT'
city: 'VARCHAR(20)'
data: [
id: 1
person_id: 1
city: 'Munich'
,
id: 2
person_id: 1
city: 'New York'
]
before (done) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
queries = []
for table in Object.keys example
fields = Object.keys(example[table].struct).map (e) -> "#{e} #{example[table].struct[e]}"
.join ', '
queries.push "CREATE TABLE #{table} (#{fields})"
for e in example[table].data
queries.push "INSERT INTO #{table} SET " + (
Object.keys(e).map (k) ->
"#{k} = " + switch
when not e[k]?
'NULL'
when typeof e[k] is 'number'
e[k]
else
"'#{e[k]}'"
.join ', '
)
async.eachSeries queries, (sql, cb) ->
db.exec sql, cb
, (err) ->
expect(err, 'error on init data').to.not.exist
db.close done
after (done) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
async.eachSeries Object.keys(example), (table, cb) ->
db.exec "DROP TABLE IF EXISTS #{table}", cb
, (err) ->
expect(err, 'error after drop').to.not.exist
db.close done
list = (obj, data, sql, check, cb) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
expect(object2sql(obj, db), 'sql').to.equal sql
db.list obj, data, (err, res) ->
expect(err, 'server error').to.not.exist
expect(res, 'result').to.deep.equal check
cb()
record = (obj, data, sql, check, cb) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
expect(object2sql(obj, db), 'sql').to.equal sql
db.record obj, data, (err, res) ->
expect(err, 'server error').to.not.exist
expect(res, 'result').to.deep.equal check
cb()
value = (obj, data, sql, check, cb) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
expect(object2sql(obj, db), 'sql').to.equal sql
db.value obj, data, (err, res) ->
expect(err, 'server error').to.not.exist
expect(res, 'result').to.deep.equal check
cb()
describe "SELECT", ->
it "should get all fields", (cb) ->
list
select: '*'
from: '@person'
, null
, "SELECT * FROM `person`;"
, example.person.data
, cb
it "should get all fields from table", (cb) ->
list
select: '@person.*'
from: '@person'
, null
, "SELECT `person`.* FROM `person`;"
, example.person.data
, cb
it "should get multiple fields", (cb) ->
list
select: ['@name', '@age']
from: '@person'
, null
, "SELECT `name`, `age` FROM `person`;"
, example.person.data.map((e) ->
n = {}
for k, v of e
n[k] = v if k in ['name', 'age']
n
)
, cb
it "should get fields with alias", (cb) ->
list
select:
Name: '@name'
Age: '@age'
from: '@person'
, null
, "SELECT `name` AS `Name`, `age` AS `Age` FROM `person`;"
, example.person.data.map((e) ->
n = {}
for k, v of e
n[util.string.ucFirst k] = v if k in ['name', 'age']
n
)
, cb
it "should read multiple tables", (cb) ->
list
select: '*'
from: ['@person', '@address']
, null
, "SELECT * FROM `person`, `address`;"
, (
->
n = []
for a in example.address.data
for p in example.person.data
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
n
)()
, cb
it "should allow table alias", (cb) ->
list
select: '*'
from:
p: '@person'
a: '@address'
, null
, "SELECT * FROM `person` AS `p`, `address` AS `a`;"
, (
->
n = []
for a in example.address.data
for p in example.person.data
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
n
)()
, cb
describe "DISTINCT", ->
it "should get distinct records", (cb) ->
list
select: '@person_id'
distinct: true
from: '@address'
, null
, "SELECT DISTINCT `person_id` FROM `address`;"
, util.array.unique(
example.address.data.map((e) -> e.person_id)
).map((e) -> return {person_id: e})
, cb
describe "functions", ->
it "should support count", (cb) ->
list
select:
$count: '*'
from: '@person'
, null
, "SELECT COUNT(*) FROM `person`;"
, [
'COUNT(*)': example.person.data.length
]
, cb
it "should support count as named", (cb) ->
list
select:
sum:
$count: '*'
from: '@person'
, null
, "SELECT COUNT(*) AS `sum` FROM `person`;"
, [
'sum': example.person.data.length
]
, cb
it "should support eq operator", (cb) ->
list
select:
ok:
age:
$eq: 30
from: '@person'
, null
, "SELECT `age` = 30 AS `ok` FROM `person`;"
, example.person.data.map((e) -> {ok: if e.age is 30 then 1 else 0})
, cb
describe "FROM", ->
it "should use one table", (cb) ->
list
select: '*'
from: '@person'
, null
, "SELECT * FROM `person`;"
, example.person.data
, cb
it "should use multiple tables", (cb) ->
list
select: '*'
from: ['@person', '@address']
, null
, "SELECT * FROM `person`, `address`;"
, (
->
n = []
for a in example.address.data
for p in example.person.data
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
n
)()
, cb
it "should support alias", (cb) ->
list
select: '*'
from:
Person: '@person'
, null
, "SELECT * FROM `person` AS `Person`;"
, example.person.data
, cb
it "should support left join", (cb) ->
list
select: '*'
from:
Person: '@person'
Address:
address:
join: 'left' # left, right, outer, inner
on: # join criteria
person_id: '@Person.id'
, null
, "SELECT * FROM `person` AS `Person` LEFT JOIN `address` AS `Address`
ON `Address`.`person_id` = `Person`.`id`;"
, (
->
n = []
for p in example.person.data
found = false
for a in example.address.data
continue unless a.person_id is p.id
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
found = true
unless found
o = util.clone p
o.comment ?= null # add because missing else
for k of example.address.struct
o[k] = null # add because missing else
n.push o
n
)()
, cb
it "should support join in array", (cb) ->
list
select: '*'
from: [
Person: '@person'
,
Address:
address:
join: 'left' # left, right, outer, inner
on: # join criteria
person_id: '@Person.id'
]
, null
, "SELECT * FROM `person` AS `Person` LEFT JOIN `address` AS `Address` ON `Address`.`person_id` = `Person`.`id`;"
, (
->
n = []
for p in example.person.data
found = false
for a in example.address.data
continue unless a.person_id is p.id
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
found = true
unless found
o = util.clone p
o.comment ?= null # add because missing else
for k of example.address.struct
o[k] = null # add because missing else
n.push o
n
)()
, cb
describe "WHILE", ->
it "should allow conditions", (cb) ->
list
select: '*'
from: '@person'
where:
age: 30
, null
, "SELECT * FROM `person` WHERE `age` = 30;"
, example.person.data.filter((e) -> e.age is 30)
, cb
describe "placeholder", ->
| true | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
async = require 'async'
database = require '../../src/index'
util= require 'alinex-util'
describe "Mysql object", ->
Driver = require '../../src/driver/mysql'
object2sql = require '../../src/object2sql'
driver = new Driver 'mocha',
server:
type: 'mysql'
example =
person:
struct:
id: 'INT AUTO_INCREMENT PRIMARY KEY'
name: 'VARCHAR(10)'
age: 'INT'
comment: 'VARCHAR(32)'
data: [
id: 1
age: 30
name: "PI:NAME:<NAME>END_PI"
comment: null
,
id: 2
name: "PI:NAME:<NAME>END_PI"
age: 35
comment: null
]
address:
struct:
id: 'INT AUTO_INCREMENT PRIMARY KEY'
person_id: 'INT'
city: 'VARCHAR(20)'
data: [
id: 1
person_id: 1
city: 'Munich'
,
id: 2
person_id: 1
city: 'New York'
]
before (done) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
queries = []
for table in Object.keys example
fields = Object.keys(example[table].struct).map (e) -> "#{e} #{example[table].struct[e]}"
.join ', '
queries.push "CREATE TABLE #{table} (#{fields})"
for e in example[table].data
queries.push "INSERT INTO #{table} SET " + (
Object.keys(e).map (k) ->
"#{k} = " + switch
when not e[k]?
'NULL'
when typeof e[k] is 'number'
e[k]
else
"'#{e[k]}'"
.join ', '
)
async.eachSeries queries, (sql, cb) ->
db.exec sql, cb
, (err) ->
expect(err, 'error on init data').to.not.exist
db.close done
after (done) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
async.eachSeries Object.keys(example), (table, cb) ->
db.exec "DROP TABLE IF EXISTS #{table}", cb
, (err) ->
expect(err, 'error after drop').to.not.exist
db.close done
list = (obj, data, sql, check, cb) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
expect(object2sql(obj, db), 'sql').to.equal sql
db.list obj, data, (err, res) ->
expect(err, 'server error').to.not.exist
expect(res, 'result').to.deep.equal check
cb()
record = (obj, data, sql, check, cb) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
expect(object2sql(obj, db), 'sql').to.equal sql
db.record obj, data, (err, res) ->
expect(err, 'server error').to.not.exist
expect(res, 'result').to.deep.equal check
cb()
value = (obj, data, sql, check, cb) ->
database.instance 'test-mysql', (err, db) ->
throw err if err
expect(object2sql(obj, db), 'sql').to.equal sql
db.value obj, data, (err, res) ->
expect(err, 'server error').to.not.exist
expect(res, 'result').to.deep.equal check
cb()
describe "SELECT", ->
it "should get all fields", (cb) ->
list
select: '*'
from: '@person'
, null
, "SELECT * FROM `person`;"
, example.person.data
, cb
it "should get all fields from table", (cb) ->
list
select: '@person.*'
from: '@person'
, null
, "SELECT `person`.* FROM `person`;"
, example.person.data
, cb
it "should get multiple fields", (cb) ->
list
select: ['@name', '@age']
from: '@person'
, null
, "SELECT `name`, `age` FROM `person`;"
, example.person.data.map((e) ->
n = {}
for k, v of e
n[k] = v if k in ['name', 'age']
n
)
, cb
it "should get fields with alias", (cb) ->
list
select:
Name: '@name'
Age: '@age'
from: '@person'
, null
, "SELECT `name` AS `Name`, `age` AS `Age` FROM `person`;"
, example.person.data.map((e) ->
n = {}
for k, v of e
n[util.string.ucFirst k] = v if k in ['name', 'age']
n
)
, cb
it "should read multiple tables", (cb) ->
list
select: '*'
from: ['@person', '@address']
, null
, "SELECT * FROM `person`, `address`;"
, (
->
n = []
for a in example.address.data
for p in example.person.data
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
n
)()
, cb
it "should allow table alias", (cb) ->
list
select: '*'
from:
p: '@person'
a: '@address'
, null
, "SELECT * FROM `person` AS `p`, `address` AS `a`;"
, (
->
n = []
for a in example.address.data
for p in example.person.data
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
n
)()
, cb
describe "DISTINCT", ->
it "should get distinct records", (cb) ->
list
select: '@person_id'
distinct: true
from: '@address'
, null
, "SELECT DISTINCT `person_id` FROM `address`;"
, util.array.unique(
example.address.data.map((e) -> e.person_id)
).map((e) -> return {person_id: e})
, cb
describe "functions", ->
it "should support count", (cb) ->
list
select:
$count: '*'
from: '@person'
, null
, "SELECT COUNT(*) FROM `person`;"
, [
'COUNT(*)': example.person.data.length
]
, cb
it "should support count as named", (cb) ->
list
select:
sum:
$count: '*'
from: '@person'
, null
, "SELECT COUNT(*) AS `sum` FROM `person`;"
, [
'sum': example.person.data.length
]
, cb
it "should support eq operator", (cb) ->
list
select:
ok:
age:
$eq: 30
from: '@person'
, null
, "SELECT `age` = 30 AS `ok` FROM `person`;"
, example.person.data.map((e) -> {ok: if e.age is 30 then 1 else 0})
, cb
describe "FROM", ->
it "should use one table", (cb) ->
list
select: '*'
from: '@person'
, null
, "SELECT * FROM `person`;"
, example.person.data
, cb
it "should use multiple tables", (cb) ->
list
select: '*'
from: ['@person', '@address']
, null
, "SELECT * FROM `person`, `address`;"
, (
->
n = []
for a in example.address.data
for p in example.person.data
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
n
)()
, cb
it "should support alias", (cb) ->
list
select: '*'
from:
Person: '@person'
, null
, "SELECT * FROM `person` AS `Person`;"
, example.person.data
, cb
it "should support left join", (cb) ->
list
select: '*'
from:
Person: '@person'
Address:
address:
join: 'left' # left, right, outer, inner
on: # join criteria
person_id: '@Person.id'
, null
, "SELECT * FROM `person` AS `Person` LEFT JOIN `address` AS `Address`
ON `Address`.`person_id` = `Person`.`id`;"
, (
->
n = []
for p in example.person.data
found = false
for a in example.address.data
continue unless a.person_id is p.id
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
found = true
unless found
o = util.clone p
o.comment ?= null # add because missing else
for k of example.address.struct
o[k] = null # add because missing else
n.push o
n
)()
, cb
it "should support join in array", (cb) ->
list
select: '*'
from: [
Person: '@person'
,
Address:
address:
join: 'left' # left, right, outer, inner
on: # join criteria
person_id: '@Person.id'
]
, null
, "SELECT * FROM `person` AS `Person` LEFT JOIN `address` AS `Address` ON `Address`.`person_id` = `Person`.`id`;"
, (
->
n = []
for p in example.person.data
found = false
for a in example.address.data
continue unless a.person_id is p.id
o = util.extend 'MODE CLONE', p, a
o.comment ?= null # add because missing else
n.push o
found = true
unless found
o = util.clone p
o.comment ?= null # add because missing else
for k of example.address.struct
o[k] = null # add because missing else
n.push o
n
)()
, cb
describe "WHILE", ->
it "should allow conditions", (cb) ->
list
select: '*'
from: '@person'
where:
age: 30
, null
, "SELECT * FROM `person` WHERE `age` = 30;"
, example.person.data.filter((e) -> e.age is 30)
, cb
describe "placeholder", ->
|
[
{
"context": "# Hello! I am Paws! Come read about me, and find out how I work.\n#\n#",
"end": 18,
"score": 0.9943361282348633,
"start": 14,
"tag": "NAME",
"value": "Paws"
}
] | code/Paws/Source/Paws.coffee | mitchellurgero/illacceptanything | 1 | # Hello! I am Paws! Come read about me, and find out how I work.
#
# ,d88b.d88b,
# 88888888888
# `Y8888888Y'
# `Y888Y'
# `Y'
process.title = 'paws.js'
Paws = require './data.coffee'
Paws.utilities = require './utilities.coffee'
Paws.parse = require './parser.coffee'
Paws.reactor = require './reactor.coffee'
Paws.primitives = (bag)->
require("./primitives/#{bag}.coffee")()
Paws.generateRoot = (code = '')->
code = Paws.parse Paws.parse.prepare code if typeof code == 'string'
code = new Execution code
code.locals.inject Paws.primitives 'infrastructure'
code.locals.inject Paws.primitives 'implementation'
return code
Paws.start =
Paws.js = (code)->
root = Paws.generateRoot code
here = new Paws.reactor.Unit
here.stage root
here.start()
Paws.infect = (globals)-> @utilities.infect globals, this
module.exports = Paws
| 111976 | # Hello! I am <NAME>! Come read about me, and find out how I work.
#
# ,d88b.d88b,
# 88888888888
# `Y8888888Y'
# `Y888Y'
# `Y'
process.title = 'paws.js'
Paws = require './data.coffee'
Paws.utilities = require './utilities.coffee'
Paws.parse = require './parser.coffee'
Paws.reactor = require './reactor.coffee'
Paws.primitives = (bag)->
require("./primitives/#{bag}.coffee")()
Paws.generateRoot = (code = '')->
code = Paws.parse Paws.parse.prepare code if typeof code == 'string'
code = new Execution code
code.locals.inject Paws.primitives 'infrastructure'
code.locals.inject Paws.primitives 'implementation'
return code
Paws.start =
Paws.js = (code)->
root = Paws.generateRoot code
here = new Paws.reactor.Unit
here.stage root
here.start()
Paws.infect = (globals)-> @utilities.infect globals, this
module.exports = Paws
| true | # Hello! I am PI:NAME:<NAME>END_PI! Come read about me, and find out how I work.
#
# ,d88b.d88b,
# 88888888888
# `Y8888888Y'
# `Y888Y'
# `Y'
process.title = 'paws.js'
Paws = require './data.coffee'
Paws.utilities = require './utilities.coffee'
Paws.parse = require './parser.coffee'
Paws.reactor = require './reactor.coffee'
Paws.primitives = (bag)->
require("./primitives/#{bag}.coffee")()
Paws.generateRoot = (code = '')->
code = Paws.parse Paws.parse.prepare code if typeof code == 'string'
code = new Execution code
code.locals.inject Paws.primitives 'infrastructure'
code.locals.inject Paws.primitives 'implementation'
return code
Paws.start =
Paws.js = (code)->
root = Paws.generateRoot code
here = new Paws.reactor.Unit
here.stage root
here.start()
Paws.infect = (globals)-> @utilities.infect globals, this
module.exports = Paws
|
[
{
"context": "an be fed directly into [Jison](http://github.com/zaach/jison). These\n# are read by jison in the `parser",
"end": 434,
"score": 0.9989122152328491,
"start": 429,
"tag": "USERNAME",
"value": "zaach"
},
{
"context": "ndent\n @pair 'OUTDENT'\n @token 'OUTDE... | src/lexer.coffee | charlieflowers/coffee-script | 0 | # The CoffeeScript Lexer. Uses a series of token-matching regexes to attempt
# matches against the beginning of the source code. When a match is found,
# a token is produced, we consume the match, and start again. Tokens are in the
# form:
#
# [tag, value, locationData]
#
# where locationData is {first_line, first_column, last_line, last_column}, which is a
# format that can be fed directly into [Jison](http://github.com/zaach/jison). These
# are read by jison in the `parser.lexer` function defined in coffee-script.coffee.
{Rewriter, INVERSES} = require './rewriter'
# Import the helpers we need.
{count, starts, compact, last, repeat, invertLiterate,
locationDataToString, throwSyntaxError} = require './helpers'
# The Lexer Class
# ---------------
# The Lexer class reads a stream of CoffeeScript and divvies it up into tagged
# tokens. Some potential ambiguity in the grammar has been avoided by
# pushing some extra smarts into the Lexer.
exports.Lexer = class Lexer
# **tokenize** is the Lexer's main method. Scan by attempting to match tokens
# one at a time, using a regular expression anchored at the start of the
# remaining code, or a custom recursive token-matching method
# (for interpolations). When the next token has been recorded, we move forward
# within the code past the token, and begin again.
#
# Each tokenizing method is responsible for returning the number of characters
# it has consumed.
#
# Before returning the token stream, run it through the [Rewriter](rewriter.html)
# unless explicitly asked not to.
tokenize: (code, opts = {}) ->
@literate = opts.literate # Are we lexing literate CoffeeScript?
@indent = 0 # The current indentation level.
@baseIndent = 0 # The overall minimum indentation level
@indebt = 0 # The over-indentation at the current level.
@outdebt = 0 # The under-outdentation at the current level.
@indents = [] # The stack of all current indentation levels.
@ends = [] # The stack for pairing up tokens.
@tokens = [] # Stream of parsed tokens in the form `['TYPE', value, location data]`.
@chunkLine =
opts.line or 0 # The start line for the current @chunk.
@chunkColumn =
opts.column or 0 # The start column of the current @chunk.
code = @clean code # The stripped, cleaned original source code.
# At every position, run through this list of attempted matches,
# short-circuiting if any of them succeed. Their order determines precedence:
# `@literalToken` is the fallback catch-all.
i = 0
while @chunk = code[i..]
consumed = \
@identifierToken() or
@commentToken() or
@whitespaceToken() or
@lineToken() or
@heredocToken() or
@stringToken() or
@numberToken() or
@regexToken() or
@jsToken() or
@literalToken()
# Update position
[@chunkLine, @chunkColumn] = @getLineAndColumnFromChunk consumed
i += consumed
@closeIndentation()
@error "missing #{tag}" if tag = @ends.pop()
return @tokens if opts.rewrite is off
(new Rewriter).rewrite @tokens
# Preprocess the code to remove leading and trailing whitespace, carriage
# returns, etc. If we're lexing literate CoffeeScript, strip external Markdown
# by removing all lines that aren't indented by at least four spaces or a tab.
clean: (code) ->
code = code.slice(1) if code.charCodeAt(0) is BOM
code = code.replace(/\r/g, '').replace TRAILING_SPACES, ''
if WHITESPACE.test code
code = "\n#{code}"
@chunkLine--
code = invertLiterate code if @literate
code
# Tokenizers
# ----------
# Matches identifying literals: variables, keywords, method names, etc.
# Check to ensure that JavaScript reserved words aren't being used as
# identifiers. Because CoffeeScript reserves a handful of keywords that are
# allowed in JavaScript, we're careful not to tag them as keywords when
# referenced as property names here, so you can still do `jQuery.is()` even
# though `is` means `===` otherwise.
identifierToken: ->
return 0 unless match = IDENTIFIER.exec @chunk
[input, id, colon] = match
# Preserve length of id for location data
idLength = id.length
poppedToken = undefined
# This if handles "for own key, value of myObject", loop over keys and values of obj, ignoring proptotype
# If previous token's tag was 'FOR' and this is 'OWN', then make a token called 'OWN'
if id is 'own' and @tag() is 'FOR'
@token 'OWN', id
return id.length
# colon will be truthy if the identifier ended in a single colon, which is
# how you define object members in object literal (json) format.
# In that case, we set "forcedIdentifier" to true. It means, "damn it, this is an identifier, I'm sure of it."
# But forcedIdentifier can ALSO be true if the previous token was ".", "?.", :: or ?::
# OR, it can be true if the previos token was NOT SPACED and it is "@". All that makes sense.
forcedIdentifier = colon or
(prev = last @tokens) and (prev[0] in ['.', '?.', '::', '?::'] or
not prev.spaced and prev[0] is '@') # if the previous token was "@" and there is no space between(?)
tag = 'IDENTIFIER'
# only do this if it is nOT forcedIdentifier. See if the identifier is in JS_KEYWORDS or COFFEE_KEYWORDS
if not forcedIdentifier and (id in JS_KEYWORDS or id in COFFEE_KEYWORDS)
tag = id.toUpperCase()
# if we're using WHEN, and the previous tag was LINE_BREAK, then this is a LEADING_WHEN token.
if tag is 'WHEN' and @tag() in LINE_BREAK
tag = 'LEADING_WHEN'
else if tag is 'FOR' # just make a note we've seen FOR. in a CLASS VAR, so it outlives this stack frame.
@seenFor = yes
else if tag is 'UNLESS' # UNLESS is turned into an IF token
tag = 'IF'
else if tag in UNARY # meaning, tag is "~" or "!
tag = 'UNARY'
else if tag in RELATION # meaning, IN, OF, or INSTANCEOF
if tag isnt 'INSTANCEOF' and @seenFor
# tag could be "FORIN" or "FOROF" ()
# but note, @seenFor is a CLASS variable. So we're REMEMBERING that context across many tokens. So, FOR ... IN and FOR ... OF
# Yech, i hate the way that's handled.
tag = 'FOR' + tag
@seenFor = no
else
# here, it could be IN, OF, or INSTANCEOF, and @seenFor was not true.
tag = 'RELATION' # so all uses of IN, OF and INSTANCEOF outside of FOR are considered RELATIONS.
# @value() is another function for peeking at the previous token, but it gets the VALUE of that token. So it the value
# was "!", pop that token off! Change our ID to "!IN", "!FOR" or "!INSTANCEOF" (note, that's our VALUE, not our TAG)
# so he is merely consolidating the 2 tags into one.
if @value() is '!'
poppedToken = @tokens.pop()
id = '!' + id
# if id is one of the js or cs reserved words (and a few others), but forcedIndentifier is true, label it an an identifier.
# otherwise, if it is RESERVED, error out.
if id in JS_FORBIDDEN
if forcedIdentifier
tag = 'IDENTIFIER'
id = new String id
id.reserved = yes
else if id in RESERVED
# you can get here if forcedIdentifier is NOT TRUE, and the id is in RESERVED.
@error "reserved word \"#{id}\""
# if forcedIdentifier is FALSE, and the id IS in JS_FORBIDDEN, but NOT in RESERVED, you'll keep going. Those possibilities
# are: JS_KEYWORDS and STRICT_PROSCRIBED, so things like "true, false, typeof" or "eval, arguments"
# continuing with the case above, if you are using one of the reserved words, and forcedIdentifier is false, go inside this block
# but also, of course, if you're not even using a reserved work and forcedIdentifier is false.
unless forcedIdentifier
# change id to the coffee alias (resolve the coffee alias) if it is one of those
id = COFFEE_ALIAS_MAP[id] if id in COFFEE_ALIASES
# handle these cases here because they were created by alias resolution!
tag = switch id
when '!' then 'UNARY'
when '==', '!=' then 'COMPARE'
when '&&', '||' then 'LOGIC'
when 'true', 'false' then 'BOOL'
when 'break', 'continue' then 'STATEMENT'
else tag
# now, we make a token using the tag we have chosen.
tagToken = @token tag, id, 0, idLength
if poppedToken
# if he previously consolidated 2 tokens, lets correct the location data to encompass the span of both of them
[tagToken[2].first_line, tagToken[2].first_column] =
[poppedToken[2].first_line, poppedToken[2].first_column]
if colon
colonOffset = input.lastIndexOf ':'
@token ':', ':', colonOffset, colon.length # The colon token is a *separate* token! ok, but it fucks up my mental model.
# As always, we return the length
input.length
# Matches numbers, including decimals, hex, and exponential notation.
# Be careful not to interfere with ranges-in-progress.
numberToken: ->
return 0 unless match = NUMBER.exec @chunk
number = match[0]
if /^0[BOX]/.test number
@error "radix prefix '#{number}' must be lowercase"
else if /E/.test(number) and not /^0x/.test number
@error "exponential notation '#{number}' must be indicated with a lowercase 'e'"
else if /^0\d*[89]/.test number
@error "decimal literal '#{number}' must not be prefixed with '0'"
else if /^0\d+/.test number
@error "octal literal '#{number}' must be prefixed with '0o'"
lexedLength = number.length
if octalLiteral = /^0o([0-7]+)/.exec number
number = '0x' + parseInt(octalLiteral[1], 8).toString 16
if binaryLiteral = /^0b([01]+)/.exec number
number = '0x' + parseInt(binaryLiteral[1], 2).toString 16
@token 'NUMBER', number, 0, lexedLength
lexedLength
# Matches strings, including multi-line strings. Ensures that quotation marks
# are balanced within the string's contents, and within nested interpolations.
stringToken: ->
switch quote = @chunk.charAt 0
# when 1st char is single quote, match SIMPLESTR.
# The [string] = syntax uses destructuring. It means, expect the rhs to be an
# array of 1 item, and set string to that one item. If the regex match returns
# undefined, then default to an empty array, meaning string will be undefined.
when "'" then [string] = SIMPLESTR.exec(@chunk) || []
# when the first char is double quotes, call @balancedString on the chunk,
# passing in a double quote.
#
# The interesting thing here is that he supports strings within interpolated strings within interpolated strings, ad infinitum, as long as things are balanced. I need to see an example of that.
#
when '"' then string = @balancedString @chunk, '"'
return 0 unless string
trimmed = @removeNewlines string[1...-1]
if quote is '"' and 0 < string.indexOf '#{', 1
@interpolateString trimmed, strOffset: 1, lexedLength: string.length
else
@token 'STRING', quote + @escapeLines(trimmed) + quote, 0, string.length
if octalEsc = /^(?:\\.|[^\\])*\\(?:0[0-7]|[1-7])/.test string
@error "octal escape sequences #{string} are not allowed"
string.length
# Matches heredocs, adjusting indentation to the correct level, as heredocs
# preserve whitespace, but ignore indentation to the left.
heredocToken: ->
return 0 unless match = HEREDOC.exec @chunk
heredoc = match[0]
quote = heredoc.charAt 0
doc = @sanitizeHeredoc match[2], quote: quote, indent: null
if quote is '"' and 0 <= doc.indexOf '#{'
@interpolateString doc, heredoc: yes, strOffset: 3, lexedLength: heredoc.length
else
@token 'STRING', @makeString(doc, quote, yes), 0, heredoc.length
heredoc.length
# Matches and consumes comments.
commentToken: ->
return 0 unless match = @chunk.match COMMENT
[comment, here] = match
if here
@token 'HERECOMMENT',
(@sanitizeHeredoc here,
herecomment: true, indent: repeat ' ', @indent),
0, comment.length
comment.length
# Matches JavaScript interpolated directly into the source via backticks.
jsToken: ->
return 0 unless @chunk.charAt(0) is '`' and match = JSTOKEN.exec @chunk
@token 'JS', (script = match[0])[1...-1], 0, script.length
script.length
# Matches regular expression literals. Lexing regular expressions is difficult
# to distinguish from division, so we borrow some basic heuristics from
# JavaScript and Ruby.
regexToken: ->
return 0 if @chunk.charAt(0) isnt '/'
return length if length = @heregexToken()
prev = last @tokens
return 0 if prev and (prev[0] in (if prev.spaced then NOT_REGEX else NOT_SPACED_REGEX))
return 0 unless match = REGEX.exec @chunk
[match, regex, flags] = match
# Avoid conflicts with floor division operator.
return 0 if regex is '//'
if regex[..1] is '/*' then @error 'regular expressions cannot begin with `*`'
@token 'REGEX', "#{regex}#{flags}", 0, match.length
match.length
# Matches multiline extended regular expressions.
heregexToken: ->
return 0 unless match = HEREGEX.exec @chunk
[heregex, body, flags] = match
if 0 > body.indexOf '#{'
re = @escapeLines body.replace(HEREGEX_OMIT, '$1$2').replace(/\//g, '\\/'), yes
if re.match /^\*/ then @error 'regular expressions cannot begin with `*`'
@token 'REGEX', "/#{ re or '(?:)' }/#{flags}", 0, heregex.length
return heregex.length
@token 'IDENTIFIER', 'RegExp', 0, 0
@token 'CALL_START', '(', 0, 0
tokens = []
for token in @interpolateString(body, regex: yes)
[tag, value] = token
if tag is 'TOKENS'
tokens.push value...
else if tag is 'NEOSTRING'
continue unless value = value.replace HEREGEX_OMIT, '$1$2'
# Convert NEOSTRING into STRING
value = value.replace /\\/g, '\\\\'
token[0] = 'STRING'
token[1] = @makeString(value, '"', yes)
tokens.push token
else
@error "Unexpected #{tag}"
prev = last @tokens
plusToken = ['+', '+']
plusToken[2] = prev[2] # Copy location data
tokens.push plusToken
# Remove the extra "+"
tokens.pop()
unless tokens[0]?[0] is 'STRING'
@token 'STRING', '""', 0, 0
@token '+', '+', 0, 0
@tokens.push tokens...
if flags
# Find the flags in the heregex
flagsOffset = heregex.lastIndexOf flags
@token ',', ',', flagsOffset, 0
@token 'STRING', '"' + flags + '"', flagsOffset, flags.length
@token ')', ')', heregex.length-1, 0
heregex.length
# Matches newlines, indents, and outdents, and determines which is which.
# If we can detect that the current line is continued onto the the next line,
# then the newline is suppressed:
#
# elements
# .each( ... )
# .map( ... )
#
# Keeps track of the level of indentation, because a single outdent token
# can close multiple indents, so we need to know how far in we happen to be.
lineToken: ->
# if the next token is not \n, then return 0
return 0 unless match = MULTI_DENT.exec @chunk
# the regex captures at least one of "newline plus trailing whitespace stopping at nonwhitespace or next newline."
# so: /n <space> <tab> <space> /n /n <space> /n /n would ALL be matched. And match[0] would contain that entire string. (match[0] is all this fn uses).
#
indent = match[0] # now indent = the full matched text
@seenFor = no
size = indent.length - 1 - indent.lastIndexOf '\n' # size, for my example, would be 9 - 1 - 8 = zero! And that makes sense, because I DID do some indenting in there, but
# that indenting was "covered up" by subsequent newlines that did not re-state that indenting. You could treat it as indent if you wanted, but it would be followed immediately
# by enough OUTDENTS to cancel it out. So makes sense to ignore them. Just get the amount of whitespace I put after the LAST newline.
# now, consider the case of: \n <space> <tab> <space> \n \n <space> \n \n <space> <tab> (I added <space> and <tab> to end of previous example)
# size would now be 11 - 1 - 8 = 2, which is due to the 2 whitespace charas i have on the end!
noNewlines = @unfinished() # certain expressions are ended by newline (such as comments). If we're in one of these, noNewLines will now be true.
# why would the amount of TRAILING WHITESPACE *AFTER* a newline be relevant or important? Well, DUH! If it is AFTER a newline, then it is ON THE NEXT LINE!!!!
# So this whitespace is whitespace AT THE START OF A NEW LINE.
#
# So what are these class variables?
# 1) @indent: Set to zero at the entry point, it is labelled as "the current indent level"
# 2) @indebt: Set to 0 at entry, it is labelled as "the overindentation at the current point". But WTF does that mean?
if size - @indebt is @indent
console.log "Branch 1: size - @indebt is @indent, indentation was kept same"
# @token 'HERECOMMENT', 'HERECOMMENT', 0, 0
# WARNING!!! "@indent" is NOT THE SAME AS "indent"!!!
# WARNING!!! "@indebt" is different too!
# So, if the amount of whitespace on the new line minus @indebt == @indent, then we are going to make a token
# The normal case is that token will be a newlineToken(0). But if we're inside one of those "unfinished" expressions, it will be @suppressNewLines.
# @newlineToken is a fn that usually makes a TERMINATOR token. But it won't if the last token is ALREADY a TERMINATOR. And it pops off all the ";" tokens first.
#
# BUT: if noNewLines is true (which means we're in one of those "unfinished" expressions), then DON'T call newlineToken and DON'T make a TERMINATOR.
# Instead, call suppressNewlines, which says, if the last token was a \, then just consume that \, and don't create a newline token. The \ means the coder wants to
# suppress a newline. If the last token was not \, we won't pop a token, and we won't make a TERMINATOR token either. So it is as if there was no newline there.
# I suspect these "unfinished" tokens are things that are allowed to span many lines. Let's see ... //, LOGIC, +, etc.
if noNewlines
console.log "Branch 1.1: noNewLines is true, so suppressNewLines"
@suppressNewlines()
else
console.log "Branch 1.2: newNoewLines is false, so add a newlineToken (aka TERMINATOR)
@newlineToken 0
return indent.length
console.log "Branch 2: indentation is not kept same"
# Next case: if the new indentation is > the current indent level, then we have indented further.
if size > @indent
console.log "Branch 3: size of new indent is > previous indent, we've indented further"
if noNewlines
console.log "Branch 3.1: noNewLines is true, so suppressNewLines"
# if this is one of those unfinished expressions, change the INDEBT to the amount that the new whitespace exceeds the current indent level
@indebt = size - @indent
# then, suppressNewlines and return
@suppressNewlines()
return indent.length
# but if we're NOT in one of those unfinished expressions, then ...
# if there are no tokens lexed yet, set the baseIndent and indent to the amount of whitespace found.
console.log "Branch 3.2: noNewLines is false"
unless @tokens.length
console.log "Branch 3.3: there are not any tokens yet, so set base indent and don't return any token"
@baseIndent = @indent = size
# And don't return any token.
return indent.length
console.log "Branch 3.4: there are some tokens already, so make an INDENT token"
diff = size - @indent + @outdebt # ugh!! Next step is to see what @outdebt is. But it has become clear to me that I will do multiple passes, and my FIRST pass will be WHAT'S REALLY IN THE FILE!
# shit. outdebt is defined as the "underoutdentation of the current line". What in the holy fuck does that mean?
@token 'INDENT', diff, indent.length - size, size
@indents.push diff
@ends.push 'OUTDENT'
@outdebt = @indebt = 0
@indent = size
else if size < @baseIndent
console.log "Branch 4: size is not greater than @indent, and size is < @baseIndent. This is ERROR, missing identation"
@error 'missing indentation', indent.length
else
console.log "Branch 5: size is not > @indent, and size is not < @baseIndent. Make an OUTDENT token"
# understanding this branch. size <= @indent, meaning we have outdented. But we did not outdent too far to make error, so create outdent
@indebt = 0
@outdentToken @indent - size, noNewlines, indent.length
indent.length
# Record an outdent token or multiple tokens, if we happen to be moving back
# inwards past several recorded indents. Sets new @indent value.
outdentToken: (moveOut, noNewlines, outdentLength) ->
decreasedIndent = @indent - moveOut
while moveOut > 0
lastIndent = @indents[@indents.length - 1]
if not lastIndent
moveOut = 0
else if lastIndent is @outdebt
moveOut -= @outdebt
@outdebt = 0
else if lastIndent < @outdebt
@outdebt -= lastIndent
moveOut -= lastIndent
else
dent = @indents.pop() + @outdebt
if outdentLength and @chunk[outdentLength] in INDENTABLE_CLOSERS
decreasedIndent -= dent - moveOut
moveOut = dent
@outdebt = 0
# pair might call outdentToken, so preserve decreasedIndent
@pair 'OUTDENT'
@token 'OUTDENT', moveOut, 0, outdentLength
moveOut -= dent
@outdebt -= moveOut if dent
@tokens.pop() while @value() is ';'
@token 'TERMINATOR', '\n', outdentLength, 0 unless @tag() is 'TERMINATOR' or noNewlines
@indent = decreasedIndent
this
# Matches and consumes non-meaningful whitespace. Tag the previous token
# as being "spaced", because there are some cases where it makes a difference.
whitespaceToken: ->
return 0 unless (match = WHITESPACE.exec @chunk) or
(nline = @chunk.charAt(0) is '\n')
prev = last @tokens
prev[if match then 'spaced' else 'newLine'] = true if prev
if match then match[0].length else 0
# Generate a newline token. Consecutive newlines get merged together.
# crf newlineToken: While the last token in the token array is ";", pop. So, remove all the semicolon tokens at the end of the token array.
# If the previously paresed tag was TERMINATOR, do NOTHING! Otherwise, create a TERMINATOR token whose value is \n at the offset passed in
# and a length of 0.
newlineToken: (offset) ->
@tokens.pop() while @value() is ';'
@token 'TERMINATOR', '\n', offset, 0 unless @tag() is 'TERMINATOR'
this
# Use a `\` at a line-ending to suppress the newline.
# The slash is removed here once its job is done.
suppressNewlines: ->
@tokens.pop() if @value() is '\\'
this
# We treat all other single characters as a token. E.g.: `( ) , . !`
# Multi-character operators are also literal tokens, so that Jison can assign
# the proper order of operations. There are some symbols that we tag specially
# here. `;` and newlines are both treated as a `TERMINATOR`, we distinguish
# parentheses that indicate a method call from regular parentheses, and so on.
literalToken: ->
if match = OPERATOR.exec @chunk
[value] = match
@tagParameters() if CODE.test value
else
value = @chunk.charAt 0
tag = value
prev = last @tokens
if value is '=' and prev
if not prev[1].reserved and prev[1] in JS_FORBIDDEN
@error "reserved word \"#{@value()}\" can't be assigned"
if prev[1] in ['||', '&&']
prev[0] = 'COMPOUND_ASSIGN'
prev[1] += '='
return value.length
if value is ';'
@seenFor = no
tag = 'TERMINATOR'
else if value in MATH then tag = 'MATH'
else if value in COMPARE then tag = 'COMPARE'
else if value in COMPOUND_ASSIGN then tag = 'COMPOUND_ASSIGN'
else if value in UNARY then tag = 'UNARY'
else if value in UNARY_MATH then tag = 'UNARY_MATH'
else if value in SHIFT then tag = 'SHIFT'
else if value in LOGIC or value is '?' and prev?.spaced then tag = 'LOGIC'
else if prev and not prev.spaced
if value is '(' and prev[0] in CALLABLE
prev[0] = 'FUNC_EXIST' if prev[0] is '?'
tag = 'CALL_START'
else if value is '[' and prev[0] in INDEXABLE
tag = 'INDEX_START'
switch prev[0]
when '?' then prev[0] = 'INDEX_SOAK'
switch value
when '(', '{', '[' then @ends.push INVERSES[value]
when ')', '}', ']' then @pair value
@token tag, value
value.length
# Token Manipulators
# ------------------
# Sanitize a heredoc or herecomment by
# erasing all external indentation on the left-hand side.
sanitizeHeredoc: (doc, options) ->
{indent, herecomment} = options
if herecomment
if HEREDOC_ILLEGAL.test doc
@error "block comment cannot contain \"*/\", starting"
return doc if doc.indexOf('\n') < 0
else
while match = HEREDOC_INDENT.exec doc
attempt = match[1]
indent = attempt if indent is null or 0 < attempt.length < indent.length
doc = doc.replace /// \n #{indent} ///g, '\n' if indent
doc = doc.replace /^\n/, '' unless herecomment
doc
# A source of ambiguity in our grammar used to be parameter lists in function
# definitions versus argument lists in function calls. Walk backwards, tagging
# parameters specially in order to make things easier for the parser.
tagParameters: ->
return this if @tag() isnt ')'
stack = []
{tokens} = this
i = tokens.length
tokens[--i][0] = 'PARAM_END'
while tok = tokens[--i]
switch tok[0]
when ')'
stack.push tok
when '(', 'CALL_START'
if stack.length then stack.pop()
else if tok[0] is '('
tok[0] = 'PARAM_START'
return this
else return this
this
# Close up all remaining open blocks at the end of the file.
closeIndentation: ->
@outdentToken @indent
# Matches a balanced group such as a single or double-quoted string. Pass in
# a series of delimiters, all of which must be nested correctly within the
# contents of the string. This method allows us to have strings within
# interpolations within strings, ad infinitum.
#
# crf balancedString
balancedString: (str, end) ->
continueCount = 0
stack = [end]
for i in [1...str.length]
if continueCount
--continueCount
continue
switch letter = str.charAt i
when '\\'
++continueCount
continue
when end
stack.pop()
unless stack.length
return str[0..i]
end = stack[stack.length - 1]
continue
if end is '}' and letter in ['"', "'"]
stack.push end = letter
else if end is '}' and letter is '/' and match = (HEREGEX.exec(str[i..]) or REGEX.exec(str[i..]))
continueCount += match[0].length - 1
else if end is '}' and letter is '{'
stack.push end = '}'
else if end is '"' and prev is '#' and letter is '{'
stack.push end = '}'
prev = letter
@error "missing #{ stack.pop() }, starting"
# Expand variables and expressions inside double-quoted strings using
# Ruby-like notation for substitution of arbitrary expressions.
#
# "Hello #{name.capitalize()}."
#
# If it encounters an interpolation, this method will recursively create a
# new Lexer, tokenize the interpolated contents, and merge them into the
# token stream.
#
# - `str` is the start of the string contents (IE with the " or """ stripped
# off.)
# - `options.offsetInChunk` is the start of the interpolated string in the
# current chunk, including the " or """, etc... If not provided, this is
# assumed to be 0. `options.lexedLength` is the length of the
# interpolated string, including both the start and end quotes. Both of these
# values are ignored if `options.regex` is true.
# - `options.strOffset` is the offset of str, relative to the start of the
# current chunk.
interpolateString: (str, options = {}) ->
{heredoc, regex, offsetInChunk, strOffset, lexedLength} = options
offsetInChunk ||= 0
strOffset ||= 0
lexedLength ||= str.length
# Parse the string.
tokens = []
pi = 0
i = -1
while letter = str.charAt i += 1
if letter is '\\'
i += 1
continue
unless letter is '#' and str.charAt(i+1) is '{' and
(expr = @balancedString str[i + 1..], '}')
continue
# NEOSTRING is a fake token. This will be converted to a string below.
tokens.push @makeToken('NEOSTRING', str[pi...i], strOffset + pi) if pi < i
unless errorToken
errorToken = @makeToken '', 'string interpolation', offsetInChunk + i + 1, 2
inner = expr[1...-1]
if inner.length
[line, column] = @getLineAndColumnFromChunk(strOffset + i + 1)
nested = new Lexer().tokenize inner, line: line, column: column, rewrite: off
popped = nested.pop()
popped = nested.shift() if nested[0]?[0] is 'TERMINATOR'
if len = nested.length
if len > 1
nested.unshift @makeToken '(', '(', strOffset + i + 1, 0
nested.push @makeToken ')', ')', strOffset + i + 1 + inner.length, 0
# Push a fake 'TOKENS' token, which will get turned into real tokens below.
tokens.push ['TOKENS', nested]
i += expr.length
pi = i + 1
tokens.push @makeToken('NEOSTRING', str[pi..], strOffset + pi) if i > pi < str.length
# If regex, then return now and let the regex code deal with all these fake tokens
return tokens if regex
# If we didn't find any tokens, then just return an empty string.
return @token 'STRING', '""', offsetInChunk, lexedLength unless tokens.length
# If the first token is not a string, add a fake empty string to the beginning.
tokens.unshift @makeToken('NEOSTRING', '', offsetInChunk) unless tokens[0][0] is 'NEOSTRING'
if interpolated = tokens.length > 1
@token '(', '(', offsetInChunk, 0, errorToken
# Push all the tokens
for token, i in tokens
[tag, value] = token
if i
# Create a 0-length "+" token.
plusToken = @token '+', '+' if i
locationToken = if tag == 'TOKENS' then value[0] else token
plusToken[2] =
first_line: locationToken[2].first_line
first_column: locationToken[2].first_column
last_line: locationToken[2].first_line
last_column: locationToken[2].first_column
if tag is 'TOKENS'
# Push all the tokens in the fake 'TOKENS' token. These already have
# sane location data.
@tokens.push value...
else if tag is 'NEOSTRING'
# Convert NEOSTRING into STRING
token[0] = 'STRING'
token[1] = @makeString value, '"', heredoc
@tokens.push token
else
@error "Unexpected #{tag}"
if interpolated
rparen = @makeToken ')', ')', offsetInChunk + lexedLength, 0
rparen.stringEnd = true
@tokens.push rparen
tokens
# Pairs up a closing token, ensuring that all listed pairs of tokens are
# correctly balanced throughout the course of the token stream.
pair: (tag) ->
unless tag is wanted = last @ends
@error "unmatched #{tag}" unless 'OUTDENT' is wanted
# Auto-close INDENT to support syntax like this:
#
# el.click((event) ->
# el.hide())
#
@outdentToken last(@indents), true
return @pair tag
@ends.pop()
# Helpers
# -------
# Returns the line and column number from an offset into the current chunk.
#
# `offset` is a number of characters into @chunk.
getLineAndColumnFromChunk: (offset) ->
if offset is 0
return [@chunkLine, @chunkColumn]
if offset >= @chunk.length
string = @chunk
else
string = @chunk[..offset-1]
lineCount = count string, '\n'
column = @chunkColumn
if lineCount > 0
lines = string.split '\n'
column = last(lines).length
else
column += string.length
[@chunkLine + lineCount, column]
# Same as "token", exception this just returns the token without adding it
# to the results.
makeToken: (tag, value, offsetInChunk = 0, length = value.length) ->
locationData = {}
[locationData.first_line, locationData.first_column] =
@getLineAndColumnFromChunk offsetInChunk
# Use length - 1 for the final offset - we're supplying the last_line and the last_column,
# so if last_column == first_column, then we're looking at a character of length 1.
lastCharacter = Math.max 0, length - 1
[locationData.last_line, locationData.last_column] =
@getLineAndColumnFromChunk offsetInChunk + lastCharacter
token = [tag, value, locationData]
token
# Add a token to the results.
# `offset` is the offset into the current @chunk where the token starts.
# `length` is the length of the token in the @chunk, after the offset. If
# not specified, the length of `value` will be used.
#
# Returns the new token.
# crf token
token: (tag, value, offsetInChunk, length, origin) ->
token = @makeToken tag, value, offsetInChunk, length
token.origin = origin if origin
@tokens.push token
token
# crf tag:
# Find the last token that was parsed (unless you pass an index), and either return its TAG field, or set its TAG field.
# Peek at a tag in the current token stream.
tag: (index, tag) ->
(tok = last @tokens, index) and if tag then tok[0] = tag else tok[0]
# crf value
# This is a helper that is usually called as a getter, but can also be called as a "setter". To call it as a getter, call with no args, as in foo = @value();
# It will call "last" on the tokens array. "last" is the 4th helper from helpers.coffee. It gets the tail element of the array.
# # So, as a getter, this gets the last token from the tokens array and returns its tok[1]. tok[1] is the "value" field of the token (a token is [tag, value, locationData])
# as a "setter", it changes the "value" field of the last token.
# Peek at a value in the current token stream.
value: (index, val) ->
(tok = last @tokens, index) and if val then tok[1] = val else tok[1]
# Are we in the midst of an unfinished expression?
unfinished: ->
LINE_CONTINUER.test(@chunk) or
@tag() in ['\\', '.', '?.', '?::', 'UNARY', 'MATH', 'UNARY_MATH', '+', '-',
'**', 'SHIFT', 'RELATION', 'COMPARE', 'LOGIC', 'THROW', 'EXTENDS']
# Remove newlines from beginning and (non escaped) from end of string literals.
removeNewlines: (str) ->
str.replace(/^\s*\n\s*/, '')
.replace(/([^\\]|\\\\)\s*\n\s*$/, '$1')
# Converts newlines for string literals.
escapeLines: (str, heredoc) ->
# Ignore escaped backslashes and remove escaped newlines
str = str.replace /\\[^\S\n]*(\n|\\)\s*/g, (escaped, character) ->
if character is '\n' then '' else escaped
if heredoc
str.replace MULTILINER, '\\n'
else
str.replace /\s*\n\s*/g, ' '
# Constructs a string token by escaping quotes and newlines.
makeString: (body, quote, heredoc) ->
return quote + quote unless body
# Ignore escaped backslashes and unescape quotes
body = body.replace /// \\( #{quote} | \\ ) ///g, (match, contents) ->
if contents is quote then contents else match
body = body.replace /// #{quote} ///g, '\\$&'
quote + @escapeLines(body, heredoc) + quote
# Throws a compiler error on the current position.
error: (message, offset = 0) ->
# TODO: Are there some cases we could improve the error line number by
# passing the offset in the chunk where the error happened?
[first_line, first_column] = @getLineAndColumnFromChunk offset
throwSyntaxError message, {first_line, first_column}
# Constants
# ---------
# Keywords that CoffeeScript shares in common with JavaScript.
JS_KEYWORDS = [
'true', 'false', 'null', 'this'
'new', 'delete', 'typeof', 'in', 'instanceof'
'return', 'throw', 'break', 'continue', 'debugger'
'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally'
'class', 'extends', 'super'
]
# CoffeeScript-only keywords.
COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when']
COFFEE_ALIAS_MAP =
and : '&&'
or : '||'
is : '=='
isnt : '!='
not : '!'
yes : 'true'
no : 'false'
on : 'true'
off : 'false'
COFFEE_ALIASES = (key for key of COFFEE_ALIAS_MAP)
COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat COFFEE_ALIASES
# The list of keywords that are reserved by JavaScript, but not used, or are
# used by CoffeeScript internally. We throw an error when these are encountered,
# to avoid having a JavaScript error at runtime.
RESERVED = [
'case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum'
'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind'
'__indexOf', 'implements', 'interface', 'package', 'private', 'protected'
'public', 'static', 'yield'
]
STRICT_PROSCRIBED = ['arguments', 'eval']
# The superset of both JavaScript keywords and reserved words, none of which may
# be used as identifiers or properties.
JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED)
exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED)
exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED
# The character code of the nasty Microsoft madness otherwise known as the BOM.
BOM = 65279
# Token matching regexes.
IDENTIFIER = /// ^
( [$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]* )
( [^\n\S]* : (?!:) )? # Is this a property name?
///
NUMBER = ///
^ 0b[01]+ | # binary
^ 0o[0-7]+ | # octal
^ 0x[\da-f]+ | # hex
^ \d*\.?\d+ (?:e[+-]?\d+)? # decimal
///i
HEREDOC = /// ^ ("""|''') ((?: \\[\s\S] | [^\\] )*?) (?:\n[^\n\S]*)? \1 ///
OPERATOR = /// ^ (
?: [-=]> # function
| [-+*/%<>&|^!?=]= # compound assign / compare
| >>>=? # zero-fill right shift
| ([-+:])\1 # doubles
| ([&|<>*/%])\2=? # logic / shift / power / floor division / modulo
| \?(\.|::) # soak access
| \.{2,3} # range or splat
) ///
WHITESPACE = /^[^\n\S]+/
COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/
CODE = /^[-=]>/
MULTI_DENT = /^(?:\n[^\n\S]*)+/
SIMPLESTR = /^'[^\\']*(?:\\[\s\S][^\\']*)*'/
JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/
# Regex-matching-regexes.
REGEX = /// ^
(/ (?! [\s=] ) # disallow leading whitespace or equals signs
[^ [ / \n \\ ]* # every other thing
(?:
(?: \\[\s\S] # anything escaped
| \[ # character class
[^ \] \n \\ ]*
(?: \\[\s\S] [^ \] \n \\ ]* )*
]
) [^ [ / \n \\ ]*
)*
/) ([imgy]{0,4}) (?!\w)
///
HEREGEX = /// ^ /{3} ((?:\\?[\s\S])+?) /{3} ([imgy]{0,4}) (?!\w) ///
HEREGEX_OMIT = ///
((?:\\\\)+) # consume (and preserve) an even number of backslashes
| \\(\s|/) # preserve escaped whitespace and "de-escape" slashes
| \s+(?:#.*)? # remove whitespace and comments
///g
# Token cleaning regexes.
MULTILINER = /\n/g
HEREDOC_INDENT = /\n+([^\n\S]*)/g
HEREDOC_ILLEGAL = /\*\//
LINE_CONTINUER = /// ^ \s* (?: , | \??\.(?![.\d]) | :: ) ///
TRAILING_SPACES = /\s+$/
# Compound assignment tokens.
COMPOUND_ASSIGN = [
'-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>='
'&=', '^=', '|=', '**=', '//=', '%%='
]
# Unary tokens.
UNARY = ['NEW', 'TYPEOF', 'DELETE', 'DO']
UNARY_MATH = ['!', '~']
# Logical tokens.
LOGIC = ['&&', '||', '&', '|', '^']
# Bit-shifting tokens.
SHIFT = ['<<', '>>', '>>>']
# Comparison tokens.
COMPARE = ['==', '!=', '<', '>', '<=', '>=']
# Mathematical tokens.
MATH = ['*', '/', '%', '//', '%%']
# Relational tokens that are negatable with `not` prefix.
RELATION = ['IN', 'OF', 'INSTANCEOF']
# Boolean tokens.
BOOL = ['TRUE', 'FALSE']
# Tokens which a regular expression will never immediately follow, but which
# a division operator might.
#
# See: http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
#
# Our list is shorter, due to sans-parentheses method calls.
NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', 'NULL', 'UNDEFINED', '++', '--']
# If the previous token is not spaced, there are more preceding tokens that
# force a division parse:
NOT_SPACED_REGEX = NOT_REGEX.concat ')', '}', 'THIS', 'IDENTIFIER', 'STRING', ']'
# Tokens which could legitimately be invoked or indexed. An opening
# parentheses or bracket following these tokens will be recorded as the start
# of a function invocation or indexing operation.
CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER']
INDEXABLE = CALLABLE.concat 'NUMBER', 'BOOL', 'NULL', 'UNDEFINED'
# Tokens that, when immediately preceding a `WHEN`, indicate that the `WHEN`
# occurs at the start of a line. We disambiguate these from trailing whens to
# avoid an ambiguity in the grammar.
LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR']
# Additional indent in front of these is ignored.
INDENTABLE_CLOSERS = [')', '}', ']']
| 197179 | # The CoffeeScript Lexer. Uses a series of token-matching regexes to attempt
# matches against the beginning of the source code. When a match is found,
# a token is produced, we consume the match, and start again. Tokens are in the
# form:
#
# [tag, value, locationData]
#
# where locationData is {first_line, first_column, last_line, last_column}, which is a
# format that can be fed directly into [Jison](http://github.com/zaach/jison). These
# are read by jison in the `parser.lexer` function defined in coffee-script.coffee.
{Rewriter, INVERSES} = require './rewriter'
# Import the helpers we need.
{count, starts, compact, last, repeat, invertLiterate,
locationDataToString, throwSyntaxError} = require './helpers'
# The Lexer Class
# ---------------
# The Lexer class reads a stream of CoffeeScript and divvies it up into tagged
# tokens. Some potential ambiguity in the grammar has been avoided by
# pushing some extra smarts into the Lexer.
exports.Lexer = class Lexer
# **tokenize** is the Lexer's main method. Scan by attempting to match tokens
# one at a time, using a regular expression anchored at the start of the
# remaining code, or a custom recursive token-matching method
# (for interpolations). When the next token has been recorded, we move forward
# within the code past the token, and begin again.
#
# Each tokenizing method is responsible for returning the number of characters
# it has consumed.
#
# Before returning the token stream, run it through the [Rewriter](rewriter.html)
# unless explicitly asked not to.
tokenize: (code, opts = {}) ->
@literate = opts.literate # Are we lexing literate CoffeeScript?
@indent = 0 # The current indentation level.
@baseIndent = 0 # The overall minimum indentation level
@indebt = 0 # The over-indentation at the current level.
@outdebt = 0 # The under-outdentation at the current level.
@indents = [] # The stack of all current indentation levels.
@ends = [] # The stack for pairing up tokens.
@tokens = [] # Stream of parsed tokens in the form `['TYPE', value, location data]`.
@chunkLine =
opts.line or 0 # The start line for the current @chunk.
@chunkColumn =
opts.column or 0 # The start column of the current @chunk.
code = @clean code # The stripped, cleaned original source code.
# At every position, run through this list of attempted matches,
# short-circuiting if any of them succeed. Their order determines precedence:
# `@literalToken` is the fallback catch-all.
i = 0
while @chunk = code[i..]
consumed = \
@identifierToken() or
@commentToken() or
@whitespaceToken() or
@lineToken() or
@heredocToken() or
@stringToken() or
@numberToken() or
@regexToken() or
@jsToken() or
@literalToken()
# Update position
[@chunkLine, @chunkColumn] = @getLineAndColumnFromChunk consumed
i += consumed
@closeIndentation()
@error "missing #{tag}" if tag = @ends.pop()
return @tokens if opts.rewrite is off
(new Rewriter).rewrite @tokens
# Preprocess the code to remove leading and trailing whitespace, carriage
# returns, etc. If we're lexing literate CoffeeScript, strip external Markdown
# by removing all lines that aren't indented by at least four spaces or a tab.
clean: (code) ->
code = code.slice(1) if code.charCodeAt(0) is BOM
code = code.replace(/\r/g, '').replace TRAILING_SPACES, ''
if WHITESPACE.test code
code = "\n#{code}"
@chunkLine--
code = invertLiterate code if @literate
code
# Tokenizers
# ----------
# Matches identifying literals: variables, keywords, method names, etc.
# Check to ensure that JavaScript reserved words aren't being used as
# identifiers. Because CoffeeScript reserves a handful of keywords that are
# allowed in JavaScript, we're careful not to tag them as keywords when
# referenced as property names here, so you can still do `jQuery.is()` even
# though `is` means `===` otherwise.
identifierToken: ->
return 0 unless match = IDENTIFIER.exec @chunk
[input, id, colon] = match
# Preserve length of id for location data
idLength = id.length
poppedToken = undefined
# This if handles "for own key, value of myObject", loop over keys and values of obj, ignoring proptotype
# If previous token's tag was 'FOR' and this is 'OWN', then make a token called 'OWN'
if id is 'own' and @tag() is 'FOR'
@token 'OWN', id
return id.length
# colon will be truthy if the identifier ended in a single colon, which is
# how you define object members in object literal (json) format.
# In that case, we set "forcedIdentifier" to true. It means, "damn it, this is an identifier, I'm sure of it."
# But forcedIdentifier can ALSO be true if the previous token was ".", "?.", :: or ?::
# OR, it can be true if the previos token was NOT SPACED and it is "@". All that makes sense.
forcedIdentifier = colon or
(prev = last @tokens) and (prev[0] in ['.', '?.', '::', '?::'] or
not prev.spaced and prev[0] is '@') # if the previous token was "@" and there is no space between(?)
tag = 'IDENTIFIER'
# only do this if it is nOT forcedIdentifier. See if the identifier is in JS_KEYWORDS or COFFEE_KEYWORDS
if not forcedIdentifier and (id in JS_KEYWORDS or id in COFFEE_KEYWORDS)
tag = id.toUpperCase()
# if we're using WHEN, and the previous tag was LINE_BREAK, then this is a LEADING_WHEN token.
if tag is 'WHEN' and @tag() in LINE_BREAK
tag = 'LEADING_WHEN'
else if tag is 'FOR' # just make a note we've seen FOR. in a CLASS VAR, so it outlives this stack frame.
@seenFor = yes
else if tag is 'UNLESS' # UNLESS is turned into an IF token
tag = 'IF'
else if tag in UNARY # meaning, tag is "~" or "!
tag = 'UNARY'
else if tag in RELATION # meaning, IN, OF, or INSTANCEOF
if tag isnt 'INSTANCEOF' and @seenFor
# tag could be "FORIN" or "FOROF" ()
# but note, @seenFor is a CLASS variable. So we're REMEMBERING that context across many tokens. So, FOR ... IN and FOR ... OF
# Yech, i hate the way that's handled.
tag = 'FOR' + tag
@seenFor = no
else
# here, it could be IN, OF, or INSTANCEOF, and @seenFor was not true.
tag = 'RELATION' # so all uses of IN, OF and INSTANCEOF outside of FOR are considered RELATIONS.
# @value() is another function for peeking at the previous token, but it gets the VALUE of that token. So it the value
# was "!", pop that token off! Change our ID to "!IN", "!FOR" or "!INSTANCEOF" (note, that's our VALUE, not our TAG)
# so he is merely consolidating the 2 tags into one.
if @value() is '!'
poppedToken = @tokens.pop()
id = '!' + id
# if id is one of the js or cs reserved words (and a few others), but forcedIndentifier is true, label it an an identifier.
# otherwise, if it is RESERVED, error out.
if id in JS_FORBIDDEN
if forcedIdentifier
tag = 'IDENTIFIER'
id = new String id
id.reserved = yes
else if id in RESERVED
# you can get here if forcedIdentifier is NOT TRUE, and the id is in RESERVED.
@error "reserved word \"#{id}\""
# if forcedIdentifier is FALSE, and the id IS in JS_FORBIDDEN, but NOT in RESERVED, you'll keep going. Those possibilities
# are: JS_KEYWORDS and STRICT_PROSCRIBED, so things like "true, false, typeof" or "eval, arguments"
# continuing with the case above, if you are using one of the reserved words, and forcedIdentifier is false, go inside this block
# but also, of course, if you're not even using a reserved work and forcedIdentifier is false.
unless forcedIdentifier
# change id to the coffee alias (resolve the coffee alias) if it is one of those
id = COFFEE_ALIAS_MAP[id] if id in COFFEE_ALIASES
# handle these cases here because they were created by alias resolution!
tag = switch id
when '!' then 'UNARY'
when '==', '!=' then 'COMPARE'
when '&&', '||' then 'LOGIC'
when 'true', 'false' then 'BOOL'
when 'break', 'continue' then 'STATEMENT'
else tag
# now, we make a token using the tag we have chosen.
tagToken = @token tag, id, 0, idLength
if poppedToken
# if he previously consolidated 2 tokens, lets correct the location data to encompass the span of both of them
[tagToken[2].first_line, tagToken[2].first_column] =
[poppedToken[2].first_line, poppedToken[2].first_column]
if colon
colonOffset = input.lastIndexOf ':'
@token ':', ':', colonOffset, colon.length # The colon token is a *separate* token! ok, but it fucks up my mental model.
# As always, we return the length
input.length
# Matches numbers, including decimals, hex, and exponential notation.
# Be careful not to interfere with ranges-in-progress.
numberToken: ->
return 0 unless match = NUMBER.exec @chunk
number = match[0]
if /^0[BOX]/.test number
@error "radix prefix '#{number}' must be lowercase"
else if /E/.test(number) and not /^0x/.test number
@error "exponential notation '#{number}' must be indicated with a lowercase 'e'"
else if /^0\d*[89]/.test number
@error "decimal literal '#{number}' must not be prefixed with '0'"
else if /^0\d+/.test number
@error "octal literal '#{number}' must be prefixed with '0o'"
lexedLength = number.length
if octalLiteral = /^0o([0-7]+)/.exec number
number = '0x' + parseInt(octalLiteral[1], 8).toString 16
if binaryLiteral = /^0b([01]+)/.exec number
number = '0x' + parseInt(binaryLiteral[1], 2).toString 16
@token 'NUMBER', number, 0, lexedLength
lexedLength
# Matches strings, including multi-line strings. Ensures that quotation marks
# are balanced within the string's contents, and within nested interpolations.
stringToken: ->
switch quote = @chunk.charAt 0
# when 1st char is single quote, match SIMPLESTR.
# The [string] = syntax uses destructuring. It means, expect the rhs to be an
# array of 1 item, and set string to that one item. If the regex match returns
# undefined, then default to an empty array, meaning string will be undefined.
when "'" then [string] = SIMPLESTR.exec(@chunk) || []
# when the first char is double quotes, call @balancedString on the chunk,
# passing in a double quote.
#
# The interesting thing here is that he supports strings within interpolated strings within interpolated strings, ad infinitum, as long as things are balanced. I need to see an example of that.
#
when '"' then string = @balancedString @chunk, '"'
return 0 unless string
trimmed = @removeNewlines string[1...-1]
if quote is '"' and 0 < string.indexOf '#{', 1
@interpolateString trimmed, strOffset: 1, lexedLength: string.length
else
@token 'STRING', quote + @escapeLines(trimmed) + quote, 0, string.length
if octalEsc = /^(?:\\.|[^\\])*\\(?:0[0-7]|[1-7])/.test string
@error "octal escape sequences #{string} are not allowed"
string.length
# Matches heredocs, adjusting indentation to the correct level, as heredocs
# preserve whitespace, but ignore indentation to the left.
heredocToken: ->
return 0 unless match = HEREDOC.exec @chunk
heredoc = match[0]
quote = heredoc.charAt 0
doc = @sanitizeHeredoc match[2], quote: quote, indent: null
if quote is '"' and 0 <= doc.indexOf '#{'
@interpolateString doc, heredoc: yes, strOffset: 3, lexedLength: heredoc.length
else
@token 'STRING', @makeString(doc, quote, yes), 0, heredoc.length
heredoc.length
# Matches and consumes comments.
commentToken: ->
return 0 unless match = @chunk.match COMMENT
[comment, here] = match
if here
@token 'HERECOMMENT',
(@sanitizeHeredoc here,
herecomment: true, indent: repeat ' ', @indent),
0, comment.length
comment.length
# Matches JavaScript interpolated directly into the source via backticks.
jsToken: ->
return 0 unless @chunk.charAt(0) is '`' and match = JSTOKEN.exec @chunk
@token 'JS', (script = match[0])[1...-1], 0, script.length
script.length
# Matches regular expression literals. Lexing regular expressions is difficult
# to distinguish from division, so we borrow some basic heuristics from
# JavaScript and Ruby.
regexToken: ->
return 0 if @chunk.charAt(0) isnt '/'
return length if length = @heregexToken()
prev = last @tokens
return 0 if prev and (prev[0] in (if prev.spaced then NOT_REGEX else NOT_SPACED_REGEX))
return 0 unless match = REGEX.exec @chunk
[match, regex, flags] = match
# Avoid conflicts with floor division operator.
return 0 if regex is '//'
if regex[..1] is '/*' then @error 'regular expressions cannot begin with `*`'
@token 'REGEX', "#{regex}#{flags}", 0, match.length
match.length
# Matches multiline extended regular expressions.
heregexToken: ->
return 0 unless match = HEREGEX.exec @chunk
[heregex, body, flags] = match
if 0 > body.indexOf '#{'
re = @escapeLines body.replace(HEREGEX_OMIT, '$1$2').replace(/\//g, '\\/'), yes
if re.match /^\*/ then @error 'regular expressions cannot begin with `*`'
@token 'REGEX', "/#{ re or '(?:)' }/#{flags}", 0, heregex.length
return heregex.length
@token 'IDENTIFIER', 'RegExp', 0, 0
@token 'CALL_START', '(', 0, 0
tokens = []
for token in @interpolateString(body, regex: yes)
[tag, value] = token
if tag is 'TOKENS'
tokens.push value...
else if tag is 'NEOSTRING'
continue unless value = value.replace HEREGEX_OMIT, '$1$2'
# Convert NEOSTRING into STRING
value = value.replace /\\/g, '\\\\'
token[0] = 'STRING'
token[1] = @makeString(value, '"', yes)
tokens.push token
else
@error "Unexpected #{tag}"
prev = last @tokens
plusToken = ['+', '+']
plusToken[2] = prev[2] # Copy location data
tokens.push plusToken
# Remove the extra "+"
tokens.pop()
unless tokens[0]?[0] is 'STRING'
@token 'STRING', '""', 0, 0
@token '+', '+', 0, 0
@tokens.push tokens...
if flags
# Find the flags in the heregex
flagsOffset = heregex.lastIndexOf flags
@token ',', ',', flagsOffset, 0
@token 'STRING', '"' + flags + '"', flagsOffset, flags.length
@token ')', ')', heregex.length-1, 0
heregex.length
# Matches newlines, indents, and outdents, and determines which is which.
# If we can detect that the current line is continued onto the the next line,
# then the newline is suppressed:
#
# elements
# .each( ... )
# .map( ... )
#
# Keeps track of the level of indentation, because a single outdent token
# can close multiple indents, so we need to know how far in we happen to be.
lineToken: ->
# if the next token is not \n, then return 0
return 0 unless match = MULTI_DENT.exec @chunk
# the regex captures at least one of "newline plus trailing whitespace stopping at nonwhitespace or next newline."
# so: /n <space> <tab> <space> /n /n <space> /n /n would ALL be matched. And match[0] would contain that entire string. (match[0] is all this fn uses).
#
indent = match[0] # now indent = the full matched text
@seenFor = no
size = indent.length - 1 - indent.lastIndexOf '\n' # size, for my example, would be 9 - 1 - 8 = zero! And that makes sense, because I DID do some indenting in there, but
# that indenting was "covered up" by subsequent newlines that did not re-state that indenting. You could treat it as indent if you wanted, but it would be followed immediately
# by enough OUTDENTS to cancel it out. So makes sense to ignore them. Just get the amount of whitespace I put after the LAST newline.
# now, consider the case of: \n <space> <tab> <space> \n \n <space> \n \n <space> <tab> (I added <space> and <tab> to end of previous example)
# size would now be 11 - 1 - 8 = 2, which is due to the 2 whitespace charas i have on the end!
noNewlines = @unfinished() # certain expressions are ended by newline (such as comments). If we're in one of these, noNewLines will now be true.
# why would the amount of TRAILING WHITESPACE *AFTER* a newline be relevant or important? Well, DUH! If it is AFTER a newline, then it is ON THE NEXT LINE!!!!
# So this whitespace is whitespace AT THE START OF A NEW LINE.
#
# So what are these class variables?
# 1) @indent: Set to zero at the entry point, it is labelled as "the current indent level"
# 2) @indebt: Set to 0 at entry, it is labelled as "the overindentation at the current point". But WTF does that mean?
if size - @indebt is @indent
console.log "Branch 1: size - @indebt is @indent, indentation was kept same"
# @token 'HERECOMMENT', 'HERECOMMENT', 0, 0
# WARNING!!! "@indent" is NOT THE SAME AS "indent"!!!
# WARNING!!! "@indebt" is different too!
# So, if the amount of whitespace on the new line minus @indebt == @indent, then we are going to make a token
# The normal case is that token will be a newlineToken(0). But if we're inside one of those "unfinished" expressions, it will be @suppressNewLines.
# @newlineToken is a fn that usually makes a TERMINATOR token. But it won't if the last token is ALREADY a TERMINATOR. And it pops off all the ";" tokens first.
#
# BUT: if noNewLines is true (which means we're in one of those "unfinished" expressions), then DON'T call newlineToken and DON'T make a TERMINATOR.
# Instead, call suppressNewlines, which says, if the last token was a \, then just consume that \, and don't create a newline token. The \ means the coder wants to
# suppress a newline. If the last token was not \, we won't pop a token, and we won't make a TERMINATOR token either. So it is as if there was no newline there.
# I suspect these "unfinished" tokens are things that are allowed to span many lines. Let's see ... //, LOGIC, +, etc.
if noNewlines
console.log "Branch 1.1: noNewLines is true, so suppressNewLines"
@suppressNewlines()
else
console.log "Branch 1.2: newNoewLines is false, so add a newlineToken (aka TERMINATOR)
@newlineToken 0
return indent.length
console.log "Branch 2: indentation is not kept same"
# Next case: if the new indentation is > the current indent level, then we have indented further.
if size > @indent
console.log "Branch 3: size of new indent is > previous indent, we've indented further"
if noNewlines
console.log "Branch 3.1: noNewLines is true, so suppressNewLines"
# if this is one of those unfinished expressions, change the INDEBT to the amount that the new whitespace exceeds the current indent level
@indebt = size - @indent
# then, suppressNewlines and return
@suppressNewlines()
return indent.length
# but if we're NOT in one of those unfinished expressions, then ...
# if there are no tokens lexed yet, set the baseIndent and indent to the amount of whitespace found.
console.log "Branch 3.2: noNewLines is false"
unless @tokens.length
console.log "Branch 3.3: there are not any tokens yet, so set base indent and don't return any token"
@baseIndent = @indent = size
# And don't return any token.
return indent.length
console.log "Branch 3.4: there are some tokens already, so make an INDENT token"
diff = size - @indent + @outdebt # ugh!! Next step is to see what @outdebt is. But it has become clear to me that I will do multiple passes, and my FIRST pass will be WHAT'S REALLY IN THE FILE!
# shit. outdebt is defined as the "underoutdentation of the current line". What in the holy fuck does that mean?
@token 'INDENT', diff, indent.length - size, size
@indents.push diff
@ends.push 'OUTDENT'
@outdebt = @indebt = 0
@indent = size
else if size < @baseIndent
console.log "Branch 4: size is not greater than @indent, and size is < @baseIndent. This is ERROR, missing identation"
@error 'missing indentation', indent.length
else
console.log "Branch 5: size is not > @indent, and size is not < @baseIndent. Make an OUTDENT token"
# understanding this branch. size <= @indent, meaning we have outdented. But we did not outdent too far to make error, so create outdent
@indebt = 0
@outdentToken @indent - size, noNewlines, indent.length
indent.length
# Record an outdent token or multiple tokens, if we happen to be moving back
# inwards past several recorded indents. Sets new @indent value.
outdentToken: (moveOut, noNewlines, outdentLength) ->
decreasedIndent = @indent - moveOut
while moveOut > 0
lastIndent = @indents[@indents.length - 1]
if not lastIndent
moveOut = 0
else if lastIndent is @outdebt
moveOut -= @outdebt
@outdebt = 0
else if lastIndent < @outdebt
@outdebt -= lastIndent
moveOut -= lastIndent
else
dent = @indents.pop() + @outdebt
if outdentLength and @chunk[outdentLength] in INDENTABLE_CLOSERS
decreasedIndent -= dent - moveOut
moveOut = dent
@outdebt = 0
# pair might call outdentToken, so preserve decreasedIndent
@pair 'OUTDENT'
@token 'OUTD<PASSWORD>', moveOut, 0, outdentLength
moveOut -= dent
@outdebt -= moveOut if dent
@tokens.pop() while @value() is ';'
@token 'TERMINATOR', '\n', outdentLength, 0 unless @tag() is 'TERMINATOR' or noNewlines
@indent = decreasedIndent
this
# Matches and consumes non-meaningful whitespace. Tag the previous token
# as being "spaced", because there are some cases where it makes a difference.
whitespaceToken: ->
return 0 unless (match = WHITESPACE.exec @chunk) or
(nline = @chunk.charAt(0) is '\n')
prev = last @tokens
prev[if match then 'spaced' else 'newLine'] = true if prev
if match then match[0].length else 0
# Generate a newline token. Consecutive newlines get merged together.
# crf newlineToken: While the last token in the token array is ";", pop. So, remove all the semicolon tokens at the end of the token array.
# If the previously paresed tag was TERMINATOR, do NOTHING! Otherwise, create a TERMINATOR token whose value is \n at the offset passed in
# and a length of 0.
newlineToken: (offset) ->
@tokens.pop() while @value() is ';'
@token 'TERMINATOR', '\n', offset, 0 unless @tag() is 'TERMINATOR'
this
# Use a `\` at a line-ending to suppress the newline.
# The slash is removed here once its job is done.
suppressNewlines: ->
@tokens.pop() if @value() is '\\'
this
# We treat all other single characters as a token. E.g.: `( ) , . !`
# Multi-character operators are also literal tokens, so that Jison can assign
# the proper order of operations. There are some symbols that we tag specially
# here. `;` and newlines are both treated as a `TERMINATOR`, we distinguish
# parentheses that indicate a method call from regular parentheses, and so on.
literalToken: ->
if match = OPERATOR.exec @chunk
[value] = match
@tagParameters() if CODE.test value
else
value = @chunk.charAt 0
tag = value
prev = last @tokens
if value is '=' and prev
if not prev[1].reserved and prev[1] in JS_FORBIDDEN
@error "reserved word \"#{@value()}\" can't be assigned"
if prev[1] in ['||', '&&']
prev[0] = 'COMPOUND_ASSIGN'
prev[1] += '='
return value.length
if value is ';'
@seenFor = no
tag = 'TERMINATOR'
else if value in MATH then tag = 'MATH'
else if value in COMPARE then tag = 'COMPARE'
else if value in COMPOUND_ASSIGN then tag = 'COMPOUND_ASSIGN'
else if value in UNARY then tag = 'UNARY'
else if value in UNARY_MATH then tag = 'UNARY_MATH'
else if value in SHIFT then tag = 'SHIFT'
else if value in LOGIC or value is '?' and prev?.spaced then tag = 'LOGIC'
else if prev and not prev.spaced
if value is '(' and prev[0] in CALLABLE
prev[0] = 'FUNC_EXIST' if prev[0] is '?'
tag = 'CALL_START'
else if value is '[' and prev[0] in INDEXABLE
tag = 'INDEX_START'
switch prev[0]
when '?' then prev[0] = 'INDEX_SOAK'
switch value
when '(', '{', '[' then @ends.push INVERSES[value]
when ')', '}', ']' then @pair value
@token tag, value
value.length
# Token Manipulators
# ------------------
# Sanitize a heredoc or herecomment by
# erasing all external indentation on the left-hand side.
sanitizeHeredoc: (doc, options) ->
{indent, herecomment} = options
if herecomment
if HEREDOC_ILLEGAL.test doc
@error "block comment cannot contain \"*/\", starting"
return doc if doc.indexOf('\n') < 0
else
while match = HEREDOC_INDENT.exec doc
attempt = match[1]
indent = attempt if indent is null or 0 < attempt.length < indent.length
doc = doc.replace /// \n #{indent} ///g, '\n' if indent
doc = doc.replace /^\n/, '' unless herecomment
doc
# A source of ambiguity in our grammar used to be parameter lists in function
# definitions versus argument lists in function calls. Walk backwards, tagging
# parameters specially in order to make things easier for the parser.
tagParameters: ->
return this if @tag() isnt ')'
stack = []
{tokens} = this
i = tokens.length
tokens[--i][0] = 'PARAM_END'
while tok = tokens[--i]
switch tok[0]
when ')'
stack.push tok
when '(', 'CALL_START'
if stack.length then stack.pop()
else if tok[0] is '('
tok[0] = 'PARAM_START'
return this
else return this
this
# Close up all remaining open blocks at the end of the file.
closeIndentation: ->
@outdentToken @indent
# Matches a balanced group such as a single or double-quoted string. Pass in
# a series of delimiters, all of which must be nested correctly within the
# contents of the string. This method allows us to have strings within
# interpolations within strings, ad infinitum.
#
# crf balancedString
balancedString: (str, end) ->
continueCount = 0
stack = [end]
for i in [1...str.length]
if continueCount
--continueCount
continue
switch letter = str.charAt i
when '\\'
++continueCount
continue
when end
stack.pop()
unless stack.length
return str[0..i]
end = stack[stack.length - 1]
continue
if end is '}' and letter in ['"', "'"]
stack.push end = letter
else if end is '}' and letter is '/' and match = (HEREGEX.exec(str[i..]) or REGEX.exec(str[i..]))
continueCount += match[0].length - 1
else if end is '}' and letter is '{'
stack.push end = '}'
else if end is '"' and prev is '#' and letter is '{'
stack.push end = '}'
prev = letter
@error "missing #{ stack.pop() }, starting"
# Expand variables and expressions inside double-quoted strings using
# Ruby-like notation for substitution of arbitrary expressions.
#
# "Hello #{name.capitalize()}."
#
# If it encounters an interpolation, this method will recursively create a
# new Lexer, tokenize the interpolated contents, and merge them into the
# token stream.
#
# - `str` is the start of the string contents (IE with the " or """ stripped
# off.)
# - `options.offsetInChunk` is the start of the interpolated string in the
# current chunk, including the " or """, etc... If not provided, this is
# assumed to be 0. `options.lexedLength` is the length of the
# interpolated string, including both the start and end quotes. Both of these
# values are ignored if `options.regex` is true.
# - `options.strOffset` is the offset of str, relative to the start of the
# current chunk.
interpolateString: (str, options = {}) ->
{heredoc, regex, offsetInChunk, strOffset, lexedLength} = options
offsetInChunk ||= 0
strOffset ||= 0
lexedLength ||= str.length
# Parse the string.
tokens = []
pi = 0
i = -1
while letter = str.charAt i += 1
if letter is '\\'
i += 1
continue
unless letter is '#' and str.charAt(i+1) is '{' and
(expr = @balancedString str[i + 1..], '}')
continue
# NEOSTRING is a fake token. This will be converted to a string below.
tokens.push @makeToken('NEOSTRING', str[pi...i], strOffset + pi) if pi < i
unless errorToken
errorToken = @makeToken '', 'string interpolation', offsetInChunk + i + 1, 2
inner = expr[1...-1]
if inner.length
[line, column] = @getLineAndColumnFromChunk(strOffset + i + 1)
nested = new Lexer().tokenize inner, line: line, column: column, rewrite: off
popped = nested.pop()
popped = nested.shift() if nested[0]?[0] is 'TERMINATOR'
if len = nested.length
if len > 1
nested.unshift @makeToken '(', '(', strOffset + i + 1, 0
nested.push @makeToken ')', ')', strOffset + i + 1 + inner.length, 0
# Push a fake 'TOKENS' token, which will get turned into real tokens below.
tokens.push ['TOKENS', nested]
i += expr.length
pi = i + 1
tokens.push @makeToken('NEOSTRING', str[pi..], strOffset + pi) if i > pi < str.length
# If regex, then return now and let the regex code deal with all these fake tokens
return tokens if regex
# If we didn't find any tokens, then just return an empty string.
return @token 'STRING', '""', offsetInChunk, lexedLength unless tokens.length
# If the first token is not a string, add a fake empty string to the beginning.
tokens.unshift @makeToken('NEOSTRING', '', offsetInChunk) unless tokens[0][0] is 'NEOSTRING'
if interpolated = tokens.length > 1
@token '(', '(', offsetInChunk, 0, errorToken
# Push all the tokens
for token, i in tokens
[tag, value] = token
if i
# Create a 0-length "+" token.
plusToken = @token '+', '+' if i
locationToken = if tag == 'TOKENS' then value[0] else token
plusToken[2] =
first_line: locationToken[2].first_line
first_column: locationToken[2].first_column
last_line: locationToken[2].first_line
last_column: locationToken[2].first_column
if tag is 'TOKENS'
# Push all the tokens in the fake 'TOKENS' token. These already have
# sane location data.
@tokens.push value...
else if tag is 'NEOSTRING'
# Convert NEOSTRING into STRING
token[0] = 'STRING'
token[1] = @makeString value, '"', heredoc
@tokens.push token
else
@error "Unexpected #{tag}"
if interpolated
rparen = @makeToken ')', ')', offsetInChunk + lexedLength, 0
rparen.stringEnd = true
@tokens.push rparen
tokens
# Pairs up a closing token, ensuring that all listed pairs of tokens are
# correctly balanced throughout the course of the token stream.
pair: (tag) ->
unless tag is wanted = last @ends
@error "unmatched #{tag}" unless 'OUTDENT' is wanted
# Auto-close INDENT to support syntax like this:
#
# el.click((event) ->
# el.hide())
#
@outdentToken last(@indents), true
return @pair tag
@ends.pop()
# Helpers
# -------
# Returns the line and column number from an offset into the current chunk.
#
# `offset` is a number of characters into @chunk.
getLineAndColumnFromChunk: (offset) ->
if offset is 0
return [@chunkLine, @chunkColumn]
if offset >= @chunk.length
string = @chunk
else
string = @chunk[..offset-1]
lineCount = count string, '\n'
column = @chunkColumn
if lineCount > 0
lines = string.split '\n'
column = last(lines).length
else
column += string.length
[@chunkLine + lineCount, column]
# Same as "token", exception this just returns the token without adding it
# to the results.
makeToken: (tag, value, offsetInChunk = 0, length = value.length) ->
locationData = {}
[locationData.first_line, locationData.first_column] =
@getLineAndColumnFromChunk offsetInChunk
# Use length - 1 for the final offset - we're supplying the last_line and the last_column,
# so if last_column == first_column, then we're looking at a character of length 1.
lastCharacter = Math.max 0, length - 1
[locationData.last_line, locationData.last_column] =
@getLineAndColumnFromChunk offsetInChunk + lastCharacter
token = [tag, value, locationData]
token
# Add a token to the results.
# `offset` is the offset into the current @chunk where the token starts.
# `length` is the length of the token in the @chunk, after the offset. If
# not specified, the length of `value` will be used.
#
# Returns the new token.
# crf token
token: (tag, value, offsetInChunk, length, origin) ->
token = @makeToken tag, value, offsetInChunk, length
token.origin = origin if origin
@tokens.push token
token
# crf tag:
# Find the last token that was parsed (unless you pass an index), and either return its TAG field, or set its TAG field.
# Peek at a tag in the current token stream.
tag: (index, tag) ->
(tok = last @tokens, index) and if tag then tok[0] = tag else tok[0]
# crf value
# This is a helper that is usually called as a getter, but can also be called as a "setter". To call it as a getter, call with no args, as in foo = @value();
# It will call "last" on the tokens array. "last" is the 4th helper from helpers.coffee. It gets the tail element of the array.
# # So, as a getter, this gets the last token from the tokens array and returns its tok[1]. tok[1] is the "value" field of the token (a token is [tag, value, locationData])
# as a "setter", it changes the "value" field of the last token.
# Peek at a value in the current token stream.
value: (index, val) ->
(tok = last @tokens, index) and if val then tok[1] = val else tok[1]
# Are we in the midst of an unfinished expression?
unfinished: ->
LINE_CONTINUER.test(@chunk) or
@tag() in ['\\', '.', '?.', '?::', 'UNARY', 'MATH', 'UNARY_MATH', '+', '-',
'**', 'SHIFT', 'RELATION', 'COMPARE', 'LOGIC', 'THROW', 'EXTENDS']
# Remove newlines from beginning and (non escaped) from end of string literals.
removeNewlines: (str) ->
str.replace(/^\s*\n\s*/, '')
.replace(/([^\\]|\\\\)\s*\n\s*$/, '$1')
# Converts newlines for string literals.
escapeLines: (str, heredoc) ->
# Ignore escaped backslashes and remove escaped newlines
str = str.replace /\\[^\S\n]*(\n|\\)\s*/g, (escaped, character) ->
if character is '\n' then '' else escaped
if heredoc
str.replace MULTILINER, '\\n'
else
str.replace /\s*\n\s*/g, ' '
# Constructs a string token by escaping quotes and newlines.
makeString: (body, quote, heredoc) ->
return quote + quote unless body
# Ignore escaped backslashes and unescape quotes
body = body.replace /// \\( #{quote} | \\ ) ///g, (match, contents) ->
if contents is quote then contents else match
body = body.replace /// #{quote} ///g, '\\$&'
quote + @escapeLines(body, heredoc) + quote
# Throws a compiler error on the current position.
error: (message, offset = 0) ->
# TODO: Are there some cases we could improve the error line number by
# passing the offset in the chunk where the error happened?
[first_line, first_column] = @getLineAndColumnFromChunk offset
throwSyntaxError message, {first_line, first_column}
# Constants
# ---------
# Keywords that CoffeeScript shares in common with JavaScript.
JS_KEYWORDS = [
'true', 'false', 'null', 'this'
'new', 'delete', 'typeof', 'in', 'instanceof'
'return', 'throw', 'break', 'continue', 'debugger'
'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally'
'class', 'extends', 'super'
]
# CoffeeScript-only keywords.
COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when']
COFFEE_ALIAS_MAP =
and : '&&'
or : '||'
is : '=='
isnt : '!='
not : '!'
yes : 'true'
no : 'false'
on : 'true'
off : 'false'
COFFEE_ALIASES = (key for key of COFFEE_ALIAS_MAP)
COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat COFFEE_ALIASES
# The list of keywords that are reserved by JavaScript, but not used, or are
# used by CoffeeScript internally. We throw an error when these are encountered,
# to avoid having a JavaScript error at runtime.
RESERVED = [
'case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum'
'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind'
'__indexOf', 'implements', 'interface', 'package', 'private', 'protected'
'public', 'static', 'yield'
]
STRICT_PROSCRIBED = ['arguments', 'eval']
# The superset of both JavaScript keywords and reserved words, none of which may
# be used as identifiers or properties.
JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED)
exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED)
exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED
# The character code of the nasty Microsoft madness otherwise known as the BOM.
BOM = 65279
# Token matching regexes.
IDENTIFIER = /// ^
( [$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]* )
( [^\n\S]* : (?!:) )? # Is this a property name?
///
NUMBER = ///
^ 0b[01]+ | # binary
^ 0o[0-7]+ | # octal
^ 0x[\da-f]+ | # hex
^ \d*\.?\d+ (?:e[+-]?\d+)? # decimal
///i
HEREDOC = /// ^ ("""|''') ((?: \\[\s\S] | [^\\] )*?) (?:\n[^\n\S]*)? \1 ///
OPERATOR = /// ^ (
?: [-=]> # function
| [-+*/%<>&|^!?=]= # compound assign / compare
| >>>=? # zero-fill right shift
| ([-+:])\1 # doubles
| ([&|<>*/%])\2=? # logic / shift / power / floor division / modulo
| \?(\.|::) # soak access
| \.{2,3} # range or splat
) ///
WHITESPACE = /^[^\n\S]+/
COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/
CODE = /^[-=]>/
MULTI_DENT = /^(?:\n[^\n\S]*)+/
SIMPLESTR = /^'[^\\']*(?:\\[\s\S][^\\']*)*'/
JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/
# Regex-matching-regexes.
REGEX = /// ^
(/ (?! [\s=] ) # disallow leading whitespace or equals signs
[^ [ / \n \\ ]* # every other thing
(?:
(?: \\[\s\S] # anything escaped
| \[ # character class
[^ \] \n \\ ]*
(?: \\[\s\S] [^ \] \n \\ ]* )*
]
) [^ [ / \n \\ ]*
)*
/) ([imgy]{0,4}) (?!\w)
///
HEREGEX = /// ^ /{3} ((?:\\?[\s\S])+?) /{3} ([imgy]{0,4}) (?!\w) ///
HEREGEX_OMIT = ///
((?:\\\\)+) # consume (and preserve) an even number of backslashes
| \\(\s|/) # preserve escaped whitespace and "de-escape" slashes
| \s+(?:#.*)? # remove whitespace and comments
///g
# Token cleaning regexes.
MULTILINER = /\n/g
HEREDOC_INDENT = /\n+([^\n\S]*)/g
HEREDOC_ILLEGAL = /\*\//
LINE_CONTINUER = /// ^ \s* (?: , | \??\.(?![.\d]) | :: ) ///
TRAILING_SPACES = /\s+$/
# Compound assignment tokens.
COMPOUND_ASSIGN = [
'-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>='
'&=', '^=', '|=', '**=', '//=', '%%='
]
# Unary tokens.
UNARY = ['NEW', 'TYPEOF', 'DELETE', 'DO']
UNARY_MATH = ['!', '~']
# Logical tokens.
LOGIC = ['&&', '||', '&', '|', '^']
# Bit-shifting tokens.
SHIFT = ['<<', '>>', '>>>']
# Comparison tokens.
COMPARE = ['==', '!=', '<', '>', '<=', '>=']
# Mathematical tokens.
MATH = ['*', '/', '%', '//', '%%']
# Relational tokens that are negatable with `not` prefix.
RELATION = ['IN', 'OF', 'INSTANCEOF']
# Boolean tokens.
BOOL = ['TRUE', 'FALSE']
# Tokens which a regular expression will never immediately follow, but which
# a division operator might.
#
# See: http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
#
# Our list is shorter, due to sans-parentheses method calls.
NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', 'NULL', 'UNDEFINED', '++', '--']
# If the previous token is not spaced, there are more preceding tokens that
# force a division parse:
NOT_SPACED_REGEX = NOT_REGEX.concat ')', '}', 'THIS', 'IDENTIFIER', 'STRING', ']'
# Tokens which could legitimately be invoked or indexed. An opening
# parentheses or bracket following these tokens will be recorded as the start
# of a function invocation or indexing operation.
CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER']
INDEXABLE = CALLABLE.concat 'NUMBER', 'BOOL', 'NULL', 'UNDEFINED'
# Tokens that, when immediately preceding a `WHEN`, indicate that the `WHEN`
# occurs at the start of a line. We disambiguate these from trailing whens to
# avoid an ambiguity in the grammar.
LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR']
# Additional indent in front of these is ignored.
INDENTABLE_CLOSERS = [')', '}', ']']
| true | # The CoffeeScript Lexer. Uses a series of token-matching regexes to attempt
# matches against the beginning of the source code. When a match is found,
# a token is produced, we consume the match, and start again. Tokens are in the
# form:
#
# [tag, value, locationData]
#
# where locationData is {first_line, first_column, last_line, last_column}, which is a
# format that can be fed directly into [Jison](http://github.com/zaach/jison). These
# are read by jison in the `parser.lexer` function defined in coffee-script.coffee.
{Rewriter, INVERSES} = require './rewriter'
# Import the helpers we need.
{count, starts, compact, last, repeat, invertLiterate,
locationDataToString, throwSyntaxError} = require './helpers'
# The Lexer Class
# ---------------
# The Lexer class reads a stream of CoffeeScript and divvies it up into tagged
# tokens. Some potential ambiguity in the grammar has been avoided by
# pushing some extra smarts into the Lexer.
exports.Lexer = class Lexer
# **tokenize** is the Lexer's main method. Scan by attempting to match tokens
# one at a time, using a regular expression anchored at the start of the
# remaining code, or a custom recursive token-matching method
# (for interpolations). When the next token has been recorded, we move forward
# within the code past the token, and begin again.
#
# Each tokenizing method is responsible for returning the number of characters
# it has consumed.
#
# Before returning the token stream, run it through the [Rewriter](rewriter.html)
# unless explicitly asked not to.
tokenize: (code, opts = {}) ->
@literate = opts.literate # Are we lexing literate CoffeeScript?
@indent = 0 # The current indentation level.
@baseIndent = 0 # The overall minimum indentation level
@indebt = 0 # The over-indentation at the current level.
@outdebt = 0 # The under-outdentation at the current level.
@indents = [] # The stack of all current indentation levels.
@ends = [] # The stack for pairing up tokens.
@tokens = [] # Stream of parsed tokens in the form `['TYPE', value, location data]`.
@chunkLine =
opts.line or 0 # The start line for the current @chunk.
@chunkColumn =
opts.column or 0 # The start column of the current @chunk.
code = @clean code # The stripped, cleaned original source code.
# At every position, run through this list of attempted matches,
# short-circuiting if any of them succeed. Their order determines precedence:
# `@literalToken` is the fallback catch-all.
i = 0
while @chunk = code[i..]
consumed = \
@identifierToken() or
@commentToken() or
@whitespaceToken() or
@lineToken() or
@heredocToken() or
@stringToken() or
@numberToken() or
@regexToken() or
@jsToken() or
@literalToken()
# Update position
[@chunkLine, @chunkColumn] = @getLineAndColumnFromChunk consumed
i += consumed
@closeIndentation()
@error "missing #{tag}" if tag = @ends.pop()
return @tokens if opts.rewrite is off
(new Rewriter).rewrite @tokens
# Preprocess the code to remove leading and trailing whitespace, carriage
# returns, etc. If we're lexing literate CoffeeScript, strip external Markdown
# by removing all lines that aren't indented by at least four spaces or a tab.
clean: (code) ->
code = code.slice(1) if code.charCodeAt(0) is BOM
code = code.replace(/\r/g, '').replace TRAILING_SPACES, ''
if WHITESPACE.test code
code = "\n#{code}"
@chunkLine--
code = invertLiterate code if @literate
code
# Tokenizers
# ----------
# Matches identifying literals: variables, keywords, method names, etc.
# Check to ensure that JavaScript reserved words aren't being used as
# identifiers. Because CoffeeScript reserves a handful of keywords that are
# allowed in JavaScript, we're careful not to tag them as keywords when
# referenced as property names here, so you can still do `jQuery.is()` even
# though `is` means `===` otherwise.
identifierToken: ->
return 0 unless match = IDENTIFIER.exec @chunk
[input, id, colon] = match
# Preserve length of id for location data
idLength = id.length
poppedToken = undefined
# This if handles "for own key, value of myObject", loop over keys and values of obj, ignoring proptotype
# If previous token's tag was 'FOR' and this is 'OWN', then make a token called 'OWN'
if id is 'own' and @tag() is 'FOR'
@token 'OWN', id
return id.length
# colon will be truthy if the identifier ended in a single colon, which is
# how you define object members in object literal (json) format.
# In that case, we set "forcedIdentifier" to true. It means, "damn it, this is an identifier, I'm sure of it."
# But forcedIdentifier can ALSO be true if the previous token was ".", "?.", :: or ?::
# OR, it can be true if the previos token was NOT SPACED and it is "@". All that makes sense.
forcedIdentifier = colon or
(prev = last @tokens) and (prev[0] in ['.', '?.', '::', '?::'] or
not prev.spaced and prev[0] is '@') # if the previous token was "@" and there is no space between(?)
tag = 'IDENTIFIER'
# only do this if it is nOT forcedIdentifier. See if the identifier is in JS_KEYWORDS or COFFEE_KEYWORDS
if not forcedIdentifier and (id in JS_KEYWORDS or id in COFFEE_KEYWORDS)
tag = id.toUpperCase()
# if we're using WHEN, and the previous tag was LINE_BREAK, then this is a LEADING_WHEN token.
if tag is 'WHEN' and @tag() in LINE_BREAK
tag = 'LEADING_WHEN'
else if tag is 'FOR' # just make a note we've seen FOR. in a CLASS VAR, so it outlives this stack frame.
@seenFor = yes
else if tag is 'UNLESS' # UNLESS is turned into an IF token
tag = 'IF'
else if tag in UNARY # meaning, tag is "~" or "!
tag = 'UNARY'
else if tag in RELATION # meaning, IN, OF, or INSTANCEOF
if tag isnt 'INSTANCEOF' and @seenFor
# tag could be "FORIN" or "FOROF" ()
# but note, @seenFor is a CLASS variable. So we're REMEMBERING that context across many tokens. So, FOR ... IN and FOR ... OF
# Yech, i hate the way that's handled.
tag = 'FOR' + tag
@seenFor = no
else
# here, it could be IN, OF, or INSTANCEOF, and @seenFor was not true.
tag = 'RELATION' # so all uses of IN, OF and INSTANCEOF outside of FOR are considered RELATIONS.
# @value() is another function for peeking at the previous token, but it gets the VALUE of that token. So it the value
# was "!", pop that token off! Change our ID to "!IN", "!FOR" or "!INSTANCEOF" (note, that's our VALUE, not our TAG)
# so he is merely consolidating the 2 tags into one.
if @value() is '!'
poppedToken = @tokens.pop()
id = '!' + id
# if id is one of the js or cs reserved words (and a few others), but forcedIndentifier is true, label it an an identifier.
# otherwise, if it is RESERVED, error out.
if id in JS_FORBIDDEN
if forcedIdentifier
tag = 'IDENTIFIER'
id = new String id
id.reserved = yes
else if id in RESERVED
# you can get here if forcedIdentifier is NOT TRUE, and the id is in RESERVED.
@error "reserved word \"#{id}\""
# if forcedIdentifier is FALSE, and the id IS in JS_FORBIDDEN, but NOT in RESERVED, you'll keep going. Those possibilities
# are: JS_KEYWORDS and STRICT_PROSCRIBED, so things like "true, false, typeof" or "eval, arguments"
# continuing with the case above, if you are using one of the reserved words, and forcedIdentifier is false, go inside this block
# but also, of course, if you're not even using a reserved work and forcedIdentifier is false.
unless forcedIdentifier
# change id to the coffee alias (resolve the coffee alias) if it is one of those
id = COFFEE_ALIAS_MAP[id] if id in COFFEE_ALIASES
# handle these cases here because they were created by alias resolution!
tag = switch id
when '!' then 'UNARY'
when '==', '!=' then 'COMPARE'
when '&&', '||' then 'LOGIC'
when 'true', 'false' then 'BOOL'
when 'break', 'continue' then 'STATEMENT'
else tag
# now, we make a token using the tag we have chosen.
tagToken = @token tag, id, 0, idLength
if poppedToken
# if he previously consolidated 2 tokens, lets correct the location data to encompass the span of both of them
[tagToken[2].first_line, tagToken[2].first_column] =
[poppedToken[2].first_line, poppedToken[2].first_column]
if colon
colonOffset = input.lastIndexOf ':'
@token ':', ':', colonOffset, colon.length # The colon token is a *separate* token! ok, but it fucks up my mental model.
# As always, we return the length
input.length
# Matches numbers, including decimals, hex, and exponential notation.
# Be careful not to interfere with ranges-in-progress.
numberToken: ->
return 0 unless match = NUMBER.exec @chunk
number = match[0]
if /^0[BOX]/.test number
@error "radix prefix '#{number}' must be lowercase"
else if /E/.test(number) and not /^0x/.test number
@error "exponential notation '#{number}' must be indicated with a lowercase 'e'"
else if /^0\d*[89]/.test number
@error "decimal literal '#{number}' must not be prefixed with '0'"
else if /^0\d+/.test number
@error "octal literal '#{number}' must be prefixed with '0o'"
lexedLength = number.length
if octalLiteral = /^0o([0-7]+)/.exec number
number = '0x' + parseInt(octalLiteral[1], 8).toString 16
if binaryLiteral = /^0b([01]+)/.exec number
number = '0x' + parseInt(binaryLiteral[1], 2).toString 16
@token 'NUMBER', number, 0, lexedLength
lexedLength
# Matches strings, including multi-line strings. Ensures that quotation marks
# are balanced within the string's contents, and within nested interpolations.
stringToken: ->
switch quote = @chunk.charAt 0
# when 1st char is single quote, match SIMPLESTR.
# The [string] = syntax uses destructuring. It means, expect the rhs to be an
# array of 1 item, and set string to that one item. If the regex match returns
# undefined, then default to an empty array, meaning string will be undefined.
when "'" then [string] = SIMPLESTR.exec(@chunk) || []
# when the first char is double quotes, call @balancedString on the chunk,
# passing in a double quote.
#
# The interesting thing here is that he supports strings within interpolated strings within interpolated strings, ad infinitum, as long as things are balanced. I need to see an example of that.
#
when '"' then string = @balancedString @chunk, '"'
return 0 unless string
trimmed = @removeNewlines string[1...-1]
if quote is '"' and 0 < string.indexOf '#{', 1
@interpolateString trimmed, strOffset: 1, lexedLength: string.length
else
@token 'STRING', quote + @escapeLines(trimmed) + quote, 0, string.length
if octalEsc = /^(?:\\.|[^\\])*\\(?:0[0-7]|[1-7])/.test string
@error "octal escape sequences #{string} are not allowed"
string.length
# Matches heredocs, adjusting indentation to the correct level, as heredocs
# preserve whitespace, but ignore indentation to the left.
heredocToken: ->
return 0 unless match = HEREDOC.exec @chunk
heredoc = match[0]
quote = heredoc.charAt 0
doc = @sanitizeHeredoc match[2], quote: quote, indent: null
if quote is '"' and 0 <= doc.indexOf '#{'
@interpolateString doc, heredoc: yes, strOffset: 3, lexedLength: heredoc.length
else
@token 'STRING', @makeString(doc, quote, yes), 0, heredoc.length
heredoc.length
# Matches and consumes comments.
commentToken: ->
return 0 unless match = @chunk.match COMMENT
[comment, here] = match
if here
@token 'HERECOMMENT',
(@sanitizeHeredoc here,
herecomment: true, indent: repeat ' ', @indent),
0, comment.length
comment.length
# Matches JavaScript interpolated directly into the source via backticks.
jsToken: ->
return 0 unless @chunk.charAt(0) is '`' and match = JSTOKEN.exec @chunk
@token 'JS', (script = match[0])[1...-1], 0, script.length
script.length
# Matches regular expression literals. Lexing regular expressions is difficult
# to distinguish from division, so we borrow some basic heuristics from
# JavaScript and Ruby.
regexToken: ->
return 0 if @chunk.charAt(0) isnt '/'
return length if length = @heregexToken()
prev = last @tokens
return 0 if prev and (prev[0] in (if prev.spaced then NOT_REGEX else NOT_SPACED_REGEX))
return 0 unless match = REGEX.exec @chunk
[match, regex, flags] = match
# Avoid conflicts with floor division operator.
return 0 if regex is '//'
if regex[..1] is '/*' then @error 'regular expressions cannot begin with `*`'
@token 'REGEX', "#{regex}#{flags}", 0, match.length
match.length
# Matches multiline extended regular expressions.
heregexToken: ->
return 0 unless match = HEREGEX.exec @chunk
[heregex, body, flags] = match
if 0 > body.indexOf '#{'
re = @escapeLines body.replace(HEREGEX_OMIT, '$1$2').replace(/\//g, '\\/'), yes
if re.match /^\*/ then @error 'regular expressions cannot begin with `*`'
@token 'REGEX', "/#{ re or '(?:)' }/#{flags}", 0, heregex.length
return heregex.length
@token 'IDENTIFIER', 'RegExp', 0, 0
@token 'CALL_START', '(', 0, 0
tokens = []
for token in @interpolateString(body, regex: yes)
[tag, value] = token
if tag is 'TOKENS'
tokens.push value...
else if tag is 'NEOSTRING'
continue unless value = value.replace HEREGEX_OMIT, '$1$2'
# Convert NEOSTRING into STRING
value = value.replace /\\/g, '\\\\'
token[0] = 'STRING'
token[1] = @makeString(value, '"', yes)
tokens.push token
else
@error "Unexpected #{tag}"
prev = last @tokens
plusToken = ['+', '+']
plusToken[2] = prev[2] # Copy location data
tokens.push plusToken
# Remove the extra "+"
tokens.pop()
unless tokens[0]?[0] is 'STRING'
@token 'STRING', '""', 0, 0
@token '+', '+', 0, 0
@tokens.push tokens...
if flags
# Find the flags in the heregex
flagsOffset = heregex.lastIndexOf flags
@token ',', ',', flagsOffset, 0
@token 'STRING', '"' + flags + '"', flagsOffset, flags.length
@token ')', ')', heregex.length-1, 0
heregex.length
# Matches newlines, indents, and outdents, and determines which is which.
# If we can detect that the current line is continued onto the the next line,
# then the newline is suppressed:
#
# elements
# .each( ... )
# .map( ... )
#
# Keeps track of the level of indentation, because a single outdent token
# can close multiple indents, so we need to know how far in we happen to be.
lineToken: ->
# if the next token is not \n, then return 0
return 0 unless match = MULTI_DENT.exec @chunk
# the regex captures at least one of "newline plus trailing whitespace stopping at nonwhitespace or next newline."
# so: /n <space> <tab> <space> /n /n <space> /n /n would ALL be matched. And match[0] would contain that entire string. (match[0] is all this fn uses).
#
indent = match[0] # now indent = the full matched text
@seenFor = no
size = indent.length - 1 - indent.lastIndexOf '\n' # size, for my example, would be 9 - 1 - 8 = zero! And that makes sense, because I DID do some indenting in there, but
# that indenting was "covered up" by subsequent newlines that did not re-state that indenting. You could treat it as indent if you wanted, but it would be followed immediately
# by enough OUTDENTS to cancel it out. So makes sense to ignore them. Just get the amount of whitespace I put after the LAST newline.
# now, consider the case of: \n <space> <tab> <space> \n \n <space> \n \n <space> <tab> (I added <space> and <tab> to end of previous example)
# size would now be 11 - 1 - 8 = 2, which is due to the 2 whitespace charas i have on the end!
noNewlines = @unfinished() # certain expressions are ended by newline (such as comments). If we're in one of these, noNewLines will now be true.
# why would the amount of TRAILING WHITESPACE *AFTER* a newline be relevant or important? Well, DUH! If it is AFTER a newline, then it is ON THE NEXT LINE!!!!
# So this whitespace is whitespace AT THE START OF A NEW LINE.
#
# So what are these class variables?
# 1) @indent: Set to zero at the entry point, it is labelled as "the current indent level"
# 2) @indebt: Set to 0 at entry, it is labelled as "the overindentation at the current point". But WTF does that mean?
if size - @indebt is @indent
console.log "Branch 1: size - @indebt is @indent, indentation was kept same"
# @token 'HERECOMMENT', 'HERECOMMENT', 0, 0
# WARNING!!! "@indent" is NOT THE SAME AS "indent"!!!
# WARNING!!! "@indebt" is different too!
# So, if the amount of whitespace on the new line minus @indebt == @indent, then we are going to make a token
# The normal case is that token will be a newlineToken(0). But if we're inside one of those "unfinished" expressions, it will be @suppressNewLines.
# @newlineToken is a fn that usually makes a TERMINATOR token. But it won't if the last token is ALREADY a TERMINATOR. And it pops off all the ";" tokens first.
#
# BUT: if noNewLines is true (which means we're in one of those "unfinished" expressions), then DON'T call newlineToken and DON'T make a TERMINATOR.
# Instead, call suppressNewlines, which says, if the last token was a \, then just consume that \, and don't create a newline token. The \ means the coder wants to
# suppress a newline. If the last token was not \, we won't pop a token, and we won't make a TERMINATOR token either. So it is as if there was no newline there.
# I suspect these "unfinished" tokens are things that are allowed to span many lines. Let's see ... //, LOGIC, +, etc.
if noNewlines
console.log "Branch 1.1: noNewLines is true, so suppressNewLines"
@suppressNewlines()
else
console.log "Branch 1.2: newNoewLines is false, so add a newlineToken (aka TERMINATOR)
@newlineToken 0
return indent.length
console.log "Branch 2: indentation is not kept same"
# Next case: if the new indentation is > the current indent level, then we have indented further.
if size > @indent
console.log "Branch 3: size of new indent is > previous indent, we've indented further"
if noNewlines
console.log "Branch 3.1: noNewLines is true, so suppressNewLines"
# if this is one of those unfinished expressions, change the INDEBT to the amount that the new whitespace exceeds the current indent level
@indebt = size - @indent
# then, suppressNewlines and return
@suppressNewlines()
return indent.length
# but if we're NOT in one of those unfinished expressions, then ...
# if there are no tokens lexed yet, set the baseIndent and indent to the amount of whitespace found.
console.log "Branch 3.2: noNewLines is false"
unless @tokens.length
console.log "Branch 3.3: there are not any tokens yet, so set base indent and don't return any token"
@baseIndent = @indent = size
# And don't return any token.
return indent.length
console.log "Branch 3.4: there are some tokens already, so make an INDENT token"
diff = size - @indent + @outdebt # ugh!! Next step is to see what @outdebt is. But it has become clear to me that I will do multiple passes, and my FIRST pass will be WHAT'S REALLY IN THE FILE!
# shit. outdebt is defined as the "underoutdentation of the current line". What in the holy fuck does that mean?
@token 'INDENT', diff, indent.length - size, size
@indents.push diff
@ends.push 'OUTDENT'
@outdebt = @indebt = 0
@indent = size
else if size < @baseIndent
console.log "Branch 4: size is not greater than @indent, and size is < @baseIndent. This is ERROR, missing identation"
@error 'missing indentation', indent.length
else
console.log "Branch 5: size is not > @indent, and size is not < @baseIndent. Make an OUTDENT token"
# understanding this branch. size <= @indent, meaning we have outdented. But we did not outdent too far to make error, so create outdent
@indebt = 0
@outdentToken @indent - size, noNewlines, indent.length
indent.length
# Record an outdent token or multiple tokens, if we happen to be moving back
# inwards past several recorded indents. Sets new @indent value.
outdentToken: (moveOut, noNewlines, outdentLength) ->
decreasedIndent = @indent - moveOut
while moveOut > 0
lastIndent = @indents[@indents.length - 1]
if not lastIndent
moveOut = 0
else if lastIndent is @outdebt
moveOut -= @outdebt
@outdebt = 0
else if lastIndent < @outdebt
@outdebt -= lastIndent
moveOut -= lastIndent
else
dent = @indents.pop() + @outdebt
if outdentLength and @chunk[outdentLength] in INDENTABLE_CLOSERS
decreasedIndent -= dent - moveOut
moveOut = dent
@outdebt = 0
# pair might call outdentToken, so preserve decreasedIndent
@pair 'OUTDENT'
@token 'OUTDPI:PASSWORD:<PASSWORD>END_PI', moveOut, 0, outdentLength
moveOut -= dent
@outdebt -= moveOut if dent
@tokens.pop() while @value() is ';'
@token 'TERMINATOR', '\n', outdentLength, 0 unless @tag() is 'TERMINATOR' or noNewlines
@indent = decreasedIndent
this
# Matches and consumes non-meaningful whitespace. Tag the previous token
# as being "spaced", because there are some cases where it makes a difference.
whitespaceToken: ->
return 0 unless (match = WHITESPACE.exec @chunk) or
(nline = @chunk.charAt(0) is '\n')
prev = last @tokens
prev[if match then 'spaced' else 'newLine'] = true if prev
if match then match[0].length else 0
# Generate a newline token. Consecutive newlines get merged together.
# crf newlineToken: While the last token in the token array is ";", pop. So, remove all the semicolon tokens at the end of the token array.
# If the previously paresed tag was TERMINATOR, do NOTHING! Otherwise, create a TERMINATOR token whose value is \n at the offset passed in
# and a length of 0.
newlineToken: (offset) ->
@tokens.pop() while @value() is ';'
@token 'TERMINATOR', '\n', offset, 0 unless @tag() is 'TERMINATOR'
this
# Use a `\` at a line-ending to suppress the newline.
# The slash is removed here once its job is done.
suppressNewlines: ->
@tokens.pop() if @value() is '\\'
this
# We treat all other single characters as a token. E.g.: `( ) , . !`
# Multi-character operators are also literal tokens, so that Jison can assign
# the proper order of operations. There are some symbols that we tag specially
# here. `;` and newlines are both treated as a `TERMINATOR`, we distinguish
# parentheses that indicate a method call from regular parentheses, and so on.
literalToken: ->
if match = OPERATOR.exec @chunk
[value] = match
@tagParameters() if CODE.test value
else
value = @chunk.charAt 0
tag = value
prev = last @tokens
if value is '=' and prev
if not prev[1].reserved and prev[1] in JS_FORBIDDEN
@error "reserved word \"#{@value()}\" can't be assigned"
if prev[1] in ['||', '&&']
prev[0] = 'COMPOUND_ASSIGN'
prev[1] += '='
return value.length
if value is ';'
@seenFor = no
tag = 'TERMINATOR'
else if value in MATH then tag = 'MATH'
else if value in COMPARE then tag = 'COMPARE'
else if value in COMPOUND_ASSIGN then tag = 'COMPOUND_ASSIGN'
else if value in UNARY then tag = 'UNARY'
else if value in UNARY_MATH then tag = 'UNARY_MATH'
else if value in SHIFT then tag = 'SHIFT'
else if value in LOGIC or value is '?' and prev?.spaced then tag = 'LOGIC'
else if prev and not prev.spaced
if value is '(' and prev[0] in CALLABLE
prev[0] = 'FUNC_EXIST' if prev[0] is '?'
tag = 'CALL_START'
else if value is '[' and prev[0] in INDEXABLE
tag = 'INDEX_START'
switch prev[0]
when '?' then prev[0] = 'INDEX_SOAK'
switch value
when '(', '{', '[' then @ends.push INVERSES[value]
when ')', '}', ']' then @pair value
@token tag, value
value.length
# Token Manipulators
# ------------------
# Sanitize a heredoc or herecomment by
# erasing all external indentation on the left-hand side.
sanitizeHeredoc: (doc, options) ->
{indent, herecomment} = options
if herecomment
if HEREDOC_ILLEGAL.test doc
@error "block comment cannot contain \"*/\", starting"
return doc if doc.indexOf('\n') < 0
else
while match = HEREDOC_INDENT.exec doc
attempt = match[1]
indent = attempt if indent is null or 0 < attempt.length < indent.length
doc = doc.replace /// \n #{indent} ///g, '\n' if indent
doc = doc.replace /^\n/, '' unless herecomment
doc
# A source of ambiguity in our grammar used to be parameter lists in function
# definitions versus argument lists in function calls. Walk backwards, tagging
# parameters specially in order to make things easier for the parser.
tagParameters: ->
return this if @tag() isnt ')'
stack = []
{tokens} = this
i = tokens.length
tokens[--i][0] = 'PARAM_END'
while tok = tokens[--i]
switch tok[0]
when ')'
stack.push tok
when '(', 'CALL_START'
if stack.length then stack.pop()
else if tok[0] is '('
tok[0] = 'PARAM_START'
return this
else return this
this
# Close up all remaining open blocks at the end of the file.
closeIndentation: ->
@outdentToken @indent
# Matches a balanced group such as a single or double-quoted string. Pass in
# a series of delimiters, all of which must be nested correctly within the
# contents of the string. This method allows us to have strings within
# interpolations within strings, ad infinitum.
#
# crf balancedString
balancedString: (str, end) ->
continueCount = 0
stack = [end]
for i in [1...str.length]
if continueCount
--continueCount
continue
switch letter = str.charAt i
when '\\'
++continueCount
continue
when end
stack.pop()
unless stack.length
return str[0..i]
end = stack[stack.length - 1]
continue
if end is '}' and letter in ['"', "'"]
stack.push end = letter
else if end is '}' and letter is '/' and match = (HEREGEX.exec(str[i..]) or REGEX.exec(str[i..]))
continueCount += match[0].length - 1
else if end is '}' and letter is '{'
stack.push end = '}'
else if end is '"' and prev is '#' and letter is '{'
stack.push end = '}'
prev = letter
@error "missing #{ stack.pop() }, starting"
# Expand variables and expressions inside double-quoted strings using
# Ruby-like notation for substitution of arbitrary expressions.
#
# "Hello #{name.capitalize()}."
#
# If it encounters an interpolation, this method will recursively create a
# new Lexer, tokenize the interpolated contents, and merge them into the
# token stream.
#
# - `str` is the start of the string contents (IE with the " or """ stripped
# off.)
# - `options.offsetInChunk` is the start of the interpolated string in the
# current chunk, including the " or """, etc... If not provided, this is
# assumed to be 0. `options.lexedLength` is the length of the
# interpolated string, including both the start and end quotes. Both of these
# values are ignored if `options.regex` is true.
# - `options.strOffset` is the offset of str, relative to the start of the
# current chunk.
interpolateString: (str, options = {}) ->
{heredoc, regex, offsetInChunk, strOffset, lexedLength} = options
offsetInChunk ||= 0
strOffset ||= 0
lexedLength ||= str.length
# Parse the string.
tokens = []
pi = 0
i = -1
while letter = str.charAt i += 1
if letter is '\\'
i += 1
continue
unless letter is '#' and str.charAt(i+1) is '{' and
(expr = @balancedString str[i + 1..], '}')
continue
# NEOSTRING is a fake token. This will be converted to a string below.
tokens.push @makeToken('NEOSTRING', str[pi...i], strOffset + pi) if pi < i
unless errorToken
errorToken = @makeToken '', 'string interpolation', offsetInChunk + i + 1, 2
inner = expr[1...-1]
if inner.length
[line, column] = @getLineAndColumnFromChunk(strOffset + i + 1)
nested = new Lexer().tokenize inner, line: line, column: column, rewrite: off
popped = nested.pop()
popped = nested.shift() if nested[0]?[0] is 'TERMINATOR'
if len = nested.length
if len > 1
nested.unshift @makeToken '(', '(', strOffset + i + 1, 0
nested.push @makeToken ')', ')', strOffset + i + 1 + inner.length, 0
# Push a fake 'TOKENS' token, which will get turned into real tokens below.
tokens.push ['TOKENS', nested]
i += expr.length
pi = i + 1
tokens.push @makeToken('NEOSTRING', str[pi..], strOffset + pi) if i > pi < str.length
# If regex, then return now and let the regex code deal with all these fake tokens
return tokens if regex
# If we didn't find any tokens, then just return an empty string.
return @token 'STRING', '""', offsetInChunk, lexedLength unless tokens.length
# If the first token is not a string, add a fake empty string to the beginning.
tokens.unshift @makeToken('NEOSTRING', '', offsetInChunk) unless tokens[0][0] is 'NEOSTRING'
if interpolated = tokens.length > 1
@token '(', '(', offsetInChunk, 0, errorToken
# Push all the tokens
for token, i in tokens
[tag, value] = token
if i
# Create a 0-length "+" token.
plusToken = @token '+', '+' if i
locationToken = if tag == 'TOKENS' then value[0] else token
plusToken[2] =
first_line: locationToken[2].first_line
first_column: locationToken[2].first_column
last_line: locationToken[2].first_line
last_column: locationToken[2].first_column
if tag is 'TOKENS'
# Push all the tokens in the fake 'TOKENS' token. These already have
# sane location data.
@tokens.push value...
else if tag is 'NEOSTRING'
# Convert NEOSTRING into STRING
token[0] = 'STRING'
token[1] = @makeString value, '"', heredoc
@tokens.push token
else
@error "Unexpected #{tag}"
if interpolated
rparen = @makeToken ')', ')', offsetInChunk + lexedLength, 0
rparen.stringEnd = true
@tokens.push rparen
tokens
# Pairs up a closing token, ensuring that all listed pairs of tokens are
# correctly balanced throughout the course of the token stream.
pair: (tag) ->
unless tag is wanted = last @ends
@error "unmatched #{tag}" unless 'OUTDENT' is wanted
# Auto-close INDENT to support syntax like this:
#
# el.click((event) ->
# el.hide())
#
@outdentToken last(@indents), true
return @pair tag
@ends.pop()
# Helpers
# -------
# Returns the line and column number from an offset into the current chunk.
#
# `offset` is a number of characters into @chunk.
getLineAndColumnFromChunk: (offset) ->
if offset is 0
return [@chunkLine, @chunkColumn]
if offset >= @chunk.length
string = @chunk
else
string = @chunk[..offset-1]
lineCount = count string, '\n'
column = @chunkColumn
if lineCount > 0
lines = string.split '\n'
column = last(lines).length
else
column += string.length
[@chunkLine + lineCount, column]
# Same as "token", exception this just returns the token without adding it
# to the results.
makeToken: (tag, value, offsetInChunk = 0, length = value.length) ->
locationData = {}
[locationData.first_line, locationData.first_column] =
@getLineAndColumnFromChunk offsetInChunk
# Use length - 1 for the final offset - we're supplying the last_line and the last_column,
# so if last_column == first_column, then we're looking at a character of length 1.
lastCharacter = Math.max 0, length - 1
[locationData.last_line, locationData.last_column] =
@getLineAndColumnFromChunk offsetInChunk + lastCharacter
token = [tag, value, locationData]
token
# Add a token to the results.
# `offset` is the offset into the current @chunk where the token starts.
# `length` is the length of the token in the @chunk, after the offset. If
# not specified, the length of `value` will be used.
#
# Returns the new token.
# crf token
token: (tag, value, offsetInChunk, length, origin) ->
token = @makeToken tag, value, offsetInChunk, length
token.origin = origin if origin
@tokens.push token
token
# crf tag:
# Find the last token that was parsed (unless you pass an index), and either return its TAG field, or set its TAG field.
# Peek at a tag in the current token stream.
tag: (index, tag) ->
(tok = last @tokens, index) and if tag then tok[0] = tag else tok[0]
# crf value
# This is a helper that is usually called as a getter, but can also be called as a "setter". To call it as a getter, call with no args, as in foo = @value();
# It will call "last" on the tokens array. "last" is the 4th helper from helpers.coffee. It gets the tail element of the array.
# # So, as a getter, this gets the last token from the tokens array and returns its tok[1]. tok[1] is the "value" field of the token (a token is [tag, value, locationData])
# as a "setter", it changes the "value" field of the last token.
# Peek at a value in the current token stream.
value: (index, val) ->
(tok = last @tokens, index) and if val then tok[1] = val else tok[1]
# Are we in the midst of an unfinished expression?
unfinished: ->
LINE_CONTINUER.test(@chunk) or
@tag() in ['\\', '.', '?.', '?::', 'UNARY', 'MATH', 'UNARY_MATH', '+', '-',
'**', 'SHIFT', 'RELATION', 'COMPARE', 'LOGIC', 'THROW', 'EXTENDS']
# Remove newlines from beginning and (non escaped) from end of string literals.
removeNewlines: (str) ->
str.replace(/^\s*\n\s*/, '')
.replace(/([^\\]|\\\\)\s*\n\s*$/, '$1')
# Converts newlines for string literals.
escapeLines: (str, heredoc) ->
# Ignore escaped backslashes and remove escaped newlines
str = str.replace /\\[^\S\n]*(\n|\\)\s*/g, (escaped, character) ->
if character is '\n' then '' else escaped
if heredoc
str.replace MULTILINER, '\\n'
else
str.replace /\s*\n\s*/g, ' '
# Constructs a string token by escaping quotes and newlines.
makeString: (body, quote, heredoc) ->
return quote + quote unless body
# Ignore escaped backslashes and unescape quotes
body = body.replace /// \\( #{quote} | \\ ) ///g, (match, contents) ->
if contents is quote then contents else match
body = body.replace /// #{quote} ///g, '\\$&'
quote + @escapeLines(body, heredoc) + quote
# Throws a compiler error on the current position.
error: (message, offset = 0) ->
# TODO: Are there some cases we could improve the error line number by
# passing the offset in the chunk where the error happened?
[first_line, first_column] = @getLineAndColumnFromChunk offset
throwSyntaxError message, {first_line, first_column}
# Constants
# ---------
# Keywords that CoffeeScript shares in common with JavaScript.
JS_KEYWORDS = [
'true', 'false', 'null', 'this'
'new', 'delete', 'typeof', 'in', 'instanceof'
'return', 'throw', 'break', 'continue', 'debugger'
'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally'
'class', 'extends', 'super'
]
# CoffeeScript-only keywords.
COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when']
COFFEE_ALIAS_MAP =
and : '&&'
or : '||'
is : '=='
isnt : '!='
not : '!'
yes : 'true'
no : 'false'
on : 'true'
off : 'false'
COFFEE_ALIASES = (key for key of COFFEE_ALIAS_MAP)
COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat COFFEE_ALIASES
# The list of keywords that are reserved by JavaScript, but not used, or are
# used by CoffeeScript internally. We throw an error when these are encountered,
# to avoid having a JavaScript error at runtime.
RESERVED = [
'case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum'
'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind'
'__indexOf', 'implements', 'interface', 'package', 'private', 'protected'
'public', 'static', 'yield'
]
STRICT_PROSCRIBED = ['arguments', 'eval']
# The superset of both JavaScript keywords and reserved words, none of which may
# be used as identifiers or properties.
JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED)
exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED)
exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED
# The character code of the nasty Microsoft madness otherwise known as the BOM.
BOM = 65279
# Token matching regexes.
IDENTIFIER = /// ^
( [$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]* )
( [^\n\S]* : (?!:) )? # Is this a property name?
///
NUMBER = ///
^ 0b[01]+ | # binary
^ 0o[0-7]+ | # octal
^ 0x[\da-f]+ | # hex
^ \d*\.?\d+ (?:e[+-]?\d+)? # decimal
///i
HEREDOC = /// ^ ("""|''') ((?: \\[\s\S] | [^\\] )*?) (?:\n[^\n\S]*)? \1 ///
OPERATOR = /// ^ (
?: [-=]> # function
| [-+*/%<>&|^!?=]= # compound assign / compare
| >>>=? # zero-fill right shift
| ([-+:])\1 # doubles
| ([&|<>*/%])\2=? # logic / shift / power / floor division / modulo
| \?(\.|::) # soak access
| \.{2,3} # range or splat
) ///
WHITESPACE = /^[^\n\S]+/
COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/
CODE = /^[-=]>/
MULTI_DENT = /^(?:\n[^\n\S]*)+/
SIMPLESTR = /^'[^\\']*(?:\\[\s\S][^\\']*)*'/
JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/
# Regex-matching-regexes.
REGEX = /// ^
(/ (?! [\s=] ) # disallow leading whitespace or equals signs
[^ [ / \n \\ ]* # every other thing
(?:
(?: \\[\s\S] # anything escaped
| \[ # character class
[^ \] \n \\ ]*
(?: \\[\s\S] [^ \] \n \\ ]* )*
]
) [^ [ / \n \\ ]*
)*
/) ([imgy]{0,4}) (?!\w)
///
HEREGEX = /// ^ /{3} ((?:\\?[\s\S])+?) /{3} ([imgy]{0,4}) (?!\w) ///
HEREGEX_OMIT = ///
((?:\\\\)+) # consume (and preserve) an even number of backslashes
| \\(\s|/) # preserve escaped whitespace and "de-escape" slashes
| \s+(?:#.*)? # remove whitespace and comments
///g
# Token cleaning regexes.
MULTILINER = /\n/g
HEREDOC_INDENT = /\n+([^\n\S]*)/g
HEREDOC_ILLEGAL = /\*\//
LINE_CONTINUER = /// ^ \s* (?: , | \??\.(?![.\d]) | :: ) ///
TRAILING_SPACES = /\s+$/
# Compound assignment tokens.
COMPOUND_ASSIGN = [
'-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>='
'&=', '^=', '|=', '**=', '//=', '%%='
]
# Unary tokens.
UNARY = ['NEW', 'TYPEOF', 'DELETE', 'DO']
UNARY_MATH = ['!', '~']
# Logical tokens.
LOGIC = ['&&', '||', '&', '|', '^']
# Bit-shifting tokens.
SHIFT = ['<<', '>>', '>>>']
# Comparison tokens.
COMPARE = ['==', '!=', '<', '>', '<=', '>=']
# Mathematical tokens.
MATH = ['*', '/', '%', '//', '%%']
# Relational tokens that are negatable with `not` prefix.
RELATION = ['IN', 'OF', 'INSTANCEOF']
# Boolean tokens.
BOOL = ['TRUE', 'FALSE']
# Tokens which a regular expression will never immediately follow, but which
# a division operator might.
#
# See: http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
#
# Our list is shorter, due to sans-parentheses method calls.
NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', 'NULL', 'UNDEFINED', '++', '--']
# If the previous token is not spaced, there are more preceding tokens that
# force a division parse:
NOT_SPACED_REGEX = NOT_REGEX.concat ')', '}', 'THIS', 'IDENTIFIER', 'STRING', ']'
# Tokens which could legitimately be invoked or indexed. An opening
# parentheses or bracket following these tokens will be recorded as the start
# of a function invocation or indexing operation.
CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER']
INDEXABLE = CALLABLE.concat 'NUMBER', 'BOOL', 'NULL', 'UNDEFINED'
# Tokens that, when immediately preceding a `WHEN`, indicate that the `WHEN`
# occurs at the start of a line. We disambiguate these from trailing whens to
# avoid an ambiguity in the grammar.
LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR']
# Additional indent in front of these is ignored.
INDENTABLE_CLOSERS = [')', '}', ']']
|
[
{
"context": "ictionaryDirectory)).toBe true\n\n string = 'Kein Kine vermöchten möchtzn'\n\n expect(@fixture.checkS",
"end": 9623,
"score": 0.6165922284126282,
"start": 9616,
"tag": "NAME",
"value": "in Kine"
}
] | spec/spellchecker-spec.coffee | LaudateCorpus1/node-spellchecker | 3 | {Spellchecker} = require '../lib/spellchecker'
path = require 'path'
enUS = 'A robot is a mechanical or virtual artificial agent, usually an electronic machine'
deDE = 'Ein Roboter ist eine technische Apparatur, die üblicherweise dazu dient, dem Menschen mechanische Arbeit abzunehmen.'
frFR = 'Les robots les plus évolués sont capables de se déplacer et de se recharger par eux-mêmes'
defaultLanguage = if process.platform is 'darwin' then '' else 'en_US'
dictionaryDirectory = path.join(__dirname, 'dictionaries')
# We can get different results based on using Hunspell, Mac, or Windows
# checkers. To simplify the rules, we create a variable that contains
# 'hunspell', 'mac', or 'win' for filtering. We also create an index variable
# to go into arrays.
if process.env.SPELLCHECKER_PREFER_HUNSPELL
spellType = 'hunspell'
spellIndex = 0
else if process.platform is 'darwin'
spellType = 'mac'
spellIndex = 1
else if process.platform is 'win32'
spellType = 'win'
spellIndex = 2
else
spellType = 'hunspell'
spellIndex = 0
# Because we are dealing with C++ and buffers, we want
# to make sure the user doesn't pass in a string that
# causes a buffer overrun. We limit our buffers to
# 256 characters (64-character word in UTF-8).
maximumLength1Byte = 'a'.repeat(256)
maximumLength2Byte = 'ö'.repeat(128)
maximumLength3Byte = 'ऐ'.repeat(85)
maximumLength4Byte = '𐅐'.repeat(64)
invalidLength1Byte = maximumLength1Byte + 'a'
invalidLength2Byte = maximumLength2Byte + 'ö'
invalidLength3Byte = maximumLength3Byte + 'ऐ'
invalidLength4Byte = maximumLength4Byte + '𐄇'
maximumLength1BytePair = [maximumLength1Byte, maximumLength1Byte].join " "
maximumLength2BytePair = [maximumLength2Byte, maximumLength2Byte].join " "
maximumLength3BytePair = [maximumLength3Byte, maximumLength3Byte].join " "
maximumLength4BytePair = [maximumLength4Byte, maximumLength4Byte].join " "
invalidLength1BytePair = [invalidLength1Byte, invalidLength1Byte].join " "
invalidLength2BytePair = [invalidLength2Byte, invalidLength2Byte].join " "
invalidLength3BytePair = [invalidLength3Byte, invalidLength3Byte].join " "
invalidLength4BytePair = [invalidLength4Byte, invalidLength4Byte].join " "
describe 'SpellChecker', ->
describe '.setDictionary', ->
beforeEach ->
@fixture = new Spellchecker()
it 'returns true for en_US', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
it 'returns true for de_DE_frami', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
it 'returns true for de_DE', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
it 'returns true for fr', ->
@fixture.setDictionary('fr', dictionaryDirectory)
describe '.isMisspelled(word)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns true if the word is mispelled', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
expect(@fixture.isMisspelled('wwoorrddd')).toBe true
it 'returns false if the word is not mispelled: word', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
expect(@fixture.isMisspelled('word')).toBe false
it 'returns false if the word is not mispelled: cheese', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
expect(@fixture.isMisspelled('cheese')).toBe false
it 'returns true if Latin German word is misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Kine')).toBe true
it 'returns true if Latin German word is misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Kine')).toBe true
it 'returns false if Latin German word is not misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Nacht')).toBe false
it 'returns false if Latin German word is not misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Nacht')).toBe false
it 'returns true if Unicode German word is misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('möchtzn')).toBe true
it 'returns true if Unicode German word is misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('möchtzn')).toBe true
it 'returns false if Unicode German word is not misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('vermöchten')).toBe false
it 'returns false if Unicode German word is not misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('vermöchten')).toBe false
it 'throws an exception when no word specified', ->
expect(-> @fixture.isMisspelled()).toThrow()
it 'returns true for a string of 256 1-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength1Byte)).toBe true
it 'returns true for a string of 128 2-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength2Byte)).toBe true
it 'returns true for a string of 85 3-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength3Byte)).toBe true
it 'returns true for a string of 64 4-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength4Byte)).toBe true
it 'returns false for a string of 257 1-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength1Byte)).toBe false
it 'returns false for a string of 65 2-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength2Byte)).toBe false
it 'returns false for a string of 86 3-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength3Byte)).toBe false
it 'returns false for a string of 65 4-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength4Byte)).toBe false
describe '.checkSpelling(string)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'automatically detects languages on OS X', ->
return unless process.platform is 'darwin'
expect(@fixture.checkSpelling(enUS)).toEqual []
expect(@fixture.checkSpelling(deDE)).toEqual []
expect(@fixture.checkSpelling(frFR)).toEqual []
it 'correctly switches languages', ->
expect(@fixture.setDictionary('en_US', dictionaryDirectory)).toBe true
expect(@fixture.checkSpelling(enUS)).toEqual []
expect(@fixture.checkSpelling(deDE)).not.toEqual []
expect(@fixture.checkSpelling(frFR)).not.toEqual []
# de_DE_frami is invalid outside of Hunspell dictionaries.
if spellType is 'hunspell'
if @fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(enUS)).not.toEqual []
expect(@fixture.checkSpelling(deDE)).toEqual []
expect(@fixture.checkSpelling(frFR)).not.toEqual []
if @fixture.setDictionary('de_DE', dictionaryDirectory)
expect(@fixture.checkSpelling(enUS)).not.toEqual []
expect(@fixture.checkSpelling(deDE)).toEqual []
expect(@fixture.checkSpelling(frFR)).not.toEqual []
@fixture = new Spellchecker()
if @fixture.setDictionary('fr_FR', dictionaryDirectory)
expect(@fixture.checkSpelling(enUS)).not.toEqual []
expect(@fixture.checkSpelling(deDE)).not.toEqual []
expect(@fixture.checkSpelling(frFR)).toEqual []
it 'returns an array of character ranges of misspelled words', ->
string = 'cat caat dog dooog'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 4, end: 8},
{start: 13, end: 18},
]
it 'returns an array of character ranges of misspelled German words with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
string = 'Kein Kine vermöchten möchtzn'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 5, end: 9},
{start: 21, end: 28},
]
it 'returns an array of character ranges of misspelled German words with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
string = 'Kein Kine vermöchten möchtzn'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 5, end: 9},
{start: 21, end: 28},
]
it 'returns an array of character ranges of misspelled French words', ->
expect(@fixture.setDictionary('fr', dictionaryDirectory)).toBe true
string = 'Française Françoize'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 10, end: 19},
]
it 'accounts for UTF16 pairs', ->
string = '😎 cat caat dog dooog'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 7, end: 11},
{start: 16, end: 21},
]
it "accounts for other non-word characters", ->
string = "'cat' (caat. <dog> :dooog)"
expect(@fixture.checkSpelling(string)).toEqual [
{start: 7, end: 11},
{start: 20, end: 25},
]
it 'does not treat non-english letters as word boundaries', ->
@fixture.add('cliché')
expect(@fixture.checkSpelling('what cliché nonsense')).toEqual []
@fixture.remove('cliché')
it 'handles words with apostrophes', ->
string = "doesn't isn't aint hasn't"
expect(@fixture.checkSpelling(string)).toEqual [
{start: string.indexOf("aint"), end: string.indexOf("aint") + 4}
]
string = "you say you're 'certain', but are you really?"
expect(@fixture.checkSpelling(string)).toEqual []
string = "you say you're 'sertan', but are you really?"
expect(@fixture.checkSpelling(string)).toEqual [
{start: string.indexOf("sertan"), end: string.indexOf("',")}
]
it 'handles invalid inputs', ->
fixture = @fixture
expect(fixture.checkSpelling('')).toEqual []
expect(-> fixture.checkSpelling()).toThrow('Bad argument')
expect(-> fixture.checkSpelling(null)).toThrow('Bad argument')
expect(-> fixture.checkSpelling({})).toThrow('Bad argument')
it 'returns values for a pair of 256 1-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(maximumLength1BytePair)).toEqual [
{start: 0, end: 256},
{start: 257, end: 513},
]
it 'returns values for a string of 128 2-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(maximumLength2BytePair)).toEqual [
{start: 0, end: 128},
{start: 129, end: 257},
]
it 'returns values for a string of 85 3-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(maximumLength3BytePair)).toEqual [
{start: 0, end: 85},
{start: 86, end: 171},
]
# # Linux doesn't seem to handle 4-byte encodings, so this test is just to
# # comment that fact.
# xit 'returns values for a string of 64 4-byte character strings', ->
# expect(@fixture.checkSpelling(maximumLength4BytePair)).toEqual [
# {start: 0, end: 128},
# {start: 129, end: 257},
# ]
it 'returns nothing for a pair of 257 1-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength1BytePair)).toEqual []
it 'returns nothing for a pair of 129 2-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength2BytePair)).toEqual []
it 'returns nothing for a pair of 86 3-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength3BytePair)).toEqual []
it 'returns nothing for a pair of 65 4-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength4BytePair)).toEqual []
it 'returns values for a pair of 256 1-byte character strings with encoding', ->
if process.platform is 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(maximumLength1BytePair)).toEqual [
{start: 0, end: 256},
{start: 257, end: 513},
]
it 'returns values for a string of 128 2-byte character strings with encoding', ->
if process.platform is 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(maximumLength2BytePair)).toEqual [
{start: 0, end: 128},
{start: 129, end: 257},
]
it 'returns values for a string of 85 3-byte character strings with encoding', ->
if process.platform is 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength3BytePair)
# # Linux doesn't seem to handle 4-byte encodings
#it 'returns values for a string of 64 4-byte character strings with encoding', ->
# # de_DE_frami is invalid outside of Hunspell dictionaries.
# return unless spellType is 'hunspell'
# @fixture.setDictionary('de_DE_frami', dictionaryDirectory)
# expect(@fixture.checkSpelling(maximumLength4BytePair)).toEqual [
# {start: 0, end: 128},
# {start: 129, end: 257},
# ]
it 'returns nothing for a pair of 257 1-byte character strings with encoding', ->
if process.platform is not 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(maximumLength2BytePair)).toEqual []
it 'returns nothing for a pair of 129 2-byte character strings with encoding', ->
return if process.platform is not 'linux'
# We are only testing for allocation errors.
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength2BytePair)
it 'returns nothing for a pair of 86 3-byte character strings with encoding', ->
return if process.platform is not 'linux'
# We are only testing for allocation errors.
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength3BytePair)
it 'returns nothing for a pair of 65 4-byte character strings with encoding', ->
return if process.platform is not 'linux'
# We are only testing for allocation errors.
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength4BytePair)
describe '.checkSpellingAsync(string)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns an array of character ranges of misspelled words', ->
string = 'cat caat dog dooog'
ranges = null
@fixture.checkSpellingAsync(string).then (r) -> ranges = r
waitsFor -> ranges isnt null
runs ->
expect(ranges).toEqual [
{start: 4, end: 8}
{start: 13, end: 18}
]
it 'handles invalid inputs', ->
expect(=> @fixture.checkSpelling()).toThrow('Bad argument')
expect(=> @fixture.checkSpelling(null)).toThrow('Bad argument')
expect(=> @fixture.checkSpelling(47)).toThrow('Bad argument')
describe '.getCorrectionsForMisspelling(word)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns an array of possible corrections', ->
correction = ['word', 'world', 'word'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('worrd')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'throws an exception when no word specified', ->
expect(-> @fixture.getCorrectionsForMisspelling()).toThrow()
it 'returns an array of possible corrections for a correct English word', ->
correction = ['cheese', 'chaise', 'cheesy'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('cheese')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a correct Latin German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['Acht', 'Macht', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a correct Latin German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['Acht', 'Macht', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a incorrect Latin German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['Acht', 'Nicht', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a incorrect Latin German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['Acht', 'SEE BELOW', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
if spellType == "mac"
# For some reason, the CI build will produce inconsistent results on
# the Mac based on some external factor.
expect(corrections[0] is 'Nicht' or corrections[0] is 'Macht').toEqual(true)
else
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for correct Unicode German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['vermöchten', 'vermochten', 'vermochte'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('vermöchten')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for correct Unicode German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['vermöchten', 'vermochten', 'vermochte'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('vermöchten')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for incorrect Unicode German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['möchten', 'möchten', 'möchten'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('möchtzn')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for incorrect Unicode German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['möchten', 'möchten', 'möchten'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('möchtzn')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for correct Unicode French word', ->
expect(@fixture.setDictionary('fr', dictionaryDirectory)).toBe true
correction = ['Françoise', 'Françoise', 'française'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Française')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for incorrect Unicode French word', ->
expect(@fixture.setDictionary('fr', dictionaryDirectory)).toBe true
correction = ['Françoise', 'Françoise', 'Françoise'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Françoize')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
describe '.add(word) and .remove(word)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'allows words to be added and removed to the dictionary', ->
# NB: Windows spellchecker cannot remove words, and since it holds onto
# words, rerunning this test >1 time causes it to incorrectly fail
return if process.platform is 'win32'
expect(@fixture.isMisspelled('wwoorrdd')).toBe true
@fixture.add('wwoorrdd')
expect(@fixture.isMisspelled('wwoorrdd')).toBe false
@fixture.remove('wwoorrdd')
expect(@fixture.isMisspelled('wwoorrdd')).toBe true
it 'add throws an error if no word is specified', ->
errorOccurred = false
try
@fixture.add()
catch
errorOccurred = true
expect(errorOccurred).toBe true
it 'remove throws an error if no word is specified', ->
errorOccurred = false
try
@fixture.remove()
catch
errorOccurred = true
expect(errorOccurred).toBe true
describe '.getAvailableDictionaries()', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns an array of string dictionary names', ->
# NB: getAvailableDictionaries is nop'ped in hunspell and it also doesn't
# work inside Appveyor's CI environment
return if spellType is 'hunspell' or process.env.CI
dictionaries = @fixture.getAvailableDictionaries()
expect(Array.isArray(dictionaries)).toBe true
expect(dictionaries.length).toBeGreaterThan 0
for dictionary in dictionaries.length
expect(typeof dictionary).toBe 'string'
expect(diction.length).toBeGreaterThan 0
describe '.setDictionary(lang, dictDirectory)', ->
it 'sets the spell checkers language, and dictionary directory', ->
awesome = true
expect(awesome).toBe true
| 58770 | {Spellchecker} = require '../lib/spellchecker'
path = require 'path'
enUS = 'A robot is a mechanical or virtual artificial agent, usually an electronic machine'
deDE = 'Ein Roboter ist eine technische Apparatur, die üblicherweise dazu dient, dem Menschen mechanische Arbeit abzunehmen.'
frFR = 'Les robots les plus évolués sont capables de se déplacer et de se recharger par eux-mêmes'
defaultLanguage = if process.platform is 'darwin' then '' else 'en_US'
dictionaryDirectory = path.join(__dirname, 'dictionaries')
# We can get different results based on using Hunspell, Mac, or Windows
# checkers. To simplify the rules, we create a variable that contains
# 'hunspell', 'mac', or 'win' for filtering. We also create an index variable
# to go into arrays.
if process.env.SPELLCHECKER_PREFER_HUNSPELL
spellType = 'hunspell'
spellIndex = 0
else if process.platform is 'darwin'
spellType = 'mac'
spellIndex = 1
else if process.platform is 'win32'
spellType = 'win'
spellIndex = 2
else
spellType = 'hunspell'
spellIndex = 0
# Because we are dealing with C++ and buffers, we want
# to make sure the user doesn't pass in a string that
# causes a buffer overrun. We limit our buffers to
# 256 characters (64-character word in UTF-8).
maximumLength1Byte = 'a'.repeat(256)
maximumLength2Byte = 'ö'.repeat(128)
maximumLength3Byte = 'ऐ'.repeat(85)
maximumLength4Byte = '𐅐'.repeat(64)
invalidLength1Byte = maximumLength1Byte + 'a'
invalidLength2Byte = maximumLength2Byte + 'ö'
invalidLength3Byte = maximumLength3Byte + 'ऐ'
invalidLength4Byte = maximumLength4Byte + '𐄇'
maximumLength1BytePair = [maximumLength1Byte, maximumLength1Byte].join " "
maximumLength2BytePair = [maximumLength2Byte, maximumLength2Byte].join " "
maximumLength3BytePair = [maximumLength3Byte, maximumLength3Byte].join " "
maximumLength4BytePair = [maximumLength4Byte, maximumLength4Byte].join " "
invalidLength1BytePair = [invalidLength1Byte, invalidLength1Byte].join " "
invalidLength2BytePair = [invalidLength2Byte, invalidLength2Byte].join " "
invalidLength3BytePair = [invalidLength3Byte, invalidLength3Byte].join " "
invalidLength4BytePair = [invalidLength4Byte, invalidLength4Byte].join " "
describe 'SpellChecker', ->
describe '.setDictionary', ->
beforeEach ->
@fixture = new Spellchecker()
it 'returns true for en_US', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
it 'returns true for de_DE_frami', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
it 'returns true for de_DE', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
it 'returns true for fr', ->
@fixture.setDictionary('fr', dictionaryDirectory)
describe '.isMisspelled(word)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns true if the word is mispelled', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
expect(@fixture.isMisspelled('wwoorrddd')).toBe true
it 'returns false if the word is not mispelled: word', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
expect(@fixture.isMisspelled('word')).toBe false
it 'returns false if the word is not mispelled: cheese', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
expect(@fixture.isMisspelled('cheese')).toBe false
it 'returns true if Latin German word is misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Kine')).toBe true
it 'returns true if Latin German word is misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Kine')).toBe true
it 'returns false if Latin German word is not misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Nacht')).toBe false
it 'returns false if Latin German word is not misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Nacht')).toBe false
it 'returns true if Unicode German word is misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('möchtzn')).toBe true
it 'returns true if Unicode German word is misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('möchtzn')).toBe true
it 'returns false if Unicode German word is not misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('vermöchten')).toBe false
it 'returns false if Unicode German word is not misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('vermöchten')).toBe false
it 'throws an exception when no word specified', ->
expect(-> @fixture.isMisspelled()).toThrow()
it 'returns true for a string of 256 1-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength1Byte)).toBe true
it 'returns true for a string of 128 2-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength2Byte)).toBe true
it 'returns true for a string of 85 3-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength3Byte)).toBe true
it 'returns true for a string of 64 4-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength4Byte)).toBe true
it 'returns false for a string of 257 1-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength1Byte)).toBe false
it 'returns false for a string of 65 2-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength2Byte)).toBe false
it 'returns false for a string of 86 3-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength3Byte)).toBe false
it 'returns false for a string of 65 4-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength4Byte)).toBe false
describe '.checkSpelling(string)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'automatically detects languages on OS X', ->
return unless process.platform is 'darwin'
expect(@fixture.checkSpelling(enUS)).toEqual []
expect(@fixture.checkSpelling(deDE)).toEqual []
expect(@fixture.checkSpelling(frFR)).toEqual []
it 'correctly switches languages', ->
expect(@fixture.setDictionary('en_US', dictionaryDirectory)).toBe true
expect(@fixture.checkSpelling(enUS)).toEqual []
expect(@fixture.checkSpelling(deDE)).not.toEqual []
expect(@fixture.checkSpelling(frFR)).not.toEqual []
# de_DE_frami is invalid outside of Hunspell dictionaries.
if spellType is 'hunspell'
if @fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(enUS)).not.toEqual []
expect(@fixture.checkSpelling(deDE)).toEqual []
expect(@fixture.checkSpelling(frFR)).not.toEqual []
if @fixture.setDictionary('de_DE', dictionaryDirectory)
expect(@fixture.checkSpelling(enUS)).not.toEqual []
expect(@fixture.checkSpelling(deDE)).toEqual []
expect(@fixture.checkSpelling(frFR)).not.toEqual []
@fixture = new Spellchecker()
if @fixture.setDictionary('fr_FR', dictionaryDirectory)
expect(@fixture.checkSpelling(enUS)).not.toEqual []
expect(@fixture.checkSpelling(deDE)).not.toEqual []
expect(@fixture.checkSpelling(frFR)).toEqual []
it 'returns an array of character ranges of misspelled words', ->
string = 'cat caat dog dooog'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 4, end: 8},
{start: 13, end: 18},
]
it 'returns an array of character ranges of misspelled German words with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
string = 'Kein Kine vermöchten möchtzn'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 5, end: 9},
{start: 21, end: 28},
]
it 'returns an array of character ranges of misspelled German words with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
string = 'Ke<NAME> vermöchten möchtzn'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 5, end: 9},
{start: 21, end: 28},
]
it 'returns an array of character ranges of misspelled French words', ->
expect(@fixture.setDictionary('fr', dictionaryDirectory)).toBe true
string = 'Française Françoize'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 10, end: 19},
]
it 'accounts for UTF16 pairs', ->
string = '😎 cat caat dog dooog'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 7, end: 11},
{start: 16, end: 21},
]
it "accounts for other non-word characters", ->
string = "'cat' (caat. <dog> :dooog)"
expect(@fixture.checkSpelling(string)).toEqual [
{start: 7, end: 11},
{start: 20, end: 25},
]
it 'does not treat non-english letters as word boundaries', ->
@fixture.add('cliché')
expect(@fixture.checkSpelling('what cliché nonsense')).toEqual []
@fixture.remove('cliché')
it 'handles words with apostrophes', ->
string = "doesn't isn't aint hasn't"
expect(@fixture.checkSpelling(string)).toEqual [
{start: string.indexOf("aint"), end: string.indexOf("aint") + 4}
]
string = "you say you're 'certain', but are you really?"
expect(@fixture.checkSpelling(string)).toEqual []
string = "you say you're 'sertan', but are you really?"
expect(@fixture.checkSpelling(string)).toEqual [
{start: string.indexOf("sertan"), end: string.indexOf("',")}
]
it 'handles invalid inputs', ->
fixture = @fixture
expect(fixture.checkSpelling('')).toEqual []
expect(-> fixture.checkSpelling()).toThrow('Bad argument')
expect(-> fixture.checkSpelling(null)).toThrow('Bad argument')
expect(-> fixture.checkSpelling({})).toThrow('Bad argument')
it 'returns values for a pair of 256 1-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(maximumLength1BytePair)).toEqual [
{start: 0, end: 256},
{start: 257, end: 513},
]
it 'returns values for a string of 128 2-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(maximumLength2BytePair)).toEqual [
{start: 0, end: 128},
{start: 129, end: 257},
]
it 'returns values for a string of 85 3-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(maximumLength3BytePair)).toEqual [
{start: 0, end: 85},
{start: 86, end: 171},
]
# # Linux doesn't seem to handle 4-byte encodings, so this test is just to
# # comment that fact.
# xit 'returns values for a string of 64 4-byte character strings', ->
# expect(@fixture.checkSpelling(maximumLength4BytePair)).toEqual [
# {start: 0, end: 128},
# {start: 129, end: 257},
# ]
it 'returns nothing for a pair of 257 1-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength1BytePair)).toEqual []
it 'returns nothing for a pair of 129 2-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength2BytePair)).toEqual []
it 'returns nothing for a pair of 86 3-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength3BytePair)).toEqual []
it 'returns nothing for a pair of 65 4-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength4BytePair)).toEqual []
it 'returns values for a pair of 256 1-byte character strings with encoding', ->
if process.platform is 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(maximumLength1BytePair)).toEqual [
{start: 0, end: 256},
{start: 257, end: 513},
]
it 'returns values for a string of 128 2-byte character strings with encoding', ->
if process.platform is 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(maximumLength2BytePair)).toEqual [
{start: 0, end: 128},
{start: 129, end: 257},
]
it 'returns values for a string of 85 3-byte character strings with encoding', ->
if process.platform is 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength3BytePair)
# # Linux doesn't seem to handle 4-byte encodings
#it 'returns values for a string of 64 4-byte character strings with encoding', ->
# # de_DE_frami is invalid outside of Hunspell dictionaries.
# return unless spellType is 'hunspell'
# @fixture.setDictionary('de_DE_frami', dictionaryDirectory)
# expect(@fixture.checkSpelling(maximumLength4BytePair)).toEqual [
# {start: 0, end: 128},
# {start: 129, end: 257},
# ]
it 'returns nothing for a pair of 257 1-byte character strings with encoding', ->
if process.platform is not 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(maximumLength2BytePair)).toEqual []
it 'returns nothing for a pair of 129 2-byte character strings with encoding', ->
return if process.platform is not 'linux'
# We are only testing for allocation errors.
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength2BytePair)
it 'returns nothing for a pair of 86 3-byte character strings with encoding', ->
return if process.platform is not 'linux'
# We are only testing for allocation errors.
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength3BytePair)
it 'returns nothing for a pair of 65 4-byte character strings with encoding', ->
return if process.platform is not 'linux'
# We are only testing for allocation errors.
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength4BytePair)
describe '.checkSpellingAsync(string)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns an array of character ranges of misspelled words', ->
string = 'cat caat dog dooog'
ranges = null
@fixture.checkSpellingAsync(string).then (r) -> ranges = r
waitsFor -> ranges isnt null
runs ->
expect(ranges).toEqual [
{start: 4, end: 8}
{start: 13, end: 18}
]
it 'handles invalid inputs', ->
expect(=> @fixture.checkSpelling()).toThrow('Bad argument')
expect(=> @fixture.checkSpelling(null)).toThrow('Bad argument')
expect(=> @fixture.checkSpelling(47)).toThrow('Bad argument')
describe '.getCorrectionsForMisspelling(word)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns an array of possible corrections', ->
correction = ['word', 'world', 'word'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('worrd')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'throws an exception when no word specified', ->
expect(-> @fixture.getCorrectionsForMisspelling()).toThrow()
it 'returns an array of possible corrections for a correct English word', ->
correction = ['cheese', 'chaise', 'cheesy'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('cheese')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a correct Latin German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['Acht', 'Macht', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a correct Latin German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['Acht', 'Macht', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a incorrect Latin German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['Acht', 'Nicht', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a incorrect Latin German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['Acht', 'SEE BELOW', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
if spellType == "mac"
# For some reason, the CI build will produce inconsistent results on
# the Mac based on some external factor.
expect(corrections[0] is 'Nicht' or corrections[0] is 'Macht').toEqual(true)
else
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for correct Unicode German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['vermöchten', 'vermochten', 'vermochte'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('vermöchten')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for correct Unicode German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['vermöchten', 'vermochten', 'vermochte'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('vermöchten')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for incorrect Unicode German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['möchten', 'möchten', 'möchten'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('möchtzn')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for incorrect Unicode German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['möchten', 'möchten', 'möchten'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('möchtzn')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for correct Unicode French word', ->
expect(@fixture.setDictionary('fr', dictionaryDirectory)).toBe true
correction = ['Françoise', 'Françoise', 'française'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Française')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for incorrect Unicode French word', ->
expect(@fixture.setDictionary('fr', dictionaryDirectory)).toBe true
correction = ['Françoise', 'Françoise', 'Françoise'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Françoize')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
describe '.add(word) and .remove(word)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'allows words to be added and removed to the dictionary', ->
# NB: Windows spellchecker cannot remove words, and since it holds onto
# words, rerunning this test >1 time causes it to incorrectly fail
return if process.platform is 'win32'
expect(@fixture.isMisspelled('wwoorrdd')).toBe true
@fixture.add('wwoorrdd')
expect(@fixture.isMisspelled('wwoorrdd')).toBe false
@fixture.remove('wwoorrdd')
expect(@fixture.isMisspelled('wwoorrdd')).toBe true
it 'add throws an error if no word is specified', ->
errorOccurred = false
try
@fixture.add()
catch
errorOccurred = true
expect(errorOccurred).toBe true
it 'remove throws an error if no word is specified', ->
errorOccurred = false
try
@fixture.remove()
catch
errorOccurred = true
expect(errorOccurred).toBe true
describe '.getAvailableDictionaries()', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns an array of string dictionary names', ->
# NB: getAvailableDictionaries is nop'ped in hunspell and it also doesn't
# work inside Appveyor's CI environment
return if spellType is 'hunspell' or process.env.CI
dictionaries = @fixture.getAvailableDictionaries()
expect(Array.isArray(dictionaries)).toBe true
expect(dictionaries.length).toBeGreaterThan 0
for dictionary in dictionaries.length
expect(typeof dictionary).toBe 'string'
expect(diction.length).toBeGreaterThan 0
describe '.setDictionary(lang, dictDirectory)', ->
it 'sets the spell checkers language, and dictionary directory', ->
awesome = true
expect(awesome).toBe true
| true | {Spellchecker} = require '../lib/spellchecker'
path = require 'path'
enUS = 'A robot is a mechanical or virtual artificial agent, usually an electronic machine'
deDE = 'Ein Roboter ist eine technische Apparatur, die üblicherweise dazu dient, dem Menschen mechanische Arbeit abzunehmen.'
frFR = 'Les robots les plus évolués sont capables de se déplacer et de se recharger par eux-mêmes'
defaultLanguage = if process.platform is 'darwin' then '' else 'en_US'
dictionaryDirectory = path.join(__dirname, 'dictionaries')
# We can get different results based on using Hunspell, Mac, or Windows
# checkers. To simplify the rules, we create a variable that contains
# 'hunspell', 'mac', or 'win' for filtering. We also create an index variable
# to go into arrays.
if process.env.SPELLCHECKER_PREFER_HUNSPELL
spellType = 'hunspell'
spellIndex = 0
else if process.platform is 'darwin'
spellType = 'mac'
spellIndex = 1
else if process.platform is 'win32'
spellType = 'win'
spellIndex = 2
else
spellType = 'hunspell'
spellIndex = 0
# Because we are dealing with C++ and buffers, we want
# to make sure the user doesn't pass in a string that
# causes a buffer overrun. We limit our buffers to
# 256 characters (64-character word in UTF-8).
maximumLength1Byte = 'a'.repeat(256)
maximumLength2Byte = 'ö'.repeat(128)
maximumLength3Byte = 'ऐ'.repeat(85)
maximumLength4Byte = '𐅐'.repeat(64)
invalidLength1Byte = maximumLength1Byte + 'a'
invalidLength2Byte = maximumLength2Byte + 'ö'
invalidLength3Byte = maximumLength3Byte + 'ऐ'
invalidLength4Byte = maximumLength4Byte + '𐄇'
maximumLength1BytePair = [maximumLength1Byte, maximumLength1Byte].join " "
maximumLength2BytePair = [maximumLength2Byte, maximumLength2Byte].join " "
maximumLength3BytePair = [maximumLength3Byte, maximumLength3Byte].join " "
maximumLength4BytePair = [maximumLength4Byte, maximumLength4Byte].join " "
invalidLength1BytePair = [invalidLength1Byte, invalidLength1Byte].join " "
invalidLength2BytePair = [invalidLength2Byte, invalidLength2Byte].join " "
invalidLength3BytePair = [invalidLength3Byte, invalidLength3Byte].join " "
invalidLength4BytePair = [invalidLength4Byte, invalidLength4Byte].join " "
describe 'SpellChecker', ->
describe '.setDictionary', ->
beforeEach ->
@fixture = new Spellchecker()
it 'returns true for en_US', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
it 'returns true for de_DE_frami', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
it 'returns true for de_DE', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
it 'returns true for fr', ->
@fixture.setDictionary('fr', dictionaryDirectory)
describe '.isMisspelled(word)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns true if the word is mispelled', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
expect(@fixture.isMisspelled('wwoorrddd')).toBe true
it 'returns false if the word is not mispelled: word', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
expect(@fixture.isMisspelled('word')).toBe false
it 'returns false if the word is not mispelled: cheese', ->
@fixture.setDictionary('en_US', dictionaryDirectory)
expect(@fixture.isMisspelled('cheese')).toBe false
it 'returns true if Latin German word is misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Kine')).toBe true
it 'returns true if Latin German word is misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Kine')).toBe true
it 'returns false if Latin German word is not misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Nacht')).toBe false
it 'returns false if Latin German word is not misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('Nacht')).toBe false
it 'returns true if Unicode German word is misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('möchtzn')).toBe true
it 'returns true if Unicode German word is misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('möchtzn')).toBe true
it 'returns false if Unicode German word is not misspelled with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('vermöchten')).toBe false
it 'returns false if Unicode German word is not misspelled with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
expect(@fixture.isMisspelled('vermöchten')).toBe false
it 'throws an exception when no word specified', ->
expect(-> @fixture.isMisspelled()).toThrow()
it 'returns true for a string of 256 1-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength1Byte)).toBe true
it 'returns true for a string of 128 2-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength2Byte)).toBe true
it 'returns true for a string of 85 3-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength3Byte)).toBe true
it 'returns true for a string of 64 4-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(maximumLength4Byte)).toBe true
it 'returns false for a string of 257 1-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength1Byte)).toBe false
it 'returns false for a string of 65 2-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength2Byte)).toBe false
it 'returns false for a string of 86 3-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength3Byte)).toBe false
it 'returns false for a string of 65 4-byte characters', ->
if process.platform is 'linux'
expect(@fixture.isMisspelled(invalidLength4Byte)).toBe false
describe '.checkSpelling(string)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'automatically detects languages on OS X', ->
return unless process.platform is 'darwin'
expect(@fixture.checkSpelling(enUS)).toEqual []
expect(@fixture.checkSpelling(deDE)).toEqual []
expect(@fixture.checkSpelling(frFR)).toEqual []
it 'correctly switches languages', ->
expect(@fixture.setDictionary('en_US', dictionaryDirectory)).toBe true
expect(@fixture.checkSpelling(enUS)).toEqual []
expect(@fixture.checkSpelling(deDE)).not.toEqual []
expect(@fixture.checkSpelling(frFR)).not.toEqual []
# de_DE_frami is invalid outside of Hunspell dictionaries.
if spellType is 'hunspell'
if @fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(enUS)).not.toEqual []
expect(@fixture.checkSpelling(deDE)).toEqual []
expect(@fixture.checkSpelling(frFR)).not.toEqual []
if @fixture.setDictionary('de_DE', dictionaryDirectory)
expect(@fixture.checkSpelling(enUS)).not.toEqual []
expect(@fixture.checkSpelling(deDE)).toEqual []
expect(@fixture.checkSpelling(frFR)).not.toEqual []
@fixture = new Spellchecker()
if @fixture.setDictionary('fr_FR', dictionaryDirectory)
expect(@fixture.checkSpelling(enUS)).not.toEqual []
expect(@fixture.checkSpelling(deDE)).not.toEqual []
expect(@fixture.checkSpelling(frFR)).toEqual []
it 'returns an array of character ranges of misspelled words', ->
string = 'cat caat dog dooog'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 4, end: 8},
{start: 13, end: 18},
]
it 'returns an array of character ranges of misspelled German words with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
string = 'Kein Kine vermöchten möchtzn'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 5, end: 9},
{start: 21, end: 28},
]
it 'returns an array of character ranges of misspelled German words with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
string = 'KePI:NAME:<NAME>END_PI vermöchten möchtzn'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 5, end: 9},
{start: 21, end: 28},
]
it 'returns an array of character ranges of misspelled French words', ->
expect(@fixture.setDictionary('fr', dictionaryDirectory)).toBe true
string = 'Française Françoize'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 10, end: 19},
]
it 'accounts for UTF16 pairs', ->
string = '😎 cat caat dog dooog'
expect(@fixture.checkSpelling(string)).toEqual [
{start: 7, end: 11},
{start: 16, end: 21},
]
it "accounts for other non-word characters", ->
string = "'cat' (caat. <dog> :dooog)"
expect(@fixture.checkSpelling(string)).toEqual [
{start: 7, end: 11},
{start: 20, end: 25},
]
it 'does not treat non-english letters as word boundaries', ->
@fixture.add('cliché')
expect(@fixture.checkSpelling('what cliché nonsense')).toEqual []
@fixture.remove('cliché')
it 'handles words with apostrophes', ->
string = "doesn't isn't aint hasn't"
expect(@fixture.checkSpelling(string)).toEqual [
{start: string.indexOf("aint"), end: string.indexOf("aint") + 4}
]
string = "you say you're 'certain', but are you really?"
expect(@fixture.checkSpelling(string)).toEqual []
string = "you say you're 'sertan', but are you really?"
expect(@fixture.checkSpelling(string)).toEqual [
{start: string.indexOf("sertan"), end: string.indexOf("',")}
]
it 'handles invalid inputs', ->
fixture = @fixture
expect(fixture.checkSpelling('')).toEqual []
expect(-> fixture.checkSpelling()).toThrow('Bad argument')
expect(-> fixture.checkSpelling(null)).toThrow('Bad argument')
expect(-> fixture.checkSpelling({})).toThrow('Bad argument')
it 'returns values for a pair of 256 1-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(maximumLength1BytePair)).toEqual [
{start: 0, end: 256},
{start: 257, end: 513},
]
it 'returns values for a string of 128 2-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(maximumLength2BytePair)).toEqual [
{start: 0, end: 128},
{start: 129, end: 257},
]
it 'returns values for a string of 85 3-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(maximumLength3BytePair)).toEqual [
{start: 0, end: 85},
{start: 86, end: 171},
]
# # Linux doesn't seem to handle 4-byte encodings, so this test is just to
# # comment that fact.
# xit 'returns values for a string of 64 4-byte character strings', ->
# expect(@fixture.checkSpelling(maximumLength4BytePair)).toEqual [
# {start: 0, end: 128},
# {start: 129, end: 257},
# ]
it 'returns nothing for a pair of 257 1-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength1BytePair)).toEqual []
it 'returns nothing for a pair of 129 2-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength2BytePair)).toEqual []
it 'returns nothing for a pair of 86 3-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength3BytePair)).toEqual []
it 'returns nothing for a pair of 65 4-byte character strings', ->
if process.platform is 'linux'
expect(@fixture.checkSpelling(invalidLength4BytePair)).toEqual []
it 'returns values for a pair of 256 1-byte character strings with encoding', ->
if process.platform is 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(maximumLength1BytePair)).toEqual [
{start: 0, end: 256},
{start: 257, end: 513},
]
it 'returns values for a string of 128 2-byte character strings with encoding', ->
if process.platform is 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(maximumLength2BytePair)).toEqual [
{start: 0, end: 128},
{start: 129, end: 257},
]
it 'returns values for a string of 85 3-byte character strings with encoding', ->
if process.platform is 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength3BytePair)
# # Linux doesn't seem to handle 4-byte encodings
#it 'returns values for a string of 64 4-byte character strings with encoding', ->
# # de_DE_frami is invalid outside of Hunspell dictionaries.
# return unless spellType is 'hunspell'
# @fixture.setDictionary('de_DE_frami', dictionaryDirectory)
# expect(@fixture.checkSpelling(maximumLength4BytePair)).toEqual [
# {start: 0, end: 128},
# {start: 129, end: 257},
# ]
it 'returns nothing for a pair of 257 1-byte character strings with encoding', ->
if process.platform is not 'linux'
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
expect(@fixture.checkSpelling(maximumLength2BytePair)).toEqual []
it 'returns nothing for a pair of 129 2-byte character strings with encoding', ->
return if process.platform is not 'linux'
# We are only testing for allocation errors.
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength2BytePair)
it 'returns nothing for a pair of 86 3-byte character strings with encoding', ->
return if process.platform is not 'linux'
# We are only testing for allocation errors.
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength3BytePair)
it 'returns nothing for a pair of 65 4-byte character strings with encoding', ->
return if process.platform is not 'linux'
# We are only testing for allocation errors.
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
@fixture.setDictionary('de_DE_frami', dictionaryDirectory)
@fixture.checkSpelling(invalidLength4BytePair)
describe '.checkSpellingAsync(string)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns an array of character ranges of misspelled words', ->
string = 'cat caat dog dooog'
ranges = null
@fixture.checkSpellingAsync(string).then (r) -> ranges = r
waitsFor -> ranges isnt null
runs ->
expect(ranges).toEqual [
{start: 4, end: 8}
{start: 13, end: 18}
]
it 'handles invalid inputs', ->
expect(=> @fixture.checkSpelling()).toThrow('Bad argument')
expect(=> @fixture.checkSpelling(null)).toThrow('Bad argument')
expect(=> @fixture.checkSpelling(47)).toThrow('Bad argument')
describe '.getCorrectionsForMisspelling(word)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns an array of possible corrections', ->
correction = ['word', 'world', 'word'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('worrd')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'throws an exception when no word specified', ->
expect(-> @fixture.getCorrectionsForMisspelling()).toThrow()
it 'returns an array of possible corrections for a correct English word', ->
correction = ['cheese', 'chaise', 'cheesy'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('cheese')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a correct Latin German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['Acht', 'Macht', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a correct Latin German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['Acht', 'Macht', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a incorrect Latin German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['Acht', 'Nicht', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for a incorrect Latin German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['Acht', 'SEE BELOW', 'Acht'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Nacht')
expect(corrections.length).toBeGreaterThan 0
if spellType == "mac"
# For some reason, the CI build will produce inconsistent results on
# the Mac based on some external factor.
expect(corrections[0] is 'Nicht' or corrections[0] is 'Macht').toEqual(true)
else
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for correct Unicode German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['vermöchten', 'vermochten', 'vermochte'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('vermöchten')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for correct Unicode German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['vermöchten', 'vermochten', 'vermochte'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('vermöchten')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for incorrect Unicode German word with ISO8859-1 file', ->
# de_DE_frami is invalid outside of Hunspell dictionaries.
return unless spellType is 'hunspell'
expect(@fixture.setDictionary('de_DE_frami', dictionaryDirectory)).toBe true
correction = ['möchten', 'möchten', 'möchten'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('möchtzn')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for incorrect Unicode German word with UTF-8 file', ->
expect(@fixture.setDictionary('de_DE', dictionaryDirectory)).toBe true
correction = ['möchten', 'möchten', 'möchten'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('möchtzn')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for correct Unicode French word', ->
expect(@fixture.setDictionary('fr', dictionaryDirectory)).toBe true
correction = ['Françoise', 'Françoise', 'française'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Française')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
it 'returns an array of possible corrections for incorrect Unicode French word', ->
expect(@fixture.setDictionary('fr', dictionaryDirectory)).toBe true
correction = ['Françoise', 'Françoise', 'Françoise'][spellIndex]
corrections = @fixture.getCorrectionsForMisspelling('Françoize')
expect(corrections.length).toBeGreaterThan 0
expect(corrections[0]).toEqual(correction)
describe '.add(word) and .remove(word)', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'allows words to be added and removed to the dictionary', ->
# NB: Windows spellchecker cannot remove words, and since it holds onto
# words, rerunning this test >1 time causes it to incorrectly fail
return if process.platform is 'win32'
expect(@fixture.isMisspelled('wwoorrdd')).toBe true
@fixture.add('wwoorrdd')
expect(@fixture.isMisspelled('wwoorrdd')).toBe false
@fixture.remove('wwoorrdd')
expect(@fixture.isMisspelled('wwoorrdd')).toBe true
it 'add throws an error if no word is specified', ->
errorOccurred = false
try
@fixture.add()
catch
errorOccurred = true
expect(errorOccurred).toBe true
it 'remove throws an error if no word is specified', ->
errorOccurred = false
try
@fixture.remove()
catch
errorOccurred = true
expect(errorOccurred).toBe true
describe '.getAvailableDictionaries()', ->
beforeEach ->
@fixture = new Spellchecker()
@fixture.setDictionary defaultLanguage, dictionaryDirectory
it 'returns an array of string dictionary names', ->
# NB: getAvailableDictionaries is nop'ped in hunspell and it also doesn't
# work inside Appveyor's CI environment
return if spellType is 'hunspell' or process.env.CI
dictionaries = @fixture.getAvailableDictionaries()
expect(Array.isArray(dictionaries)).toBe true
expect(dictionaries.length).toBeGreaterThan 0
for dictionary in dictionaries.length
expect(typeof dictionary).toBe 'string'
expect(diction.length).toBeGreaterThan 0
describe '.setDictionary(lang, dictDirectory)', ->
it 'sets the spell checkers language, and dictionary directory', ->
awesome = true
expect(awesome).toBe true
|
[
{
"context": "serif')\ntext.on 'click', ->\n text.html = 'This is Audrey Hepburn<br> in Funny Face'\n return\n# Animate borderRadiu",
"end": 1126,
"score": 0.9993821382522583,
"start": 1112,
"tag": "NAME",
"value": "Audrey Hepburn"
}
] | example_home_made.framer/app.coffee | bflaven/BlogArticlesExamples | 5 | # Welcome to Framer
### values ###
bgcolor = '#000000'
shadowcolor = '#FF0000'
### Use a device ###
device = new (Framer.DeviceComponent)
device.setupContext()
# Display only the device
# device.deviceType = "iphone-5c-pink";
# Display a hand with the device
device.deviceType = 'iphone-5c-pink-hand'
# Change the size
device.setDeviceScale 0.3
# Draw a white square
whiteSquare = new Layer(
backgroundColor: '' + bgcolor + ''
width: 400
height: 120
y: 0)
# Center horizontally
whiteSquare.centerX()
# Draw an image
#imageLayer = new Layer({x:0, y:0, width:128, height:128, image:"images/Icon.png"})
# imageLayer.center()
pic = new Layer(
image: 'images/audrey_in_funny_face_audrey_hepburn_400x400.jpg'
width: 400
height: 300
y: 120)
pic.centerX()
# Write text
text = new Layer(
backgroundColor: '' + bgcolor + ''
width: Screen.width
height: 160
y: 420
html: 'Who am I ?'
style:
fontSize: '20px'
textAlign: 'center'
color: '#FFFFFF'
paddingTop: '15px'
lineHeight: '50px'
fontFamily: 'Tahoma, Geneva, sans-serif')
text.on 'click', ->
text.html = 'This is Audrey Hepburn<br> in Funny Face'
return
# Animate borderRadius
whiteSquare.animate
properties: borderRadius: whiteSquare.width / 8
time: 2
curve: 'ease-in-out'
# Animate Shadow
whiteSquare.on 'click', ->
# Set the shadow color first
whiteSquare.shadowColor = '#555555'
whiteSquare.animate 'properties':
shadowBlur: 40
shadowSpread: 10
return
# Add two states
pic.states.add
'myState1': borderRadius: 100
'myState2': borderRadius: 200
# Change state when clicked
pic.on 'click', ->
# Switch to myState2
pic.states.switch 'myState2'
return
bg = new BackgroundLayer(backgroundColor: '' + bgcolor + '')
# ---
# generated by js2coffee 2.2.0
| 76688 | # Welcome to Framer
### values ###
bgcolor = '#000000'
shadowcolor = '#FF0000'
### Use a device ###
device = new (Framer.DeviceComponent)
device.setupContext()
# Display only the device
# device.deviceType = "iphone-5c-pink";
# Display a hand with the device
device.deviceType = 'iphone-5c-pink-hand'
# Change the size
device.setDeviceScale 0.3
# Draw a white square
whiteSquare = new Layer(
backgroundColor: '' + bgcolor + ''
width: 400
height: 120
y: 0)
# Center horizontally
whiteSquare.centerX()
# Draw an image
#imageLayer = new Layer({x:0, y:0, width:128, height:128, image:"images/Icon.png"})
# imageLayer.center()
pic = new Layer(
image: 'images/audrey_in_funny_face_audrey_hepburn_400x400.jpg'
width: 400
height: 300
y: 120)
pic.centerX()
# Write text
text = new Layer(
backgroundColor: '' + bgcolor + ''
width: Screen.width
height: 160
y: 420
html: 'Who am I ?'
style:
fontSize: '20px'
textAlign: 'center'
color: '#FFFFFF'
paddingTop: '15px'
lineHeight: '50px'
fontFamily: 'Tahoma, Geneva, sans-serif')
text.on 'click', ->
text.html = 'This is <NAME><br> in Funny Face'
return
# Animate borderRadius
whiteSquare.animate
properties: borderRadius: whiteSquare.width / 8
time: 2
curve: 'ease-in-out'
# Animate Shadow
whiteSquare.on 'click', ->
# Set the shadow color first
whiteSquare.shadowColor = '#555555'
whiteSquare.animate 'properties':
shadowBlur: 40
shadowSpread: 10
return
# Add two states
pic.states.add
'myState1': borderRadius: 100
'myState2': borderRadius: 200
# Change state when clicked
pic.on 'click', ->
# Switch to myState2
pic.states.switch 'myState2'
return
bg = new BackgroundLayer(backgroundColor: '' + bgcolor + '')
# ---
# generated by js2coffee 2.2.0
| true | # Welcome to Framer
### values ###
bgcolor = '#000000'
shadowcolor = '#FF0000'
### Use a device ###
device = new (Framer.DeviceComponent)
device.setupContext()
# Display only the device
# device.deviceType = "iphone-5c-pink";
# Display a hand with the device
device.deviceType = 'iphone-5c-pink-hand'
# Change the size
device.setDeviceScale 0.3
# Draw a white square
whiteSquare = new Layer(
backgroundColor: '' + bgcolor + ''
width: 400
height: 120
y: 0)
# Center horizontally
whiteSquare.centerX()
# Draw an image
#imageLayer = new Layer({x:0, y:0, width:128, height:128, image:"images/Icon.png"})
# imageLayer.center()
pic = new Layer(
image: 'images/audrey_in_funny_face_audrey_hepburn_400x400.jpg'
width: 400
height: 300
y: 120)
pic.centerX()
# Write text
text = new Layer(
backgroundColor: '' + bgcolor + ''
width: Screen.width
height: 160
y: 420
html: 'Who am I ?'
style:
fontSize: '20px'
textAlign: 'center'
color: '#FFFFFF'
paddingTop: '15px'
lineHeight: '50px'
fontFamily: 'Tahoma, Geneva, sans-serif')
text.on 'click', ->
text.html = 'This is PI:NAME:<NAME>END_PI<br> in Funny Face'
return
# Animate borderRadius
whiteSquare.animate
properties: borderRadius: whiteSquare.width / 8
time: 2
curve: 'ease-in-out'
# Animate Shadow
whiteSquare.on 'click', ->
# Set the shadow color first
whiteSquare.shadowColor = '#555555'
whiteSquare.animate 'properties':
shadowBlur: 40
shadowSpread: 10
return
# Add two states
pic.states.add
'myState1': borderRadius: 100
'myState2': borderRadius: 200
# Change state when clicked
pic.on 'click', ->
# Switch to myState2
pic.states.switch 'myState2'
return
bg = new BackgroundLayer(backgroundColor: '' + bgcolor + '')
# ---
# generated by js2coffee 2.2.0
|
[
{
"context": "one) ->\n scope.cred =\n username: 'bob@acme.com'\n password: 'pswd'\n mockHttpServi",
"end": 3762,
"score": 0.999927818775177,
"start": 3750,
"tag": "EMAIL",
"value": "bob@acme.com"
},
{
"context": " username: 'bob@acme.com'\n ... | test/unit/client/controllers/login.coffee | valueflowquality/gi-security-update | 0 | describe 'Login controller', ->
beforeEach angular.mock.module 'ngResource'
beforeEach angular.mock.module 'gi.util'
beforeEach angular.mock.module 'gi.security'
allSettingsResult = null
mockSettingService = null
mockAuthService = {}
mockFacebookService = {}
mockHttpService = {}
mockFilterService = null
controller = null
scope = null
ctrl = null
q = null
dependencies = null
beforeEach inject ($rootScope, $httpBackend, $injector, $controller, $q
, $filter) ->
controller = $controller
scope = $rootScope.$new()
mockHttpService = $httpBackend
q = $q
allSettingsResult = sinon.stub()
mockSettingService =
all: () ->
then: allSettingsResult
mockFacebookService =
init: sinon.spy()
dependencies =
$scope: scope
$filter: $filter
authService: mockAuthService
Facebook: mockFacebookService
Setting: mockSettingService
sinon.spy console, 'log'
afterEach ->
console.log.restore()
describe 'initializing', ->
it 'Gets all settings', (done) ->
sinon.spy mockSettingService, 'all'
ctrl = controller 'loginController', dependencies
expect(mockSettingService.all.calledOnce).to.be.true
done()
it 'sets allowFacebookLogin to the value in facebookAppId setting'
, (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'facebookAppId', value: 'setting2'}
{key: 'loginWithFacebook', value: 'bob'}
]
ctrl = controller 'loginController', dependencies
expect(scope.allowFacebookLogin).to.equal 'bob'
done()
it 'sets allowFacebookLogin to false if no setting'
, (done) ->
allSettingsResult.callsArgWith 0, []
ctrl = controller 'loginController', dependencies
expect(scope.allowFacebookLogin).to.equal false
done()
it 'does not init facebook if facebook login is not enabled'
, (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'facebookAppId', value: 'setting2'}
]
ctrl = controller 'loginController', dependencies
expect(mockFacebookService.init.notCalled, 'facebook was initialised')
.to.be.true
expect(console.log.notCalled, 'tried to intialize facebook')
.to.be.true
done()
it 'inits facebook with on the setting with key facebookAppId ' +
'if facebook login is enabled', (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'loginWithFacebook', value: true}
{key: 'facebookAppId', value: 'setting2'}
]
ctrl = controller 'loginController', dependencies
expect(mockFacebookService.init.calledWithExactly 'setting2').to.be.true
expect(console.log.called).to.be.false
done()
it 'logs an error to the console if no appId setting found', (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'loginWithFacebook', value: true}
]
ctrl = controller 'loginController', dependencies
expect(console.log.calledWithExactly('error initializing facebook login')
,"initializing facebook login had problem")
.to.be.true
done()
it 'sets scope.loginStatus.failed to false', (done) ->
ctrl = controller 'loginController', dependencies
expect(scope.loginStatus.failed).to.be.false
done()
describe '$scope functions', ->
beforeEach ->
ctrl = controller 'loginController', dependencies
describe '$scope.login()', ->
it 'sets $scope.loginStatus.failed to true if login fails', (done) ->
scope.cred =
username: 'bob@acme.com'
password: 'pswd'
mockHttpService.expectPOST('/api/login', scope.cred)
.respond(401)
scope.login()
mockHttpService.flush()
expect(scope.loginStatus.failed, 'loginStatus.failed not set')
.to.be.true
done()
describe '$scope.dismissLoginAlert()', () ->
it 'sets $scope.loginStatus.failed to false', (done) ->
scope.loginStatus.failed = true
scope.dismissLoginAlert()
expect(scope.loginStatus.failed).to.be.false
done()
| 117375 | describe 'Login controller', ->
beforeEach angular.mock.module 'ngResource'
beforeEach angular.mock.module 'gi.util'
beforeEach angular.mock.module 'gi.security'
allSettingsResult = null
mockSettingService = null
mockAuthService = {}
mockFacebookService = {}
mockHttpService = {}
mockFilterService = null
controller = null
scope = null
ctrl = null
q = null
dependencies = null
beforeEach inject ($rootScope, $httpBackend, $injector, $controller, $q
, $filter) ->
controller = $controller
scope = $rootScope.$new()
mockHttpService = $httpBackend
q = $q
allSettingsResult = sinon.stub()
mockSettingService =
all: () ->
then: allSettingsResult
mockFacebookService =
init: sinon.spy()
dependencies =
$scope: scope
$filter: $filter
authService: mockAuthService
Facebook: mockFacebookService
Setting: mockSettingService
sinon.spy console, 'log'
afterEach ->
console.log.restore()
describe 'initializing', ->
it 'Gets all settings', (done) ->
sinon.spy mockSettingService, 'all'
ctrl = controller 'loginController', dependencies
expect(mockSettingService.all.calledOnce).to.be.true
done()
it 'sets allowFacebookLogin to the value in facebookAppId setting'
, (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'facebookAppId', value: 'setting2'}
{key: 'loginWithFacebook', value: 'bob'}
]
ctrl = controller 'loginController', dependencies
expect(scope.allowFacebookLogin).to.equal 'bob'
done()
it 'sets allowFacebookLogin to false if no setting'
, (done) ->
allSettingsResult.callsArgWith 0, []
ctrl = controller 'loginController', dependencies
expect(scope.allowFacebookLogin).to.equal false
done()
it 'does not init facebook if facebook login is not enabled'
, (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'facebookAppId', value: 'setting2'}
]
ctrl = controller 'loginController', dependencies
expect(mockFacebookService.init.notCalled, 'facebook was initialised')
.to.be.true
expect(console.log.notCalled, 'tried to intialize facebook')
.to.be.true
done()
it 'inits facebook with on the setting with key facebookAppId ' +
'if facebook login is enabled', (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'loginWithFacebook', value: true}
{key: 'facebookAppId', value: 'setting2'}
]
ctrl = controller 'loginController', dependencies
expect(mockFacebookService.init.calledWithExactly 'setting2').to.be.true
expect(console.log.called).to.be.false
done()
it 'logs an error to the console if no appId setting found', (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'loginWithFacebook', value: true}
]
ctrl = controller 'loginController', dependencies
expect(console.log.calledWithExactly('error initializing facebook login')
,"initializing facebook login had problem")
.to.be.true
done()
it 'sets scope.loginStatus.failed to false', (done) ->
ctrl = controller 'loginController', dependencies
expect(scope.loginStatus.failed).to.be.false
done()
describe '$scope functions', ->
beforeEach ->
ctrl = controller 'loginController', dependencies
describe '$scope.login()', ->
it 'sets $scope.loginStatus.failed to true if login fails', (done) ->
scope.cred =
username: '<EMAIL>'
password: '<PASSWORD>'
mockHttpService.expectPOST('/api/login', scope.cred)
.respond(401)
scope.login()
mockHttpService.flush()
expect(scope.loginStatus.failed, 'loginStatus.failed not set')
.to.be.true
done()
describe '$scope.dismissLoginAlert()', () ->
it 'sets $scope.loginStatus.failed to false', (done) ->
scope.loginStatus.failed = true
scope.dismissLoginAlert()
expect(scope.loginStatus.failed).to.be.false
done()
| true | describe 'Login controller', ->
beforeEach angular.mock.module 'ngResource'
beforeEach angular.mock.module 'gi.util'
beforeEach angular.mock.module 'gi.security'
allSettingsResult = null
mockSettingService = null
mockAuthService = {}
mockFacebookService = {}
mockHttpService = {}
mockFilterService = null
controller = null
scope = null
ctrl = null
q = null
dependencies = null
beforeEach inject ($rootScope, $httpBackend, $injector, $controller, $q
, $filter) ->
controller = $controller
scope = $rootScope.$new()
mockHttpService = $httpBackend
q = $q
allSettingsResult = sinon.stub()
mockSettingService =
all: () ->
then: allSettingsResult
mockFacebookService =
init: sinon.spy()
dependencies =
$scope: scope
$filter: $filter
authService: mockAuthService
Facebook: mockFacebookService
Setting: mockSettingService
sinon.spy console, 'log'
afterEach ->
console.log.restore()
describe 'initializing', ->
it 'Gets all settings', (done) ->
sinon.spy mockSettingService, 'all'
ctrl = controller 'loginController', dependencies
expect(mockSettingService.all.calledOnce).to.be.true
done()
it 'sets allowFacebookLogin to the value in facebookAppId setting'
, (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'facebookAppId', value: 'setting2'}
{key: 'loginWithFacebook', value: 'bob'}
]
ctrl = controller 'loginController', dependencies
expect(scope.allowFacebookLogin).to.equal 'bob'
done()
it 'sets allowFacebookLogin to false if no setting'
, (done) ->
allSettingsResult.callsArgWith 0, []
ctrl = controller 'loginController', dependencies
expect(scope.allowFacebookLogin).to.equal false
done()
it 'does not init facebook if facebook login is not enabled'
, (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'facebookAppId', value: 'setting2'}
]
ctrl = controller 'loginController', dependencies
expect(mockFacebookService.init.notCalled, 'facebook was initialised')
.to.be.true
expect(console.log.notCalled, 'tried to intialize facebook')
.to.be.true
done()
it 'inits facebook with on the setting with key facebookAppId ' +
'if facebook login is enabled', (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'loginWithFacebook', value: true}
{key: 'facebookAppId', value: 'setting2'}
]
ctrl = controller 'loginController', dependencies
expect(mockFacebookService.init.calledWithExactly 'setting2').to.be.true
expect(console.log.called).to.be.false
done()
it 'logs an error to the console if no appId setting found', (done) ->
allSettingsResult.callsArgWith 0, [
{key: 'setting1', value: 'setting1'}
{key: 'loginWithFacebook', value: true}
]
ctrl = controller 'loginController', dependencies
expect(console.log.calledWithExactly('error initializing facebook login')
,"initializing facebook login had problem")
.to.be.true
done()
it 'sets scope.loginStatus.failed to false', (done) ->
ctrl = controller 'loginController', dependencies
expect(scope.loginStatus.failed).to.be.false
done()
describe '$scope functions', ->
beforeEach ->
ctrl = controller 'loginController', dependencies
describe '$scope.login()', ->
it 'sets $scope.loginStatus.failed to true if login fails', (done) ->
scope.cred =
username: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
mockHttpService.expectPOST('/api/login', scope.cred)
.respond(401)
scope.login()
mockHttpService.flush()
expect(scope.loginStatus.failed, 'loginStatus.failed not set')
.to.be.true
done()
describe '$scope.dismissLoginAlert()', () ->
it 'sets $scope.loginStatus.failed to false', (done) ->
scope.loginStatus.failed = true
scope.dismissLoginAlert()
expect(scope.loginStatus.failed).to.be.false
done()
|
[
{
"context": "oard.RoadmapModel',\n id: 'Foo',\n name: \"bar\",\n plans: []\n\n column = Ext.create 'Rally",
"end": 1171,
"score": 0.9312586188316345,
"start": 1168,
"tag": "NAME",
"value": "bar"
}
] | test/spec/roadmapplanningboard/BacklogBoardColumnSpec.coffee | RallyHackathon/app-catalog | 1 | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.apps.roadmapplanningboard.BacklogBoardColumn'
'Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper'
]
describe 'Rally.apps.roadmapplanningboard.BacklogBoardColumn', ->
beforeEach ->
Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper.loadDependencies()
@target = Ext.getBody()
@backlogColumn = Ext.create 'Rally.apps.roadmapplanningboard.BacklogBoardColumn',
renderTo: @target
contentCell: @target
headerCell: @target
store: Deft.Injector.resolve('featureStore')
lowestPIType: 'PortfolioItem/Feature'
roadmap: Deft.Injector.resolve('roadmapStore').getById('413617ecef8623df1391fabc')
return @backlogColumn
afterEach ->
Deft.Injector.reset()
@backlogColumn?.destroy()
it 'is using injected stores', ->
expect(@backlogColumn.planStore).toBeTruthy()
it 'has a backlog filter', ->
expect(@backlogColumn.getCards().length).toBe(5)
it 'will filter by roadmap in addition to feature and plans', ->
roadMapModel = Ext.create 'Rally.apps.roadmapplanningboard.RoadmapModel',
id: 'Foo',
name: "bar",
plans: []
column = Ext.create 'Rally.apps.roadmapplanningboard.BacklogBoardColumn',
renderTo: Ext.getBody()
contentCell: Ext.getBody()
headerCell: Ext.getBody()
roadmap: roadMapModel
store: Deft.Injector.resolve('featureStore')
lowestPIType: 'feature'
expect(column.getCards().length).toBe(10)
column.destroy()
| 41396 | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.apps.roadmapplanningboard.BacklogBoardColumn'
'Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper'
]
describe 'Rally.apps.roadmapplanningboard.BacklogBoardColumn', ->
beforeEach ->
Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper.loadDependencies()
@target = Ext.getBody()
@backlogColumn = Ext.create 'Rally.apps.roadmapplanningboard.BacklogBoardColumn',
renderTo: @target
contentCell: @target
headerCell: @target
store: Deft.Injector.resolve('featureStore')
lowestPIType: 'PortfolioItem/Feature'
roadmap: Deft.Injector.resolve('roadmapStore').getById('413617ecef8623df1391fabc')
return @backlogColumn
afterEach ->
Deft.Injector.reset()
@backlogColumn?.destroy()
it 'is using injected stores', ->
expect(@backlogColumn.planStore).toBeTruthy()
it 'has a backlog filter', ->
expect(@backlogColumn.getCards().length).toBe(5)
it 'will filter by roadmap in addition to feature and plans', ->
roadMapModel = Ext.create 'Rally.apps.roadmapplanningboard.RoadmapModel',
id: 'Foo',
name: "<NAME>",
plans: []
column = Ext.create 'Rally.apps.roadmapplanningboard.BacklogBoardColumn',
renderTo: Ext.getBody()
contentCell: Ext.getBody()
headerCell: Ext.getBody()
roadmap: roadMapModel
store: Deft.Injector.resolve('featureStore')
lowestPIType: 'feature'
expect(column.getCards().length).toBe(10)
column.destroy()
| true | Ext = window.Ext4 || window.Ext
Ext.require [
'Rally.apps.roadmapplanningboard.BacklogBoardColumn'
'Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper'
]
describe 'Rally.apps.roadmapplanningboard.BacklogBoardColumn', ->
beforeEach ->
Rally.test.apps.roadmapplanningboard.helper.TestDependencyHelper.loadDependencies()
@target = Ext.getBody()
@backlogColumn = Ext.create 'Rally.apps.roadmapplanningboard.BacklogBoardColumn',
renderTo: @target
contentCell: @target
headerCell: @target
store: Deft.Injector.resolve('featureStore')
lowestPIType: 'PortfolioItem/Feature'
roadmap: Deft.Injector.resolve('roadmapStore').getById('413617ecef8623df1391fabc')
return @backlogColumn
afterEach ->
Deft.Injector.reset()
@backlogColumn?.destroy()
it 'is using injected stores', ->
expect(@backlogColumn.planStore).toBeTruthy()
it 'has a backlog filter', ->
expect(@backlogColumn.getCards().length).toBe(5)
it 'will filter by roadmap in addition to feature and plans', ->
roadMapModel = Ext.create 'Rally.apps.roadmapplanningboard.RoadmapModel',
id: 'Foo',
name: "PI:NAME:<NAME>END_PI",
plans: []
column = Ext.create 'Rally.apps.roadmapplanningboard.BacklogBoardColumn',
renderTo: Ext.getBody()
contentCell: Ext.getBody()
headerCell: Ext.getBody()
roadmap: roadMapModel
store: Deft.Injector.resolve('featureStore')
lowestPIType: 'feature'
expect(column.getCards().length).toBe(10)
column.destroy()
|
[
{
"context": "# Author: maartyl\n\n# I will need:\n# @inject : info about what it re",
"end": 17,
"score": 0.9997296333312988,
"start": 10,
"tag": "USERNAME",
"value": "maartyl"
},
{
"context": " systems goes through all objects and asks:\n# Hey, mate, are you an inject? and if so, i... | src/subsystems.coffee | Maartyl/subsystems-js | 0 | # Author: maartyl
# I will need:
# @inject : info about what it requires (nothing more)
# @system : provides :start which toposorts and starts all subsystems
# @start function :: System -> It'sAPI (generally map of started subsystems)
#
#
# solve problem of defining deps on this system
# HAS TO BE EXPLICIT ^
#
# and cont gets map of all the started subsystems
#
# systems goes through all objects and asks:
# Hey, mate, are you an inject? and if so, it's a dependency.
# : how do I put such injects on this system itself? ...
# - maybe the most simple way: just provide inject, instead of subsystem, yeah...
# - I like this and I'm pretty sure it will work ^^
# //since all must be resolved, before start is called.
#
# each system has to provide everything for his subs, even if all he can do is explicitly state he needs it.
#
# if a dependency CANNOT BE FOUND: must produce nice error
# if a CYCLIC dependency is found: must produce nice error
#
# how will I perform the INJECTION ITSELF?
# : all 'done' store in a map
# : keep info who needs what: take from the map, before calling start
# -- (Will be there by the time it's needed; if not: missing dependency (would probably notice in toposort anyway))
# : keep 'meta' who needs what, though. (should be a function! (for simplicity, composability...))
# -- and THAT FUNCTION CAN JUST END WITH CALLING START, having everything ordered implicitly
# -- takes rest of initialization as argument... - all async and good ^^
#
# let's call that: next(started, cont) (== inject + call start)
# : this function itself probably needs current context (loaded deps map; what to call at end; sorted deps...)
#
# NO DEPENDENCY CAN BE CALLED START
#
#
# CONT used by start:: (err, api)->()
topo = require 'toposort'
util = require 'util'
jstr = (o) -> util.inspect o, depth:5
isFn = (o) -> typeof o is 'function'
OK = null # passed in error field
class SubsystemInjectorStub
constructor: (@dep)->@
isInjector = (obj)-> obj instanceof SubsystemInjectorStub
inject = (dependency_name) ->
if dependency_name is 'start' then throw new Error "No dependency may be called 'start'."
new SubsystemInjectorStub dependency_name
@inject = inject
# retuns list of dependencies
# [[to from]] (to: which fild to inject) (from: dependency name)
scan = (obj) -> [k, v.dep] for k, v of obj when isInjector v
# get dependencies of a subsystem
# @dependencies = scan #possibly in the future, if needed
# builds edges(dependencies)
# FOR SINGLE NODE name
make_edges = (name, scanned) -> [dep, name] for [field, dep] in scanned
# returns list that can be passed topo (to get order of starting)
# map_subs :: (dependency_name -> subsystem)
# cont :: (err, all_dep_edges, nexts(functions to start component + inject)) -> ()
make_deps = (map_subs, cont) ->
deps_edges = []
nexts = {}
for dep, sub of map_subs
scanned = scan sub #get all fields with InjectorStub and what they depend on
deps_edges = deps_edges.concat make_edges dep, scanned #append all dependencies to edges
unless isFn sub.start
return cont new Error "Passed subsystem doesn't have start method - #{jstr dep}:#{jstr sub}."
nexts[dep] = do(dep, scanned, sub, starter=sub.start)-> (started, cont) ->
sub.start = (cont) -> cont OK, started[dep] #replace start method with just map lookup to cashed result
if dep of started then return cont OK, started[dep] #probably always checked outside, but better safe...
for [field, sub_dep] in scanned #start_map check doesn't catch some edge cases (unreal dep...)
unless sub_dep of started then return cont new Error "Unmet dependency: #{jstr sub_dep}."
sub[field] = started[sub_dep] #inject: set field to required from map of started deps
starter.call sub, cont
cont OK, deps_edges, nexts
build_context = (nodes, nexts, started, final_cont) ->
index: 0 #where am I on nodes (which to start next)
nodes: nodes # toposorted dependency names
nexts: nexts # functions to start subsystems
started: started #already started subsystems
cont: final_cont
execute_context = (cxt) ->
if cxt.index >= cxt.nodes.length # already started all subsystems
return cxt.cont OK, cxt.started
dep = cxt.nodes[cxt.index++]
if dep of cxt.started then return execute_context cxt # already started (needs to be here, not in nexts[])
#injects + provides api: stored in started and used by following nexts
cxt.nexts[dep] cxt.started, (err, sub_api) ->
if err then return cxt.cont err
cxt.started[dep] = sub_api
execute_context cxt
# map :: (dependency_name -> subsystem)
# started: (dep_name -> api) #for when this system already depends on another
start_map = (map, started, final_cont) -> make_deps map, (err, deps, nexts) ->
if err then return final_cont err
unsorted_nodes = do->(k for k, v of map) # include all nodes (even if unmentioned in depepndencies)
try nodes = topo.array unsorted_nodes, deps #topologically sort dependency graph
catch err then return final_cont err #cyclic dependency
unmets = (jstr dep for dep in nodes when not (nexts[dep]? or dep of started))
if unmets.length isnt 0
return final_cont new Error "Unmet dependencies: #{unmets}."
execute_context build_context nodes, nexts, started, final_cont
# @system: something that 'just' composes it, START is what matters
# + keeps track of which deps are met externally (injects) and which need to be started
map2system = (map) ->
unmet_keys = [] # whether system itself has some :inject values
met_keys =[]
for k, v of map
if isInjector v
unmet_keys.push k
else
met_keys.push k
map.start = (cont) ->
started = {}
unstarted = {}
for k in unmet_keys
if isInjector map[k] then cont new Error "System with unmet dependency: #{jstr k}."
started[k] = map[k]
for k in met_keys
unstarted[k] = map[k]
start_map unstarted, started, cont
map
# creates subsystem which starts all subsystems in map and passes to
# cont(of it's start) all APIs produced (with same keys as original subsystems)
# map :: (dependency_name -> subsystem)
@system = (map) ->
if map.start? then throw new Error "No dependency may be called 'start'."
map2system map
# this system is assumed to have no unmet dependencies
@start = (system, cont) ->
s = scan system
if s.length isnt 0
then cont new Error "Cannot start system with unmet dependencies: #{jstr dep for [k, dep] in s}."
else
unless isFn system.start
then cont new Error 'No start method on system.'
else system.start cont
## UTILS
fmap = (dep, fn) -> new class
value: inject dep
start: (cont) => # cont OK, fn @value
try v = fn @value #if fn throws: fail continuation
catch err then return cont err
cont OK, v
# subsystem which exports some function of it's single dependency
@fmap = fmap
# field of a dependency (following arguments are used as gield of that and of that...)
@field = (dep, fields...) -> fmap dep, (v)->
ret = v
for field in fields
unless field of Object ret
throw new Error "Field #{jstr field} not present."
ret = ret[field]
ret
rename = (system, map) ->
s = scan system
for [key, old] in s when dep = map[old]
system[key] = inject dep
system
# rename dependencies
# MUTATES system ('s injects)
# map (old(inside(require))name -> new(outside)name)
@rename = (system, map) ->
if map.start? then throw new Error "No dependency may be called 'start'."
rename system, map
wrap = (api) -> start: (cont) -> cont OK, api
#just wrap value into a system structure
@wrap = wrap
api_diff = (ss) ->
reference = {} #store what is curretnlty in ss, so one can do diff at end and only export changes
for k, v of ss
reference[k] = v
() -> #returns function that creats api from diff compared to first call
api = {}
for k, v of ss
unless reference[k] is v #if already present in reference: not new: don't export
api[k] = v #put all diffs on ss to api
api
subsystem = (core) -> (deps, ctor) ->
if deps.start? then throw new Error "No dependency field may be called 'start'."
-> #return creator function
ss = {} #subsystem
for k, v of deps
ss[k] = inject v
ss.start = core ctor.bind(ss), ss
ss
#start versions
#ctor:: ()->()
subsystem.sync = (ctor, ss) -> (cont) ->
mk_api = api_diff ss
try do ctor #update (initialize) ss, after all deps met
catch err then return cont err
cont OK, do mk_api
#ctor:: (cont::(err)->()) -> ()
subsystem.async = (ctor, ss) -> (cont) ->
mk_api = api_diff ss
try ctor (err) ->
if err then return cont err
cont OK, do mk_api
#ctor:: () -> api
subsystem.ret = (ctor, ss) -> (cont) ->
cont.apply undefined,
try [OK, do ctor]
catch err then [err]
#ctor:: (cont) -> ()
#cont:: (err, api) -> ()
# subsystem.ret.async = (ctor, ss) -> (cont) -> ctor cont
subsystem.ret.async = (ctor, ss) -> ctor
#allows very simple creation of (lowest level) subsystems
#exports diff of `this` created by ctor
# :: (deps, ctor) -> (args...) -> system
# deps :: {field -> dep_name}
# ctor :: ()->() - updates `this`
@subsystem = subsystem subsystem.sync
@subsystem.async = subsystem subsystem.async
@subsystem.ret = subsystem subsystem.ret
@subsystem.ret.async = subsystem subsystem.ret.async
| 220725 | # Author: maartyl
# I will need:
# @inject : info about what it requires (nothing more)
# @system : provides :start which toposorts and starts all subsystems
# @start function :: System -> It'sAPI (generally map of started subsystems)
#
#
# solve problem of defining deps on this system
# HAS TO BE EXPLICIT ^
#
# and cont gets map of all the started subsystems
#
# systems goes through all objects and asks:
# Hey, <NAME>, are you an inject? and if so, it's a dependency.
# : how do I put such injects on this system itself? ...
# - maybe the most simple way: just provide inject, instead of subsystem, yeah...
# - I like this and I'm pretty sure it will work ^^
# //since all must be resolved, before start is called.
#
# each system has to provide everything for his subs, even if all he can do is explicitly state he needs it.
#
# if a dependency CANNOT BE FOUND: must produce nice error
# if a CYCLIC dependency is found: must produce nice error
#
# how will I perform the INJECTION ITSELF?
# : all 'done' store in a map
# : keep info who needs what: take from the map, before calling start
# -- (Will be there by the time it's needed; if not: missing dependency (would probably notice in toposort anyway))
# : keep 'meta' who needs what, though. (should be a function! (for simplicity, composability...))
# -- and THAT FUNCTION CAN JUST END WITH CALLING START, having everything ordered implicitly
# -- takes rest of initialization as argument... - all async and good ^^
#
# let's call that: next(started, cont) (== inject + call start)
# : this function itself probably needs current context (loaded deps map; what to call at end; sorted deps...)
#
# NO DEPENDENCY CAN BE CALLED START
#
#
# CONT used by start:: (err, api)->()
topo = require 'toposort'
util = require 'util'
jstr = (o) -> util.inspect o, depth:5
isFn = (o) -> typeof o is 'function'
OK = null # passed in error field
class SubsystemInjectorStub
constructor: (@dep)->@
isInjector = (obj)-> obj instanceof SubsystemInjectorStub
inject = (dependency_name) ->
if dependency_name is 'start' then throw new Error "No dependency may be called 'start'."
new SubsystemInjectorStub dependency_name
@inject = inject
# retuns list of dependencies
# [[to from]] (to: which fild to inject) (from: dependency name)
scan = (obj) -> [k, v.dep] for k, v of obj when isInjector v
# get dependencies of a subsystem
# @dependencies = scan #possibly in the future, if needed
# builds edges(dependencies)
# FOR SINGLE NODE name
make_edges = (name, scanned) -> [dep, name] for [field, dep] in scanned
# returns list that can be passed topo (to get order of starting)
# map_subs :: (dependency_name -> subsystem)
# cont :: (err, all_dep_edges, nexts(functions to start component + inject)) -> ()
make_deps = (map_subs, cont) ->
deps_edges = []
nexts = {}
for dep, sub of map_subs
scanned = scan sub #get all fields with InjectorStub and what they depend on
deps_edges = deps_edges.concat make_edges dep, scanned #append all dependencies to edges
unless isFn sub.start
return cont new Error "Passed subsystem doesn't have start method - #{jstr dep}:#{jstr sub}."
nexts[dep] = do(dep, scanned, sub, starter=sub.start)-> (started, cont) ->
sub.start = (cont) -> cont OK, started[dep] #replace start method with just map lookup to cashed result
if dep of started then return cont OK, started[dep] #probably always checked outside, but better safe...
for [field, sub_dep] in scanned #start_map check doesn't catch some edge cases (unreal dep...)
unless sub_dep of started then return cont new Error "Unmet dependency: #{jstr sub_dep}."
sub[field] = started[sub_dep] #inject: set field to required from map of started deps
starter.call sub, cont
cont OK, deps_edges, nexts
build_context = (nodes, nexts, started, final_cont) ->
index: 0 #where am I on nodes (which to start next)
nodes: nodes # toposorted dependency names
nexts: nexts # functions to start subsystems
started: started #already started subsystems
cont: final_cont
execute_context = (cxt) ->
if cxt.index >= cxt.nodes.length # already started all subsystems
return cxt.cont OK, cxt.started
dep = cxt.nodes[cxt.index++]
if dep of cxt.started then return execute_context cxt # already started (needs to be here, not in nexts[])
#injects + provides api: stored in started and used by following nexts
cxt.nexts[dep] cxt.started, (err, sub_api) ->
if err then return cxt.cont err
cxt.started[dep] = sub_api
execute_context cxt
# map :: (dependency_name -> subsystem)
# started: (dep_name -> api) #for when this system already depends on another
start_map = (map, started, final_cont) -> make_deps map, (err, deps, nexts) ->
if err then return final_cont err
unsorted_nodes = do->(k for k, v of map) # include all nodes (even if unmentioned in depepndencies)
try nodes = topo.array unsorted_nodes, deps #topologically sort dependency graph
catch err then return final_cont err #cyclic dependency
unmets = (jstr dep for dep in nodes when not (nexts[dep]? or dep of started))
if unmets.length isnt 0
return final_cont new Error "Unmet dependencies: #{unmets}."
execute_context build_context nodes, nexts, started, final_cont
# @system: something that 'just' composes it, START is what matters
# + keeps track of which deps are met externally (injects) and which need to be started
map2system = (map) ->
unmet_keys = [] # whether system itself has some :inject values
met_keys =[]
for k, v of map
if isInjector v
unmet_keys.push k
else
met_keys.push k
map.start = (cont) ->
started = {}
unstarted = {}
for k in unmet_keys
if isInjector map[k] then cont new Error "System with unmet dependency: #{jstr k}."
started[k] = map[k]
for k in met_keys
unstarted[k] = map[k]
start_map unstarted, started, cont
map
# creates subsystem which starts all subsystems in map and passes to
# cont(of it's start) all APIs produced (with same keys as original subsystems)
# map :: (dependency_name -> subsystem)
@system = (map) ->
if map.start? then throw new Error "No dependency may be called 'start'."
map2system map
# this system is assumed to have no unmet dependencies
@start = (system, cont) ->
s = scan system
if s.length isnt 0
then cont new Error "Cannot start system with unmet dependencies: #{jstr dep for [k, dep] in s}."
else
unless isFn system.start
then cont new Error 'No start method on system.'
else system.start cont
## UTILS
fmap = (dep, fn) -> new class
value: inject dep
start: (cont) => # cont OK, fn @value
try v = fn @value #if fn throws: fail continuation
catch err then return cont err
cont OK, v
# subsystem which exports some function of it's single dependency
@fmap = fmap
# field of a dependency (following arguments are used as gield of that and of that...)
@field = (dep, fields...) -> fmap dep, (v)->
ret = v
for field in fields
unless field of Object ret
throw new Error "Field #{jstr field} not present."
ret = ret[field]
ret
rename = (system, map) ->
s = scan system
for [key, old] in s when dep = map[old]
system[key] = inject dep
system
# rename dependencies
# MUTATES system ('s injects)
# map (old(inside(require))name -> new(outside)name)
@rename = (system, map) ->
if map.start? then throw new Error "No dependency may be called 'start'."
rename system, map
wrap = (api) -> start: (cont) -> cont OK, api
#just wrap value into a system structure
@wrap = wrap
api_diff = (ss) ->
reference = {} #store what is curretnlty in ss, so one can do diff at end and only export changes
for k, v of ss
reference[k] = v
() -> #returns function that creats api from diff compared to first call
api = {}
for k, v of ss
unless reference[k] is v #if already present in reference: not new: don't export
api[k] = v #put all diffs on ss to api
api
subsystem = (core) -> (deps, ctor) ->
if deps.start? then throw new Error "No dependency field may be called 'start'."
-> #return creator function
ss = {} #subsystem
for k, v of deps
ss[k] = inject v
ss.start = core ctor.bind(ss), ss
ss
#start versions
#ctor:: ()->()
subsystem.sync = (ctor, ss) -> (cont) ->
mk_api = api_diff ss
try do ctor #update (initialize) ss, after all deps met
catch err then return cont err
cont OK, do mk_api
#ctor:: (cont::(err)->()) -> ()
subsystem.async = (ctor, ss) -> (cont) ->
mk_api = api_diff ss
try ctor (err) ->
if err then return cont err
cont OK, do mk_api
#ctor:: () -> api
subsystem.ret = (ctor, ss) -> (cont) ->
cont.apply undefined,
try [OK, do ctor]
catch err then [err]
#ctor:: (cont) -> ()
#cont:: (err, api) -> ()
# subsystem.ret.async = (ctor, ss) -> (cont) -> ctor cont
subsystem.ret.async = (ctor, ss) -> ctor
#allows very simple creation of (lowest level) subsystems
#exports diff of `this` created by ctor
# :: (deps, ctor) -> (args...) -> system
# deps :: {field -> dep_name}
# ctor :: ()->() - updates `this`
@subsystem = subsystem subsystem.sync
@subsystem.async = subsystem subsystem.async
@subsystem.ret = subsystem subsystem.ret
@subsystem.ret.async = subsystem subsystem.ret.async
| true | # Author: maartyl
# I will need:
# @inject : info about what it requires (nothing more)
# @system : provides :start which toposorts and starts all subsystems
# @start function :: System -> It'sAPI (generally map of started subsystems)
#
#
# solve problem of defining deps on this system
# HAS TO BE EXPLICIT ^
#
# and cont gets map of all the started subsystems
#
# systems goes through all objects and asks:
# Hey, PI:NAME:<NAME>END_PI, are you an inject? and if so, it's a dependency.
# : how do I put such injects on this system itself? ...
# - maybe the most simple way: just provide inject, instead of subsystem, yeah...
# - I like this and I'm pretty sure it will work ^^
# //since all must be resolved, before start is called.
#
# each system has to provide everything for his subs, even if all he can do is explicitly state he needs it.
#
# if a dependency CANNOT BE FOUND: must produce nice error
# if a CYCLIC dependency is found: must produce nice error
#
# how will I perform the INJECTION ITSELF?
# : all 'done' store in a map
# : keep info who needs what: take from the map, before calling start
# -- (Will be there by the time it's needed; if not: missing dependency (would probably notice in toposort anyway))
# : keep 'meta' who needs what, though. (should be a function! (for simplicity, composability...))
# -- and THAT FUNCTION CAN JUST END WITH CALLING START, having everything ordered implicitly
# -- takes rest of initialization as argument... - all async and good ^^
#
# let's call that: next(started, cont) (== inject + call start)
# : this function itself probably needs current context (loaded deps map; what to call at end; sorted deps...)
#
# NO DEPENDENCY CAN BE CALLED START
#
#
# CONT used by start:: (err, api)->()
topo = require 'toposort'
util = require 'util'
jstr = (o) -> util.inspect o, depth:5
isFn = (o) -> typeof o is 'function'
OK = null # passed in error field
class SubsystemInjectorStub
constructor: (@dep)->@
isInjector = (obj)-> obj instanceof SubsystemInjectorStub
inject = (dependency_name) ->
if dependency_name is 'start' then throw new Error "No dependency may be called 'start'."
new SubsystemInjectorStub dependency_name
@inject = inject
# retuns list of dependencies
# [[to from]] (to: which fild to inject) (from: dependency name)
scan = (obj) -> [k, v.dep] for k, v of obj when isInjector v
# get dependencies of a subsystem
# @dependencies = scan #possibly in the future, if needed
# builds edges(dependencies)
# FOR SINGLE NODE name
make_edges = (name, scanned) -> [dep, name] for [field, dep] in scanned
# returns list that can be passed topo (to get order of starting)
# map_subs :: (dependency_name -> subsystem)
# cont :: (err, all_dep_edges, nexts(functions to start component + inject)) -> ()
make_deps = (map_subs, cont) ->
deps_edges = []
nexts = {}
for dep, sub of map_subs
scanned = scan sub #get all fields with InjectorStub and what they depend on
deps_edges = deps_edges.concat make_edges dep, scanned #append all dependencies to edges
unless isFn sub.start
return cont new Error "Passed subsystem doesn't have start method - #{jstr dep}:#{jstr sub}."
nexts[dep] = do(dep, scanned, sub, starter=sub.start)-> (started, cont) ->
sub.start = (cont) -> cont OK, started[dep] #replace start method with just map lookup to cashed result
if dep of started then return cont OK, started[dep] #probably always checked outside, but better safe...
for [field, sub_dep] in scanned #start_map check doesn't catch some edge cases (unreal dep...)
unless sub_dep of started then return cont new Error "Unmet dependency: #{jstr sub_dep}."
sub[field] = started[sub_dep] #inject: set field to required from map of started deps
starter.call sub, cont
cont OK, deps_edges, nexts
build_context = (nodes, nexts, started, final_cont) ->
index: 0 #where am I on nodes (which to start next)
nodes: nodes # toposorted dependency names
nexts: nexts # functions to start subsystems
started: started #already started subsystems
cont: final_cont
execute_context = (cxt) ->
if cxt.index >= cxt.nodes.length # already started all subsystems
return cxt.cont OK, cxt.started
dep = cxt.nodes[cxt.index++]
if dep of cxt.started then return execute_context cxt # already started (needs to be here, not in nexts[])
#injects + provides api: stored in started and used by following nexts
cxt.nexts[dep] cxt.started, (err, sub_api) ->
if err then return cxt.cont err
cxt.started[dep] = sub_api
execute_context cxt
# map :: (dependency_name -> subsystem)
# started: (dep_name -> api) #for when this system already depends on another
start_map = (map, started, final_cont) -> make_deps map, (err, deps, nexts) ->
if err then return final_cont err
unsorted_nodes = do->(k for k, v of map) # include all nodes (even if unmentioned in depepndencies)
try nodes = topo.array unsorted_nodes, deps #topologically sort dependency graph
catch err then return final_cont err #cyclic dependency
unmets = (jstr dep for dep in nodes when not (nexts[dep]? or dep of started))
if unmets.length isnt 0
return final_cont new Error "Unmet dependencies: #{unmets}."
execute_context build_context nodes, nexts, started, final_cont
# @system: something that 'just' composes it, START is what matters
# + keeps track of which deps are met externally (injects) and which need to be started
map2system = (map) ->
unmet_keys = [] # whether system itself has some :inject values
met_keys =[]
for k, v of map
if isInjector v
unmet_keys.push k
else
met_keys.push k
map.start = (cont) ->
started = {}
unstarted = {}
for k in unmet_keys
if isInjector map[k] then cont new Error "System with unmet dependency: #{jstr k}."
started[k] = map[k]
for k in met_keys
unstarted[k] = map[k]
start_map unstarted, started, cont
map
# creates subsystem which starts all subsystems in map and passes to
# cont(of it's start) all APIs produced (with same keys as original subsystems)
# map :: (dependency_name -> subsystem)
@system = (map) ->
if map.start? then throw new Error "No dependency may be called 'start'."
map2system map
# this system is assumed to have no unmet dependencies
@start = (system, cont) ->
s = scan system
if s.length isnt 0
then cont new Error "Cannot start system with unmet dependencies: #{jstr dep for [k, dep] in s}."
else
unless isFn system.start
then cont new Error 'No start method on system.'
else system.start cont
## UTILS
fmap = (dep, fn) -> new class
value: inject dep
start: (cont) => # cont OK, fn @value
try v = fn @value #if fn throws: fail continuation
catch err then return cont err
cont OK, v
# subsystem which exports some function of it's single dependency
@fmap = fmap
# field of a dependency (following arguments are used as gield of that and of that...)
@field = (dep, fields...) -> fmap dep, (v)->
ret = v
for field in fields
unless field of Object ret
throw new Error "Field #{jstr field} not present."
ret = ret[field]
ret
rename = (system, map) ->
s = scan system
for [key, old] in s when dep = map[old]
system[key] = inject dep
system
# rename dependencies
# MUTATES system ('s injects)
# map (old(inside(require))name -> new(outside)name)
@rename = (system, map) ->
if map.start? then throw new Error "No dependency may be called 'start'."
rename system, map
wrap = (api) -> start: (cont) -> cont OK, api
#just wrap value into a system structure
@wrap = wrap
api_diff = (ss) ->
reference = {} #store what is curretnlty in ss, so one can do diff at end and only export changes
for k, v of ss
reference[k] = v
() -> #returns function that creats api from diff compared to first call
api = {}
for k, v of ss
unless reference[k] is v #if already present in reference: not new: don't export
api[k] = v #put all diffs on ss to api
api
subsystem = (core) -> (deps, ctor) ->
if deps.start? then throw new Error "No dependency field may be called 'start'."
-> #return creator function
ss = {} #subsystem
for k, v of deps
ss[k] = inject v
ss.start = core ctor.bind(ss), ss
ss
#start versions
#ctor:: ()->()
subsystem.sync = (ctor, ss) -> (cont) ->
mk_api = api_diff ss
try do ctor #update (initialize) ss, after all deps met
catch err then return cont err
cont OK, do mk_api
#ctor:: (cont::(err)->()) -> ()
subsystem.async = (ctor, ss) -> (cont) ->
mk_api = api_diff ss
try ctor (err) ->
if err then return cont err
cont OK, do mk_api
#ctor:: () -> api
subsystem.ret = (ctor, ss) -> (cont) ->
cont.apply undefined,
try [OK, do ctor]
catch err then [err]
#ctor:: (cont) -> ()
#cont:: (err, api) -> ()
# subsystem.ret.async = (ctor, ss) -> (cont) -> ctor cont
subsystem.ret.async = (ctor, ss) -> ctor
#allows very simple creation of (lowest level) subsystems
#exports diff of `this` created by ctor
# :: (deps, ctor) -> (args...) -> system
# deps :: {field -> dep_name}
# ctor :: ()->() - updates `this`
@subsystem = subsystem subsystem.sync
@subsystem.async = subsystem subsystem.async
@subsystem.ret = subsystem subsystem.ret
@subsystem.ret.async = subsystem subsystem.ret.async
|
[
{
"context": "xec()\n\n user = new User(\n email : \"user@user.com\"\n firstName: \"Full Name\"\n lastName ",
"end": 666,
"score": 0.9999041557312012,
"start": 653,
"tag": "EMAIL",
"value": "user@user.com"
},
{
"context": " lastName : \"Last Name\"\... | test/deal/api.coffee | gertu/gertu | 1 | should = require "should"
app = require "../../server"
mongoose = require "mongoose"
request = require "supertest"
passportStub = require "passport-stub"
Deal = mongoose.model "Deal"
User = mongoose.model "User"
Shop = mongoose.model "Shop"
passportStub.install app
server = request.agent(app)
apiPreffix = '/api/v1'
deal = undefined
user = undefined
user2 = undefined
user3 = undefined
shop = undefined
describe "<Unit test>", ->
describe "API Deal:", ->
before (done) ->
Deal.remove().exec()
User.remove().exec()
Shop.remove().exec()
user = new User(
email : "user@user.com"
firstName: "Full Name"
lastName : "Last Name"
password : "pass11"
)
user.save()
user2 = new User(
email : "user2@user2.com"
firstName: "Full Name"
lastName : "Last Name"
password : "pass11"
)
user2.save()
user3 = new User(
email : "user3@user3.com"
firstName: "Full Name"
lastName : "Last Name"
password : "pass11"
)
user3.save()
shop = new Shop(
email : "shop@shop.com"
name : "shop name"
password: "pass11"
)
shop.save()
deal = new Deal(
name : "deal name"
description : "This is a fake deal"
price : 20
gertuprice : 10
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
)
deal.save()
setTimeout(
-> done()
1000
)
describe "API deal", ->
it "should create a new deal", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal1"
description : "This is a fake deal"
price : 50
gertuprice : 25
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 0
done()
it "should not be create because it does not exist this shop", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal2"
description : "This is a fake deal"
price : 50
gertuprice : 25
discount : 50
shop : "***fakeObjectIdOfShop***"
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 404
done()
it "should not be created because no data", (done) ->
server.post(apiPreffix + "/deals").send().end (err, res) ->
res.should.have.status 422
done()
it "should not be created because name is missing", (done) ->
server.post(apiPreffix + "/deals").send(
description : "This is a fake deal"
price : 50
gertuprice : 25
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should not be created because price is missing", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal name"
description : "This is a fake deal"
gertuprice : 25
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should not be created because gertuprice is missing", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal name"
description : "This is a fake deal"
price : 50
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should not be created because discount is missing", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal name"
description : "This is a fake deal"
price : 50
gertuprice : 25
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should find only two deals in DB", (done) ->
Deal.find {}, (error, deals) ->
deals.should.have.length 2
done()
# unit tests about Comments
it "should be able to add a comment", (done) ->
passportStub.login user
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
rating : 7
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 7
res.body.shop.average.should.have.eql 0.2
done()
it "should not add a comment because description is missing", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
rating : 7
).end (err, res) ->
res.should.have.status 422
done()
it "should not add a comment because rating is missing", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
).end (err, res) ->
res.should.have.status 422
done()
it "should not add a comment because this user has already written on this deal", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
rating : 8
).end (err, res) ->
res.should.have.status 409
passportStub.logout user
done()
it "should update the average score of the deal", (done) ->
passportStub.login user2
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user2._id
description: "This is a very important test"
rating : 8
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 7.5
res.body.shop.average.should.have.eql 0.5
passportStub.logout user2
done()
it "should update the average score of the shop", (done) ->
passportStub.login user3
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user3._id
description: "This is a very important test"
rating : 3
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 6
res.body.shop.average.should.have.eql 0.3
passportStub.logout user3
done()
it "should not add a comment because it does not exist this user", (done) ->
passportStub.login "***fakeObjectIdOfUser****"
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : "***fakeObjectIdOfUser****"
description: "This is a very important test"
rating : 7
).end (err, res) ->
res.should.have.status 404
passportStub.logout "***fakeObjectIdOfUser****"
done()
it "should not add a comment because the user is not logged", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
rating : 7
).end (err, res) ->
res.should.have.status 401
done()
after (done) ->
Deal.remove().exec()
User.remove().exec()
Shop.remove().exec()
done() | 211179 | should = require "should"
app = require "../../server"
mongoose = require "mongoose"
request = require "supertest"
passportStub = require "passport-stub"
Deal = mongoose.model "Deal"
User = mongoose.model "User"
Shop = mongoose.model "Shop"
passportStub.install app
server = request.agent(app)
apiPreffix = '/api/v1'
deal = undefined
user = undefined
user2 = undefined
user3 = undefined
shop = undefined
describe "<Unit test>", ->
describe "API Deal:", ->
before (done) ->
Deal.remove().exec()
User.remove().exec()
Shop.remove().exec()
user = new User(
email : "<EMAIL>"
firstName: "Full Name"
lastName : "Last Name"
password : "<PASSWORD>"
)
user.save()
user2 = new User(
email : "<EMAIL>"
firstName: "Full Name"
lastName : "Last Name"
password : "<PASSWORD>"
)
user2.save()
user3 = new User(
email : "<EMAIL>"
firstName: "Full Name"
lastName : "Last Name"
password : "<PASSWORD>"
)
user3.save()
shop = new Shop(
email : "<EMAIL>"
name : "shop name"
password: "<PASSWORD>"
)
shop.save()
deal = new Deal(
name : "deal name"
description : "This is a fake deal"
price : 20
gertuprice : 10
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
)
deal.save()
setTimeout(
-> done()
1000
)
describe "API deal", ->
it "should create a new deal", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal1"
description : "This is a fake deal"
price : 50
gertuprice : 25
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 0
done()
it "should not be create because it does not exist this shop", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal2"
description : "This is a fake deal"
price : 50
gertuprice : 25
discount : 50
shop : "***fakeObjectIdOfShop***"
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 404
done()
it "should not be created because no data", (done) ->
server.post(apiPreffix + "/deals").send().end (err, res) ->
res.should.have.status 422
done()
it "should not be created because name is missing", (done) ->
server.post(apiPreffix + "/deals").send(
description : "This is a fake deal"
price : 50
gertuprice : 25
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should not be created because price is missing", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal name"
description : "This is a fake deal"
gertuprice : 25
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should not be created because gertuprice is missing", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal name"
description : "This is a fake deal"
price : 50
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should not be created because discount is missing", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal name"
description : "This is a fake deal"
price : 50
gertuprice : 25
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should find only two deals in DB", (done) ->
Deal.find {}, (error, deals) ->
deals.should.have.length 2
done()
# unit tests about Comments
it "should be able to add a comment", (done) ->
passportStub.login user
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
rating : 7
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 7
res.body.shop.average.should.have.eql 0.2
done()
it "should not add a comment because description is missing", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
rating : 7
).end (err, res) ->
res.should.have.status 422
done()
it "should not add a comment because rating is missing", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
).end (err, res) ->
res.should.have.status 422
done()
it "should not add a comment because this user has already written on this deal", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
rating : 8
).end (err, res) ->
res.should.have.status 409
passportStub.logout user
done()
it "should update the average score of the deal", (done) ->
passportStub.login user2
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user2._id
description: "This is a very important test"
rating : 8
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 7.5
res.body.shop.average.should.have.eql 0.5
passportStub.logout user2
done()
it "should update the average score of the shop", (done) ->
passportStub.login user3
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user3._id
description: "This is a very important test"
rating : 3
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 6
res.body.shop.average.should.have.eql 0.3
passportStub.logout user3
done()
it "should not add a comment because it does not exist this user", (done) ->
passportStub.login "***fakeObjectIdOfUser****"
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : "***fakeObjectIdOfUser****"
description: "This is a very important test"
rating : 7
).end (err, res) ->
res.should.have.status 404
passportStub.logout "***fakeObjectIdOfUser****"
done()
it "should not add a comment because the user is not logged", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
rating : 7
).end (err, res) ->
res.should.have.status 401
done()
after (done) ->
Deal.remove().exec()
User.remove().exec()
Shop.remove().exec()
done() | true | should = require "should"
app = require "../../server"
mongoose = require "mongoose"
request = require "supertest"
passportStub = require "passport-stub"
Deal = mongoose.model "Deal"
User = mongoose.model "User"
Shop = mongoose.model "Shop"
passportStub.install app
server = request.agent(app)
apiPreffix = '/api/v1'
deal = undefined
user = undefined
user2 = undefined
user3 = undefined
shop = undefined
describe "<Unit test>", ->
describe "API Deal:", ->
before (done) ->
Deal.remove().exec()
User.remove().exec()
Shop.remove().exec()
user = new User(
email : "PI:EMAIL:<EMAIL>END_PI"
firstName: "Full Name"
lastName : "Last Name"
password : "PI:PASSWORD:<PASSWORD>END_PI"
)
user.save()
user2 = new User(
email : "PI:EMAIL:<EMAIL>END_PI"
firstName: "Full Name"
lastName : "Last Name"
password : "PI:PASSWORD:<PASSWORD>END_PI"
)
user2.save()
user3 = new User(
email : "PI:EMAIL:<EMAIL>END_PI"
firstName: "Full Name"
lastName : "Last Name"
password : "PI:PASSWORD:<PASSWORD>END_PI"
)
user3.save()
shop = new Shop(
email : "PI:EMAIL:<EMAIL>END_PI"
name : "shop name"
password: "PI:PASSWORD:<PASSWORD>END_PI"
)
shop.save()
deal = new Deal(
name : "deal name"
description : "This is a fake deal"
price : 20
gertuprice : 10
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
)
deal.save()
setTimeout(
-> done()
1000
)
describe "API deal", ->
it "should create a new deal", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal1"
description : "This is a fake deal"
price : 50
gertuprice : 25
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 0
done()
it "should not be create because it does not exist this shop", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal2"
description : "This is a fake deal"
price : 50
gertuprice : 25
discount : 50
shop : "***fakeObjectIdOfShop***"
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 404
done()
it "should not be created because no data", (done) ->
server.post(apiPreffix + "/deals").send().end (err, res) ->
res.should.have.status 422
done()
it "should not be created because name is missing", (done) ->
server.post(apiPreffix + "/deals").send(
description : "This is a fake deal"
price : 50
gertuprice : 25
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should not be created because price is missing", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal name"
description : "This is a fake deal"
gertuprice : 25
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should not be created because gertuprice is missing", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal name"
description : "This is a fake deal"
price : 50
discount : 50
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should not be created because discount is missing", (done) ->
server.post(apiPreffix + "/deals").send(
name : "deal name"
description : "This is a fake deal"
price : 50
gertuprice : 25
shop : shop._id
categoryname: "Category Name"
quantity : 20
).end (err, res) ->
res.should.have.status 422
done()
it "should find only two deals in DB", (done) ->
Deal.find {}, (error, deals) ->
deals.should.have.length 2
done()
# unit tests about Comments
it "should be able to add a comment", (done) ->
passportStub.login user
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
rating : 7
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 7
res.body.shop.average.should.have.eql 0.2
done()
it "should not add a comment because description is missing", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
rating : 7
).end (err, res) ->
res.should.have.status 422
done()
it "should not add a comment because rating is missing", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
).end (err, res) ->
res.should.have.status 422
done()
it "should not add a comment because this user has already written on this deal", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
rating : 8
).end (err, res) ->
res.should.have.status 409
passportStub.logout user
done()
it "should update the average score of the deal", (done) ->
passportStub.login user2
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user2._id
description: "This is a very important test"
rating : 8
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 7.5
res.body.shop.average.should.have.eql 0.5
passportStub.logout user2
done()
it "should update the average score of the shop", (done) ->
passportStub.login user3
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user3._id
description: "This is a very important test"
rating : 3
).end (err, res) ->
res.should.have.status 200
res.body.average.should.have.eql 6
res.body.shop.average.should.have.eql 0.3
passportStub.logout user3
done()
it "should not add a comment because it does not exist this user", (done) ->
passportStub.login "***fakeObjectIdOfUser****"
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : "***fakeObjectIdOfUser****"
description: "This is a very important test"
rating : 7
).end (err, res) ->
res.should.have.status 404
passportStub.logout "***fakeObjectIdOfUser****"
done()
it "should not add a comment because the user is not logged", (done) ->
server.put(apiPreffix + "/deals/" + deal._id + "/addcomment").send(
author : user._id
description: "This is a very important test"
rating : 7
).end (err, res) ->
res.should.have.status 401
done()
after (done) ->
Deal.remove().exec()
User.remove().exec()
Shop.remove().exec()
done() |
[
{
"context": " test.describeProperty Knight, 'title', {title: 'Sir'}, setter: false\n test.describeProperty Knight",
"end": 1815,
"score": 0.997093915939331,
"start": 1812,
"tag": "NAME",
"value": "Sir"
}
] | coffee/test/util/test.spec.coffee | athenalabs/athena-lib-js | 1 | goog.provide 'athena.lib.util.specs.test'
goog.require 'athena.lib.util.test'
goog.require 'athena.lib.FormView'
describe 'athena.lib.util.test', ->
test = athena.lib.util.test
it 'should be part of athena.lib.util', ->
expect(test).toBeDefined()
it 'should be an object', ->
expect(_.isObject util).toBe true
describe 'test.throwsExceptionWithString', ->
throwyFn = (param) -> throw Error('Hai! 42')
fn = (param) ->
it 'throws an exception when it should', ->
expect(test.throwsExceptionWithString '42', throwyFn).toBe true
expect(test.throwsExceptionWithString '42', throwyFn, []).toBe true
expect(test.throwsExceptionWithString '42', throwyFn, [ 'ey' ]).toBe true
it 'doesn\'t throw an exception when it shouldn\'t', ->
expect(test.throwsExceptionWithString '45', throwyFn).toBe false
expect(test.throwsExceptionWithString '45', throwyFn, []).toBe false
expect(test.throwsExceptionWithString '45', throwyFn, [ 'ey' ]).toBe false
expect(test.throwsExceptionWithString '42', fn).toBe false
expect(test.throwsExceptionWithString '42', fn, []).toBe false
expect(test.throwsExceptionWithString '42', fn, [ 'ey' ]).toBe false
describe 'test.describeProperty', ->
toSeekTheGrail = 'To seek the Holy Grail'
class Knight extends athena.lib.Model
name: @property 'name'
title: @property('title', setter: false)
color: @property('color', default: 'blue')
quest: @property('quest', {default: toSeekTheGrail, setter: false})
@callback = ->
it 'should run this test within the block', ->
expect(true).toBe true
spy = spyOn(@, 'callback').andCallThrough()
test.describeProperty Knight, 'name', {}, {}, @callback
test.describeProperty Knight, 'title', {title: 'Sir'}, setter: false
test.describeProperty Knight, 'color', {}, default: 'blue'
test.describeProperty Knight, 'quest', {},
default: toSeekTheGrail
setter: false
it 'should call the callback', ->
expect(spy).toHaveBeenCalled()
describe 'test.describeView', ->
class View extends athena.lib.View
initialize: =>
super
View.calledWithOptions = @options
options = {a:1, b:2}
@callback = ->
it 'should run this test within the block', ->
expect(true).toBe true
spy = spyOn(@, 'callback').andCallThrough()
test.describeView View, athena.lib.View, options, @callback
it 'should call the View initialize with given options', ->
expect(View.calledWithOptions).toBe options
it 'should call the callback', ->
expect(spy).toHaveBeenCalled()
class BadView extends athena.lib.View
initialize: =>
throw new Error 'options are bogus'
defaults: {}
events: => 5
render: =>
super
undefined
# uncomment below to ensure the tests fail :)
# test.describeView BadView, View
describe 'test.describeSubview', ->
class ChildView extends athena.lib.View
class ParentView extends athena.lib.View
initialize: =>
super
ParentView.calledWithOptions = @options
@namedSubview = new ChildView eventhub: @eventhub
render: =>
super
@$el.append @namedSubview.render().el
@
class GrandParentView extends athena.lib.View
initialize: =>
super
options = _.extend {}, @options, eventhub: @eventhub
@childSubview = new ParentView options
@grandchildSubview = @childSubview.namedSubview
render: =>
super
@$el.append @childSubview.render().el
@
# test with the GrandParentView
options =
View: ParentView
viewOptions: {a: 1, b:2}
subviewAttr: 'namedSubview'
Subview: ChildView
callback: ->
it 'should run this test within the block', ->
expect(true).toBe true
spy = spyOn(options, 'callback').andCallThrough()
test.describeSubview options, options.callback
it 'should call the ParentView initialize with given options', ->
expect(ParentView.calledWithOptions).toBe options.viewOptions
it 'should call the callback', ->
expect(spy).toHaveBeenCalled()
# test with the GrandParentView
test.describeSubview
View: GrandParentView
subviewAttr: 'grandchildSubview'
Subview: ChildView
checkDOM: (subEl, el) -> subEl.parentNode.parentNode is el
describe 'test.describeFormComponent', ->
options =
id: 'foo'
type: 'text'
label: 'Foo'
placeholder: 'enter foo'
helpBlock: 'The Foo to end all Foos'
helpInline: 'Some Foo, that is.'
class FooFormView extends athena.lib.FormView
initialize: =>
super
@foo = new athena.lib.FormComponentView _.extend {}, options,
eventhub: @eventhub
@addComponentView @foo
test.describeFormComponent _.extend {}, options,
View: FooFormView
name: 'foo'
describe 'EventSpy', ->
it 'should be a function', ->
expect(_.isFunction test.EventSpy).toBe true
it 'should listen to Backbone event triggers', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggered).toBe false
m.trigger 'event'
expect(s.triggered).toBe true
it 'should not listen to Backbone events not specified', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggered).toBe false
m.trigger 'otherevent'
expect(s.triggered).toBe false
m.trigger 'event'
expect(s.triggered).toBe true
it 'should count how many times an event is triggered', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggerCount).toBe 1
m.trigger 'event'
expect(s.triggerCount).toBe 2
m.trigger 'event'
expect(s.triggerCount).toBe 3
it 'should not count events not specified', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggerCount).toBe 1
m.trigger 'otherevent'
expect(s.triggerCount).toBe 1
m.trigger 'event'
expect(s.triggerCount).toBe 2
it 'should have a reset function', ->
expect(typeof test.EventSpy::reset).toBe 'function'
it 'should wipe counts on calling reset', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggered).toBe false
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggered).toBe true
expect(s.triggerCount).toBe 1
m.trigger 'event'
expect(s.triggered).toBe true
expect(s.triggerCount).toBe 2
s.reset()
expect(s.triggered).toBe false
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggered).toBe true
expect(s.triggerCount).toBe 1
it 'should support spying on all events', ->
m = new Backbone.Model
s = new test.EventSpy m, 'all'
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggerCount).toBe 1
m.trigger 'otherevent'
expect(s.triggerCount).toBe 2
m.trigger 'yetanotherevent'
expect(s.triggerCount).toBe 3
m.trigger 'event'
expect(s.triggerCount).toBe 4
it 'should track the arguments of event calls', ->
m = new Backbone.Model
s = new test.EventSpy m, 'all'
expect(s.arguments).toEqual []
m.trigger 'a'
expect(s.arguments).toEqual [['a']]
m.trigger 'b', 1
expect(s.arguments).toEqual [['a'], ['b', 1]]
m.trigger 'c', 'hi', 'hello'
expect(s.arguments).toEqual [['a'], ['b', 1], ['c', 'hi', 'hello']]
it 'should wipe the arguments on calling reset', ->
m = new Backbone.Model
s = new test.EventSpy m, 'all'
expect(s.arguments).toEqual []
m.trigger 'a'
expect(s.arguments).toEqual [['a']]
m.trigger 'b', 1
expect(s.arguments).toEqual [['a'], ['b', 1]]
m.trigger 'c', 'hi', 'hello'
expect(s.arguments).toEqual [['a'], ['b', 1], ['c', 'hi', 'hello']]
s.reset()
expect(s.arguments).toEqual []
m.trigger 'b', {pedro: 'ah'}
expect(s.arguments).toEqual [['b', {pedro: 'ah'}]]
describe 'expectEventSpyBehaviors', ->
it 'should be a function', ->
expect(typeof test.expectEventSpyBehaviors).toBe 'function'
it 'should test that events were triggered', ->
m = new Backbone.Model
spies =
seeSpy: new test.EventSpy m, 'see'
hearSpy: new test.EventSpy m, 'hear'
speakSpy: new test.EventSpy m, 'speak'
allSpy: new test.EventSpy m, 'all'
fns = [
->
m.trigger 'see'
expectations =
seeSpy: undefined
allSpy: undefined
->
m.trigger 'hear'
expectations =
hearSpy: undefined
allSpy: undefined
->
m.trigger 'speak'
expectations =
speakSpy: undefined
allSpy: undefined
->
m.trigger 'see'
m.trigger 'hear'
expectations =
seeSpy: undefined
hearSpy: undefined
allSpy: undefined
->
m.trigger 'see'
m.trigger 'hear'
m.trigger 'speak'
expectations =
seeSpy: undefined
hearSpy: undefined
speakSpy: undefined
allSpy: undefined
]
test.expectEventSpyBehaviors spies, fns
it 'should test that events were triggered with specific arguments', ->
m = new Backbone.Model
spies =
seeSpy: new test.EventSpy m, 'see'
hearSpy: new test.EventSpy m, 'hear'
speakSpy: new test.EventSpy m, 'speak'
allSpy: new test.EventSpy m, 'all'
fns = [
->
evil = 'murdering children'
m.trigger 'see', evil
expectations =
seeSpy: evil
allSpy: ['see', evil]
->
evil = 'tripping an old lady'
m.trigger 'hear', evil
expectations =
hearSpy: evil
allSpy: ['hear', evil]
->
evil = 'stealing candy from children'
m.trigger 'speak', evil
expectations =
speakSpy: evil
allSpy: ['speak', evil]
->
evil = 'slipping a laxative into the bake sale cookies'
m.trigger 'hear', evil
m.trigger 'speak', evil
expectations =
hearSpy: evil
speakSpy: evil
allSpy: ['speak', evil]
->
evil = 'throwing a red ball in front of a blind man\'s guide dog, and
yelling fetch'
m.trigger 'speak', evil
m.trigger 'hear', evil
m.trigger 'see', evil
expectations =
seeSpy: evil
hearSpy: evil
speakSpy: evil
allSpy: ['see', evil]
]
test.expectEventSpyBehaviors spies, fns
| 18900 | goog.provide 'athena.lib.util.specs.test'
goog.require 'athena.lib.util.test'
goog.require 'athena.lib.FormView'
describe 'athena.lib.util.test', ->
test = athena.lib.util.test
it 'should be part of athena.lib.util', ->
expect(test).toBeDefined()
it 'should be an object', ->
expect(_.isObject util).toBe true
describe 'test.throwsExceptionWithString', ->
throwyFn = (param) -> throw Error('Hai! 42')
fn = (param) ->
it 'throws an exception when it should', ->
expect(test.throwsExceptionWithString '42', throwyFn).toBe true
expect(test.throwsExceptionWithString '42', throwyFn, []).toBe true
expect(test.throwsExceptionWithString '42', throwyFn, [ 'ey' ]).toBe true
it 'doesn\'t throw an exception when it shouldn\'t', ->
expect(test.throwsExceptionWithString '45', throwyFn).toBe false
expect(test.throwsExceptionWithString '45', throwyFn, []).toBe false
expect(test.throwsExceptionWithString '45', throwyFn, [ 'ey' ]).toBe false
expect(test.throwsExceptionWithString '42', fn).toBe false
expect(test.throwsExceptionWithString '42', fn, []).toBe false
expect(test.throwsExceptionWithString '42', fn, [ 'ey' ]).toBe false
describe 'test.describeProperty', ->
toSeekTheGrail = 'To seek the Holy Grail'
class Knight extends athena.lib.Model
name: @property 'name'
title: @property('title', setter: false)
color: @property('color', default: 'blue')
quest: @property('quest', {default: toSeekTheGrail, setter: false})
@callback = ->
it 'should run this test within the block', ->
expect(true).toBe true
spy = spyOn(@, 'callback').andCallThrough()
test.describeProperty Knight, 'name', {}, {}, @callback
test.describeProperty Knight, 'title', {title: '<NAME>'}, setter: false
test.describeProperty Knight, 'color', {}, default: 'blue'
test.describeProperty Knight, 'quest', {},
default: toSeekTheGrail
setter: false
it 'should call the callback', ->
expect(spy).toHaveBeenCalled()
describe 'test.describeView', ->
class View extends athena.lib.View
initialize: =>
super
View.calledWithOptions = @options
options = {a:1, b:2}
@callback = ->
it 'should run this test within the block', ->
expect(true).toBe true
spy = spyOn(@, 'callback').andCallThrough()
test.describeView View, athena.lib.View, options, @callback
it 'should call the View initialize with given options', ->
expect(View.calledWithOptions).toBe options
it 'should call the callback', ->
expect(spy).toHaveBeenCalled()
class BadView extends athena.lib.View
initialize: =>
throw new Error 'options are bogus'
defaults: {}
events: => 5
render: =>
super
undefined
# uncomment below to ensure the tests fail :)
# test.describeView BadView, View
describe 'test.describeSubview', ->
class ChildView extends athena.lib.View
class ParentView extends athena.lib.View
initialize: =>
super
ParentView.calledWithOptions = @options
@namedSubview = new ChildView eventhub: @eventhub
render: =>
super
@$el.append @namedSubview.render().el
@
class GrandParentView extends athena.lib.View
initialize: =>
super
options = _.extend {}, @options, eventhub: @eventhub
@childSubview = new ParentView options
@grandchildSubview = @childSubview.namedSubview
render: =>
super
@$el.append @childSubview.render().el
@
# test with the GrandParentView
options =
View: ParentView
viewOptions: {a: 1, b:2}
subviewAttr: 'namedSubview'
Subview: ChildView
callback: ->
it 'should run this test within the block', ->
expect(true).toBe true
spy = spyOn(options, 'callback').andCallThrough()
test.describeSubview options, options.callback
it 'should call the ParentView initialize with given options', ->
expect(ParentView.calledWithOptions).toBe options.viewOptions
it 'should call the callback', ->
expect(spy).toHaveBeenCalled()
# test with the GrandParentView
test.describeSubview
View: GrandParentView
subviewAttr: 'grandchildSubview'
Subview: ChildView
checkDOM: (subEl, el) -> subEl.parentNode.parentNode is el
describe 'test.describeFormComponent', ->
options =
id: 'foo'
type: 'text'
label: 'Foo'
placeholder: 'enter foo'
helpBlock: 'The Foo to end all Foos'
helpInline: 'Some Foo, that is.'
class FooFormView extends athena.lib.FormView
initialize: =>
super
@foo = new athena.lib.FormComponentView _.extend {}, options,
eventhub: @eventhub
@addComponentView @foo
test.describeFormComponent _.extend {}, options,
View: FooFormView
name: 'foo'
describe 'EventSpy', ->
it 'should be a function', ->
expect(_.isFunction test.EventSpy).toBe true
it 'should listen to Backbone event triggers', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggered).toBe false
m.trigger 'event'
expect(s.triggered).toBe true
it 'should not listen to Backbone events not specified', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggered).toBe false
m.trigger 'otherevent'
expect(s.triggered).toBe false
m.trigger 'event'
expect(s.triggered).toBe true
it 'should count how many times an event is triggered', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggerCount).toBe 1
m.trigger 'event'
expect(s.triggerCount).toBe 2
m.trigger 'event'
expect(s.triggerCount).toBe 3
it 'should not count events not specified', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggerCount).toBe 1
m.trigger 'otherevent'
expect(s.triggerCount).toBe 1
m.trigger 'event'
expect(s.triggerCount).toBe 2
it 'should have a reset function', ->
expect(typeof test.EventSpy::reset).toBe 'function'
it 'should wipe counts on calling reset', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggered).toBe false
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggered).toBe true
expect(s.triggerCount).toBe 1
m.trigger 'event'
expect(s.triggered).toBe true
expect(s.triggerCount).toBe 2
s.reset()
expect(s.triggered).toBe false
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggered).toBe true
expect(s.triggerCount).toBe 1
it 'should support spying on all events', ->
m = new Backbone.Model
s = new test.EventSpy m, 'all'
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggerCount).toBe 1
m.trigger 'otherevent'
expect(s.triggerCount).toBe 2
m.trigger 'yetanotherevent'
expect(s.triggerCount).toBe 3
m.trigger 'event'
expect(s.triggerCount).toBe 4
it 'should track the arguments of event calls', ->
m = new Backbone.Model
s = new test.EventSpy m, 'all'
expect(s.arguments).toEqual []
m.trigger 'a'
expect(s.arguments).toEqual [['a']]
m.trigger 'b', 1
expect(s.arguments).toEqual [['a'], ['b', 1]]
m.trigger 'c', 'hi', 'hello'
expect(s.arguments).toEqual [['a'], ['b', 1], ['c', 'hi', 'hello']]
it 'should wipe the arguments on calling reset', ->
m = new Backbone.Model
s = new test.EventSpy m, 'all'
expect(s.arguments).toEqual []
m.trigger 'a'
expect(s.arguments).toEqual [['a']]
m.trigger 'b', 1
expect(s.arguments).toEqual [['a'], ['b', 1]]
m.trigger 'c', 'hi', 'hello'
expect(s.arguments).toEqual [['a'], ['b', 1], ['c', 'hi', 'hello']]
s.reset()
expect(s.arguments).toEqual []
m.trigger 'b', {pedro: 'ah'}
expect(s.arguments).toEqual [['b', {pedro: 'ah'}]]
describe 'expectEventSpyBehaviors', ->
it 'should be a function', ->
expect(typeof test.expectEventSpyBehaviors).toBe 'function'
it 'should test that events were triggered', ->
m = new Backbone.Model
spies =
seeSpy: new test.EventSpy m, 'see'
hearSpy: new test.EventSpy m, 'hear'
speakSpy: new test.EventSpy m, 'speak'
allSpy: new test.EventSpy m, 'all'
fns = [
->
m.trigger 'see'
expectations =
seeSpy: undefined
allSpy: undefined
->
m.trigger 'hear'
expectations =
hearSpy: undefined
allSpy: undefined
->
m.trigger 'speak'
expectations =
speakSpy: undefined
allSpy: undefined
->
m.trigger 'see'
m.trigger 'hear'
expectations =
seeSpy: undefined
hearSpy: undefined
allSpy: undefined
->
m.trigger 'see'
m.trigger 'hear'
m.trigger 'speak'
expectations =
seeSpy: undefined
hearSpy: undefined
speakSpy: undefined
allSpy: undefined
]
test.expectEventSpyBehaviors spies, fns
it 'should test that events were triggered with specific arguments', ->
m = new Backbone.Model
spies =
seeSpy: new test.EventSpy m, 'see'
hearSpy: new test.EventSpy m, 'hear'
speakSpy: new test.EventSpy m, 'speak'
allSpy: new test.EventSpy m, 'all'
fns = [
->
evil = 'murdering children'
m.trigger 'see', evil
expectations =
seeSpy: evil
allSpy: ['see', evil]
->
evil = 'tripping an old lady'
m.trigger 'hear', evil
expectations =
hearSpy: evil
allSpy: ['hear', evil]
->
evil = 'stealing candy from children'
m.trigger 'speak', evil
expectations =
speakSpy: evil
allSpy: ['speak', evil]
->
evil = 'slipping a laxative into the bake sale cookies'
m.trigger 'hear', evil
m.trigger 'speak', evil
expectations =
hearSpy: evil
speakSpy: evil
allSpy: ['speak', evil]
->
evil = 'throwing a red ball in front of a blind man\'s guide dog, and
yelling fetch'
m.trigger 'speak', evil
m.trigger 'hear', evil
m.trigger 'see', evil
expectations =
seeSpy: evil
hearSpy: evil
speakSpy: evil
allSpy: ['see', evil]
]
test.expectEventSpyBehaviors spies, fns
| true | goog.provide 'athena.lib.util.specs.test'
goog.require 'athena.lib.util.test'
goog.require 'athena.lib.FormView'
describe 'athena.lib.util.test', ->
test = athena.lib.util.test
it 'should be part of athena.lib.util', ->
expect(test).toBeDefined()
it 'should be an object', ->
expect(_.isObject util).toBe true
describe 'test.throwsExceptionWithString', ->
throwyFn = (param) -> throw Error('Hai! 42')
fn = (param) ->
it 'throws an exception when it should', ->
expect(test.throwsExceptionWithString '42', throwyFn).toBe true
expect(test.throwsExceptionWithString '42', throwyFn, []).toBe true
expect(test.throwsExceptionWithString '42', throwyFn, [ 'ey' ]).toBe true
it 'doesn\'t throw an exception when it shouldn\'t', ->
expect(test.throwsExceptionWithString '45', throwyFn).toBe false
expect(test.throwsExceptionWithString '45', throwyFn, []).toBe false
expect(test.throwsExceptionWithString '45', throwyFn, [ 'ey' ]).toBe false
expect(test.throwsExceptionWithString '42', fn).toBe false
expect(test.throwsExceptionWithString '42', fn, []).toBe false
expect(test.throwsExceptionWithString '42', fn, [ 'ey' ]).toBe false
describe 'test.describeProperty', ->
toSeekTheGrail = 'To seek the Holy Grail'
class Knight extends athena.lib.Model
name: @property 'name'
title: @property('title', setter: false)
color: @property('color', default: 'blue')
quest: @property('quest', {default: toSeekTheGrail, setter: false})
@callback = ->
it 'should run this test within the block', ->
expect(true).toBe true
spy = spyOn(@, 'callback').andCallThrough()
test.describeProperty Knight, 'name', {}, {}, @callback
test.describeProperty Knight, 'title', {title: 'PI:NAME:<NAME>END_PI'}, setter: false
test.describeProperty Knight, 'color', {}, default: 'blue'
test.describeProperty Knight, 'quest', {},
default: toSeekTheGrail
setter: false
it 'should call the callback', ->
expect(spy).toHaveBeenCalled()
describe 'test.describeView', ->
class View extends athena.lib.View
initialize: =>
super
View.calledWithOptions = @options
options = {a:1, b:2}
@callback = ->
it 'should run this test within the block', ->
expect(true).toBe true
spy = spyOn(@, 'callback').andCallThrough()
test.describeView View, athena.lib.View, options, @callback
it 'should call the View initialize with given options', ->
expect(View.calledWithOptions).toBe options
it 'should call the callback', ->
expect(spy).toHaveBeenCalled()
class BadView extends athena.lib.View
initialize: =>
throw new Error 'options are bogus'
defaults: {}
events: => 5
render: =>
super
undefined
# uncomment below to ensure the tests fail :)
# test.describeView BadView, View
describe 'test.describeSubview', ->
class ChildView extends athena.lib.View
class ParentView extends athena.lib.View
initialize: =>
super
ParentView.calledWithOptions = @options
@namedSubview = new ChildView eventhub: @eventhub
render: =>
super
@$el.append @namedSubview.render().el
@
class GrandParentView extends athena.lib.View
initialize: =>
super
options = _.extend {}, @options, eventhub: @eventhub
@childSubview = new ParentView options
@grandchildSubview = @childSubview.namedSubview
render: =>
super
@$el.append @childSubview.render().el
@
# test with the GrandParentView
options =
View: ParentView
viewOptions: {a: 1, b:2}
subviewAttr: 'namedSubview'
Subview: ChildView
callback: ->
it 'should run this test within the block', ->
expect(true).toBe true
spy = spyOn(options, 'callback').andCallThrough()
test.describeSubview options, options.callback
it 'should call the ParentView initialize with given options', ->
expect(ParentView.calledWithOptions).toBe options.viewOptions
it 'should call the callback', ->
expect(spy).toHaveBeenCalled()
# test with the GrandParentView
test.describeSubview
View: GrandParentView
subviewAttr: 'grandchildSubview'
Subview: ChildView
checkDOM: (subEl, el) -> subEl.parentNode.parentNode is el
describe 'test.describeFormComponent', ->
options =
id: 'foo'
type: 'text'
label: 'Foo'
placeholder: 'enter foo'
helpBlock: 'The Foo to end all Foos'
helpInline: 'Some Foo, that is.'
class FooFormView extends athena.lib.FormView
initialize: =>
super
@foo = new athena.lib.FormComponentView _.extend {}, options,
eventhub: @eventhub
@addComponentView @foo
test.describeFormComponent _.extend {}, options,
View: FooFormView
name: 'foo'
describe 'EventSpy', ->
it 'should be a function', ->
expect(_.isFunction test.EventSpy).toBe true
it 'should listen to Backbone event triggers', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggered).toBe false
m.trigger 'event'
expect(s.triggered).toBe true
it 'should not listen to Backbone events not specified', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggered).toBe false
m.trigger 'otherevent'
expect(s.triggered).toBe false
m.trigger 'event'
expect(s.triggered).toBe true
it 'should count how many times an event is triggered', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggerCount).toBe 1
m.trigger 'event'
expect(s.triggerCount).toBe 2
m.trigger 'event'
expect(s.triggerCount).toBe 3
it 'should not count events not specified', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggerCount).toBe 1
m.trigger 'otherevent'
expect(s.triggerCount).toBe 1
m.trigger 'event'
expect(s.triggerCount).toBe 2
it 'should have a reset function', ->
expect(typeof test.EventSpy::reset).toBe 'function'
it 'should wipe counts on calling reset', ->
m = new Backbone.Model
s = new test.EventSpy m, 'event'
expect(s.triggered).toBe false
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggered).toBe true
expect(s.triggerCount).toBe 1
m.trigger 'event'
expect(s.triggered).toBe true
expect(s.triggerCount).toBe 2
s.reset()
expect(s.triggered).toBe false
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggered).toBe true
expect(s.triggerCount).toBe 1
it 'should support spying on all events', ->
m = new Backbone.Model
s = new test.EventSpy m, 'all'
expect(s.triggerCount).toBe 0
m.trigger 'event'
expect(s.triggerCount).toBe 1
m.trigger 'otherevent'
expect(s.triggerCount).toBe 2
m.trigger 'yetanotherevent'
expect(s.triggerCount).toBe 3
m.trigger 'event'
expect(s.triggerCount).toBe 4
it 'should track the arguments of event calls', ->
m = new Backbone.Model
s = new test.EventSpy m, 'all'
expect(s.arguments).toEqual []
m.trigger 'a'
expect(s.arguments).toEqual [['a']]
m.trigger 'b', 1
expect(s.arguments).toEqual [['a'], ['b', 1]]
m.trigger 'c', 'hi', 'hello'
expect(s.arguments).toEqual [['a'], ['b', 1], ['c', 'hi', 'hello']]
it 'should wipe the arguments on calling reset', ->
m = new Backbone.Model
s = new test.EventSpy m, 'all'
expect(s.arguments).toEqual []
m.trigger 'a'
expect(s.arguments).toEqual [['a']]
m.trigger 'b', 1
expect(s.arguments).toEqual [['a'], ['b', 1]]
m.trigger 'c', 'hi', 'hello'
expect(s.arguments).toEqual [['a'], ['b', 1], ['c', 'hi', 'hello']]
s.reset()
expect(s.arguments).toEqual []
m.trigger 'b', {pedro: 'ah'}
expect(s.arguments).toEqual [['b', {pedro: 'ah'}]]
describe 'expectEventSpyBehaviors', ->
it 'should be a function', ->
expect(typeof test.expectEventSpyBehaviors).toBe 'function'
it 'should test that events were triggered', ->
m = new Backbone.Model
spies =
seeSpy: new test.EventSpy m, 'see'
hearSpy: new test.EventSpy m, 'hear'
speakSpy: new test.EventSpy m, 'speak'
allSpy: new test.EventSpy m, 'all'
fns = [
->
m.trigger 'see'
expectations =
seeSpy: undefined
allSpy: undefined
->
m.trigger 'hear'
expectations =
hearSpy: undefined
allSpy: undefined
->
m.trigger 'speak'
expectations =
speakSpy: undefined
allSpy: undefined
->
m.trigger 'see'
m.trigger 'hear'
expectations =
seeSpy: undefined
hearSpy: undefined
allSpy: undefined
->
m.trigger 'see'
m.trigger 'hear'
m.trigger 'speak'
expectations =
seeSpy: undefined
hearSpy: undefined
speakSpy: undefined
allSpy: undefined
]
test.expectEventSpyBehaviors spies, fns
it 'should test that events were triggered with specific arguments', ->
m = new Backbone.Model
spies =
seeSpy: new test.EventSpy m, 'see'
hearSpy: new test.EventSpy m, 'hear'
speakSpy: new test.EventSpy m, 'speak'
allSpy: new test.EventSpy m, 'all'
fns = [
->
evil = 'murdering children'
m.trigger 'see', evil
expectations =
seeSpy: evil
allSpy: ['see', evil]
->
evil = 'tripping an old lady'
m.trigger 'hear', evil
expectations =
hearSpy: evil
allSpy: ['hear', evil]
->
evil = 'stealing candy from children'
m.trigger 'speak', evil
expectations =
speakSpy: evil
allSpy: ['speak', evil]
->
evil = 'slipping a laxative into the bake sale cookies'
m.trigger 'hear', evil
m.trigger 'speak', evil
expectations =
hearSpy: evil
speakSpy: evil
allSpy: ['speak', evil]
->
evil = 'throwing a red ball in front of a blind man\'s guide dog, and
yelling fetch'
m.trigger 'speak', evil
m.trigger 'hear', evil
m.trigger 'see', evil
expectations =
seeSpy: evil
hearSpy: evil
speakSpy: evil
allSpy: ['see', evil]
]
test.expectEventSpyBehaviors spies, fns
|
[
{
"context": "###\nCopyright © 201{5,6} Jess Austin <jess.austin@gmail.com>\nReleased under MIT Licens",
"end": 36,
"score": 0.9997433423995972,
"start": 25,
"tag": "NAME",
"value": "Jess Austin"
},
{
"context": "###\nCopyright © 201{5,6} Jess Austin <jess.austin@gmail.com>\nReleased... | test.coffee | jessaustin/koa-signed-url | 2 | ###
Copyright © 201{5,6} Jess Austin <jess.austin@gmail.com>
Released under MIT License
###
{ createServer } = require 'http'
koa = require 'koa'
request = require 'co-request'
sleep = require 'co-sleep'
signed = require '.'
require('tape') 'Koa-Signed-URL Test', require('co-tape') (tape) ->
body = 'This is a test.'
port = 2999
keysList = [
ks = ['secret', 'another']
ks[0]
require('keygrip') ks
]
pathParts = ['', 'path', '/subpath/', 'leaf.ext', '?q=query', '&r=queries']
tape.plan 9 * pathParts.length * keysList.length
for keys in keysList
url = "http://localhost:#{port}/"
app = koa()
signedUrl = signed keys
app.use signedUrl
app.use (next) ->
@body = body
yield next
server = createServer app.callback()
.listen port
for part in pathParts
url += part
sig = signedUrl.sign url
tape.equal "#{sig}#fragment", signedUrl.sign("#{url}#fragment"),
'Should ignore fragment'
resp = yield request sig
tape.equal resp.statusCode, 200, 'Should verify correct signature.'
tape.equal resp.body, body, 'Should serve correct body.'
resp = yield request sig.replace /[?&]sig=.*$/, ''
tape.equal resp.statusCode, 404, 'Should reject lack of signature.'
resp = yield request sig + 'x'
tape.equal resp.statusCode, 404, 'Should reject expanded signature.'
resp = yield request sig[...-3]
tape.equal resp.statusCode, 404, 'Should reject truncated signature.'
resp = yield request sig + '&yet=another_query'
tape.equal resp.statusCode, 404, 'Should reject non-canonical URL.'
sig = signedUrl.sign url, 10000
resp = yield request sig
tape.equal resp.statusCode, 200, 'Should verify correct signature.'
sig = signedUrl.sign url, 1
resp = yield request sig
yield sleep 100
tape.equal resp.statusCode, 404, 'Should reject expired url'
server.close()
| 138297 | ###
Copyright © 201{5,6} <NAME> <<EMAIL>>
Released under MIT License
###
{ createServer } = require 'http'
koa = require 'koa'
request = require 'co-request'
sleep = require 'co-sleep'
signed = require '.'
require('tape') 'Koa-Signed-URL Test', require('co-tape') (tape) ->
body = 'This is a test.'
port = 2999
keysList = [
ks = ['secret', 'another']
ks[0]
require('keygrip') ks
]
pathParts = ['', 'path', '/subpath/', 'leaf.ext', '?q=query', '&r=queries']
tape.plan 9 * pathParts.length * keysList.length
for keys in keysList
url = "http://localhost:#{port}/"
app = koa()
signedUrl = signed keys
app.use signedUrl
app.use (next) ->
@body = body
yield next
server = createServer app.callback()
.listen port
for part in pathParts
url += part
sig = signedUrl.sign url
tape.equal "#{sig}#fragment", signedUrl.sign("#{url}#fragment"),
'Should ignore fragment'
resp = yield request sig
tape.equal resp.statusCode, 200, 'Should verify correct signature.'
tape.equal resp.body, body, 'Should serve correct body.'
resp = yield request sig.replace /[?&]sig=.*$/, ''
tape.equal resp.statusCode, 404, 'Should reject lack of signature.'
resp = yield request sig + 'x'
tape.equal resp.statusCode, 404, 'Should reject expanded signature.'
resp = yield request sig[...-3]
tape.equal resp.statusCode, 404, 'Should reject truncated signature.'
resp = yield request sig + '&yet=another_query'
tape.equal resp.statusCode, 404, 'Should reject non-canonical URL.'
sig = signedUrl.sign url, 10000
resp = yield request sig
tape.equal resp.statusCode, 200, 'Should verify correct signature.'
sig = signedUrl.sign url, 1
resp = yield request sig
yield sleep 100
tape.equal resp.statusCode, 404, 'Should reject expired url'
server.close()
| true | ###
Copyright © 201{5,6} PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Released under MIT License
###
{ createServer } = require 'http'
koa = require 'koa'
request = require 'co-request'
sleep = require 'co-sleep'
signed = require '.'
require('tape') 'Koa-Signed-URL Test', require('co-tape') (tape) ->
body = 'This is a test.'
port = 2999
keysList = [
ks = ['secret', 'another']
ks[0]
require('keygrip') ks
]
pathParts = ['', 'path', '/subpath/', 'leaf.ext', '?q=query', '&r=queries']
tape.plan 9 * pathParts.length * keysList.length
for keys in keysList
url = "http://localhost:#{port}/"
app = koa()
signedUrl = signed keys
app.use signedUrl
app.use (next) ->
@body = body
yield next
server = createServer app.callback()
.listen port
for part in pathParts
url += part
sig = signedUrl.sign url
tape.equal "#{sig}#fragment", signedUrl.sign("#{url}#fragment"),
'Should ignore fragment'
resp = yield request sig
tape.equal resp.statusCode, 200, 'Should verify correct signature.'
tape.equal resp.body, body, 'Should serve correct body.'
resp = yield request sig.replace /[?&]sig=.*$/, ''
tape.equal resp.statusCode, 404, 'Should reject lack of signature.'
resp = yield request sig + 'x'
tape.equal resp.statusCode, 404, 'Should reject expanded signature.'
resp = yield request sig[...-3]
tape.equal resp.statusCode, 404, 'Should reject truncated signature.'
resp = yield request sig + '&yet=another_query'
tape.equal resp.statusCode, 404, 'Should reject non-canonical URL.'
sig = signedUrl.sign url, 10000
resp = yield request sig
tape.equal resp.statusCode, 200, 'Should verify correct signature.'
sig = signedUrl.sign url, 1
resp = yield request sig
yield sleep 100
tape.equal resp.statusCode, 404, 'Should reject expired url'
server.close()
|
[
{
"context": "###\n Pokemon Go(c) MITM node proxy\n by Michael Strassburger <codepoet@cpan.org>\n\n Spinning a Pokestop - a gi",
"end": 61,
"score": 0.9998748898506165,
"start": 41,
"tag": "NAME",
"value": "Michael Strassburger"
},
{
"context": " Go(c) MITM node proxy\n by Michae... | example.spawnMasterball.coffee | BuloZB/pokemon-go-mitm-node | 393 | ###
Pokemon Go(c) MITM node proxy
by Michael Strassburger <codepoet@cpan.org>
Spinning a Pokestop - a gift that keeps on giving
Be aware: you can see it, you can touch it - you won't own it :)
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
server = new PokemonGoMITM port: 8081
.addResponseHandler "FortSearch", (data) ->
data.items_awarded = [
{item_type: 'ITEM_MASTER_BALL', item_count: 1}
{item_type: 'ITEM_SPECIAL_CAMERA', item_count: 1}
{item_type: 'ITEM_PINAP_BERRY', item_count: 1}
{item_type: 'ITEM_STORAGE_UPGRADE', item_count: 1}
]
data.xp_awarded = 1337
data | 217179 | ###
Pokemon Go(c) MITM node proxy
by <NAME> <<EMAIL>>
Spinning a Pokestop - a gift that keeps on giving
Be aware: you can see it, you can touch it - you won't own it :)
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
server = new PokemonGoMITM port: 8081
.addResponseHandler "FortSearch", (data) ->
data.items_awarded = [
{item_type: 'ITEM_MASTER_BALL', item_count: 1}
{item_type: 'ITEM_SPECIAL_CAMERA', item_count: 1}
{item_type: 'ITEM_PINAP_BERRY', item_count: 1}
{item_type: 'ITEM_STORAGE_UPGRADE', item_count: 1}
]
data.xp_awarded = 1337
data | true | ###
Pokemon Go(c) MITM node proxy
by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Spinning a Pokestop - a gift that keeps on giving
Be aware: you can see it, you can touch it - you won't own it :)
###
PokemonGoMITM = require './lib/pokemon-go-mitm'
server = new PokemonGoMITM port: 8081
.addResponseHandler "FortSearch", (data) ->
data.items_awarded = [
{item_type: 'ITEM_MASTER_BALL', item_count: 1}
{item_type: 'ITEM_SPECIAL_CAMERA', item_count: 1}
{item_type: 'ITEM_PINAP_BERRY', item_count: 1}
{item_type: 'ITEM_STORAGE_UPGRADE', item_count: 1}
]
data.xp_awarded = 1337
data |
[
{
"context": "ey]\n # expand paths\n for key in ['output', 'config', 'contents', 'templates']\n if opt",
"end": 2756,
"score": 0.545798122882843,
"start": 2756,
"tag": "KEY",
"value": ""
},
{
"context": "hs\n for key in ['output', 'config', 'contents', 'template... | src/cli/common.coffee | rakyll/wintersmith | 1 |
fs = require 'fs'
path = require 'path'
async = require 'async'
{logger, readJSON} = require '../common'
exports.fileExists = fileExists = fs.exists or path.exists
exports.commonOptions = defaults =
config:
alias: 'c'
default: './config.json'
contents:
alias: 'i'
default: './contents'
templates:
alias: 't'
default: './templates'
locals:
alias: 'L'
default: {}
chdir:
alias: 'C'
default: null
require:
alias: 'R'
default: []
plugins:
alias: 'P'
default: []
ignore:
alias: 'I'
default: []
exports.commonUsage = [
"-C, --chdir [path] change the working directory"
" -c, --config [path] path to config (defaults to #{ defaults.config.default })"
" -i, --contents [path] contents location (defaults to #{ defaults.contents.default })"
" -t, --templates [path] template location (defaults to #{ defaults.templates.default })"
" -L, --locals [path] optional path to json file containing template context data"
" -R, --require comma separated list of modules to add to the template context"
" -P, --plugins comma separated list of modules to load as plugins"
" -I, --ignore comma separated list of files/glob-patterns to ignore"
].join '\n'
exports.getOptions = (argv, callback) ->
### resolves options with the hierarchy: argv > configfile > defaults
returns a options object ###
workDir = path.resolve (argv.chdir or process.cwd())
logger.verbose "resolving options - work directory: #{ workDir }"
resolveModule = (moduleName, callback) ->
if moduleName[...2] is './'
callback null, path.resolve workDir, moduleName
else
callback null, moduleName
async.waterfall [
(callback) ->
# load config if present
configPath = path.join workDir, argv.config
fileExists configPath, (exists) ->
if exists
logger.info "using config file: #{ configPath }"
readJSON configPath, callback
else
logger.verbose "no config file found"
callback null, {}
(options, callback) ->
logger.verbose 'options:', options
for key of defaults
# assing defaults to missing conf options
options[key] ?= defaults[key].default
# ovveride conf and default options with any command line options
if argv[key]? and argv[key] != defaults[key].default
options[key] = argv[key]
# pass along extra arguments from argv
for key of argv
# don't include optimist stuff
if key[0] == '_' or key[0] == '$'
continue
options[key] ?= argv[key]
# expand paths
for key in ['output', 'config', 'contents', 'templates']
if options[key]
options[key] = path.resolve workDir, options[key]
callback null, options
(options, callback) ->
# load locals json if neccessary
if typeof options.locals == 'string'
filename = path.join workDir, options.locals
logger.verbose "loading locals from: #{ filename }"
readJSON filename, (error, result) ->
if error
callback error
else
options.locals = result
callback null, options
else
callback null, options
# provide modules specefied with the require option to the template context
(options, callback) ->
if typeof options.require is 'string'
options.require = options.require.split ','
# resolve module paths
async.map options.require, resolveModule, (error, result) ->
options.require = result
callback error, options
(options, callback) ->
# load modules and add them to options.locals
async.forEach options.require, (moduleName, callback) ->
moduleAlias = moduleName.split('/')[-1..]
logger.verbose "loading module #{ moduleName } available in locals as: #{ moduleAlias }"
try
options.locals[moduleAlias] = require moduleName
callback()
catch error
callback error
, (error) ->
callback error, options
(options, callback) ->
if typeof options.plugins is 'string'
options.plugins = options.plugins.split ','
# resolve plugin paths if required as file
async.map options.plugins, resolveModule, (error, result) ->
options.plugins = result
callback error, options
(options, callback) ->
# split list of files to ignore if needed
if typeof options.ignore is 'string'
options.ignore = options.ignore.split ','
callback null, options
(options, callback) ->
logger.verbose 'resolved options:', options
logger.verbose 'validating paths'
paths = ['contents', 'templates']
async.forEach paths, (filepath, callback) ->
fileExists options[filepath], (exists) ->
if exists
callback()
else
callback new Error "#{ filepath } path invalid (#{ options[filepath] })"
, (error) ->
callback error, options
], callback
| 97148 |
fs = require 'fs'
path = require 'path'
async = require 'async'
{logger, readJSON} = require '../common'
exports.fileExists = fileExists = fs.exists or path.exists
exports.commonOptions = defaults =
config:
alias: 'c'
default: './config.json'
contents:
alias: 'i'
default: './contents'
templates:
alias: 't'
default: './templates'
locals:
alias: 'L'
default: {}
chdir:
alias: 'C'
default: null
require:
alias: 'R'
default: []
plugins:
alias: 'P'
default: []
ignore:
alias: 'I'
default: []
exports.commonUsage = [
"-C, --chdir [path] change the working directory"
" -c, --config [path] path to config (defaults to #{ defaults.config.default })"
" -i, --contents [path] contents location (defaults to #{ defaults.contents.default })"
" -t, --templates [path] template location (defaults to #{ defaults.templates.default })"
" -L, --locals [path] optional path to json file containing template context data"
" -R, --require comma separated list of modules to add to the template context"
" -P, --plugins comma separated list of modules to load as plugins"
" -I, --ignore comma separated list of files/glob-patterns to ignore"
].join '\n'
exports.getOptions = (argv, callback) ->
### resolves options with the hierarchy: argv > configfile > defaults
returns a options object ###
workDir = path.resolve (argv.chdir or process.cwd())
logger.verbose "resolving options - work directory: #{ workDir }"
resolveModule = (moduleName, callback) ->
if moduleName[...2] is './'
callback null, path.resolve workDir, moduleName
else
callback null, moduleName
async.waterfall [
(callback) ->
# load config if present
configPath = path.join workDir, argv.config
fileExists configPath, (exists) ->
if exists
logger.info "using config file: #{ configPath }"
readJSON configPath, callback
else
logger.verbose "no config file found"
callback null, {}
(options, callback) ->
logger.verbose 'options:', options
for key of defaults
# assing defaults to missing conf options
options[key] ?= defaults[key].default
# ovveride conf and default options with any command line options
if argv[key]? and argv[key] != defaults[key].default
options[key] = argv[key]
# pass along extra arguments from argv
for key of argv
# don't include optimist stuff
if key[0] == '_' or key[0] == '$'
continue
options[key] ?= argv[key]
# expand paths
for key in ['output<KEY>', 'config', 'contents<KEY>', 'templates']
if options[key]
options[key] = path.resolve workDir, options[key]
callback null, options
(options, callback) ->
# load locals json if neccessary
if typeof options.locals == 'string'
filename = path.join workDir, options.locals
logger.verbose "loading locals from: #{ filename }"
readJSON filename, (error, result) ->
if error
callback error
else
options.locals = result
callback null, options
else
callback null, options
# provide modules specefied with the require option to the template context
(options, callback) ->
if typeof options.require is 'string'
options.require = options.require.split ','
# resolve module paths
async.map options.require, resolveModule, (error, result) ->
options.require = result
callback error, options
(options, callback) ->
# load modules and add them to options.locals
async.forEach options.require, (moduleName, callback) ->
moduleAlias = moduleName.split('/')[-1..]
logger.verbose "loading module #{ moduleName } available in locals as: #{ moduleAlias }"
try
options.locals[moduleAlias] = require moduleName
callback()
catch error
callback error
, (error) ->
callback error, options
(options, callback) ->
if typeof options.plugins is 'string'
options.plugins = options.plugins.split ','
# resolve plugin paths if required as file
async.map options.plugins, resolveModule, (error, result) ->
options.plugins = result
callback error, options
(options, callback) ->
# split list of files to ignore if needed
if typeof options.ignore is 'string'
options.ignore = options.ignore.split ','
callback null, options
(options, callback) ->
logger.verbose 'resolved options:', options
logger.verbose 'validating paths'
paths = ['contents', 'templates']
async.forEach paths, (filepath, callback) ->
fileExists options[filepath], (exists) ->
if exists
callback()
else
callback new Error "#{ filepath } path invalid (#{ options[filepath] })"
, (error) ->
callback error, options
], callback
| true |
fs = require 'fs'
path = require 'path'
async = require 'async'
{logger, readJSON} = require '../common'
exports.fileExists = fileExists = fs.exists or path.exists
exports.commonOptions = defaults =
config:
alias: 'c'
default: './config.json'
contents:
alias: 'i'
default: './contents'
templates:
alias: 't'
default: './templates'
locals:
alias: 'L'
default: {}
chdir:
alias: 'C'
default: null
require:
alias: 'R'
default: []
plugins:
alias: 'P'
default: []
ignore:
alias: 'I'
default: []
exports.commonUsage = [
"-C, --chdir [path] change the working directory"
" -c, --config [path] path to config (defaults to #{ defaults.config.default })"
" -i, --contents [path] contents location (defaults to #{ defaults.contents.default })"
" -t, --templates [path] template location (defaults to #{ defaults.templates.default })"
" -L, --locals [path] optional path to json file containing template context data"
" -R, --require comma separated list of modules to add to the template context"
" -P, --plugins comma separated list of modules to load as plugins"
" -I, --ignore comma separated list of files/glob-patterns to ignore"
].join '\n'
exports.getOptions = (argv, callback) ->
### resolves options with the hierarchy: argv > configfile > defaults
returns a options object ###
workDir = path.resolve (argv.chdir or process.cwd())
logger.verbose "resolving options - work directory: #{ workDir }"
resolveModule = (moduleName, callback) ->
if moduleName[...2] is './'
callback null, path.resolve workDir, moduleName
else
callback null, moduleName
async.waterfall [
(callback) ->
# load config if present
configPath = path.join workDir, argv.config
fileExists configPath, (exists) ->
if exists
logger.info "using config file: #{ configPath }"
readJSON configPath, callback
else
logger.verbose "no config file found"
callback null, {}
(options, callback) ->
logger.verbose 'options:', options
for key of defaults
# assing defaults to missing conf options
options[key] ?= defaults[key].default
# ovveride conf and default options with any command line options
if argv[key]? and argv[key] != defaults[key].default
options[key] = argv[key]
# pass along extra arguments from argv
for key of argv
# don't include optimist stuff
if key[0] == '_' or key[0] == '$'
continue
options[key] ?= argv[key]
# expand paths
for key in ['outputPI:KEY:<KEY>END_PI', 'config', 'contentsPI:KEY:<KEY>END_PI', 'templates']
if options[key]
options[key] = path.resolve workDir, options[key]
callback null, options
(options, callback) ->
# load locals json if neccessary
if typeof options.locals == 'string'
filename = path.join workDir, options.locals
logger.verbose "loading locals from: #{ filename }"
readJSON filename, (error, result) ->
if error
callback error
else
options.locals = result
callback null, options
else
callback null, options
# provide modules specefied with the require option to the template context
(options, callback) ->
if typeof options.require is 'string'
options.require = options.require.split ','
# resolve module paths
async.map options.require, resolveModule, (error, result) ->
options.require = result
callback error, options
(options, callback) ->
# load modules and add them to options.locals
async.forEach options.require, (moduleName, callback) ->
moduleAlias = moduleName.split('/')[-1..]
logger.verbose "loading module #{ moduleName } available in locals as: #{ moduleAlias }"
try
options.locals[moduleAlias] = require moduleName
callback()
catch error
callback error
, (error) ->
callback error, options
(options, callback) ->
if typeof options.plugins is 'string'
options.plugins = options.plugins.split ','
# resolve plugin paths if required as file
async.map options.plugins, resolveModule, (error, result) ->
options.plugins = result
callback error, options
(options, callback) ->
# split list of files to ignore if needed
if typeof options.ignore is 'string'
options.ignore = options.ignore.split ','
callback null, options
(options, callback) ->
logger.verbose 'resolved options:', options
logger.verbose 'validating paths'
paths = ['contents', 'templates']
async.forEach paths, (filepath, callback) ->
fileExists options[filepath], (exists) ->
if exists
callback()
else
callback new Error "#{ filepath } path invalid (#{ options[filepath] })"
, (error) ->
callback error, options
], callback
|
[
{
"context": "f 40 plus the key in @_TOKENS\n ## e.g. 8b804dd8-7a88-4142-8b33-913a586d67b4----backend so that the following comes true\n ## @",
"end": 418,
"score": 0.9712027311325073,
"start": 371,
"tag": "KEY",
"value": "8b804dd8-7a88-4142-8b33-913a586d67b4----backend... | lib/auth/AuthContext.coffee | nero-networks/floyd | 0 |
##
## Basic Authenticating Context
##
## handles static, unencrypted PSKs.
## does not provide dynamic logins
##
module.exports =
class AuthContext extends floyd.Context
##
##
##
configure: (config)->
## a static token has to be of the length of 40 plus the key in @_TOKENS
## e.g. 8b804dd8-7a88-4142-8b33-913a586d67b4----backend so that the following comes true
## @_TOKENS['backend'] is '8b804dd8-7a88-4142-8b33-913a586d67b4----backend'
@_TOKENS = config.tokens
super config
##
##
##
authorize: (token, fn)->
if !token
@logger.warning 'AuthContext.authorize NO TOKEN'
return fn new Error 'AuthContext.authorize NO TOKEN'
if @_TOKENS && @_TOKENS[token.substr 40] is token
fn()
else
fn new Error 'AuthContext.authorize unauthorized token'
##
## console.log identity.id, 'super err', err
##
authenticate: (identity, fn)->
identity.token (err, token)=>
if err || !token
@logger.warning 'AuthContext.authenticate NO TOKEN', identity.id
return fn(err || new Error 'AuthContext.authenticate NO TOKEN')
##
if @_TOKENS && @_TOKENS[token.substr 40] is token
@logger.debug 'found known Token, authenticate SUCCESS', identity.id
fn()
else
fn new Error 'AuthContext.authenticate TOKEN NOT FOUND'
##
##
##
login: (token, user, pass, fn)-> fn new Error 'login impossible'
##
##
##
logout: (token, fn)-> fn()
| 80780 |
##
## Basic Authenticating Context
##
## handles static, unencrypted PSKs.
## does not provide dynamic logins
##
module.exports =
class AuthContext extends floyd.Context
##
##
##
configure: (config)->
## a static token has to be of the length of 40 plus the key in @_TOKENS
## e.g. <KEY> so that the following comes true
## @_TOKENS['backend'] is '<KEY>'
@_TOKENS = config.tokens
super config
##
##
##
authorize: (token, fn)->
if !token
@logger.warning 'AuthContext.authorize NO TOKEN'
return fn new Error 'AuthContext.authorize NO TOKEN'
if @_TOKENS && @_TOKENS[token.substr 40] is token
fn()
else
fn new Error 'AuthContext.authorize unauthorized token'
##
## console.log identity.id, 'super err', err
##
authenticate: (identity, fn)->
identity.token (err, token)=>
if err || !token
@logger.warning 'AuthContext.authenticate NO TOKEN', identity.id
return fn(err || new Error 'AuthContext.authenticate NO TOKEN')
##
if @_TOKENS && @_TOKENS[token.substr 40] is token
@logger.debug 'found known Token, authenticate SUCCESS', identity.id
fn()
else
fn new Error 'AuthContext.authenticate TOKEN NOT FOUND'
##
##
##
login: (token, user, pass, fn)-> fn new Error 'login impossible'
##
##
##
logout: (token, fn)-> fn()
| true |
##
## Basic Authenticating Context
##
## handles static, unencrypted PSKs.
## does not provide dynamic logins
##
module.exports =
class AuthContext extends floyd.Context
##
##
##
configure: (config)->
## a static token has to be of the length of 40 plus the key in @_TOKENS
## e.g. PI:KEY:<KEY>END_PI so that the following comes true
## @_TOKENS['backend'] is 'PI:KEY:<KEY>END_PI'
@_TOKENS = config.tokens
super config
##
##
##
authorize: (token, fn)->
if !token
@logger.warning 'AuthContext.authorize NO TOKEN'
return fn new Error 'AuthContext.authorize NO TOKEN'
if @_TOKENS && @_TOKENS[token.substr 40] is token
fn()
else
fn new Error 'AuthContext.authorize unauthorized token'
##
## console.log identity.id, 'super err', err
##
authenticate: (identity, fn)->
identity.token (err, token)=>
if err || !token
@logger.warning 'AuthContext.authenticate NO TOKEN', identity.id
return fn(err || new Error 'AuthContext.authenticate NO TOKEN')
##
if @_TOKENS && @_TOKENS[token.substr 40] is token
@logger.debug 'found known Token, authenticate SUCCESS', identity.id
fn()
else
fn new Error 'AuthContext.authenticate TOKEN NOT FOUND'
##
##
##
login: (token, user, pass, fn)-> fn new Error 'login impossible'
##
##
##
logout: (token, fn)-> fn()
|
[
{
"context": "\t\t\t\t\temail: credentials.username,\n\t\t\t\t\tpassword: 'NOT-THE-CORRECT-PASSWORD'\n\n\t\t\t\tm.chai.expect(promise).to.be.rejectedWith('",
"end": 1160,
"score": 0.9991521239280701,
"start": 1136,
"tag": "PASSWORD",
"value": "NOT-THE-CORRECT-PASSWORD"
},
{
"context"... | tests/integration/auth.spec.coffee | josecoelho/balena-sdk | 0 | m = require('mochainon')
{ balena, sdkOpts, credentials, givenLoggedInUser, givenLoggedInUserWithApiKey } = require('./setup')
describe 'SDK authentication', ->
describe 'when not logged in', ->
beforeEach ->
balena.auth.logout()
describe 'balena.auth.isLoggedIn()', ->
it 'should eventually be false', ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
describe 'balena.auth.whoami()', ->
it 'should eventually be undefined', ->
promise = balena.auth.whoami()
m.chai.expect(promise).to.eventually.be.undefined
describe 'balena.auth.logout()', ->
it 'should not be rejected', ->
promise = balena.auth.logout()
m.chai.expect(promise).to.not.be.rejected
describe 'balena.auth.authenticate()', ->
it 'should not save the token given valid credentials', ->
balena.auth.authenticate(credentials).then ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
it 'should be rejected given invalid credentials', ->
promise = balena.auth.authenticate
email: credentials.username,
password: 'NOT-THE-CORRECT-PASSWORD'
m.chai.expect(promise).to.be.rejectedWith('Unauthorized')
describe 'balena.auth.getToken()', ->
it 'should be rejected', ->
promise = balena.auth.getToken()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe 'balena.auth.loginWithToken()', ->
it 'should be able to login with a session token', ->
balena.auth.authenticate(credentials)
.then(balena.auth.loginWithToken)
.then(balena.auth.getToken)
.then (key) ->
m.chai.expect(key).to.be.a('string')
it 'should be able to login with an API Key', ->
balena.auth.authenticate(credentials)
.then(balena.auth.loginWithToken)
.then ->
balena.models.apiKey.create('apiKey')
.tap(balena.auth.logout)
.then(balena.auth.loginWithToken)
.then(balena.auth.getToken)
.then (key) ->
m.chai.expect(key).to.be.a('string')
describe 'balena.auth.getEmail()', ->
it 'should be rejected with an error', ->
promise = balena.auth.getEmail()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe 'balena.auth.getUserId()', ->
it 'should be rejected with an error', ->
promise = balena.auth.getUserId()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe.skip 'balena.auth.register()', ->
beforeEach ->
balena.auth.login
email: credentials.register.email
password: credentials.register.password
.then(balena.auth.getUserId)
.then (userId) ->
return balena.request.send
method: 'DELETE'
url: "/v2/user(#{userId})"
baseUrl: sdkOpts.apiUrl
.then(balena.auth.logout)
.catch(message: 'Request error: Unauthorized', ->)
it 'should be able to register an account', ->
balena.auth.register
email: credentials.register.email
password: credentials.register.password
.then(balena.auth.loginWithToken)
.then(balena.auth.isLoggedIn)
.then (isLoggedIn) ->
m.chai.expect(isLoggedIn).to.be.true
it 'should not save the token automatically', ->
balena.auth.register
email: credentials.register.email
password: credentials.register.password
.then(balena.auth.isLoggedIn)
.then (isLoggedIn) ->
m.chai.expect(isLoggedIn).to.be.false
it 'should be rejected if the email is invalid', ->
promise = balena.auth.register
email: 'foobarbaz'
password: credentials.register.password
m.chai.expect(promise).to.be.rejectedWith('Invalid email')
it 'should be rejected if the email is taken', ->
promise = balena.auth.register
email: credentials.email
password: credentials.register.password
m.chai.expect(promise).to.be.rejectedWith('This email is already taken')
describe 'when logged in with credentials', ->
givenLoggedInUser(beforeEach)
describe 'balena.auth.isLoggedIn()', ->
it 'should eventually be true', ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.true
describe 'balena.auth.logout()', ->
it 'should logout the user', ->
balena.auth.logout().then ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
describe 'balena.auth.whoami()', ->
it 'should eventually be the username', ->
promise = balena.auth.whoami()
m.chai.expect(promise).to.eventually.equal(credentials.username)
describe 'balena.auth.getEmail()', ->
it 'should eventually be the email', ->
promise = balena.auth.getEmail()
m.chai.expect(promise).to.eventually.equal(credentials.email)
describe 'balena.auth.getUserId()', ->
it 'should eventually be a user id', ->
balena.auth.getUserId()
.then (userId) ->
m.chai.expect(userId).to.be.a('number')
m.chai.expect(userId).to.be.greaterThan(0)
describe 'when logged in with API key', ->
givenLoggedInUserWithApiKey(beforeEach)
describe 'balena.auth.isLoggedIn()', ->
it 'should eventually be true', ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.true
describe 'balena.auth.logout()', ->
it 'should logout the user', ->
balena.auth.logout().then ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
it 'should reset the token on logout', ->
balena.auth.logout().then ->
promise = balena.auth.getToken()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe 'balena.auth.whoami()', ->
it 'should eventually be the username', ->
promise = balena.auth.whoami()
m.chai.expect(promise).to.eventually.equal(credentials.username)
describe 'balena.auth.getEmail()', ->
it 'should eventually be the email', ->
promise = balena.auth.getEmail()
m.chai.expect(promise).to.eventually.equal(credentials.email)
describe 'balena.auth.getUserId()', ->
it 'should eventually be a user id', ->
balena.auth.getUserId()
.then (userId) ->
m.chai.expect(userId).to.be.a('number')
m.chai.expect(userId).to.be.greaterThan(0)
| 35385 | m = require('mochainon')
{ balena, sdkOpts, credentials, givenLoggedInUser, givenLoggedInUserWithApiKey } = require('./setup')
describe 'SDK authentication', ->
describe 'when not logged in', ->
beforeEach ->
balena.auth.logout()
describe 'balena.auth.isLoggedIn()', ->
it 'should eventually be false', ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
describe 'balena.auth.whoami()', ->
it 'should eventually be undefined', ->
promise = balena.auth.whoami()
m.chai.expect(promise).to.eventually.be.undefined
describe 'balena.auth.logout()', ->
it 'should not be rejected', ->
promise = balena.auth.logout()
m.chai.expect(promise).to.not.be.rejected
describe 'balena.auth.authenticate()', ->
it 'should not save the token given valid credentials', ->
balena.auth.authenticate(credentials).then ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
it 'should be rejected given invalid credentials', ->
promise = balena.auth.authenticate
email: credentials.username,
password: '<PASSWORD>'
m.chai.expect(promise).to.be.rejectedWith('Unauthorized')
describe 'balena.auth.getToken()', ->
it 'should be rejected', ->
promise = balena.auth.getToken()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe 'balena.auth.loginWithToken()', ->
it 'should be able to login with a session token', ->
balena.auth.authenticate(credentials)
.then(balena.auth.loginWithToken)
.then(balena.auth.getToken)
.then (key) ->
m.chai.expect(key).to.be.a('string')
it 'should be able to login with an API Key', ->
balena.auth.authenticate(credentials)
.then(balena.auth.loginWithToken)
.then ->
balena.models.apiKey.create('apiKey')
.tap(balena.auth.logout)
.then(balena.auth.loginWithToken)
.then(balena.auth.getToken)
.then (key) ->
m.chai.expect(key).to.be.a('string')
describe 'balena.auth.getEmail()', ->
it 'should be rejected with an error', ->
promise = balena.auth.getEmail()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe 'balena.auth.getUserId()', ->
it 'should be rejected with an error', ->
promise = balena.auth.getUserId()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe.skip 'balena.auth.register()', ->
beforeEach ->
balena.auth.login
email: credentials.register.email
password: <PASSWORD>
.then(balena.auth.getUserId)
.then (userId) ->
return balena.request.send
method: 'DELETE'
url: "/v2/user(#{userId})"
baseUrl: sdkOpts.apiUrl
.then(balena.auth.logout)
.catch(message: 'Request error: Unauthorized', ->)
it 'should be able to register an account', ->
balena.auth.register
email: credentials.register.email
password: <PASSWORD>
.then(balena.auth.loginWithToken)
.then(balena.auth.isLoggedIn)
.then (isLoggedIn) ->
m.chai.expect(isLoggedIn).to.be.true
it 'should not save the token automatically', ->
balena.auth.register
email: credentials.register.email
password: <PASSWORD>
.then(balena.auth.isLoggedIn)
.then (isLoggedIn) ->
m.chai.expect(isLoggedIn).to.be.false
it 'should be rejected if the email is invalid', ->
promise = balena.auth.register
email: 'foobarbaz'
password: <PASSWORD>
m.chai.expect(promise).to.be.rejectedWith('Invalid email')
it 'should be rejected if the email is taken', ->
promise = balena.auth.register
email: credentials.email
password: <PASSWORD>
m.chai.expect(promise).to.be.rejectedWith('This email is already taken')
describe 'when logged in with credentials', ->
givenLoggedInUser(beforeEach)
describe 'balena.auth.isLoggedIn()', ->
it 'should eventually be true', ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.true
describe 'balena.auth.logout()', ->
it 'should logout the user', ->
balena.auth.logout().then ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
describe 'balena.auth.whoami()', ->
it 'should eventually be the username', ->
promise = balena.auth.whoami()
m.chai.expect(promise).to.eventually.equal(credentials.username)
describe 'balena.auth.getEmail()', ->
it 'should eventually be the email', ->
promise = balena.auth.getEmail()
m.chai.expect(promise).to.eventually.equal(credentials.email)
describe 'balena.auth.getUserId()', ->
it 'should eventually be a user id', ->
balena.auth.getUserId()
.then (userId) ->
m.chai.expect(userId).to.be.a('number')
m.chai.expect(userId).to.be.greaterThan(0)
describe 'when logged in with API key', ->
givenLoggedInUserWithApiKey(beforeEach)
describe 'balena.auth.isLoggedIn()', ->
it 'should eventually be true', ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.true
describe 'balena.auth.logout()', ->
it 'should logout the user', ->
balena.auth.logout().then ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
it 'should reset the token on logout', ->
balena.auth.logout().then ->
promise = balena.auth.getToken()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe 'balena.auth.whoami()', ->
it 'should eventually be the username', ->
promise = balena.auth.whoami()
m.chai.expect(promise).to.eventually.equal(credentials.username)
describe 'balena.auth.getEmail()', ->
it 'should eventually be the email', ->
promise = balena.auth.getEmail()
m.chai.expect(promise).to.eventually.equal(credentials.email)
describe 'balena.auth.getUserId()', ->
it 'should eventually be a user id', ->
balena.auth.getUserId()
.then (userId) ->
m.chai.expect(userId).to.be.a('number')
m.chai.expect(userId).to.be.greaterThan(0)
| true | m = require('mochainon')
{ balena, sdkOpts, credentials, givenLoggedInUser, givenLoggedInUserWithApiKey } = require('./setup')
describe 'SDK authentication', ->
describe 'when not logged in', ->
beforeEach ->
balena.auth.logout()
describe 'balena.auth.isLoggedIn()', ->
it 'should eventually be false', ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
describe 'balena.auth.whoami()', ->
it 'should eventually be undefined', ->
promise = balena.auth.whoami()
m.chai.expect(promise).to.eventually.be.undefined
describe 'balena.auth.logout()', ->
it 'should not be rejected', ->
promise = balena.auth.logout()
m.chai.expect(promise).to.not.be.rejected
describe 'balena.auth.authenticate()', ->
it 'should not save the token given valid credentials', ->
balena.auth.authenticate(credentials).then ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
it 'should be rejected given invalid credentials', ->
promise = balena.auth.authenticate
email: credentials.username,
password: 'PI:PASSWORD:<PASSWORD>END_PI'
m.chai.expect(promise).to.be.rejectedWith('Unauthorized')
describe 'balena.auth.getToken()', ->
it 'should be rejected', ->
promise = balena.auth.getToken()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe 'balena.auth.loginWithToken()', ->
it 'should be able to login with a session token', ->
balena.auth.authenticate(credentials)
.then(balena.auth.loginWithToken)
.then(balena.auth.getToken)
.then (key) ->
m.chai.expect(key).to.be.a('string')
it 'should be able to login with an API Key', ->
balena.auth.authenticate(credentials)
.then(balena.auth.loginWithToken)
.then ->
balena.models.apiKey.create('apiKey')
.tap(balena.auth.logout)
.then(balena.auth.loginWithToken)
.then(balena.auth.getToken)
.then (key) ->
m.chai.expect(key).to.be.a('string')
describe 'balena.auth.getEmail()', ->
it 'should be rejected with an error', ->
promise = balena.auth.getEmail()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe 'balena.auth.getUserId()', ->
it 'should be rejected with an error', ->
promise = balena.auth.getUserId()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe.skip 'balena.auth.register()', ->
beforeEach ->
balena.auth.login
email: credentials.register.email
password: PI:PASSWORD:<PASSWORD>END_PI
.then(balena.auth.getUserId)
.then (userId) ->
return balena.request.send
method: 'DELETE'
url: "/v2/user(#{userId})"
baseUrl: sdkOpts.apiUrl
.then(balena.auth.logout)
.catch(message: 'Request error: Unauthorized', ->)
it 'should be able to register an account', ->
balena.auth.register
email: credentials.register.email
password: PI:PASSWORD:<PASSWORD>END_PI
.then(balena.auth.loginWithToken)
.then(balena.auth.isLoggedIn)
.then (isLoggedIn) ->
m.chai.expect(isLoggedIn).to.be.true
it 'should not save the token automatically', ->
balena.auth.register
email: credentials.register.email
password: PI:PASSWORD:<PASSWORD>END_PI
.then(balena.auth.isLoggedIn)
.then (isLoggedIn) ->
m.chai.expect(isLoggedIn).to.be.false
it 'should be rejected if the email is invalid', ->
promise = balena.auth.register
email: 'foobarbaz'
password: PI:PASSWORD:<PASSWORD>END_PI
m.chai.expect(promise).to.be.rejectedWith('Invalid email')
it 'should be rejected if the email is taken', ->
promise = balena.auth.register
email: credentials.email
password: PI:PASSWORD:<PASSWORD>END_PI
m.chai.expect(promise).to.be.rejectedWith('This email is already taken')
describe 'when logged in with credentials', ->
givenLoggedInUser(beforeEach)
describe 'balena.auth.isLoggedIn()', ->
it 'should eventually be true', ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.true
describe 'balena.auth.logout()', ->
it 'should logout the user', ->
balena.auth.logout().then ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
describe 'balena.auth.whoami()', ->
it 'should eventually be the username', ->
promise = balena.auth.whoami()
m.chai.expect(promise).to.eventually.equal(credentials.username)
describe 'balena.auth.getEmail()', ->
it 'should eventually be the email', ->
promise = balena.auth.getEmail()
m.chai.expect(promise).to.eventually.equal(credentials.email)
describe 'balena.auth.getUserId()', ->
it 'should eventually be a user id', ->
balena.auth.getUserId()
.then (userId) ->
m.chai.expect(userId).to.be.a('number')
m.chai.expect(userId).to.be.greaterThan(0)
describe 'when logged in with API key', ->
givenLoggedInUserWithApiKey(beforeEach)
describe 'balena.auth.isLoggedIn()', ->
it 'should eventually be true', ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.true
describe 'balena.auth.logout()', ->
it 'should logout the user', ->
balena.auth.logout().then ->
promise = balena.auth.isLoggedIn()
m.chai.expect(promise).to.eventually.be.false
it 'should reset the token on logout', ->
balena.auth.logout().then ->
promise = balena.auth.getToken()
m.chai.expect(promise).to.be.rejected
.and.eventually.have.property('code', 'BalenaNotLoggedIn')
describe 'balena.auth.whoami()', ->
it 'should eventually be the username', ->
promise = balena.auth.whoami()
m.chai.expect(promise).to.eventually.equal(credentials.username)
describe 'balena.auth.getEmail()', ->
it 'should eventually be the email', ->
promise = balena.auth.getEmail()
m.chai.expect(promise).to.eventually.equal(credentials.email)
describe 'balena.auth.getUserId()', ->
it 'should eventually be a user id', ->
balena.auth.getUserId()
.then (userId) ->
m.chai.expect(userId).to.be.a('number')
m.chai.expect(userId).to.be.greaterThan(0)
|
[
{
"context": "t rpc response\", ->\n @Wallet.create 'test', 'password'\n @deferred.resolve {result: true}\n @ro",
"end": 362,
"score": 0.5131493210792542,
"start": 354,
"tag": "PASSWORD",
"value": "password"
}
] | spec/services/wallet_spec.coffee | AlexChien/web_wallet | 0 | describe "service: Wallet", ->
beforeEach -> module("app")
beforeEach inject ($q, $rootScope, @Wallet, RpcService) ->
@rootScope = $rootScope
@deferred = $q.defer()
@rpc = spyOn(RpcService, 'request').andReturn(@deferred.promise)
describe "#create", ->
it "should process correct rpc response", ->
@Wallet.create 'test', 'password'
@deferred.resolve {result: true}
@rootScope.$apply()
expect(@rpc).toHaveBeenCalledWith('wallet_create', ['test', 'password'])
| 141875 | describe "service: Wallet", ->
beforeEach -> module("app")
beforeEach inject ($q, $rootScope, @Wallet, RpcService) ->
@rootScope = $rootScope
@deferred = $q.defer()
@rpc = spyOn(RpcService, 'request').andReturn(@deferred.promise)
describe "#create", ->
it "should process correct rpc response", ->
@Wallet.create 'test', '<PASSWORD>'
@deferred.resolve {result: true}
@rootScope.$apply()
expect(@rpc).toHaveBeenCalledWith('wallet_create', ['test', 'password'])
| true | describe "service: Wallet", ->
beforeEach -> module("app")
beforeEach inject ($q, $rootScope, @Wallet, RpcService) ->
@rootScope = $rootScope
@deferred = $q.defer()
@rpc = spyOn(RpcService, 'request').andReturn(@deferred.promise)
describe "#create", ->
it "should process correct rpc response", ->
@Wallet.create 'test', 'PI:PASSWORD:<PASSWORD>END_PI'
@deferred.resolve {result: true}
@rootScope.$apply()
expect(@rpc).toHaveBeenCalledWith('wallet_create', ['test', 'password'])
|
[
{
"context": "es = $('.js-like').like {\n csrfToken: \"foobar\",\n likeText: \"foo like ({count})\",\n ",
"end": 586,
"score": 0.9750228524208069,
"start": 580,
"tag": "KEY",
"value": "foobar"
}
] | spirit/core/static/spirit/scripts/test/suites/like-spec.coffee | StepanBakshayev/Spirit | 1 | describe "like plugin tests", ->
likes = null
like = null
Like = null
post = null
data = null
beforeEach ->
fixtures = do jasmine.getFixtures
fixtures.fixturesPath = 'base/test/fixtures/'
loadFixtures 'like.html'
post = spyOn $, 'post'
post.and.callFake (req) ->
d = $.Deferred()
d.resolve(data) # success
#d.reject() # failure
return d.promise()
data =
url_delete: "/foo/delete/"
likes = $('.js-like').like {
csrfToken: "foobar",
likeText: "foo like ({count})",
removeLikeText: "foo remove like ({count})"
}
like = likes.first().data 'plugin_like'
Like = $.fn.like.Like
it "doesnt break selector chaining", ->
expect(likes).toEqual $('.js-like')
expect(likes.length).toEqual 2
it "can create the like", ->
expect($.post.calls.any()).toEqual false
likes.first().trigger 'click'
expect($.post.calls.any()).toEqual true
expect($.post.calls.argsFor(0)).toEqual ['/foo/create/', {csrfmiddlewaretoken: "foobar", }]
it "can create and remove the like", ->
# create
data =
url_delete: "/foo/delete/"
likes.first().trigger 'click'
expect($.post.calls.argsFor(0)).toEqual ['/foo/create/', {csrfmiddlewaretoken: "foobar", }]
expect(likes.first().text()).toEqual "foo remove like (1)"
# remove
data =
url_create: "/foo/create/"
likes.first().trigger 'click'
expect($.post.calls.argsFor(1)).toEqual ['/foo/delete/', {csrfmiddlewaretoken: "foobar", }]
expect(likes.first().text()).toEqual "foo like (0)"
# create again... and so on...
data =
url_delete: "/foo/delete/"
likes.first().trigger 'click'
expect($.post.calls.argsFor(2)).toEqual ['/foo/create/', {csrfmiddlewaretoken: "foobar", }]
expect(likes.first().text()).toEqual "foo remove like (1)"
it "will tell about an api change", ->
data =
unknown: null
likes.first().trigger 'click'
expect(likes.first().text()).toEqual "api error"
it "prevents from multiple posts while sending", ->
expect($.post.calls.any()).toEqual false
d = $.Deferred()
post.and.callFake (req) =>
d.resolve(data)
return d.promise()
always = spyOn post(), 'always'
post.calls.reset()
likes.first().trigger 'click'
expect($.post.calls.any()).toEqual true
expect(always.calls.any()).toEqual true
# next click should do nothing
post.calls.reset()
likes.first().trigger 'click'
expect($.post.calls.any()).toEqual false
it "prevents the default click behaviour", ->
event = {type: 'click', stopPropagation: (->), preventDefault: (->)}
stopPropagation = spyOn event, 'stopPropagation'
preventDefault = spyOn event, 'preventDefault'
likes.first().trigger event
expect(stopPropagation).toHaveBeenCalled()
expect(preventDefault).toHaveBeenCalled()
| 127814 | describe "like plugin tests", ->
likes = null
like = null
Like = null
post = null
data = null
beforeEach ->
fixtures = do jasmine.getFixtures
fixtures.fixturesPath = 'base/test/fixtures/'
loadFixtures 'like.html'
post = spyOn $, 'post'
post.and.callFake (req) ->
d = $.Deferred()
d.resolve(data) # success
#d.reject() # failure
return d.promise()
data =
url_delete: "/foo/delete/"
likes = $('.js-like').like {
csrfToken: "<KEY>",
likeText: "foo like ({count})",
removeLikeText: "foo remove like ({count})"
}
like = likes.first().data 'plugin_like'
Like = $.fn.like.Like
it "doesnt break selector chaining", ->
expect(likes).toEqual $('.js-like')
expect(likes.length).toEqual 2
it "can create the like", ->
expect($.post.calls.any()).toEqual false
likes.first().trigger 'click'
expect($.post.calls.any()).toEqual true
expect($.post.calls.argsFor(0)).toEqual ['/foo/create/', {csrfmiddlewaretoken: "foobar", }]
it "can create and remove the like", ->
# create
data =
url_delete: "/foo/delete/"
likes.first().trigger 'click'
expect($.post.calls.argsFor(0)).toEqual ['/foo/create/', {csrfmiddlewaretoken: "foobar", }]
expect(likes.first().text()).toEqual "foo remove like (1)"
# remove
data =
url_create: "/foo/create/"
likes.first().trigger 'click'
expect($.post.calls.argsFor(1)).toEqual ['/foo/delete/', {csrfmiddlewaretoken: "foobar", }]
expect(likes.first().text()).toEqual "foo like (0)"
# create again... and so on...
data =
url_delete: "/foo/delete/"
likes.first().trigger 'click'
expect($.post.calls.argsFor(2)).toEqual ['/foo/create/', {csrfmiddlewaretoken: "foobar", }]
expect(likes.first().text()).toEqual "foo remove like (1)"
it "will tell about an api change", ->
data =
unknown: null
likes.first().trigger 'click'
expect(likes.first().text()).toEqual "api error"
it "prevents from multiple posts while sending", ->
expect($.post.calls.any()).toEqual false
d = $.Deferred()
post.and.callFake (req) =>
d.resolve(data)
return d.promise()
always = spyOn post(), 'always'
post.calls.reset()
likes.first().trigger 'click'
expect($.post.calls.any()).toEqual true
expect(always.calls.any()).toEqual true
# next click should do nothing
post.calls.reset()
likes.first().trigger 'click'
expect($.post.calls.any()).toEqual false
it "prevents the default click behaviour", ->
event = {type: 'click', stopPropagation: (->), preventDefault: (->)}
stopPropagation = spyOn event, 'stopPropagation'
preventDefault = spyOn event, 'preventDefault'
likes.first().trigger event
expect(stopPropagation).toHaveBeenCalled()
expect(preventDefault).toHaveBeenCalled()
| true | describe "like plugin tests", ->
likes = null
like = null
Like = null
post = null
data = null
beforeEach ->
fixtures = do jasmine.getFixtures
fixtures.fixturesPath = 'base/test/fixtures/'
loadFixtures 'like.html'
post = spyOn $, 'post'
post.and.callFake (req) ->
d = $.Deferred()
d.resolve(data) # success
#d.reject() # failure
return d.promise()
data =
url_delete: "/foo/delete/"
likes = $('.js-like').like {
csrfToken: "PI:KEY:<KEY>END_PI",
likeText: "foo like ({count})",
removeLikeText: "foo remove like ({count})"
}
like = likes.first().data 'plugin_like'
Like = $.fn.like.Like
it "doesnt break selector chaining", ->
expect(likes).toEqual $('.js-like')
expect(likes.length).toEqual 2
it "can create the like", ->
expect($.post.calls.any()).toEqual false
likes.first().trigger 'click'
expect($.post.calls.any()).toEqual true
expect($.post.calls.argsFor(0)).toEqual ['/foo/create/', {csrfmiddlewaretoken: "foobar", }]
it "can create and remove the like", ->
# create
data =
url_delete: "/foo/delete/"
likes.first().trigger 'click'
expect($.post.calls.argsFor(0)).toEqual ['/foo/create/', {csrfmiddlewaretoken: "foobar", }]
expect(likes.first().text()).toEqual "foo remove like (1)"
# remove
data =
url_create: "/foo/create/"
likes.first().trigger 'click'
expect($.post.calls.argsFor(1)).toEqual ['/foo/delete/', {csrfmiddlewaretoken: "foobar", }]
expect(likes.first().text()).toEqual "foo like (0)"
# create again... and so on...
data =
url_delete: "/foo/delete/"
likes.first().trigger 'click'
expect($.post.calls.argsFor(2)).toEqual ['/foo/create/', {csrfmiddlewaretoken: "foobar", }]
expect(likes.first().text()).toEqual "foo remove like (1)"
it "will tell about an api change", ->
data =
unknown: null
likes.first().trigger 'click'
expect(likes.first().text()).toEqual "api error"
it "prevents from multiple posts while sending", ->
expect($.post.calls.any()).toEqual false
d = $.Deferred()
post.and.callFake (req) =>
d.resolve(data)
return d.promise()
always = spyOn post(), 'always'
post.calls.reset()
likes.first().trigger 'click'
expect($.post.calls.any()).toEqual true
expect(always.calls.any()).toEqual true
# next click should do nothing
post.calls.reset()
likes.first().trigger 'click'
expect($.post.calls.any()).toEqual false
it "prevents the default click behaviour", ->
event = {type: 'click', stopPropagation: (->), preventDefault: (->)}
stopPropagation = spyOn event, 'stopPropagation'
preventDefault = spyOn event, 'preventDefault'
likes.first().trigger event
expect(stopPropagation).toHaveBeenCalled()
expect(preventDefault).toHaveBeenCalled()
|
[
{
"context": "ust a heavily modified version of hubot-factoid by therealklanni\n# Supports history (in case you need to",
"end": 147,
"score": 0.8991093039512634,
"start": 142,
"tag": "USERNAME",
"value": "there"
},
{
"context": "heavily modified version of hubot-factoid by thereal... | src/terminator-core.coffee | Gavitron/hubot-terminator | 0 | # Description:
# Am implementation of a glossary capability for your hubot.
# really just a heavily modified version of hubot-factoid by therealklanni
# Supports history (in case you need to revert a change), as
# well as popularity, aliases, searches, and multiline!
#
# Dependencies:
# None
#
# Commands:
# hubot learn <term> = <definition> - learn a new term
# hubot alias <term> = <term>
# hubot explain <term> - lookup the definition of <term>
# hubot forget <term> - forget a definition
# hubot remember <term> - remember a definition that was forgotten previously
# hubot drop <term> - permanently forget a definition
# hubot list all definitions - list all definitions
# hubot search <substring> - list any definitions which match (by key or result)
#
# Authors:
# gavitron (2019)
# therealklanni (2013-2017)
Definitions = require './definitions'
module.exports = (robot) ->
@definitions = new Definitions robot
robot.router.get "/#{robot.name}/definitions", (req, res) =>
res.end JSON.stringify @definitions.data, null, 2
robot.hear new RegExp("^explain (pls )?([\\w\\s-]{2,}\\w)( @.+)?", 'i'), (msg) =>
definition = @definitions.get msg.match[2]
to = msg.match[3]
if not definition? or definition.forgotten
msg.reply "Term not defined"
else
definition.popularity++
to ?= msg.message.user.name
msg.send "#{to.trim()}: *#{msg.match[2]}*\n> #{definition.value.replace(/\n/g,"\n> ")}"
robot.respond new RegExp("explain (pls )?([\\w\\s-]{2,}\\w)", 'i'), (msg) =>
definition = @definitions.get msg.match[2]
if not definition? or definition.forgotten
msg.reply "Term not defined"
else
definition.popularity++
msg.send "*#{msg.match[2]}*\n> #{definition.value.replace(/\n/g,"\n> ")}"
robot.respond /learn (.{3,}) = ([^@].+)/i, (msg) =>
user = msg.envelope.user
[key, value] = [msg.match[1], msg.match[2]]
definition = @definitions.set key, value, msg.message.user.name
if definition.value?
msg.reply "OK, I know what #{key} means"
robot.respond /forget (.{3,})/i, (msg) =>
user = msg.envelope.user
if @definitions.forget msg.match[1]
msg.reply "OK, forgot #{msg.match[1]}"
else
msg.reply 'Term not defined'
robot.respond /remember (.{3,})/i, (msg) =>
definition = @definitions.remember msg.match[1]
if definition? and not definition.forgotten
msg.reply "OK, #{msg.match[1]} is #{definition.value}"
else
msg.reply 'Term not defined'
robot.respond /list all definitions/i, (msg) =>
all = @definitions.getAll()
out = ''
if not all? or Object.keys(all).length is 0
msg.reply "Nothing defined"
else
for f of all
out += f + ': ' + all[f] + "\n"
msg.reply "All definitions: \n" + out
robot.respond /search (.{3,})/i, (msg) =>
definitions = @definitions.search msg.match[1]
if definitions.length > 0
found = definitions.join("*, *")
msg.reply "Matched the following definitions: *#{found}*"
else
msg.reply 'No definitions matched'
robot.respond /alias (.{3,}) = (.{3,})/i, (msg) =>
user = msg.envelope.user
who = msg.message.user.name
alias = msg.match[1]
target = msg.match[2]
msg.reply "OK, aliased #{alias} to #{target}" if @definitions.set msg.match[1], "@#{msg.match[2]}", msg.message.user.name, false
robot.respond /drop (.{3,})/i, (msg) =>
user = msg.envelope.user
definition = msg.match[1]
if @definitions.drop definition
msg.reply "OK, #{definition} has been dropped"
else msg.reply "Term not defined"
robot.respond /save terms/i, (msg) =>
Path = require 'path'
fs = require('fs');
path = Path.resolve('data')
filename = Path.join path, 'terminator_gestalt.json'
robot.logger.info("saving to file #{filename}")
def_json = @definitions.save()
fs.writeFile filename, def_json, (error) ->
console.log("Error writing file", error) if error
console.log def_json
if def_json
msg.reply "OK, definitions are saved"
else msg.reply "ERROR: Save failed"
robot.respond /load terms/i, (msg) =>
Path = require 'path'
fs = require('fs');
path = Path.resolve('data')
filename = Path.join path, 'terminator_gestalt.json'
robot.logger.info("loading from file #{filename}")
def_json = fs.readFileSync filename, (error) ->
robot.logging.error("Error reading file", error) if error;
if @definitions.load(def_json)
msg.reply "OK, definitions have been loaded"
else msg.reply "ERROR: Load failed"
| 151204 | # Description:
# Am implementation of a glossary capability for your hubot.
# really just a heavily modified version of hubot-factoid by there<NAME>
# Supports history (in case you need to revert a change), as
# well as popularity, aliases, searches, and multiline!
#
# Dependencies:
# None
#
# Commands:
# hubot learn <term> = <definition> - learn a new term
# hubot alias <term> = <term>
# hubot explain <term> - lookup the definition of <term>
# hubot forget <term> - forget a definition
# hubot remember <term> - remember a definition that was forgotten previously
# hubot drop <term> - permanently forget a definition
# hubot list all definitions - list all definitions
# hubot search <substring> - list any definitions which match (by key or result)
#
# Authors:
# gavitron (2019)
# there<NAME> (2013-2017)
Definitions = require './definitions'
module.exports = (robot) ->
@definitions = new Definitions robot
robot.router.get "/#{robot.name}/definitions", (req, res) =>
res.end JSON.stringify @definitions.data, null, 2
robot.hear new RegExp("^explain (pls )?([\\w\\s-]{2,}\\w)( @.+)?", 'i'), (msg) =>
definition = @definitions.get msg.match[2]
to = msg.match[3]
if not definition? or definition.forgotten
msg.reply "Term not defined"
else
definition.popularity++
to ?= msg.message.user.name
msg.send "#{to.trim()}: *#{msg.match[2]}*\n> #{definition.value.replace(/\n/g,"\n> ")}"
robot.respond new RegExp("explain (pls )?([\\w\\s-]{2,}\\w)", 'i'), (msg) =>
definition = @definitions.get msg.match[2]
if not definition? or definition.forgotten
msg.reply "Term not defined"
else
definition.popularity++
msg.send "*#{msg.match[2]}*\n> #{definition.value.replace(/\n/g,"\n> ")}"
robot.respond /learn (.{3,}) = ([^@].+)/i, (msg) =>
user = msg.envelope.user
[key, value] = [msg.match[1], msg.match[2]]
definition = @definitions.set key, value, msg.message.user.name
if definition.value?
msg.reply "OK, I know what #{key} means"
robot.respond /forget (.{3,})/i, (msg) =>
user = msg.envelope.user
if @definitions.forget msg.match[1]
msg.reply "OK, forgot #{msg.match[1]}"
else
msg.reply 'Term not defined'
robot.respond /remember (.{3,})/i, (msg) =>
definition = @definitions.remember msg.match[1]
if definition? and not definition.forgotten
msg.reply "OK, #{msg.match[1]} is #{definition.value}"
else
msg.reply 'Term not defined'
robot.respond /list all definitions/i, (msg) =>
all = @definitions.getAll()
out = ''
if not all? or Object.keys(all).length is 0
msg.reply "Nothing defined"
else
for f of all
out += f + ': ' + all[f] + "\n"
msg.reply "All definitions: \n" + out
robot.respond /search (.{3,})/i, (msg) =>
definitions = @definitions.search msg.match[1]
if definitions.length > 0
found = definitions.join("*, *")
msg.reply "Matched the following definitions: *#{found}*"
else
msg.reply 'No definitions matched'
robot.respond /alias (.{3,}) = (.{3,})/i, (msg) =>
user = msg.envelope.user
who = msg.message.user.name
alias = msg.match[1]
target = msg.match[2]
msg.reply "OK, aliased #{alias} to #{target}" if @definitions.set msg.match[1], "@#{msg.match[2]}", msg.message.user.name, false
robot.respond /drop (.{3,})/i, (msg) =>
user = msg.envelope.user
definition = msg.match[1]
if @definitions.drop definition
msg.reply "OK, #{definition} has been dropped"
else msg.reply "Term not defined"
robot.respond /save terms/i, (msg) =>
Path = require 'path'
fs = require('fs');
path = Path.resolve('data')
filename = Path.join path, 'terminator_gestalt.json'
robot.logger.info("saving to file #{filename}")
def_json = @definitions.save()
fs.writeFile filename, def_json, (error) ->
console.log("Error writing file", error) if error
console.log def_json
if def_json
msg.reply "OK, definitions are saved"
else msg.reply "ERROR: Save failed"
robot.respond /load terms/i, (msg) =>
Path = require 'path'
fs = require('fs');
path = Path.resolve('data')
filename = Path.join path, 'terminator_gestalt.json'
robot.logger.info("loading from file #{filename}")
def_json = fs.readFileSync filename, (error) ->
robot.logging.error("Error reading file", error) if error;
if @definitions.load(def_json)
msg.reply "OK, definitions have been loaded"
else msg.reply "ERROR: Load failed"
| true | # Description:
# Am implementation of a glossary capability for your hubot.
# really just a heavily modified version of hubot-factoid by therePI:NAME:<NAME>END_PI
# Supports history (in case you need to revert a change), as
# well as popularity, aliases, searches, and multiline!
#
# Dependencies:
# None
#
# Commands:
# hubot learn <term> = <definition> - learn a new term
# hubot alias <term> = <term>
# hubot explain <term> - lookup the definition of <term>
# hubot forget <term> - forget a definition
# hubot remember <term> - remember a definition that was forgotten previously
# hubot drop <term> - permanently forget a definition
# hubot list all definitions - list all definitions
# hubot search <substring> - list any definitions which match (by key or result)
#
# Authors:
# gavitron (2019)
# therePI:NAME:<NAME>END_PI (2013-2017)
Definitions = require './definitions'
module.exports = (robot) ->
@definitions = new Definitions robot
robot.router.get "/#{robot.name}/definitions", (req, res) =>
res.end JSON.stringify @definitions.data, null, 2
robot.hear new RegExp("^explain (pls )?([\\w\\s-]{2,}\\w)( @.+)?", 'i'), (msg) =>
definition = @definitions.get msg.match[2]
to = msg.match[3]
if not definition? or definition.forgotten
msg.reply "Term not defined"
else
definition.popularity++
to ?= msg.message.user.name
msg.send "#{to.trim()}: *#{msg.match[2]}*\n> #{definition.value.replace(/\n/g,"\n> ")}"
robot.respond new RegExp("explain (pls )?([\\w\\s-]{2,}\\w)", 'i'), (msg) =>
definition = @definitions.get msg.match[2]
if not definition? or definition.forgotten
msg.reply "Term not defined"
else
definition.popularity++
msg.send "*#{msg.match[2]}*\n> #{definition.value.replace(/\n/g,"\n> ")}"
robot.respond /learn (.{3,}) = ([^@].+)/i, (msg) =>
user = msg.envelope.user
[key, value] = [msg.match[1], msg.match[2]]
definition = @definitions.set key, value, msg.message.user.name
if definition.value?
msg.reply "OK, I know what #{key} means"
robot.respond /forget (.{3,})/i, (msg) =>
user = msg.envelope.user
if @definitions.forget msg.match[1]
msg.reply "OK, forgot #{msg.match[1]}"
else
msg.reply 'Term not defined'
robot.respond /remember (.{3,})/i, (msg) =>
definition = @definitions.remember msg.match[1]
if definition? and not definition.forgotten
msg.reply "OK, #{msg.match[1]} is #{definition.value}"
else
msg.reply 'Term not defined'
robot.respond /list all definitions/i, (msg) =>
all = @definitions.getAll()
out = ''
if not all? or Object.keys(all).length is 0
msg.reply "Nothing defined"
else
for f of all
out += f + ': ' + all[f] + "\n"
msg.reply "All definitions: \n" + out
robot.respond /search (.{3,})/i, (msg) =>
definitions = @definitions.search msg.match[1]
if definitions.length > 0
found = definitions.join("*, *")
msg.reply "Matched the following definitions: *#{found}*"
else
msg.reply 'No definitions matched'
robot.respond /alias (.{3,}) = (.{3,})/i, (msg) =>
user = msg.envelope.user
who = msg.message.user.name
alias = msg.match[1]
target = msg.match[2]
msg.reply "OK, aliased #{alias} to #{target}" if @definitions.set msg.match[1], "@#{msg.match[2]}", msg.message.user.name, false
robot.respond /drop (.{3,})/i, (msg) =>
user = msg.envelope.user
definition = msg.match[1]
if @definitions.drop definition
msg.reply "OK, #{definition} has been dropped"
else msg.reply "Term not defined"
robot.respond /save terms/i, (msg) =>
Path = require 'path'
fs = require('fs');
path = Path.resolve('data')
filename = Path.join path, 'terminator_gestalt.json'
robot.logger.info("saving to file #{filename}")
def_json = @definitions.save()
fs.writeFile filename, def_json, (error) ->
console.log("Error writing file", error) if error
console.log def_json
if def_json
msg.reply "OK, definitions are saved"
else msg.reply "ERROR: Save failed"
robot.respond /load terms/i, (msg) =>
Path = require 'path'
fs = require('fs');
path = Path.resolve('data')
filename = Path.join path, 'terminator_gestalt.json'
robot.logger.info("loading from file #{filename}")
def_json = fs.readFileSync filename, (error) ->
robot.logging.error("Error reading file", error) if error;
if @definitions.load(def_json)
msg.reply "OK, definitions have been loaded"
else msg.reply "ERROR: Load failed"
|
[
{
"context": "ut Me</h3>\n <div>\n <p>\n Hello, my name is Leonardo. I'd like it very much if we\n got to know ea",
"end": 120,
"score": 0.9998292326927185,
"start": 112,
"tag": "NAME",
"value": "Leonardo"
},
{
"context": "I have the utmost respect and\n admiration... | programs/about-me/src/html-ui.coffee | lbv/ka-cs-programs | 2 | htmlUI = """
<div id="Frame">
<div id="Accordion">
<h3>About Me</h3>
<div>
<p>
Hello, my name is Leonardo. I'd like it very much if we
got to know each other a little better, so here's a few
things that may help you get a better picture of who I
am.
</p>
<p>
I enjoy learning <span>n</span>ew things, and I am passionate
about education. Given this, it shouldn't be a
surprise if I tell you that I strongly appreciate the
Khan Academy, and I have the utmost respect and
admiration for Salman and his team.
</p>
<p>
I work as a software developer. I am very fond of
computer science and all related fields, although I'm
not very much into <em>technology</em> as such.
</p>
<p>
I like to read a lot, mostly literature, but also
philosophy, sci-fi or any other type of reading
material that I find interesting or entertaining.
</p>
<p>
I like music, and I play the bass guitar in a rock
band with a few friends. Good times…
</p>
<p>
I like sports. I love football (the kind where you
kick a round ball, but I also enjoy watching the other
kind from time to time). One of my favourite hobbies
right now is watching football matches from European
leagues (Spain, England, Portugal, and right now I'm
waiting for the day they start broadcasting the
Bundesliga where I live).
</p>
<p>
That's all I can think of right now. I know it's not
much, but hopefully it's a little informative :).
</p>
</div>
<h3>My Programs</h3>
<div>
<p>
You can find more about the programs I've created for
the Khan Academy environment in the following website:
</p>
<p>
<a href="http://lbv.github.io/ka-cs-programs/" target="_blank">KA CS</a>
</p>
</div>
<h3>Contact</h3>
<div>
<p>
I like meeting <span>n</span>ew people and friendly conversations.
</p>
<p>
If you want to get in touch with me, feel free to post
on the <em>Questions</em> or <em>Tips &
Feedback</em> sections of any of my programs.
</p>
</div>
</div>
</div><!-- Frame -->
"""
| 219143 | htmlUI = """
<div id="Frame">
<div id="Accordion">
<h3>About Me</h3>
<div>
<p>
Hello, my name is <NAME>. I'd like it very much if we
got to know each other a little better, so here's a few
things that may help you get a better picture of who I
am.
</p>
<p>
I enjoy learning <span>n</span>ew things, and I am passionate
about education. Given this, it shouldn't be a
surprise if I tell you that I strongly appreciate the
Khan Academy, and I have the utmost respect and
admiration for <NAME> and his team.
</p>
<p>
I work as a software developer. I am very fond of
computer science and all related fields, although I'm
not very much into <em>technology</em> as such.
</p>
<p>
I like to read a lot, mostly literature, but also
philosophy, sci-fi or any other type of reading
material that I find interesting or entertaining.
</p>
<p>
I like music, and I play the bass guitar in a rock
band with a few friends. Good times…
</p>
<p>
I like sports. I love football (the kind where you
kick a round ball, but I also enjoy watching the other
kind from time to time). One of my favourite hobbies
right now is watching football matches from European
leagues (Spain, England, Portugal, and right now I'm
waiting for the day they start broadcasting the
Bundesliga where I live).
</p>
<p>
That's all I can think of right now. I know it's not
much, but hopefully it's a little informative :).
</p>
</div>
<h3>My Programs</h3>
<div>
<p>
You can find more about the programs I've created for
the Khan Academy environment in the following website:
</p>
<p>
<a href="http://lbv.github.io/ka-cs-programs/" target="_blank">KA CS</a>
</p>
</div>
<h3>Contact</h3>
<div>
<p>
I like meeting <span>n</span>ew people and friendly conversations.
</p>
<p>
If you want to get in touch with me, feel free to post
on the <em>Questions</em> or <em>Tips &
Feedback</em> sections of any of my programs.
</p>
</div>
</div>
</div><!-- Frame -->
"""
| true | htmlUI = """
<div id="Frame">
<div id="Accordion">
<h3>About Me</h3>
<div>
<p>
Hello, my name is PI:NAME:<NAME>END_PI. I'd like it very much if we
got to know each other a little better, so here's a few
things that may help you get a better picture of who I
am.
</p>
<p>
I enjoy learning <span>n</span>ew things, and I am passionate
about education. Given this, it shouldn't be a
surprise if I tell you that I strongly appreciate the
Khan Academy, and I have the utmost respect and
admiration for PI:NAME:<NAME>END_PI and his team.
</p>
<p>
I work as a software developer. I am very fond of
computer science and all related fields, although I'm
not very much into <em>technology</em> as such.
</p>
<p>
I like to read a lot, mostly literature, but also
philosophy, sci-fi or any other type of reading
material that I find interesting or entertaining.
</p>
<p>
I like music, and I play the bass guitar in a rock
band with a few friends. Good times…
</p>
<p>
I like sports. I love football (the kind where you
kick a round ball, but I also enjoy watching the other
kind from time to time). One of my favourite hobbies
right now is watching football matches from European
leagues (Spain, England, Portugal, and right now I'm
waiting for the day they start broadcasting the
Bundesliga where I live).
</p>
<p>
That's all I can think of right now. I know it's not
much, but hopefully it's a little informative :).
</p>
</div>
<h3>My Programs</h3>
<div>
<p>
You can find more about the programs I've created for
the Khan Academy environment in the following website:
</p>
<p>
<a href="http://lbv.github.io/ka-cs-programs/" target="_blank">KA CS</a>
</p>
</div>
<h3>Contact</h3>
<div>
<p>
I like meeting <span>n</span>ew people and friendly conversations.
</p>
<p>
If you want to get in touch with me, feel free to post
on the <em>Questions</em> or <em>Tips &
Feedback</em> sections of any of my programs.
</p>
</div>
</div>
</div><!-- Frame -->
"""
|
[
{
"context": "nfiguration'\n dialog.positiveLocalizableKey = 'common.no'\n dialog.negativeLocalizableKey = 'common.yes'",
"end": 1275,
"score": 0.9524868130683899,
"start": 1266,
"tag": "KEY",
"value": "common.no"
},
{
"context": " 'common.no'\n dialog.negativeLocalizableKey... | app/src/controllers/onboarding/onboarding_view_controller.coffee | romanornr/ledger-wallet-crw | 173 | class @OnboardingViewController extends ledger.common.ViewController
view:
continueButton: '#continue_button'
navigation:
continueUrl: undefined
bumpsStepCount: true
onAfterRender: ->
super
do @unbindWindow
do @bindWindow
navigationBackParams: ->
undefined
navigationContinueParams: ->
undefined
_defaultNavigationBackParams: ->
{}
_defaultNavigationContinueParams: ->
wallet_mode: @params.wallet_mode
rootUrl: @params.rootUrl
back: @representativeUrl()
step: parseInt(@params.step) + if @_canBumpNextViewControllerStepCount() then 1 else 0
swapped_bip39: @params.swapped_bip39
_finalNavigationBackParams: ->
_.extend(@_defaultNavigationBackParams(), @navigationBackParams())
_finalNavigationContinueParams: ->
_.extend(@_defaultNavigationContinueParams(), @navigationContinueParams())
_canBumpNextViewControllerStepCount: ->
words = _.str.words(_.str.underscored(@identifier()), "_")
return words.length >= 2 && words[1] == "management" && @bumpsStepCount
navigateRoot: ->
dialog = new CommonDialogsConfirmationDialogViewController()
dialog.setMessageLocalizableKey 'onboarding.management.cancel_wallet_configuration'
dialog.positiveLocalizableKey = 'common.no'
dialog.negativeLocalizableKey = 'common.yes'
dialog.once 'click:negative', =>
ledger.app.router.go @params.rootUrl
dialog.show()
navigateBack: ->
ledger.app.router.go @params.back, @_finalNavigationBackParams()
navigateContinue: (url, params) ->
url = undefined unless _.isFunction(url?.parseAsUrl)
params = _.extend(@_defaultNavigationContinueParams(), params) if params?
ledger.app.router.go (url || @navigation.continueUrl), (params || @_finalNavigationContinueParams())
unbindWindow: ->
$(window).unbind 'keyup', null
openHelpCenter: ->
window.open t 'application.support_url'
bindWindow: ->
if @view.continueButton? and @view.continueButton.length == 1
$(window).on 'keyup', (e) =>
if (e.keyCode == 13)
if (!@view.continueButton.hasClass 'disabled')
@view.continueButton.click()
| 49609 | class @OnboardingViewController extends ledger.common.ViewController
view:
continueButton: '#continue_button'
navigation:
continueUrl: undefined
bumpsStepCount: true
onAfterRender: ->
super
do @unbindWindow
do @bindWindow
navigationBackParams: ->
undefined
navigationContinueParams: ->
undefined
_defaultNavigationBackParams: ->
{}
_defaultNavigationContinueParams: ->
wallet_mode: @params.wallet_mode
rootUrl: @params.rootUrl
back: @representativeUrl()
step: parseInt(@params.step) + if @_canBumpNextViewControllerStepCount() then 1 else 0
swapped_bip39: @params.swapped_bip39
_finalNavigationBackParams: ->
_.extend(@_defaultNavigationBackParams(), @navigationBackParams())
_finalNavigationContinueParams: ->
_.extend(@_defaultNavigationContinueParams(), @navigationContinueParams())
_canBumpNextViewControllerStepCount: ->
words = _.str.words(_.str.underscored(@identifier()), "_")
return words.length >= 2 && words[1] == "management" && @bumpsStepCount
navigateRoot: ->
dialog = new CommonDialogsConfirmationDialogViewController()
dialog.setMessageLocalizableKey 'onboarding.management.cancel_wallet_configuration'
dialog.positiveLocalizableKey = '<KEY>'
dialog.negativeLocalizableKey = '<KEY>'
dialog.once 'click:negative', =>
ledger.app.router.go @params.rootUrl
dialog.show()
navigateBack: ->
ledger.app.router.go @params.back, @_finalNavigationBackParams()
navigateContinue: (url, params) ->
url = undefined unless _.isFunction(url?.parseAsUrl)
params = _.extend(@_defaultNavigationContinueParams(), params) if params?
ledger.app.router.go (url || @navigation.continueUrl), (params || @_finalNavigationContinueParams())
unbindWindow: ->
$(window).unbind 'keyup', null
openHelpCenter: ->
window.open t 'application.support_url'
bindWindow: ->
if @view.continueButton? and @view.continueButton.length == 1
$(window).on 'keyup', (e) =>
if (e.keyCode == 13)
if (!@view.continueButton.hasClass 'disabled')
@view.continueButton.click()
| true | class @OnboardingViewController extends ledger.common.ViewController
view:
continueButton: '#continue_button'
navigation:
continueUrl: undefined
bumpsStepCount: true
onAfterRender: ->
super
do @unbindWindow
do @bindWindow
navigationBackParams: ->
undefined
navigationContinueParams: ->
undefined
_defaultNavigationBackParams: ->
{}
_defaultNavigationContinueParams: ->
wallet_mode: @params.wallet_mode
rootUrl: @params.rootUrl
back: @representativeUrl()
step: parseInt(@params.step) + if @_canBumpNextViewControllerStepCount() then 1 else 0
swapped_bip39: @params.swapped_bip39
_finalNavigationBackParams: ->
_.extend(@_defaultNavigationBackParams(), @navigationBackParams())
_finalNavigationContinueParams: ->
_.extend(@_defaultNavigationContinueParams(), @navigationContinueParams())
_canBumpNextViewControllerStepCount: ->
words = _.str.words(_.str.underscored(@identifier()), "_")
return words.length >= 2 && words[1] == "management" && @bumpsStepCount
navigateRoot: ->
dialog = new CommonDialogsConfirmationDialogViewController()
dialog.setMessageLocalizableKey 'onboarding.management.cancel_wallet_configuration'
dialog.positiveLocalizableKey = 'PI:KEY:<KEY>END_PI'
dialog.negativeLocalizableKey = 'PI:KEY:<KEY>END_PI'
dialog.once 'click:negative', =>
ledger.app.router.go @params.rootUrl
dialog.show()
navigateBack: ->
ledger.app.router.go @params.back, @_finalNavigationBackParams()
navigateContinue: (url, params) ->
url = undefined unless _.isFunction(url?.parseAsUrl)
params = _.extend(@_defaultNavigationContinueParams(), params) if params?
ledger.app.router.go (url || @navigation.continueUrl), (params || @_finalNavigationContinueParams())
unbindWindow: ->
$(window).unbind 'keyup', null
openHelpCenter: ->
window.open t 'application.support_url'
bindWindow: ->
if @view.continueButton? and @view.continueButton.length == 1
$(window).on 'keyup', (e) =>
if (e.keyCode == 13)
if (!@view.continueButton.hasClass 'disabled')
@view.continueButton.click()
|
[
{
"context": "goodApiKey = testApiKey\nbadApiKey = \"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa\"\n\nrecorderState = (recorder) -> [\n recorder.queu",
"end": 74,
"score": 0.9995381236076355,
"start": 38,
"tag": "KEY",
"value": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
}
] | src/test/recorder-spec.coffee | plyfe/myna-js | 2 | goodApiKey = testApiKey
badApiKey = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
recorderState = (recorder) -> [
recorder.queuedEvents().length, # the number of events waiting to be sent by the next call to record()
recorder.semaphore, # the number of record() methods that are currently running
recorder.waiting.length # the number of callbacks registered for future calls to record()
]
for errorCase in [ "success", "client", "server" ]
do (errorCase) ->
apiKey = switch errorCase
when "success" then goodApiKey
when "client" then badApiKey
when "server" then goodApiKey
errorStatus = switch errorCase
when "success" then "success"
when "client" then "client error"
when "server" then "server error"
initialized = (fn) ->
return ->
expt = new Myna.Experiment
uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c"
id: "id"
settings: "myna.web.sticky": false
variants: [
{ id: "variant1", weight: 0.5 }
{ id: "variant2", weight: 0.5 }
]
client = new Myna.Client
apiKey: apiKey
apiRoot: testApiRoot
settings: "myna.web.autoSync": false
experiments: [ expt ]
recorder = new Myna.Recorder client
switch errorCase
# when "success"
# # Do nothing
# when "client"
# # Do nothing
when "server"
spyOn(Myna.jsonp, "request").andCallFake (options) ->
options.error({ typename: "problem", status: 500 })
return
expt.off()
expt.unstick()
recorder.off()
recorder.listenTo(expt)
recorder.clearQueuedEvents()
recorder.semaphore = 0
recorder.waiting = []
fn(expt, client, recorder)
runs ->
@removeAllSpies()
return
describe "Myna.Recorder.sync (#{errorStatus})", ->
it "should record a single event", initialized (expt, client, recorder) ->
variant = null
success = false
error = false
withSuggestion expt, (v) ->
variant = v
waitsFor -> variant
runs ->
expect(recorderState(recorder)).toEqual([ 1, 0, 0 ])
recorder.sync(
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 1, 0 ]
when "client" then "fail"
when "server" then "fail"
)
success = true
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 0, 1, 0 ]
when "server" then [ 1, 1, 0 ]
)
error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 0, 0 ]
when "client" then [ 0, 0, 0 ]
when "server" then [ 1, 0, 0 ]
)
it "should record multiple events (#{errorStatus})", initialized (expt, client, recorder) ->
variant1 = null
variant2 = null
success = false
error = false
withSuggestion expt, (v1) ->
withReward expt, 1.0, ->
withSuggestion expt, (v2) ->
withReward expt, 1.0, ->
variant1 = v1
variant2 = v2
waitsFor -> variant1 && variant2
runs ->
expect(recorderState(recorder)).toEqual([ 4, 0, 0 ])
recorder.sync(
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 1, 0 ]
when "client" then "fail"
when "server" then "fail"
)
success = true
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 0, 1, 0 ]
when "server" then [ 4, 1, 0 ]
)
error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 0, 0 ]
when "client" then [ 0, 0, 0 ]
when "server" then [ 4, 0, 0 ]
)
it "should handle multiple concurrent calls to record (#{errorStatus})", initialized (expt, client, recorder) ->
# Myna.log statements show the likely order of execution.
variant1 = null
variant2 = null
success1 = false
success2 = false
error1 = false
error2 = false
withView expt, "variant1", (v1) ->
withReward expt, 1.0, ->
variant1 = v1
waitsFor -> variant1
runs ->
Myna.log("BLOCK 1")
expect(recorderState(recorder)).toEqual([ 2, 0, 0 ])
recorder.sync(
->
Myna.log("BLOCK 4a")
expect(errorCase).toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 2, 1, 1 ]
when "client" then "fail"
when "server" then "fail"
)
success1 = true
->
Myna.log("BLOCK 4b")
expect(errorCase).not.toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 2, 1, 1 ]
when "server" then [ 2, 1, 0 ]
)
error1 = true
)
runs ->
Myna.log("BLOCK 2")
withView expt, "variant2", (v2) ->
withReward expt, 1.0, ->
variant2 = v2
runs ->
Myna.log("BLOCK 3")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 2, 1, 0 ]
when "client" then [ 2, 1, 0 ]
when "server" then [ 4, 0, 0 ]
)
recorder.sync(
->
Myna.log("BLOCK 5a")
expect(errorCase).toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 1, 0 ]
when "client" then "fail"
when "server" then "fail"
)
success2 = true
->
Myna.log("BLOCK 5b")
expect(errorCase).not.toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 0, 1, 0 ]
when "server" then [ 4, 1, 0 ]
)
error2 = true
)
waitsFor -> (success1 || error1) && (success2 || error2)
# 6
runs ->
Myna.log("BLOCK 6")
expect(success1).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(success2).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error1).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(error2).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 0, 0 ]
when "client" then [ 0, 0, 0 ]
when "server" then [ 4, 0, 0 ]
)
it "should fire beforeSync and sync events (#{errorStatus})", initialized (expt, client, recorder) ->
variant = null
success = false
error = false
calls = []
recorder.on 'beforeSync', jasmine.createSpy('beforeSync').andCallFake (unrecorded) ->
calls.push { event: 'beforeSync', unrecorded }
recorder.on 'sync', jasmine.createSpy('sync').andCallFake (recorded, discarded, requeued) ->
calls.push { event: 'sync', recorded, discarded, requeued }
withSuggestion expt, (v) ->
variant = v
waitsFor -> variant
runs ->
recorder.sync(
-> success = true
-> error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(calls.length).toEqual(2)
expect(calls[0].event).toEqual('beforeSync')
expect(calls[0].unrecorded.length).toEqual(1)
expect(calls[0].unrecorded[0].timestamp).toBeDefined()
delete calls[0].unrecorded[0].timestamp
expect(calls[0].unrecorded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
switch errorCase
when "success"
expect(calls[1].event).toEqual('sync')
expect(calls[1].recorded.length).toEqual(1)
expect(calls[1].discarded.length).toEqual(0)
expect(calls[1].requeued.length).toEqual(0)
# Timestamp was already deleted above:
expect(calls[1].recorded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
when "client"
expect(calls[1].event).toEqual('sync')
expect(calls[1].recorded.length).toEqual(0)
expect(calls[1].discarded.length).toEqual(1)
expect(calls[1].requeued.length).toEqual(0)
# Timestamp was already deleted above:
expect(calls[1].discarded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
else
expect(calls[1].event).toEqual('sync')
expect(calls[1].recorded.length).toEqual(0)
expect(calls[1].discarded.length).toEqual(0)
expect(calls[1].requeued.length).toEqual(1)
# Timestamp was already deleted above:
expect(calls[1].requeued[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
return
it "should allow beforeSync to cancel the sync (#{errorStatus})", initialized (expt, client, recorder) ->
variant = null
success = false
error = false
calls = []
recorder.on 'beforeSync', jasmine.createSpy('beforeSync').andCallFake (unrecorded) ->
calls.push { event: 'beforeSync', unrecorded }
false
recorder.on 'sync', jasmine.createSpy('sync').andCallFake (recorded, discarded, requeued) ->
calls.push { event: 'sync', recorded, discarded, requeued }
withSuggestion expt, (v) ->
variant = v
waitsFor -> variant
runs ->
recorder.sync(
-> success = true
-> error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(false)
expect(error).toEqual(true)
expect(calls.length).toEqual(1)
expect(calls[0].event).toEqual('beforeSync')
expect(calls[0].unrecorded.length).toEqual(1)
expect(calls[0].unrecorded[0].timestamp).toBeDefined()
delete calls[0].unrecorded[0].timestamp
expect(calls[0].unrecorded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
expect(recorderState(recorder)).toEqual([ 1, 0, 0 ])
return
| 25630 | goodApiKey = testApiKey
badApiKey = "<KEY>"
recorderState = (recorder) -> [
recorder.queuedEvents().length, # the number of events waiting to be sent by the next call to record()
recorder.semaphore, # the number of record() methods that are currently running
recorder.waiting.length # the number of callbacks registered for future calls to record()
]
for errorCase in [ "success", "client", "server" ]
do (errorCase) ->
apiKey = switch errorCase
when "success" then goodApiKey
when "client" then badApiKey
when "server" then goodApiKey
errorStatus = switch errorCase
when "success" then "success"
when "client" then "client error"
when "server" then "server error"
initialized = (fn) ->
return ->
expt = new Myna.Experiment
uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c"
id: "id"
settings: "myna.web.sticky": false
variants: [
{ id: "variant1", weight: 0.5 }
{ id: "variant2", weight: 0.5 }
]
client = new Myna.Client
apiKey: apiKey
apiRoot: testApiRoot
settings: "myna.web.autoSync": false
experiments: [ expt ]
recorder = new Myna.Recorder client
switch errorCase
# when "success"
# # Do nothing
# when "client"
# # Do nothing
when "server"
spyOn(Myna.jsonp, "request").andCallFake (options) ->
options.error({ typename: "problem", status: 500 })
return
expt.off()
expt.unstick()
recorder.off()
recorder.listenTo(expt)
recorder.clearQueuedEvents()
recorder.semaphore = 0
recorder.waiting = []
fn(expt, client, recorder)
runs ->
@removeAllSpies()
return
describe "Myna.Recorder.sync (#{errorStatus})", ->
it "should record a single event", initialized (expt, client, recorder) ->
variant = null
success = false
error = false
withSuggestion expt, (v) ->
variant = v
waitsFor -> variant
runs ->
expect(recorderState(recorder)).toEqual([ 1, 0, 0 ])
recorder.sync(
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 1, 0 ]
when "client" then "fail"
when "server" then "fail"
)
success = true
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 0, 1, 0 ]
when "server" then [ 1, 1, 0 ]
)
error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 0, 0 ]
when "client" then [ 0, 0, 0 ]
when "server" then [ 1, 0, 0 ]
)
it "should record multiple events (#{errorStatus})", initialized (expt, client, recorder) ->
variant1 = null
variant2 = null
success = false
error = false
withSuggestion expt, (v1) ->
withReward expt, 1.0, ->
withSuggestion expt, (v2) ->
withReward expt, 1.0, ->
variant1 = v1
variant2 = v2
waitsFor -> variant1 && variant2
runs ->
expect(recorderState(recorder)).toEqual([ 4, 0, 0 ])
recorder.sync(
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 1, 0 ]
when "client" then "fail"
when "server" then "fail"
)
success = true
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 0, 1, 0 ]
when "server" then [ 4, 1, 0 ]
)
error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 0, 0 ]
when "client" then [ 0, 0, 0 ]
when "server" then [ 4, 0, 0 ]
)
it "should handle multiple concurrent calls to record (#{errorStatus})", initialized (expt, client, recorder) ->
# Myna.log statements show the likely order of execution.
variant1 = null
variant2 = null
success1 = false
success2 = false
error1 = false
error2 = false
withView expt, "variant1", (v1) ->
withReward expt, 1.0, ->
variant1 = v1
waitsFor -> variant1
runs ->
Myna.log("BLOCK 1")
expect(recorderState(recorder)).toEqual([ 2, 0, 0 ])
recorder.sync(
->
Myna.log("BLOCK 4a")
expect(errorCase).toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 2, 1, 1 ]
when "client" then "fail"
when "server" then "fail"
)
success1 = true
->
Myna.log("BLOCK 4b")
expect(errorCase).not.toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 2, 1, 1 ]
when "server" then [ 2, 1, 0 ]
)
error1 = true
)
runs ->
Myna.log("BLOCK 2")
withView expt, "variant2", (v2) ->
withReward expt, 1.0, ->
variant2 = v2
runs ->
Myna.log("BLOCK 3")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 2, 1, 0 ]
when "client" then [ 2, 1, 0 ]
when "server" then [ 4, 0, 0 ]
)
recorder.sync(
->
Myna.log("BLOCK 5a")
expect(errorCase).toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 1, 0 ]
when "client" then "fail"
when "server" then "fail"
)
success2 = true
->
Myna.log("BLOCK 5b")
expect(errorCase).not.toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 0, 1, 0 ]
when "server" then [ 4, 1, 0 ]
)
error2 = true
)
waitsFor -> (success1 || error1) && (success2 || error2)
# 6
runs ->
Myna.log("BLOCK 6")
expect(success1).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(success2).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error1).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(error2).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 0, 0 ]
when "client" then [ 0, 0, 0 ]
when "server" then [ 4, 0, 0 ]
)
it "should fire beforeSync and sync events (#{errorStatus})", initialized (expt, client, recorder) ->
variant = null
success = false
error = false
calls = []
recorder.on 'beforeSync', jasmine.createSpy('beforeSync').andCallFake (unrecorded) ->
calls.push { event: 'beforeSync', unrecorded }
recorder.on 'sync', jasmine.createSpy('sync').andCallFake (recorded, discarded, requeued) ->
calls.push { event: 'sync', recorded, discarded, requeued }
withSuggestion expt, (v) ->
variant = v
waitsFor -> variant
runs ->
recorder.sync(
-> success = true
-> error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(calls.length).toEqual(2)
expect(calls[0].event).toEqual('beforeSync')
expect(calls[0].unrecorded.length).toEqual(1)
expect(calls[0].unrecorded[0].timestamp).toBeDefined()
delete calls[0].unrecorded[0].timestamp
expect(calls[0].unrecorded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
switch errorCase
when "success"
expect(calls[1].event).toEqual('sync')
expect(calls[1].recorded.length).toEqual(1)
expect(calls[1].discarded.length).toEqual(0)
expect(calls[1].requeued.length).toEqual(0)
# Timestamp was already deleted above:
expect(calls[1].recorded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
when "client"
expect(calls[1].event).toEqual('sync')
expect(calls[1].recorded.length).toEqual(0)
expect(calls[1].discarded.length).toEqual(1)
expect(calls[1].requeued.length).toEqual(0)
# Timestamp was already deleted above:
expect(calls[1].discarded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
else
expect(calls[1].event).toEqual('sync')
expect(calls[1].recorded.length).toEqual(0)
expect(calls[1].discarded.length).toEqual(0)
expect(calls[1].requeued.length).toEqual(1)
# Timestamp was already deleted above:
expect(calls[1].requeued[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
return
it "should allow beforeSync to cancel the sync (#{errorStatus})", initialized (expt, client, recorder) ->
variant = null
success = false
error = false
calls = []
recorder.on 'beforeSync', jasmine.createSpy('beforeSync').andCallFake (unrecorded) ->
calls.push { event: 'beforeSync', unrecorded }
false
recorder.on 'sync', jasmine.createSpy('sync').andCallFake (recorded, discarded, requeued) ->
calls.push { event: 'sync', recorded, discarded, requeued }
withSuggestion expt, (v) ->
variant = v
waitsFor -> variant
runs ->
recorder.sync(
-> success = true
-> error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(false)
expect(error).toEqual(true)
expect(calls.length).toEqual(1)
expect(calls[0].event).toEqual('beforeSync')
expect(calls[0].unrecorded.length).toEqual(1)
expect(calls[0].unrecorded[0].timestamp).toBeDefined()
delete calls[0].unrecorded[0].timestamp
expect(calls[0].unrecorded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
expect(recorderState(recorder)).toEqual([ 1, 0, 0 ])
return
| true | goodApiKey = testApiKey
badApiKey = "PI:KEY:<KEY>END_PI"
recorderState = (recorder) -> [
recorder.queuedEvents().length, # the number of events waiting to be sent by the next call to record()
recorder.semaphore, # the number of record() methods that are currently running
recorder.waiting.length # the number of callbacks registered for future calls to record()
]
for errorCase in [ "success", "client", "server" ]
do (errorCase) ->
apiKey = switch errorCase
when "success" then goodApiKey
when "client" then badApiKey
when "server" then goodApiKey
errorStatus = switch errorCase
when "success" then "success"
when "client" then "client error"
when "server" then "server error"
initialized = (fn) ->
return ->
expt = new Myna.Experiment
uuid: "45923780-80ed-47c6-aa46-15e2ae7a0e8c"
id: "id"
settings: "myna.web.sticky": false
variants: [
{ id: "variant1", weight: 0.5 }
{ id: "variant2", weight: 0.5 }
]
client = new Myna.Client
apiKey: apiKey
apiRoot: testApiRoot
settings: "myna.web.autoSync": false
experiments: [ expt ]
recorder = new Myna.Recorder client
switch errorCase
# when "success"
# # Do nothing
# when "client"
# # Do nothing
when "server"
spyOn(Myna.jsonp, "request").andCallFake (options) ->
options.error({ typename: "problem", status: 500 })
return
expt.off()
expt.unstick()
recorder.off()
recorder.listenTo(expt)
recorder.clearQueuedEvents()
recorder.semaphore = 0
recorder.waiting = []
fn(expt, client, recorder)
runs ->
@removeAllSpies()
return
describe "Myna.Recorder.sync (#{errorStatus})", ->
it "should record a single event", initialized (expt, client, recorder) ->
variant = null
success = false
error = false
withSuggestion expt, (v) ->
variant = v
waitsFor -> variant
runs ->
expect(recorderState(recorder)).toEqual([ 1, 0, 0 ])
recorder.sync(
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 1, 0 ]
when "client" then "fail"
when "server" then "fail"
)
success = true
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 0, 1, 0 ]
when "server" then [ 1, 1, 0 ]
)
error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 0, 0 ]
when "client" then [ 0, 0, 0 ]
when "server" then [ 1, 0, 0 ]
)
it "should record multiple events (#{errorStatus})", initialized (expt, client, recorder) ->
variant1 = null
variant2 = null
success = false
error = false
withSuggestion expt, (v1) ->
withReward expt, 1.0, ->
withSuggestion expt, (v2) ->
withReward expt, 1.0, ->
variant1 = v1
variant2 = v2
waitsFor -> variant1 && variant2
runs ->
expect(recorderState(recorder)).toEqual([ 4, 0, 0 ])
recorder.sync(
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 1, 0 ]
when "client" then "fail"
when "server" then "fail"
)
success = true
->
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 0, 1, 0 ]
when "server" then [ 4, 1, 0 ]
)
error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 0, 0 ]
when "client" then [ 0, 0, 0 ]
when "server" then [ 4, 0, 0 ]
)
it "should handle multiple concurrent calls to record (#{errorStatus})", initialized (expt, client, recorder) ->
# Myna.log statements show the likely order of execution.
variant1 = null
variant2 = null
success1 = false
success2 = false
error1 = false
error2 = false
withView expt, "variant1", (v1) ->
withReward expt, 1.0, ->
variant1 = v1
waitsFor -> variant1
runs ->
Myna.log("BLOCK 1")
expect(recorderState(recorder)).toEqual([ 2, 0, 0 ])
recorder.sync(
->
Myna.log("BLOCK 4a")
expect(errorCase).toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 2, 1, 1 ]
when "client" then "fail"
when "server" then "fail"
)
success1 = true
->
Myna.log("BLOCK 4b")
expect(errorCase).not.toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 2, 1, 1 ]
when "server" then [ 2, 1, 0 ]
)
error1 = true
)
runs ->
Myna.log("BLOCK 2")
withView expt, "variant2", (v2) ->
withReward expt, 1.0, ->
variant2 = v2
runs ->
Myna.log("BLOCK 3")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 2, 1, 0 ]
when "client" then [ 2, 1, 0 ]
when "server" then [ 4, 0, 0 ]
)
recorder.sync(
->
Myna.log("BLOCK 5a")
expect(errorCase).toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 1, 0 ]
when "client" then "fail"
when "server" then "fail"
)
success2 = true
->
Myna.log("BLOCK 5b")
expect(errorCase).not.toEqual("success")
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then "fail"
when "client" then [ 0, 1, 0 ]
when "server" then [ 4, 1, 0 ]
)
error2 = true
)
waitsFor -> (success1 || error1) && (success2 || error2)
# 6
runs ->
Myna.log("BLOCK 6")
expect(success1).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(success2).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error1).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(error2).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(recorderState(recorder)).toEqual(
switch errorCase
when "success" then [ 0, 0, 0 ]
when "client" then [ 0, 0, 0 ]
when "server" then [ 4, 0, 0 ]
)
it "should fire beforeSync and sync events (#{errorStatus})", initialized (expt, client, recorder) ->
variant = null
success = false
error = false
calls = []
recorder.on 'beforeSync', jasmine.createSpy('beforeSync').andCallFake (unrecorded) ->
calls.push { event: 'beforeSync', unrecorded }
recorder.on 'sync', jasmine.createSpy('sync').andCallFake (recorded, discarded, requeued) ->
calls.push { event: 'sync', recorded, discarded, requeued }
withSuggestion expt, (v) ->
variant = v
waitsFor -> variant
runs ->
recorder.sync(
-> success = true
-> error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(
switch errorCase
when "success" then true
when "client" then false
when "server" then false
)
expect(error).toEqual(
switch errorCase
when "success" then false
when "client" then true
when "server" then true
)
expect(calls.length).toEqual(2)
expect(calls[0].event).toEqual('beforeSync')
expect(calls[0].unrecorded.length).toEqual(1)
expect(calls[0].unrecorded[0].timestamp).toBeDefined()
delete calls[0].unrecorded[0].timestamp
expect(calls[0].unrecorded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
switch errorCase
when "success"
expect(calls[1].event).toEqual('sync')
expect(calls[1].recorded.length).toEqual(1)
expect(calls[1].discarded.length).toEqual(0)
expect(calls[1].requeued.length).toEqual(0)
# Timestamp was already deleted above:
expect(calls[1].recorded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
when "client"
expect(calls[1].event).toEqual('sync')
expect(calls[1].recorded.length).toEqual(0)
expect(calls[1].discarded.length).toEqual(1)
expect(calls[1].requeued.length).toEqual(0)
# Timestamp was already deleted above:
expect(calls[1].discarded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
else
expect(calls[1].event).toEqual('sync')
expect(calls[1].recorded.length).toEqual(0)
expect(calls[1].discarded.length).toEqual(0)
expect(calls[1].requeued.length).toEqual(1)
# Timestamp was already deleted above:
expect(calls[1].requeued[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
return
it "should allow beforeSync to cancel the sync (#{errorStatus})", initialized (expt, client, recorder) ->
variant = null
success = false
error = false
calls = []
recorder.on 'beforeSync', jasmine.createSpy('beforeSync').andCallFake (unrecorded) ->
calls.push { event: 'beforeSync', unrecorded }
false
recorder.on 'sync', jasmine.createSpy('sync').andCallFake (recorded, discarded, requeued) ->
calls.push { event: 'sync', recorded, discarded, requeued }
withSuggestion expt, (v) ->
variant = v
waitsFor -> variant
runs ->
recorder.sync(
-> success = true
-> error = true
)
waitsFor -> success || error
runs ->
expect(success).toEqual(false)
expect(error).toEqual(true)
expect(calls.length).toEqual(1)
expect(calls[0].event).toEqual('beforeSync')
expect(calls[0].unrecorded.length).toEqual(1)
expect(calls[0].unrecorded[0].timestamp).toBeDefined()
delete calls[0].unrecorded[0].timestamp
expect(calls[0].unrecorded[0]).toEqual {
typename: 'view'
experiment: expt.uuid
variant: variant.id
}
expect(recorderState(recorder)).toEqual([ 1, 0, 0 ])
return
|
[
{
"context": "ace.test\", ->\n\t\tif @get(\"marketplace.test\")\n\t\t\t\"ca_5dvMyNcFzpYybDusO7oTdnS4dfErebB1\"\n\t\telse\n\t\t\t\"ca_5dvMP",
"end": 275,
"score": 0.6422910094261169,
"start": 272,
"tag": "KEY",
"value": "5dv"
},
{
"context": "\", ->\n\t\tif @get(\"marketplace.test\")\... | app/views/migrate-success.coffee | dk-dev/balanced-dashboard | 169 | `import Ember from "ember";`
View = Ember.View.extend
layoutName: 'clean-page-layout'
pageTitle: 'Migrate success'
marketplace: Ember.computed.reads("controller.model")
stripeApplicationId: Ember.computed "marketplace.test", ->
if @get("marketplace.test")
"ca_5dvMyNcFzpYybDusO7oTdnS4dfErebB1"
else
"ca_5dvMPc8m1N5R2EkNElwKsJvQ8VdRdcaN"
stripeAccountId: Ember.computed "marketplace.meta", ->
@get("marketplace.meta")["stripe.account_id"]
activateAccountHref: Ember.computed "stripeAccountId", "stripeApplicationId", ->
accountId = @get("stripeAccountId")
applicationId = @get("stripeApplicationId")
"https://dashboard.stripe.com/account/activate?client_id=#{applicationId}&user_id=#{accountId}"
`export default View;`
| 205435 | `import Ember from "ember";`
View = Ember.View.extend
layoutName: 'clean-page-layout'
pageTitle: 'Migrate success'
marketplace: Ember.computed.reads("controller.model")
stripeApplicationId: Ember.computed "marketplace.test", ->
if @get("marketplace.test")
"ca_<KEY>MyNc<KEY>"
else
"<KEY>"
stripeAccountId: Ember.computed "marketplace.meta", ->
@get("marketplace.meta")["stripe.account_id"]
activateAccountHref: Ember.computed "stripeAccountId", "stripeApplicationId", ->
accountId = @get("stripeAccountId")
applicationId = @get("stripeApplicationId")
"https://dashboard.stripe.com/account/activate?client_id=#{applicationId}&user_id=#{accountId}"
`export default View;`
| true | `import Ember from "ember";`
View = Ember.View.extend
layoutName: 'clean-page-layout'
pageTitle: 'Migrate success'
marketplace: Ember.computed.reads("controller.model")
stripeApplicationId: Ember.computed "marketplace.test", ->
if @get("marketplace.test")
"ca_PI:KEY:<KEY>END_PIMyNcPI:KEY:<KEY>END_PI"
else
"PI:KEY:<KEY>END_PI"
stripeAccountId: Ember.computed "marketplace.meta", ->
@get("marketplace.meta")["stripe.account_id"]
activateAccountHref: Ember.computed "stripeAccountId", "stripeApplicationId", ->
accountId = @get("stripeAccountId")
applicationId = @get("stripeApplicationId")
"https://dashboard.stripe.com/account/activate?client_id=#{applicationId}&user_id=#{accountId}"
`export default View;`
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.