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": "ubot cat me - Random cat gif\n#\n# Author:\n# cyrilf\n\n# Helper to generate random key\ngenerateRandomKe", "end": 232, "score": 0.9997194409370422, "start": 226, "tag": "USERNAME", "value": "cyrilf" }, { "context": " = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn...
src/cat-gif.coffee
cyrilf/hubot-catgif
0
# Description: # Return a random cat gif (from thecatapi) # # Dependencies: # None # # Configuration: # None # # Commands: # hubot show me a cat - Random cat gif # hubot cat me - Random cat gif # # Author: # cyrilf # Helper to generate random key generateRandomKey = (length) -> key = '' available = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for i in [0...length] key += available.charAt(Math.floor(Math.random() * available.length)); return key module.exports = (robot) -> robot.respond /.*(cat me|show me a cat).*/i, (msg) -> randomKey = '&' + generateRandomKey(5) msg.send 'http://thecatapi.com/api/images/get?format=src&type=gif' + randomKey
3670
# Description: # Return a random cat gif (from thecatapi) # # Dependencies: # None # # Configuration: # None # # Commands: # hubot show me a cat - Random cat gif # hubot cat me - Random cat gif # # Author: # cyrilf # Helper to generate random key generateRandomKey = (length) -> key = '' available = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst<KEY>xyz<KEY>"; for i in [0...length] key += available.charAt(Math.floor(Math.random() * available.length)); return key module.exports = (robot) -> robot.respond /.*(cat me|show me a cat).*/i, (msg) -> randomKey = <KEY>(5) msg.send 'http://thecatapi.com/api/images/get?format=src&type=gif' + randomKey
true
# Description: # Return a random cat gif (from thecatapi) # # Dependencies: # None # # Configuration: # None # # Commands: # hubot show me a cat - Random cat gif # hubot cat me - Random cat gif # # Author: # cyrilf # Helper to generate random key generateRandomKey = (length) -> key = '' available = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstPI:KEY:<KEY>END_PIxyzPI:KEY:<KEY>END_PI"; for i in [0...length] key += available.charAt(Math.floor(Math.random() * available.length)); return key module.exports = (robot) -> robot.respond /.*(cat me|show me a cat).*/i, (msg) -> randomKey = PI:KEY:<KEY>END_PI(5) msg.send 'http://thecatapi.com/api/images/get?format=src&type=gif' + randomKey
[ { "context": "bug: debug\n\n client.create(firstName: 'Shin', lastName: 'Suzuki').then((responseBody) ->\n\n ", "end": 660, "score": 0.9831539392471313, "start": 656, "tag": "NAME", "value": "Shin" }, { "context": "bug: debug\n\n client.create(firstName: 'Shin...
spec/loopback-user-client.coffee
CureApp/loopback-promised
10
LoopbackPromised = require '../src/loopback-promised' LoopbackClient = require '../src/loopback-client' LoopbackUserClient = require '../src/loopback-user-client' before -> @timeout 5000 require('./init') debug = true baseURL = 'localhost:4157/test-api' lbPromised = LoopbackPromised.createInstance baseURL: baseURL idOfShin = null accessTokenOfShin = null idOfSatake = null describe 'LoopbackUserClient', -> describe 'create', -> it 'cannot create without credential information (email/password)', -> client = lbPromised.createUserClient 'authors', debug: debug client.create(firstName: 'Shin', lastName: 'Suzuki').then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'ValidationError' assert err.statusCode is 422 ) it 'creates a user', -> client = lbPromised.createUserClient 'authors', debug: debug client.create(firstName: 'Shin', lastName: 'Suzuki', email: 'shinout310@gmail.com', password: 'daikon123').then (responseBody) -> assert responseBody.firstName is 'Shin' assert responseBody.lastName is 'Suzuki' assert responseBody.email is 'shinout310@gmail.com' assert responseBody.id? assert not responseBody.password? idOfShin = responseBody.id describe 'login', -> it 'fails with invalid credential (email/password)', -> client = lbPromised.createUserClient 'authors', debug: debug client.login(email: 'shinout310@gmail.com', password: 'daikon121').then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'LOGIN_FAILED' ) it 'returns an access token', -> client = lbPromised.createUserClient 'authors', debug: debug client.login(email: 'shinout310@gmail.com', password: 'daikon123').then (responseBody) -> assert responseBody.id? assert responseBody.ttl? assert responseBody.userId? accessTokenOfShin = responseBody.id it 'returns an access token with user information when "include" is set', -> client = lbPromised.createUserClient 'authors', debug: debug client.login(email: 'shinout310@gmail.com', password: 'daikon123', "user").then (responseBody) -> assert responseBody.id? assert responseBody.userId? assert responseBody.user? assert responseBody.user.id is responseBody.userId assert responseBody.user.email is 'shinout310@gmail.com' assert responseBody.user.firstName is 'Shin' describe 'create', -> it 'creates another user with accessToken', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.create(firstName: 'Kohta', lastName: 'Satake', email: 'satake@example.com', password: 'satake111').then (responseBody) -> assert responseBody.firstName is 'Kohta' assert responseBody.lastName is 'Satake' assert responseBody.email is 'satake@example.com' assert responseBody.id? assert not responseBody.password? idOfSatake = responseBody.id describe 'logout', -> client = lbPromised.createUserClient 'authors', debug: debug validAccessToken = null before -> client.login(email: 'shinout310@gmail.com', password: 'daikon123').then (responseBody) -> validAccessToken = responseBody.id it 'returns error when an invalid access token is given', -> invalidAccessToken = 'abcd' client.logout(invalidAccessToken).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.status is 401 ) it 'returns {} when valid access token is given', -> client.logout(validAccessToken).then (responseBody) -> assert Object.keys(responseBody).length is 0 #TODO confirm the token is deleted describe 'upsert', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug params = firstName: 'Kohta' lastName : 'Satake' email : 'satake@example.com' password : 'satake123' client.upsert(params).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'requires authorization even if the user exists', -> client = lbPromised.createUserClient 'authors', debug: debug params = id : idOfShin firstName: 'Kohta' client.upsert(params).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin params = id : idOfShin nationality: 'Japan' authedClient.upsert(params).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'count', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.count().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when user token is set', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.count().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'find', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.find().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when user token is set', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.find().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'findOne', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.findOne().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when user token is set', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.findOne().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'findById', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.findById(idOfShin).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'returns user when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.findById(idOfShin).then (responseBody) -> assert responseBody.id is idOfShin assert responseBody.firstName is 'Shin' it 'fails when given id is not the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.findById(idOfSatake).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'exists', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.exists(1).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.exists(idOfShin).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'updateAttributes', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.updateAttributes(1, firstName: 'Shinji').then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'updates user when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin data = hobby: 'music' authedClient.updateAttributes(idOfShin, data).then (responseBody) -> assert responseBody.id is idOfShin assert responseBody.firstName is 'Shin' assert responseBody.hobby is 'music' it 'fails when given id is not the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.updateAttributes(idOfSatake, hobby: 'music').then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'updateAll', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.updateAll({firstName: 'Shin'}, {lastName: 'Sasaki'}).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when condition includes the token\'s user', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin data = profession: 'doctor' authedClient.updateAll(id: idOfShin, data).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'destroyById', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.destroyById(1).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails when given id is not the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.destroyById(idOfSatake).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'deletes user when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: false, accessToken: accessTokenOfShin authedClient.destroyById(idOfShin).then (responseBody) -> assert responseBody.count is 1
102828
LoopbackPromised = require '../src/loopback-promised' LoopbackClient = require '../src/loopback-client' LoopbackUserClient = require '../src/loopback-user-client' before -> @timeout 5000 require('./init') debug = true baseURL = 'localhost:4157/test-api' lbPromised = LoopbackPromised.createInstance baseURL: baseURL idOfShin = null accessTokenOfShin = null idOfSatake = null describe 'LoopbackUserClient', -> describe 'create', -> it 'cannot create without credential information (email/password)', -> client = lbPromised.createUserClient 'authors', debug: debug client.create(firstName: '<NAME>', lastName: 'Suzuki').then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'ValidationError' assert err.statusCode is 422 ) it 'creates a user', -> client = lbPromised.createUserClient 'authors', debug: debug client.create(firstName: '<NAME>', lastName: 'Suzuki', email: '<EMAIL>', password: '<PASSWORD>').then (responseBody) -> assert responseBody.firstName is 'Shin' assert responseBody.lastName is 'Suzuki' assert responseBody.email is '<EMAIL>' assert responseBody.id? assert not responseBody.password? idOfShin = responseBody.id describe 'login', -> it 'fails with invalid credential (email/password)', -> client = lbPromised.createUserClient 'authors', debug: debug client.login(email: '<EMAIL>', password: '<PASSWORD>').then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'LOGIN_FAILED' ) it 'returns an access token', -> client = lbPromised.createUserClient 'authors', debug: debug client.login(email: '<EMAIL>', password: '<PASSWORD>').then (responseBody) -> assert responseBody.id? assert responseBody.ttl? assert responseBody.userId? accessTokenOfShin = responseBody.id it 'returns an access token with user information when "include" is set', -> client = lbPromised.createUserClient 'authors', debug: debug client.login(email: '<EMAIL>', password: '<PASSWORD>', "user").then (responseBody) -> assert responseBody.id? assert responseBody.userId? assert responseBody.user? assert responseBody.user.id is responseBody.userId assert responseBody.user.email is '<EMAIL>' assert responseBody.user.firstName is '<NAME>' describe 'create', -> it 'creates another user with accessToken', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.create(firstName: '<NAME>', lastName: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>').then (responseBody) -> assert responseBody.firstName is 'Ko<NAME>a' assert responseBody.lastName is '<NAME>' assert responseBody.email is '<EMAIL>' assert responseBody.id? assert not responseBody.password? idOfSatake = responseBody.id describe 'logout', -> client = lbPromised.createUserClient 'authors', debug: debug validAccessToken = null before -> client.login(email: '<EMAIL>', password: '<PASSWORD>').then (responseBody) -> validAccessToken = responseBody.id it 'returns error when an invalid access token is given', -> invalidAccessToken = 'abcd' client.logout(invalidAccessToken).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.status is 401 ) it 'returns {} when valid access token is given', -> client.logout(validAccessToken).then (responseBody) -> assert Object.keys(responseBody).length is 0 #TODO confirm the token is deleted describe 'upsert', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug params = firstName: '<NAME>' lastName : '<NAME>' email : '<EMAIL>' password : '<PASSWORD>' client.upsert(params).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'requires authorization even if the user exists', -> client = lbPromised.createUserClient 'authors', debug: debug params = id : idOfShin firstName: '<NAME>' client.upsert(params).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin params = id : idOfShin nationality: 'Japan' authedClient.upsert(params).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'count', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.count().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when user token is set', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.count().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'find', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.find().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when user token is set', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.find().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'findOne', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.findOne().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when user token is set', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.findOne().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'findById', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.findById(idOfShin).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'returns user when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.findById(idOfShin).then (responseBody) -> assert responseBody.id is idOfShin assert responseBody.firstName is '<NAME>' it 'fails when given id is not the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.findById(idOfSatake).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'exists', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.exists(1).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.exists(idOfShin).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'updateAttributes', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.updateAttributes(1, firstName: '<NAME>').then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'updates user when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin data = hobby: 'music' authedClient.updateAttributes(idOfShin, data).then (responseBody) -> assert responseBody.id is idOfShin assert responseBody.firstName is '<NAME>' assert responseBody.hobby is 'music' it 'fails when given id is not the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.updateAttributes(idOfSatake, hobby: 'music').then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'updateAll', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.updateAll({firstName: '<NAME>'}, {lastName: '<NAME>'}).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when condition includes the token\'s user', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin data = profession: 'doctor' authedClient.updateAll(id: idOfShin, data).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'destroyById', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.destroyById(1).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails when given id is not the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.destroyById(idOfSatake).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'deletes user when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: false, accessToken: accessTokenOfShin authedClient.destroyById(idOfShin).then (responseBody) -> assert responseBody.count is 1
true
LoopbackPromised = require '../src/loopback-promised' LoopbackClient = require '../src/loopback-client' LoopbackUserClient = require '../src/loopback-user-client' before -> @timeout 5000 require('./init') debug = true baseURL = 'localhost:4157/test-api' lbPromised = LoopbackPromised.createInstance baseURL: baseURL idOfShin = null accessTokenOfShin = null idOfSatake = null describe 'LoopbackUserClient', -> describe 'create', -> it 'cannot create without credential information (email/password)', -> client = lbPromised.createUserClient 'authors', debug: debug client.create(firstName: 'PI:NAME:<NAME>END_PI', lastName: 'Suzuki').then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'ValidationError' assert err.statusCode is 422 ) it 'creates a user', -> client = lbPromised.createUserClient 'authors', debug: debug client.create(firstName: 'PI:NAME:<NAME>END_PI', lastName: 'Suzuki', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI').then (responseBody) -> assert responseBody.firstName is 'Shin' assert responseBody.lastName is 'Suzuki' assert responseBody.email is 'PI:EMAIL:<EMAIL>END_PI' assert responseBody.id? assert not responseBody.password? idOfShin = responseBody.id describe 'login', -> it 'fails with invalid credential (email/password)', -> client = lbPromised.createUserClient 'authors', debug: debug client.login(email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI').then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'LOGIN_FAILED' ) it 'returns an access token', -> client = lbPromised.createUserClient 'authors', debug: debug client.login(email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI').then (responseBody) -> assert responseBody.id? assert responseBody.ttl? assert responseBody.userId? accessTokenOfShin = responseBody.id it 'returns an access token with user information when "include" is set', -> client = lbPromised.createUserClient 'authors', debug: debug client.login(email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI', "user").then (responseBody) -> assert responseBody.id? assert responseBody.userId? assert responseBody.user? assert responseBody.user.id is responseBody.userId assert responseBody.user.email is 'PI:EMAIL:<EMAIL>END_PI' assert responseBody.user.firstName is 'PI:NAME:<NAME>END_PI' describe 'create', -> it 'creates another user with accessToken', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.create(firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI').then (responseBody) -> assert responseBody.firstName is 'KoPI:NAME:<NAME>END_PIa' assert responseBody.lastName is 'PI:NAME:<NAME>END_PI' assert responseBody.email is 'PI:EMAIL:<EMAIL>END_PI' assert responseBody.id? assert not responseBody.password? idOfSatake = responseBody.id describe 'logout', -> client = lbPromised.createUserClient 'authors', debug: debug validAccessToken = null before -> client.login(email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI').then (responseBody) -> validAccessToken = responseBody.id it 'returns error when an invalid access token is given', -> invalidAccessToken = 'abcd' client.logout(invalidAccessToken).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.status is 401 ) it 'returns {} when valid access token is given', -> client.logout(validAccessToken).then (responseBody) -> assert Object.keys(responseBody).length is 0 #TODO confirm the token is deleted describe 'upsert', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug params = firstName: 'PI:NAME:<NAME>END_PI' lastName : 'PI:NAME:<NAME>END_PI' email : 'PI:EMAIL:<EMAIL>END_PI' password : 'PI:PASSWORD:<PASSWORD>END_PI' client.upsert(params).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'requires authorization even if the user exists', -> client = lbPromised.createUserClient 'authors', debug: debug params = id : idOfShin firstName: 'PI:NAME:<NAME>END_PI' client.upsert(params).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin params = id : idOfShin nationality: 'Japan' authedClient.upsert(params).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'count', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.count().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when user token is set', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.count().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'find', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.find().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when user token is set', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.find().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'findOne', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.findOne().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when user token is set', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.findOne().then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'findById', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.findById(idOfShin).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'returns user when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.findById(idOfShin).then (responseBody) -> assert responseBody.id is idOfShin assert responseBody.firstName is 'PI:NAME:<NAME>END_PI' it 'fails when given id is not the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.findById(idOfSatake).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'exists', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.exists(1).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.exists(idOfShin).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'updateAttributes', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.updateAttributes(1, firstName: 'PI:NAME:<NAME>END_PI').then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'updates user when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin data = hobby: 'music' authedClient.updateAttributes(idOfShin, data).then (responseBody) -> assert responseBody.id is idOfShin assert responseBody.firstName is 'PI:NAME:<NAME>END_PI' assert responseBody.hobby is 'music' it 'fails when given id is not the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.updateAttributes(idOfSatake, hobby: 'music').then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'updateAll', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.updateAll({firstName: 'PI:NAME:<NAME>END_PI'}, {lastName: 'PI:NAME:<NAME>END_PI'}).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails even when condition includes the token\'s user', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin data = profession: 'doctor' authedClient.updateAll(id: idOfShin, data).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) describe 'destroyById', -> it 'requires authorization', -> client = lbPromised.createUserClient 'authors', debug: debug client.destroyById(1).then( -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'fails when given id is not the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: debug, accessToken: accessTokenOfShin authedClient.destroyById(idOfSatake).then((responseBody) -> throw new Error('this must not be called') , (err) -> assert err instanceof Error assert err.name is 'Error' assert err.statusCode is 401 assert err.code is 'AUTHORIZATION_REQUIRED' ) it 'deletes user when given id is the token\'s user id', -> authedClient = lbPromised.createUserClient 'authors', debug: false, accessToken: accessTokenOfShin authedClient.destroyById(idOfShin).then (responseBody) -> assert responseBody.count is 1
[ { "context": "an.kill', (params) ->\n #\n # if params.name is 'Batman'\n # return true\n #\n # return false\n #\n ", "end": 1885, "score": 0.9980294108390808, "start": 1879, "tag": "NAME", "value": "Batman" } ]
app/routes.coffee
Gotham-Framework/framework
40
#-------------------------------------------------------------------------- # Routes #-------------------------------------------------------------------------- # # All routes of your application. # # @see http://gothamjs.io/documentation/1.0.0/routing ## module.exports = (route) -> #-------------------------------------------------------------------------- # Basic routing #-------------------------------------------------------------------------- # # route.match '/welcome', -> # # console.log "Hello" # # If the url is like www.domain.com/welcome, gotham will # display "Hello" in the console log. # # @see http://gothamjs.io/documentation/1.0.0/routing#basic-routing ## #-------------------------------------------------------------------------- # Route parameters #-------------------------------------------------------------------------- # # route.match '/users/show/:id', (params) -> # # console.log 'User #' + params.id # # If the url is like www.domain.com/users/show/3, gotham will # display "User #3" in the console log. # # @see http://gothamjs.io/documentation/1.0.0/routing#route-parameters ## #-------------------------------------------------------------------------- # Routing to controllers #-------------------------------------------------------------------------- # # route.match '/kill-batman', 'batman.kill' # # If the url is like www.domain.com/kill-batman, gotham will # execute the controller app/controllers/batman/kill.coffee # # @see http://gothamjs.io/documentation/1-0-0/controllers#route ## #-------------------------------------------------------------------------- # Route constraints #-------------------------------------------------------------------------- # # route.match '/kill/:name', 'batman.kill', (params) -> # # if params.name is 'Batman' # return true # # return false # # If the url is like www.domain.com/kill/joker, gotham will not # execute the controller app/controllers/batman/kill.coffee # # @see http://gothamjs.io/documentation/1.0.0/routing#route-constraints ##
171240
#-------------------------------------------------------------------------- # Routes #-------------------------------------------------------------------------- # # All routes of your application. # # @see http://gothamjs.io/documentation/1.0.0/routing ## module.exports = (route) -> #-------------------------------------------------------------------------- # Basic routing #-------------------------------------------------------------------------- # # route.match '/welcome', -> # # console.log "Hello" # # If the url is like www.domain.com/welcome, gotham will # display "Hello" in the console log. # # @see http://gothamjs.io/documentation/1.0.0/routing#basic-routing ## #-------------------------------------------------------------------------- # Route parameters #-------------------------------------------------------------------------- # # route.match '/users/show/:id', (params) -> # # console.log 'User #' + params.id # # If the url is like www.domain.com/users/show/3, gotham will # display "User #3" in the console log. # # @see http://gothamjs.io/documentation/1.0.0/routing#route-parameters ## #-------------------------------------------------------------------------- # Routing to controllers #-------------------------------------------------------------------------- # # route.match '/kill-batman', 'batman.kill' # # If the url is like www.domain.com/kill-batman, gotham will # execute the controller app/controllers/batman/kill.coffee # # @see http://gothamjs.io/documentation/1-0-0/controllers#route ## #-------------------------------------------------------------------------- # Route constraints #-------------------------------------------------------------------------- # # route.match '/kill/:name', 'batman.kill', (params) -> # # if params.name is '<NAME>' # return true # # return false # # If the url is like www.domain.com/kill/joker, gotham will not # execute the controller app/controllers/batman/kill.coffee # # @see http://gothamjs.io/documentation/1.0.0/routing#route-constraints ##
true
#-------------------------------------------------------------------------- # Routes #-------------------------------------------------------------------------- # # All routes of your application. # # @see http://gothamjs.io/documentation/1.0.0/routing ## module.exports = (route) -> #-------------------------------------------------------------------------- # Basic routing #-------------------------------------------------------------------------- # # route.match '/welcome', -> # # console.log "Hello" # # If the url is like www.domain.com/welcome, gotham will # display "Hello" in the console log. # # @see http://gothamjs.io/documentation/1.0.0/routing#basic-routing ## #-------------------------------------------------------------------------- # Route parameters #-------------------------------------------------------------------------- # # route.match '/users/show/:id', (params) -> # # console.log 'User #' + params.id # # If the url is like www.domain.com/users/show/3, gotham will # display "User #3" in the console log. # # @see http://gothamjs.io/documentation/1.0.0/routing#route-parameters ## #-------------------------------------------------------------------------- # Routing to controllers #-------------------------------------------------------------------------- # # route.match '/kill-batman', 'batman.kill' # # If the url is like www.domain.com/kill-batman, gotham will # execute the controller app/controllers/batman/kill.coffee # # @see http://gothamjs.io/documentation/1-0-0/controllers#route ## #-------------------------------------------------------------------------- # Route constraints #-------------------------------------------------------------------------- # # route.match '/kill/:name', 'batman.kill', (params) -> # # if params.name is 'PI:NAME:<NAME>END_PI' # return true # # return false # # If the url is like www.domain.com/kill/joker, gotham will not # execute the controller app/controllers/batman/kill.coffee # # @see http://gothamjs.io/documentation/1.0.0/routing#route-constraints ##
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998892545700073, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhaki...
src/database/seeders/manufactures/articles.coffee
AbdelhakimRafik/Project
1
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date June 2021 ### faker = require 'faker' ### Create articles demo data ### module.exports = (users, userStartId) -> # demo data container demoData = [] # create articles for each user for i, user of users # get random number between 1 and 9 count = faker.datatype.number min:1, max:9 # generate articles for j in [0..count] demoData.push title: do faker.lorem.sentence content: do faker.lorem.text image: faker.image.image 640, 480, true userId: parseInt(userStartId) + parseInt(i) status: true createdAt: createdDate = faker.date.between user.createdAt, new Date() updatedAt: faker.date.future 1, createdDate # return generated data return demoData
2479
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date June 2021 ### faker = require 'faker' ### Create articles demo data ### module.exports = (users, userStartId) -> # demo data container demoData = [] # create articles for each user for i, user of users # get random number between 1 and 9 count = faker.datatype.number min:1, max:9 # generate articles for j in [0..count] demoData.push title: do faker.lorem.sentence content: do faker.lorem.text image: faker.image.image 640, 480, true userId: parseInt(userStartId) + parseInt(i) status: true createdAt: createdDate = faker.date.between user.createdAt, new Date() updatedAt: faker.date.future 1, createdDate # return generated data return demoData
true
### * @author PI:NAME:<NAME>END_PI * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI * @date June 2021 ### faker = require 'faker' ### Create articles demo data ### module.exports = (users, userStartId) -> # demo data container demoData = [] # create articles for each user for i, user of users # get random number between 1 and 9 count = faker.datatype.number min:1, max:9 # generate articles for j in [0..count] demoData.push title: do faker.lorem.sentence content: do faker.lorem.text image: faker.image.image 640, 480, true userId: parseInt(userStartId) + parseInt(i) status: true createdAt: createdDate = faker.date.between user.createdAt, new Date() updatedAt: faker.date.future 1, createdDate # return generated data return demoData
[ { "context": " items: Observable [\n {name: \"Hello\"}\n {name: \"Test\"}\n ]\n\n ", "end": 323, "score": 0.9956421852111816, "start": 318, "tag": "NAME", "value": "Hello" }, { "context": "[\n {name: \"Hello\"}\n {na...
test/each.coffee
STRd6/hamlet-runtime
1
describe "each", -> describe "iterating", -> template = makeTemplate """ %ul - @items.forEach (item) -> %li= item.name """ describe "with observable arrays", -> it "should have an item for each element", -> model = items: Observable [ {name: "Hello"} {name: "Test"} ] behave template(model), -> assert.equal all("li").length, 2 assert.equal Q("li").textContent, "Hello" it "should add items when items are added to the array", -> model = items: Observable [ {name: "Hello"} {name: "Test"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.push name: "yolo" assert.equal all("li").length, 3 it "should remove items when they are removed", -> model = items: Observable [ {name: "Hello"} {name: "Test"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.pop() model.items.pop() assert.equal all("li").length, 0 model.items.push name: "wat" assert.equal all("li").length, 1 describe "with regular arrays", -> it "should have an item for each element", -> model = items: [ {name: "Hello"} {name: "Test"} ] behave template(model), -> assert.equal all("li").length, 2 assert.equal Q("li").textContent, "Hello" it "will not add items when items are added to the array", -> model = items: [ {name: "Hello"} {name: "Test"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.push name: "yolo" assert.equal all("li").length, 2 it "will not remove items when they are removed", -> model = items: [ {name: "Hello"} {name: "Test"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.pop() model.items.pop() assert.equal all("li").length, 2 describe "inline", -> template = makeTemplate """ %ul = @items.map(@itemView) """ it "should work", -> model = items: [ "Hello" "there" "stranger" ] itemView: makeTemplate """ %li= this """ behave template(model), -> assert.equal all("li").length, 3
125917
describe "each", -> describe "iterating", -> template = makeTemplate """ %ul - @items.forEach (item) -> %li= item.name """ describe "with observable arrays", -> it "should have an item for each element", -> model = items: Observable [ {name: "<NAME>"} {name: "<NAME>"} ] behave template(model), -> assert.equal all("li").length, 2 assert.equal Q("li").textContent, "Hello" it "should add items when items are added to the array", -> model = items: Observable [ {name: "<NAME>"} {name: "<NAME>"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.push name: "yolo" assert.equal all("li").length, 3 it "should remove items when they are removed", -> model = items: Observable [ {name: "<NAME>"} {name: "<NAME>"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.pop() model.items.pop() assert.equal all("li").length, 0 model.items.push name: "wat" assert.equal all("li").length, 1 describe "with regular arrays", -> it "should have an item for each element", -> model = items: [ {name: "<NAME>"} {name: "<NAME>"} ] behave template(model), -> assert.equal all("li").length, 2 assert.equal Q("li").textContent, "Hello" it "will not add items when items are added to the array", -> model = items: [ {name: "<NAME>"} {name: "<NAME>"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.push name: "yolo" assert.equal all("li").length, 2 it "will not remove items when they are removed", -> model = items: [ {name: "<NAME>"} {name: "<NAME>"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.pop() model.items.pop() assert.equal all("li").length, 2 describe "inline", -> template = makeTemplate """ %ul = @items.map(@itemView) """ it "should work", -> model = items: [ "Hello" "there" "stranger" ] itemView: makeTemplate """ %li= this """ behave template(model), -> assert.equal all("li").length, 3
true
describe "each", -> describe "iterating", -> template = makeTemplate """ %ul - @items.forEach (item) -> %li= item.name """ describe "with observable arrays", -> it "should have an item for each element", -> model = items: Observable [ {name: "PI:NAME:<NAME>END_PI"} {name: "PI:NAME:<NAME>END_PI"} ] behave template(model), -> assert.equal all("li").length, 2 assert.equal Q("li").textContent, "Hello" it "should add items when items are added to the array", -> model = items: Observable [ {name: "PI:NAME:<NAME>END_PI"} {name: "PI:NAME:<NAME>END_PI"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.push name: "yolo" assert.equal all("li").length, 3 it "should remove items when they are removed", -> model = items: Observable [ {name: "PI:NAME:<NAME>END_PI"} {name: "PI:NAME:<NAME>END_PI"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.pop() model.items.pop() assert.equal all("li").length, 0 model.items.push name: "wat" assert.equal all("li").length, 1 describe "with regular arrays", -> it "should have an item for each element", -> model = items: [ {name: "PI:NAME:<NAME>END_PI"} {name: "PI:NAME:<NAME>END_PI"} ] behave template(model), -> assert.equal all("li").length, 2 assert.equal Q("li").textContent, "Hello" it "will not add items when items are added to the array", -> model = items: [ {name: "PI:NAME:<NAME>END_PI"} {name: "PI:NAME:<NAME>END_PI"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.push name: "yolo" assert.equal all("li").length, 2 it "will not remove items when they are removed", -> model = items: [ {name: "PI:NAME:<NAME>END_PI"} {name: "PI:NAME:<NAME>END_PI"} ] behave template(model), -> assert.equal all("li").length, 2 model.items.pop() model.items.pop() assert.equal all("li").length, 2 describe "inline", -> template = makeTemplate """ %ul = @items.map(@itemView) """ it "should work", -> model = items: [ "Hello" "there" "stranger" ] itemView: makeTemplate """ %li= this """ behave template(model), -> assert.equal all("li").length, 3
[ { "context": " assert.isTrue highScore > lowScore\n\n # # TODO: (smblott)\n # # Word relevancy should take into acco", "end": 14192, "score": 0.9973873496055603, "start": 14185, "tag": "USERNAME", "value": "smblott" }, { "context": " assert.isTrue RankingUtils.matches([\"ma...
tests/unit_tests/completion_test.coffee
z0rch/vimium
0
require "./test_helper.js" extend(global, require "../../lib/utils.js") extend(global, require "../../background_scripts/completion.js") extend global, require "./test_chrome_stubs.js" global.document = createElement: -> {} context "bookmark completer", setup -> @bookmark3 = { title: "bookmark3", url: "bookmark3.com" } @bookmark2 = { title: "bookmark2", url: "bookmark2.com" } @bookmark1 = { title: "bookmark1", url: "bookmark1.com", children: [@bookmark2] } global.chrome.bookmarks = getTree: (callback) => callback([@bookmark1]) @completer = new BookmarkCompleter() should "flatten a list of bookmarks with inorder traversal", -> result = @completer.traverseBookmarks([@bookmark1, @bookmark3]) assert.arrayEqual [@bookmark1, @bookmark2, @bookmark3], result should "return matching bookmarks when searching", -> @completer.refresh() results = filterCompleter(@completer, ["mark2"]) assert.arrayEqual [@bookmark2.url], results.map (suggestion) -> suggestion.url should "return *no* matching bookmarks when there is no match", -> @completer.refresh() results = filterCompleter(@completer, ["does-not-match"]) assert.arrayEqual [], results.map (suggestion) -> suggestion.url should "construct bookmark paths correctly", -> @completer.refresh() results = filterCompleter(@completer, ["mark2"]) assert.equal "/bookmark1/bookmark2", @bookmark2.pathAndTitle should "return matching bookmark *titles* when searching *without* the folder separator character", -> @completer.refresh() results = filterCompleter(@completer, ["mark2"]) assert.arrayEqual ["bookmark2"], results.map (suggestion) -> suggestion.title should "return matching bookmark *paths* when searching with the folder separator character", -> @completer.refresh() results = filterCompleter(@completer, ["/bookmark1", "mark2"]) assert.arrayEqual ["/bookmark1/bookmark2"], results.map (suggestion) -> suggestion.title context "HistoryCache", context "binary search", setup -> @compare = (a, b) -> a - b should "find elements to the left of the middle", -> assert.equal 0, HistoryCache.binarySearch(3, [3, 5, 8], @compare) should "find elements to the right of the middle", -> assert.equal 2, HistoryCache.binarySearch(8, [3, 5, 8], @compare) context "unfound elements", should "return 0 if it should be the head of the list", -> assert.equal 0, HistoryCache.binarySearch(1, [3, 5, 8], @compare) should "return length - 1 if it should be at the end of the list", -> assert.equal 0, HistoryCache.binarySearch(3, [3, 5, 8], @compare) should "return one passed end of array (so: array.length) if greater than last element in array", -> assert.equal 3, HistoryCache.binarySearch(10, [3, 5, 8], @compare) should "found return the position if it's between two elements", -> assert.equal 1, HistoryCache.binarySearch(4, [3, 5, 8], @compare) assert.equal 2, HistoryCache.binarySearch(7, [3, 5, 8], @compare) context "fetchHistory", setup -> @history1 = { url: "b.com", lastVisitTime: 5 } @history2 = { url: "a.com", lastVisitTime: 10 } history = [@history1, @history2] @onVisitedListener = null @onVisitRemovedListener = null global.chrome.history = search: (options, callback) -> callback(history) onVisited: { addListener: (@onVisitedListener) => } onVisitRemoved: { addListener: (@onVisitRemovedListener) => } HistoryCache.reset() should "store visits sorted by url ascending", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results should "add new visits to the history", -> HistoryCache.use () -> newSite = { url: "ab.com" } @onVisitedListener(newSite) HistoryCache.use (@results) => assert.arrayEqual [@history2, newSite, @history1], @results should "replace new visits in the history", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results newSite = { url: "a.com", lastVisitTime: 15 } @onVisitedListener(newSite) HistoryCache.use (@results) => assert.arrayEqual [newSite, @history1], @results should "(not) remove page from the history, when page is not in history (it should be a no-op)", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results toRemove = { urls: [ "x.com" ], allHistory: false } @onVisitRemovedListener(toRemove) HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results should "remove pages from the history", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results toRemove = { urls: [ "a.com" ], allHistory: false } @onVisitRemovedListener(toRemove) HistoryCache.use (@results) => assert.arrayEqual [@history1], @results should "remove all pages from the history", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results toRemove = { allHistory: true } @onVisitRemovedListener(toRemove) HistoryCache.use (@results) => assert.arrayEqual [], @results context "history completer", setup -> @history1 = { title: "history1", url: "history1.com", lastVisitTime: hours(1) } @history2 = { title: "history2", url: "history2.com", lastVisitTime: hours(5) } global.chrome.history = search: (options, callback) => callback([@history1, @history2]) onVisited: { addListener: -> } onVisitRemoved: { addListener: -> } @completer = new HistoryCompleter() should "return matching history entries when searching", -> assert.arrayEqual [@history1.url], filterCompleter(@completer, ["story1"]).map (entry) -> entry.url should "rank recent results higher than nonrecent results", -> stub(Date, "now", returns(hours(24))) results = filterCompleter(@completer, ["hist"]) results.forEach (result) -> result.computeRelevancy() results.sort (a, b) -> b.relevancy - a.relevancy assert.arrayEqual [@history2.url, @history1.url], results.map (result) -> result.url context "domain completer", setup -> @history1 = { title: "history1", url: "http://history1.com", lastVisitTime: hours(1) } @history2 = { title: "history2", url: "http://history2.com", lastVisitTime: hours(1) } stub(HistoryCache, "use", (onComplete) => onComplete([@history1, @history2])) global.chrome.history = onVisited: { addListener: -> } onVisitRemoved: { addListener: -> } stub(Date, "now", returns(hours(24))) @completer = new DomainCompleter() should "return only a single matching domain", -> results = filterCompleter(@completer, ["story"]) assert.arrayEqual ["http://history1.com"], results.map (result) -> result.url should "pick domains which are more recent", -> # These domains are the same except for their last visited time. assert.equal "http://history1.com", filterCompleter(@completer, ["story"])[0].url @history2.lastVisitTime = hours(3) assert.equal "http://history2.com", filterCompleter(@completer, ["story"])[0].url should "returns no results when there's more than one query term, because clearly it's not a domain", -> assert.arrayEqual [], filterCompleter(@completer, ["his", "tory"]) context "domain completer (removing entries)", setup -> @history1 = { title: "history1", url: "http://history1.com", lastVisitTime: hours(2) } @history2 = { title: "history2", url: "http://history2.com", lastVisitTime: hours(1) } @history3 = { title: "history2something", url: "http://history2.com/something", lastVisitTime: hours(0) } stub(HistoryCache, "use", (onComplete) => onComplete([@history1, @history2, @history3])) @onVisitedListener = null @onVisitRemovedListener = null global.chrome.history = onVisited: { addListener: (@onVisitedListener) => } onVisitRemoved: { addListener: (@onVisitRemovedListener) => } stub(Date, "now", returns(hours(24))) @completer = new DomainCompleter() # Force installation of listeners. filterCompleter(@completer, ["story"]) should "remove 1 entry for domain with reference count of 1", -> @onVisitRemovedListener { allHistory: false, urls: [@history1.url] } assert.equal "http://history2.com", filterCompleter(@completer, ["story"])[0].url assert.equal 0, filterCompleter(@completer, ["story1"]).length should "remove 2 entries for domain with reference count of 2", -> @onVisitRemovedListener { allHistory: false, urls: [@history2.url] } assert.equal "http://history2.com", filterCompleter(@completer, ["story2"])[0].url @onVisitRemovedListener { allHistory: false, urls: [@history3.url] } assert.equal 0, filterCompleter(@completer, ["story2"]).length assert.equal "http://history1.com", filterCompleter(@completer, ["story"])[0].url should "remove 3 (all) matching domain entries", -> @onVisitRemovedListener { allHistory: false, urls: [@history2.url] } @onVisitRemovedListener { allHistory: false, urls: [@history1.url] } @onVisitRemovedListener { allHistory: false, urls: [@history3.url] } assert.equal 0, filterCompleter(@completer, ["story"]).length should "remove 3 (all) matching domain entries, and do it all at once", -> @onVisitRemovedListener { allHistory: false, urls: [ @history2.url, @history1.url, @history3.url ] } assert.equal 0, filterCompleter(@completer, ["story"]).length should "remove *all* domain entries", -> @onVisitRemovedListener { allHistory: true } assert.equal 0, filterCompleter(@completer, ["story"]).length context "tab completer", setup -> @tabs = [ { url: "tab1.com", title: "tab1", id: 1 } { url: "tab2.com", title: "tab2", id: 2 }] chrome.tabs = { query: (args, onComplete) => onComplete(@tabs) } @completer = new TabCompleter() should "return matching tabs", -> results = filterCompleter(@completer, ["tab2"]) assert.arrayEqual ["tab2.com"], results.map (tab) -> tab.url assert.arrayEqual [2], results.map (tab) -> tab.tabId context "search engines", setup -> searchEngines = "foo: bar?q=%s\n# comment\nbaz: qux?q=%s baz description" Settings.set 'searchEngines', searchEngines @completer = new SearchEngineCompleter() # note, I couldn't just call @completer.refresh() here as I couldn't set root.Settings without errors # workaround is below, would be good for someone that understands the testing system better than me to improve @completer.searchEngines = Settings.getSearchEngines() should "return search engine suggestion without description", -> results = filterCompleter(@completer, ["foo", "hello"]) assert.arrayEqual ["bar?q=hello"], results.map (result) -> result.url assert.arrayEqual ["foo: hello"], results.map (result) -> result.title assert.arrayEqual ["search"], results.map (result) -> result.type should "return search engine suggestion with description", -> results = filterCompleter(@completer, ["baz", "hello"]) assert.arrayEqual ["qux?q=hello"], results.map (result) -> result.url assert.arrayEqual ["hello"], results.map (result) -> result.title assert.arrayEqual ["baz description"], results.map (result) -> result.type context "suggestions", should "escape html in page titles", -> suggestion = new Suggestion(["queryterm"], "tab", "url", "title <span>", returns(1)) assert.isTrue suggestion.generateHtml().indexOf("title &lt;span&gt;") >= 0 should "highlight query words", -> suggestion = new Suggestion(["ninj", "words"], "tab", "url", "ninjawords", returns(1)) expected = "<span class='vomnibarMatch'>ninj</span>a<span class='vomnibarMatch'>words</span>" assert.isTrue suggestion.generateHtml().indexOf(expected) >= 0 should "highlight query words correctly when whey they overlap", -> suggestion = new Suggestion(["ninj", "jaword"], "tab", "url", "ninjawords", returns(1)) expected = "<span class='vomnibarMatch'>ninjaword</span>s" assert.isTrue suggestion.generateHtml().indexOf(expected) >= 0 should "shorten urls", -> suggestion = new Suggestion(["queryterm"], "tab", "http://ninjawords.com", "ninjawords", returns(1)) assert.equal -1, suggestion.generateHtml().indexOf("http://ninjawords.com") context "RankingUtils.wordRelevancy", should "score higher in shorter URLs", -> highScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/short", "a-title") lowScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/longer", "a-title") assert.isTrue highScore > lowScore should "score higher in shorter titles", -> highScore = RankingUtils.wordRelevancy(["coffee"], "a-url", "Coffeescript") lowScore = RankingUtils.wordRelevancy(["coffee"], "a-url", "Coffeescript rocks") assert.isTrue highScore > lowScore should "score higher for matching the start of a word (in a URL)", -> lowScore = RankingUtils.wordRelevancy(["stack"], "http://Xstackoverflow.com/same", "a-title") highScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflowX.com/same", "a-title") assert.isTrue highScore > lowScore should "score higher for matching the start of a word (in a title)", -> lowScore = RankingUtils.wordRelevancy(["te"], "a-url", "Dist racted") highScore = RankingUtils.wordRelevancy(["te"], "a-url", "Distrac ted") assert.isTrue highScore > lowScore should "score higher for matching a whole word (in a URL)", -> lowScore = RankingUtils.wordRelevancy(["com"], "http://stackoverflow.comX/same", "a-title") highScore = RankingUtils.wordRelevancy(["com"], "http://stackoverflowX.com/same", "a-title") assert.isTrue highScore > lowScore should "score higher for matching a whole word (in a title)", -> lowScore = RankingUtils.wordRelevancy(["com"], "a-url", "abc comX") highScore = RankingUtils.wordRelevancy(["com"], "a-url", "abcX com") assert.isTrue highScore > lowScore # # TODO: (smblott) # # Word relevancy should take into account the number of matches (it doesn't currently). # should "score higher for multiple matches (in a URL)", -> # lowScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/Xxxxxx", "a-title") # highScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/Xstack", "a-title") # assert.isTrue highScore > lowScore # should "score higher for multiple matches (in a title)", -> # lowScore = RankingUtils.wordRelevancy(["bbc"], "http://stackoverflow.com/same", "BBC Radio 4 (XBCr4)") # highScore = RankingUtils.wordRelevancy(["bbc"], "http://stackoverflow.com/same", "BBC Radio 4 (BBCr4)") # assert.isTrue highScore > lowScore context "Suggestion.pushMatchingRanges", should "extract ranges matching term (simple case, two matches)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{one}#{two}#{three}#{two}#{one}", two, ranges) assert.equal 2, Utils.zip([ ranges, [ [3,6], [11,14] ] ]).filter((pair) -> pair[0][0] == pair[1][0] and pair[0][1] == pair[1][1]).length should "extract ranges matching term (two matches, one at start of string)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{two}#{three}#{two}#{one}", two, ranges) assert.equal 2, Utils.zip([ ranges, [ [0,3], [8,11] ] ]).filter((pair) -> pair[0][0] == pair[1][0] and pair[0][1] == pair[1][1]).length should "extract ranges matching term (two matches, one at end of string)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{one}#{two}#{three}#{two}", two, ranges) assert.equal 2, Utils.zip([ ranges, [ [3,6], [11,14] ] ]).filter((pair) -> pair[0][0] == pair[1][0] and pair[0][1] == pair[1][1]).length should "extract ranges matching term (no matches)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{one}#{two}#{three}#{two}#{one}", "does-not-match", ranges) assert.equal 0, ranges.length context "RankingUtils", should "do a case insensitive match", -> assert.isTrue RankingUtils.matches(["ari"], "maRio") should "do a case insensitive match on full term", -> assert.isTrue RankingUtils.matches(["mario"], "MARio") should "do a case insensitive match on several terms", -> assert.isTrue RankingUtils.matches(["ari"], "DOES_NOT_MATCH", "DOES_NOT_MATCH_EITHER", "MARio") should "do a smartcase match (positive)", -> assert.isTrue RankingUtils.matches(["Mar"], "Mario") should "do a smartcase match (negative)", -> assert.isFalse RankingUtils.matches(["Mar"], "mario") should "do a match with regexp meta-characters (positive)", -> assert.isTrue RankingUtils.matches(["ma.io"], "ma.io") should "do a match with regexp meta-characters (negative)", -> assert.isFalse RankingUtils.matches(["ma.io"], "mario") should "do a smartcase match on full term", -> assert.isTrue RankingUtils.matches(["Mario"], "Mario") assert.isFalse RankingUtils.matches(["Mario"], "mario") should "do case insensitive word relevancy (matching)", -> assert.isTrue RankingUtils.wordRelevancy(["ari"], "MARIO", "MARio") > 0.0 should "do case insensitive word relevancy (not matching)", -> assert.isTrue RankingUtils.wordRelevancy(["DOES_NOT_MATCH"], "MARIO", "MARio") == 0.0 should "every query term must match at least one thing (matching)", -> assert.isTrue RankingUtils.matches(["cat", "dog"], "catapult", "hound dog") should "every query term must match at least one thing (not matching)", -> assert.isTrue not RankingUtils.matches(["cat", "dog", "wolf"], "catapult", "hound dog") context "RegexpCache", should "RegexpCache is in fact caching (positive case)", -> assert.isTrue RegexpCache.get("this") is RegexpCache.get("this") should "RegexpCache is in fact caching (negative case)", -> assert.isTrue RegexpCache.get("this") isnt RegexpCache.get("that") should "RegexpCache prefix/suffix wrapping is working (positive case)", -> assert.isTrue RegexpCache.get("this", "(", ")") is RegexpCache.get("this", "(", ")") should "RegexpCache prefix/suffix wrapping is working (negative case)", -> assert.isTrue RegexpCache.get("this", "(", ")") isnt RegexpCache.get("this") should "search for a string", -> assert.isTrue "hound dog".search(RegexpCache.get("dog")) == 6 should "search for a string which isn't there", -> assert.isTrue "hound dog".search(RegexpCache.get("cat")) == -1 should "search for a string with a prefix/suffix (positive case)", -> assert.isTrue "hound dog".search(RegexpCache.get("dog", "\\b", "\\b")) == 6 should "search for a string with a prefix/suffix (negative case)", -> assert.isTrue "hound dog".search(RegexpCache.get("do", "\\b", "\\b")) == -1 fakeTimeDeltaElapsing = -> context "TabRecency", setup -> @tabRecency = new TabRecency() fakeTimeDeltaElapsing = => if @tabRecency.lastVisitedTime? @tabRecency.lastVisitedTime = new Date(@tabRecency.lastVisitedTime - @tabRecency.timeDelta) @tabRecency.register 3 fakeTimeDeltaElapsing() @tabRecency.register 2 fakeTimeDeltaElapsing() @tabRecency.register 9 fakeTimeDeltaElapsing() @tabRecency.register 1 @tabRecency.deregister 9 fakeTimeDeltaElapsing() @tabRecency.register 4 fakeTimeDeltaElapsing() should "have entries for recently active tabs", -> assert.isTrue @tabRecency.cache[1] assert.isTrue @tabRecency.cache[2] assert.isTrue @tabRecency.cache[3] should "not have entries for removed tabs", -> assert.isFalse @tabRecency.cache[9] should "give a high score to the most recent tab", -> assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 1 assert.isTrue @tabRecency.recencyScore(3) < @tabRecency.recencyScore 1 assert.isTrue @tabRecency.recencyScore(2) < @tabRecency.recencyScore 1 should "give a low score to the current tab", -> assert.isTrue @tabRecency.recencyScore(1) > @tabRecency.recencyScore 4 assert.isTrue @tabRecency.recencyScore(2) > @tabRecency.recencyScore 4 assert.isTrue @tabRecency.recencyScore(3) > @tabRecency.recencyScore 4 should "rank tabs by recency", -> assert.isTrue @tabRecency.recencyScore(3) < @tabRecency.recencyScore 2 assert.isTrue @tabRecency.recencyScore(2) < @tabRecency.recencyScore 1 @tabRecency.register 3 fakeTimeDeltaElapsing() @tabRecency.register 4 # Making 3 the most recent tab which isn't the current tab. assert.isTrue @tabRecency.recencyScore(1) < @tabRecency.recencyScore 3 assert.isTrue @tabRecency.recencyScore(2) < @tabRecency.recencyScore 3 assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 3 assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 1 assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 2 # A convenience wrapper around completer.filter() so it can be called synchronously in tests. filterCompleter = (completer, queryTerms) -> results = [] completer.filter(queryTerms, (completionResults) -> results = completionResults) results hours = (n) -> 1000 * 60 * 60 * n
182238
require "./test_helper.js" extend(global, require "../../lib/utils.js") extend(global, require "../../background_scripts/completion.js") extend global, require "./test_chrome_stubs.js" global.document = createElement: -> {} context "bookmark completer", setup -> @bookmark3 = { title: "bookmark3", url: "bookmark3.com" } @bookmark2 = { title: "bookmark2", url: "bookmark2.com" } @bookmark1 = { title: "bookmark1", url: "bookmark1.com", children: [@bookmark2] } global.chrome.bookmarks = getTree: (callback) => callback([@bookmark1]) @completer = new BookmarkCompleter() should "flatten a list of bookmarks with inorder traversal", -> result = @completer.traverseBookmarks([@bookmark1, @bookmark3]) assert.arrayEqual [@bookmark1, @bookmark2, @bookmark3], result should "return matching bookmarks when searching", -> @completer.refresh() results = filterCompleter(@completer, ["mark2"]) assert.arrayEqual [@bookmark2.url], results.map (suggestion) -> suggestion.url should "return *no* matching bookmarks when there is no match", -> @completer.refresh() results = filterCompleter(@completer, ["does-not-match"]) assert.arrayEqual [], results.map (suggestion) -> suggestion.url should "construct bookmark paths correctly", -> @completer.refresh() results = filterCompleter(@completer, ["mark2"]) assert.equal "/bookmark1/bookmark2", @bookmark2.pathAndTitle should "return matching bookmark *titles* when searching *without* the folder separator character", -> @completer.refresh() results = filterCompleter(@completer, ["mark2"]) assert.arrayEqual ["bookmark2"], results.map (suggestion) -> suggestion.title should "return matching bookmark *paths* when searching with the folder separator character", -> @completer.refresh() results = filterCompleter(@completer, ["/bookmark1", "mark2"]) assert.arrayEqual ["/bookmark1/bookmark2"], results.map (suggestion) -> suggestion.title context "HistoryCache", context "binary search", setup -> @compare = (a, b) -> a - b should "find elements to the left of the middle", -> assert.equal 0, HistoryCache.binarySearch(3, [3, 5, 8], @compare) should "find elements to the right of the middle", -> assert.equal 2, HistoryCache.binarySearch(8, [3, 5, 8], @compare) context "unfound elements", should "return 0 if it should be the head of the list", -> assert.equal 0, HistoryCache.binarySearch(1, [3, 5, 8], @compare) should "return length - 1 if it should be at the end of the list", -> assert.equal 0, HistoryCache.binarySearch(3, [3, 5, 8], @compare) should "return one passed end of array (so: array.length) if greater than last element in array", -> assert.equal 3, HistoryCache.binarySearch(10, [3, 5, 8], @compare) should "found return the position if it's between two elements", -> assert.equal 1, HistoryCache.binarySearch(4, [3, 5, 8], @compare) assert.equal 2, HistoryCache.binarySearch(7, [3, 5, 8], @compare) context "fetchHistory", setup -> @history1 = { url: "b.com", lastVisitTime: 5 } @history2 = { url: "a.com", lastVisitTime: 10 } history = [@history1, @history2] @onVisitedListener = null @onVisitRemovedListener = null global.chrome.history = search: (options, callback) -> callback(history) onVisited: { addListener: (@onVisitedListener) => } onVisitRemoved: { addListener: (@onVisitRemovedListener) => } HistoryCache.reset() should "store visits sorted by url ascending", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results should "add new visits to the history", -> HistoryCache.use () -> newSite = { url: "ab.com" } @onVisitedListener(newSite) HistoryCache.use (@results) => assert.arrayEqual [@history2, newSite, @history1], @results should "replace new visits in the history", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results newSite = { url: "a.com", lastVisitTime: 15 } @onVisitedListener(newSite) HistoryCache.use (@results) => assert.arrayEqual [newSite, @history1], @results should "(not) remove page from the history, when page is not in history (it should be a no-op)", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results toRemove = { urls: [ "x.com" ], allHistory: false } @onVisitRemovedListener(toRemove) HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results should "remove pages from the history", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results toRemove = { urls: [ "a.com" ], allHistory: false } @onVisitRemovedListener(toRemove) HistoryCache.use (@results) => assert.arrayEqual [@history1], @results should "remove all pages from the history", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results toRemove = { allHistory: true } @onVisitRemovedListener(toRemove) HistoryCache.use (@results) => assert.arrayEqual [], @results context "history completer", setup -> @history1 = { title: "history1", url: "history1.com", lastVisitTime: hours(1) } @history2 = { title: "history2", url: "history2.com", lastVisitTime: hours(5) } global.chrome.history = search: (options, callback) => callback([@history1, @history2]) onVisited: { addListener: -> } onVisitRemoved: { addListener: -> } @completer = new HistoryCompleter() should "return matching history entries when searching", -> assert.arrayEqual [@history1.url], filterCompleter(@completer, ["story1"]).map (entry) -> entry.url should "rank recent results higher than nonrecent results", -> stub(Date, "now", returns(hours(24))) results = filterCompleter(@completer, ["hist"]) results.forEach (result) -> result.computeRelevancy() results.sort (a, b) -> b.relevancy - a.relevancy assert.arrayEqual [@history2.url, @history1.url], results.map (result) -> result.url context "domain completer", setup -> @history1 = { title: "history1", url: "http://history1.com", lastVisitTime: hours(1) } @history2 = { title: "history2", url: "http://history2.com", lastVisitTime: hours(1) } stub(HistoryCache, "use", (onComplete) => onComplete([@history1, @history2])) global.chrome.history = onVisited: { addListener: -> } onVisitRemoved: { addListener: -> } stub(Date, "now", returns(hours(24))) @completer = new DomainCompleter() should "return only a single matching domain", -> results = filterCompleter(@completer, ["story"]) assert.arrayEqual ["http://history1.com"], results.map (result) -> result.url should "pick domains which are more recent", -> # These domains are the same except for their last visited time. assert.equal "http://history1.com", filterCompleter(@completer, ["story"])[0].url @history2.lastVisitTime = hours(3) assert.equal "http://history2.com", filterCompleter(@completer, ["story"])[0].url should "returns no results when there's more than one query term, because clearly it's not a domain", -> assert.arrayEqual [], filterCompleter(@completer, ["his", "tory"]) context "domain completer (removing entries)", setup -> @history1 = { title: "history1", url: "http://history1.com", lastVisitTime: hours(2) } @history2 = { title: "history2", url: "http://history2.com", lastVisitTime: hours(1) } @history3 = { title: "history2something", url: "http://history2.com/something", lastVisitTime: hours(0) } stub(HistoryCache, "use", (onComplete) => onComplete([@history1, @history2, @history3])) @onVisitedListener = null @onVisitRemovedListener = null global.chrome.history = onVisited: { addListener: (@onVisitedListener) => } onVisitRemoved: { addListener: (@onVisitRemovedListener) => } stub(Date, "now", returns(hours(24))) @completer = new DomainCompleter() # Force installation of listeners. filterCompleter(@completer, ["story"]) should "remove 1 entry for domain with reference count of 1", -> @onVisitRemovedListener { allHistory: false, urls: [@history1.url] } assert.equal "http://history2.com", filterCompleter(@completer, ["story"])[0].url assert.equal 0, filterCompleter(@completer, ["story1"]).length should "remove 2 entries for domain with reference count of 2", -> @onVisitRemovedListener { allHistory: false, urls: [@history2.url] } assert.equal "http://history2.com", filterCompleter(@completer, ["story2"])[0].url @onVisitRemovedListener { allHistory: false, urls: [@history3.url] } assert.equal 0, filterCompleter(@completer, ["story2"]).length assert.equal "http://history1.com", filterCompleter(@completer, ["story"])[0].url should "remove 3 (all) matching domain entries", -> @onVisitRemovedListener { allHistory: false, urls: [@history2.url] } @onVisitRemovedListener { allHistory: false, urls: [@history1.url] } @onVisitRemovedListener { allHistory: false, urls: [@history3.url] } assert.equal 0, filterCompleter(@completer, ["story"]).length should "remove 3 (all) matching domain entries, and do it all at once", -> @onVisitRemovedListener { allHistory: false, urls: [ @history2.url, @history1.url, @history3.url ] } assert.equal 0, filterCompleter(@completer, ["story"]).length should "remove *all* domain entries", -> @onVisitRemovedListener { allHistory: true } assert.equal 0, filterCompleter(@completer, ["story"]).length context "tab completer", setup -> @tabs = [ { url: "tab1.com", title: "tab1", id: 1 } { url: "tab2.com", title: "tab2", id: 2 }] chrome.tabs = { query: (args, onComplete) => onComplete(@tabs) } @completer = new TabCompleter() should "return matching tabs", -> results = filterCompleter(@completer, ["tab2"]) assert.arrayEqual ["tab2.com"], results.map (tab) -> tab.url assert.arrayEqual [2], results.map (tab) -> tab.tabId context "search engines", setup -> searchEngines = "foo: bar?q=%s\n# comment\nbaz: qux?q=%s baz description" Settings.set 'searchEngines', searchEngines @completer = new SearchEngineCompleter() # note, I couldn't just call @completer.refresh() here as I couldn't set root.Settings without errors # workaround is below, would be good for someone that understands the testing system better than me to improve @completer.searchEngines = Settings.getSearchEngines() should "return search engine suggestion without description", -> results = filterCompleter(@completer, ["foo", "hello"]) assert.arrayEqual ["bar?q=hello"], results.map (result) -> result.url assert.arrayEqual ["foo: hello"], results.map (result) -> result.title assert.arrayEqual ["search"], results.map (result) -> result.type should "return search engine suggestion with description", -> results = filterCompleter(@completer, ["baz", "hello"]) assert.arrayEqual ["qux?q=hello"], results.map (result) -> result.url assert.arrayEqual ["hello"], results.map (result) -> result.title assert.arrayEqual ["baz description"], results.map (result) -> result.type context "suggestions", should "escape html in page titles", -> suggestion = new Suggestion(["queryterm"], "tab", "url", "title <span>", returns(1)) assert.isTrue suggestion.generateHtml().indexOf("title &lt;span&gt;") >= 0 should "highlight query words", -> suggestion = new Suggestion(["ninj", "words"], "tab", "url", "ninjawords", returns(1)) expected = "<span class='vomnibarMatch'>ninj</span>a<span class='vomnibarMatch'>words</span>" assert.isTrue suggestion.generateHtml().indexOf(expected) >= 0 should "highlight query words correctly when whey they overlap", -> suggestion = new Suggestion(["ninj", "jaword"], "tab", "url", "ninjawords", returns(1)) expected = "<span class='vomnibarMatch'>ninjaword</span>s" assert.isTrue suggestion.generateHtml().indexOf(expected) >= 0 should "shorten urls", -> suggestion = new Suggestion(["queryterm"], "tab", "http://ninjawords.com", "ninjawords", returns(1)) assert.equal -1, suggestion.generateHtml().indexOf("http://ninjawords.com") context "RankingUtils.wordRelevancy", should "score higher in shorter URLs", -> highScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/short", "a-title") lowScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/longer", "a-title") assert.isTrue highScore > lowScore should "score higher in shorter titles", -> highScore = RankingUtils.wordRelevancy(["coffee"], "a-url", "Coffeescript") lowScore = RankingUtils.wordRelevancy(["coffee"], "a-url", "Coffeescript rocks") assert.isTrue highScore > lowScore should "score higher for matching the start of a word (in a URL)", -> lowScore = RankingUtils.wordRelevancy(["stack"], "http://Xstackoverflow.com/same", "a-title") highScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflowX.com/same", "a-title") assert.isTrue highScore > lowScore should "score higher for matching the start of a word (in a title)", -> lowScore = RankingUtils.wordRelevancy(["te"], "a-url", "Dist racted") highScore = RankingUtils.wordRelevancy(["te"], "a-url", "Distrac ted") assert.isTrue highScore > lowScore should "score higher for matching a whole word (in a URL)", -> lowScore = RankingUtils.wordRelevancy(["com"], "http://stackoverflow.comX/same", "a-title") highScore = RankingUtils.wordRelevancy(["com"], "http://stackoverflowX.com/same", "a-title") assert.isTrue highScore > lowScore should "score higher for matching a whole word (in a title)", -> lowScore = RankingUtils.wordRelevancy(["com"], "a-url", "abc comX") highScore = RankingUtils.wordRelevancy(["com"], "a-url", "abcX com") assert.isTrue highScore > lowScore # # TODO: (smblott) # # Word relevancy should take into account the number of matches (it doesn't currently). # should "score higher for multiple matches (in a URL)", -> # lowScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/Xxxxxx", "a-title") # highScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/Xstack", "a-title") # assert.isTrue highScore > lowScore # should "score higher for multiple matches (in a title)", -> # lowScore = RankingUtils.wordRelevancy(["bbc"], "http://stackoverflow.com/same", "BBC Radio 4 (XBCr4)") # highScore = RankingUtils.wordRelevancy(["bbc"], "http://stackoverflow.com/same", "BBC Radio 4 (BBCr4)") # assert.isTrue highScore > lowScore context "Suggestion.pushMatchingRanges", should "extract ranges matching term (simple case, two matches)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{one}#{two}#{three}#{two}#{one}", two, ranges) assert.equal 2, Utils.zip([ ranges, [ [3,6], [11,14] ] ]).filter((pair) -> pair[0][0] == pair[1][0] and pair[0][1] == pair[1][1]).length should "extract ranges matching term (two matches, one at start of string)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{two}#{three}#{two}#{one}", two, ranges) assert.equal 2, Utils.zip([ ranges, [ [0,3], [8,11] ] ]).filter((pair) -> pair[0][0] == pair[1][0] and pair[0][1] == pair[1][1]).length should "extract ranges matching term (two matches, one at end of string)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{one}#{two}#{three}#{two}", two, ranges) assert.equal 2, Utils.zip([ ranges, [ [3,6], [11,14] ] ]).filter((pair) -> pair[0][0] == pair[1][0] and pair[0][1] == pair[1][1]).length should "extract ranges matching term (no matches)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{one}#{two}#{three}#{two}#{one}", "does-not-match", ranges) assert.equal 0, ranges.length context "RankingUtils", should "do a case insensitive match", -> assert.isTrue RankingUtils.matches(["ari"], "maRio") should "do a case insensitive match on full term", -> assert.isTrue RankingUtils.matches(["mario"], "<NAME>io") should "do a case insensitive match on several terms", -> assert.isTrue RankingUtils.matches(["ari"], "DOES_NOT_MATCH", "DOES_NOT_MATCH_EITHER", "<NAME>io") should "do a smartcase match (positive)", -> assert.isTrue RankingUtils.matches(["<NAME>"], "<NAME>") should "do a smartcase match (negative)", -> assert.isFalse RankingUtils.matches(["<NAME>"], "<NAME>") should "do a match with regexp meta-characters (positive)", -> assert.isTrue RankingUtils.matches(["ma.io"], "ma.io") should "do a match with regexp meta-characters (negative)", -> assert.isFalse RankingUtils.matches(["ma.io"], "mario") should "do a smartcase match on full term", -> assert.isTrue RankingUtils.matches(["<NAME>"], "<NAME>") assert.isFalse RankingUtils.matches(["<NAME>"], "mario") should "do case insensitive word relevancy (matching)", -> assert.isTrue RankingUtils.wordRelevancy(["ari"], "<NAME>IO", "MARio") > 0.0 should "do case insensitive word relevancy (not matching)", -> assert.isTrue RankingUtils.wordRelevancy(["DOES_NOT_MATCH"], "MARIO", "MARio") == 0.0 should "every query term must match at least one thing (matching)", -> assert.isTrue RankingUtils.matches(["cat", "dog"], "catapult", "hound dog") should "every query term must match at least one thing (not matching)", -> assert.isTrue not RankingUtils.matches(["cat", "dog", "wolf"], "catapult", "hound dog") context "RegexpCache", should "RegexpCache is in fact caching (positive case)", -> assert.isTrue RegexpCache.get("this") is RegexpCache.get("this") should "RegexpCache is in fact caching (negative case)", -> assert.isTrue RegexpCache.get("this") isnt RegexpCache.get("that") should "RegexpCache prefix/suffix wrapping is working (positive case)", -> assert.isTrue RegexpCache.get("this", "(", ")") is RegexpCache.get("this", "(", ")") should "RegexpCache prefix/suffix wrapping is working (negative case)", -> assert.isTrue RegexpCache.get("this", "(", ")") isnt RegexpCache.get("this") should "search for a string", -> assert.isTrue "hound dog".search(RegexpCache.get("dog")) == 6 should "search for a string which isn't there", -> assert.isTrue "hound dog".search(RegexpCache.get("cat")) == -1 should "search for a string with a prefix/suffix (positive case)", -> assert.isTrue "hound dog".search(RegexpCache.get("dog", "\\b", "\\b")) == 6 should "search for a string with a prefix/suffix (negative case)", -> assert.isTrue "hound dog".search(RegexpCache.get("do", "\\b", "\\b")) == -1 fakeTimeDeltaElapsing = -> context "TabRecency", setup -> @tabRecency = new TabRecency() fakeTimeDeltaElapsing = => if @tabRecency.lastVisitedTime? @tabRecency.lastVisitedTime = new Date(@tabRecency.lastVisitedTime - @tabRecency.timeDelta) @tabRecency.register 3 fakeTimeDeltaElapsing() @tabRecency.register 2 fakeTimeDeltaElapsing() @tabRecency.register 9 fakeTimeDeltaElapsing() @tabRecency.register 1 @tabRecency.deregister 9 fakeTimeDeltaElapsing() @tabRecency.register 4 fakeTimeDeltaElapsing() should "have entries for recently active tabs", -> assert.isTrue @tabRecency.cache[1] assert.isTrue @tabRecency.cache[2] assert.isTrue @tabRecency.cache[3] should "not have entries for removed tabs", -> assert.isFalse @tabRecency.cache[9] should "give a high score to the most recent tab", -> assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 1 assert.isTrue @tabRecency.recencyScore(3) < @tabRecency.recencyScore 1 assert.isTrue @tabRecency.recencyScore(2) < @tabRecency.recencyScore 1 should "give a low score to the current tab", -> assert.isTrue @tabRecency.recencyScore(1) > @tabRecency.recencyScore 4 assert.isTrue @tabRecency.recencyScore(2) > @tabRecency.recencyScore 4 assert.isTrue @tabRecency.recencyScore(3) > @tabRecency.recencyScore 4 should "rank tabs by recency", -> assert.isTrue @tabRecency.recencyScore(3) < @tabRecency.recencyScore 2 assert.isTrue @tabRecency.recencyScore(2) < @tabRecency.recencyScore 1 @tabRecency.register 3 fakeTimeDeltaElapsing() @tabRecency.register 4 # Making 3 the most recent tab which isn't the current tab. assert.isTrue @tabRecency.recencyScore(1) < @tabRecency.recencyScore 3 assert.isTrue @tabRecency.recencyScore(2) < @tabRecency.recencyScore 3 assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 3 assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 1 assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 2 # A convenience wrapper around completer.filter() so it can be called synchronously in tests. filterCompleter = (completer, queryTerms) -> results = [] completer.filter(queryTerms, (completionResults) -> results = completionResults) results hours = (n) -> 1000 * 60 * 60 * n
true
require "./test_helper.js" extend(global, require "../../lib/utils.js") extend(global, require "../../background_scripts/completion.js") extend global, require "./test_chrome_stubs.js" global.document = createElement: -> {} context "bookmark completer", setup -> @bookmark3 = { title: "bookmark3", url: "bookmark3.com" } @bookmark2 = { title: "bookmark2", url: "bookmark2.com" } @bookmark1 = { title: "bookmark1", url: "bookmark1.com", children: [@bookmark2] } global.chrome.bookmarks = getTree: (callback) => callback([@bookmark1]) @completer = new BookmarkCompleter() should "flatten a list of bookmarks with inorder traversal", -> result = @completer.traverseBookmarks([@bookmark1, @bookmark3]) assert.arrayEqual [@bookmark1, @bookmark2, @bookmark3], result should "return matching bookmarks when searching", -> @completer.refresh() results = filterCompleter(@completer, ["mark2"]) assert.arrayEqual [@bookmark2.url], results.map (suggestion) -> suggestion.url should "return *no* matching bookmarks when there is no match", -> @completer.refresh() results = filterCompleter(@completer, ["does-not-match"]) assert.arrayEqual [], results.map (suggestion) -> suggestion.url should "construct bookmark paths correctly", -> @completer.refresh() results = filterCompleter(@completer, ["mark2"]) assert.equal "/bookmark1/bookmark2", @bookmark2.pathAndTitle should "return matching bookmark *titles* when searching *without* the folder separator character", -> @completer.refresh() results = filterCompleter(@completer, ["mark2"]) assert.arrayEqual ["bookmark2"], results.map (suggestion) -> suggestion.title should "return matching bookmark *paths* when searching with the folder separator character", -> @completer.refresh() results = filterCompleter(@completer, ["/bookmark1", "mark2"]) assert.arrayEqual ["/bookmark1/bookmark2"], results.map (suggestion) -> suggestion.title context "HistoryCache", context "binary search", setup -> @compare = (a, b) -> a - b should "find elements to the left of the middle", -> assert.equal 0, HistoryCache.binarySearch(3, [3, 5, 8], @compare) should "find elements to the right of the middle", -> assert.equal 2, HistoryCache.binarySearch(8, [3, 5, 8], @compare) context "unfound elements", should "return 0 if it should be the head of the list", -> assert.equal 0, HistoryCache.binarySearch(1, [3, 5, 8], @compare) should "return length - 1 if it should be at the end of the list", -> assert.equal 0, HistoryCache.binarySearch(3, [3, 5, 8], @compare) should "return one passed end of array (so: array.length) if greater than last element in array", -> assert.equal 3, HistoryCache.binarySearch(10, [3, 5, 8], @compare) should "found return the position if it's between two elements", -> assert.equal 1, HistoryCache.binarySearch(4, [3, 5, 8], @compare) assert.equal 2, HistoryCache.binarySearch(7, [3, 5, 8], @compare) context "fetchHistory", setup -> @history1 = { url: "b.com", lastVisitTime: 5 } @history2 = { url: "a.com", lastVisitTime: 10 } history = [@history1, @history2] @onVisitedListener = null @onVisitRemovedListener = null global.chrome.history = search: (options, callback) -> callback(history) onVisited: { addListener: (@onVisitedListener) => } onVisitRemoved: { addListener: (@onVisitRemovedListener) => } HistoryCache.reset() should "store visits sorted by url ascending", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results should "add new visits to the history", -> HistoryCache.use () -> newSite = { url: "ab.com" } @onVisitedListener(newSite) HistoryCache.use (@results) => assert.arrayEqual [@history2, newSite, @history1], @results should "replace new visits in the history", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results newSite = { url: "a.com", lastVisitTime: 15 } @onVisitedListener(newSite) HistoryCache.use (@results) => assert.arrayEqual [newSite, @history1], @results should "(not) remove page from the history, when page is not in history (it should be a no-op)", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results toRemove = { urls: [ "x.com" ], allHistory: false } @onVisitRemovedListener(toRemove) HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results should "remove pages from the history", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results toRemove = { urls: [ "a.com" ], allHistory: false } @onVisitRemovedListener(toRemove) HistoryCache.use (@results) => assert.arrayEqual [@history1], @results should "remove all pages from the history", -> HistoryCache.use (@results) => assert.arrayEqual [@history2, @history1], @results toRemove = { allHistory: true } @onVisitRemovedListener(toRemove) HistoryCache.use (@results) => assert.arrayEqual [], @results context "history completer", setup -> @history1 = { title: "history1", url: "history1.com", lastVisitTime: hours(1) } @history2 = { title: "history2", url: "history2.com", lastVisitTime: hours(5) } global.chrome.history = search: (options, callback) => callback([@history1, @history2]) onVisited: { addListener: -> } onVisitRemoved: { addListener: -> } @completer = new HistoryCompleter() should "return matching history entries when searching", -> assert.arrayEqual [@history1.url], filterCompleter(@completer, ["story1"]).map (entry) -> entry.url should "rank recent results higher than nonrecent results", -> stub(Date, "now", returns(hours(24))) results = filterCompleter(@completer, ["hist"]) results.forEach (result) -> result.computeRelevancy() results.sort (a, b) -> b.relevancy - a.relevancy assert.arrayEqual [@history2.url, @history1.url], results.map (result) -> result.url context "domain completer", setup -> @history1 = { title: "history1", url: "http://history1.com", lastVisitTime: hours(1) } @history2 = { title: "history2", url: "http://history2.com", lastVisitTime: hours(1) } stub(HistoryCache, "use", (onComplete) => onComplete([@history1, @history2])) global.chrome.history = onVisited: { addListener: -> } onVisitRemoved: { addListener: -> } stub(Date, "now", returns(hours(24))) @completer = new DomainCompleter() should "return only a single matching domain", -> results = filterCompleter(@completer, ["story"]) assert.arrayEqual ["http://history1.com"], results.map (result) -> result.url should "pick domains which are more recent", -> # These domains are the same except for their last visited time. assert.equal "http://history1.com", filterCompleter(@completer, ["story"])[0].url @history2.lastVisitTime = hours(3) assert.equal "http://history2.com", filterCompleter(@completer, ["story"])[0].url should "returns no results when there's more than one query term, because clearly it's not a domain", -> assert.arrayEqual [], filterCompleter(@completer, ["his", "tory"]) context "domain completer (removing entries)", setup -> @history1 = { title: "history1", url: "http://history1.com", lastVisitTime: hours(2) } @history2 = { title: "history2", url: "http://history2.com", lastVisitTime: hours(1) } @history3 = { title: "history2something", url: "http://history2.com/something", lastVisitTime: hours(0) } stub(HistoryCache, "use", (onComplete) => onComplete([@history1, @history2, @history3])) @onVisitedListener = null @onVisitRemovedListener = null global.chrome.history = onVisited: { addListener: (@onVisitedListener) => } onVisitRemoved: { addListener: (@onVisitRemovedListener) => } stub(Date, "now", returns(hours(24))) @completer = new DomainCompleter() # Force installation of listeners. filterCompleter(@completer, ["story"]) should "remove 1 entry for domain with reference count of 1", -> @onVisitRemovedListener { allHistory: false, urls: [@history1.url] } assert.equal "http://history2.com", filterCompleter(@completer, ["story"])[0].url assert.equal 0, filterCompleter(@completer, ["story1"]).length should "remove 2 entries for domain with reference count of 2", -> @onVisitRemovedListener { allHistory: false, urls: [@history2.url] } assert.equal "http://history2.com", filterCompleter(@completer, ["story2"])[0].url @onVisitRemovedListener { allHistory: false, urls: [@history3.url] } assert.equal 0, filterCompleter(@completer, ["story2"]).length assert.equal "http://history1.com", filterCompleter(@completer, ["story"])[0].url should "remove 3 (all) matching domain entries", -> @onVisitRemovedListener { allHistory: false, urls: [@history2.url] } @onVisitRemovedListener { allHistory: false, urls: [@history1.url] } @onVisitRemovedListener { allHistory: false, urls: [@history3.url] } assert.equal 0, filterCompleter(@completer, ["story"]).length should "remove 3 (all) matching domain entries, and do it all at once", -> @onVisitRemovedListener { allHistory: false, urls: [ @history2.url, @history1.url, @history3.url ] } assert.equal 0, filterCompleter(@completer, ["story"]).length should "remove *all* domain entries", -> @onVisitRemovedListener { allHistory: true } assert.equal 0, filterCompleter(@completer, ["story"]).length context "tab completer", setup -> @tabs = [ { url: "tab1.com", title: "tab1", id: 1 } { url: "tab2.com", title: "tab2", id: 2 }] chrome.tabs = { query: (args, onComplete) => onComplete(@tabs) } @completer = new TabCompleter() should "return matching tabs", -> results = filterCompleter(@completer, ["tab2"]) assert.arrayEqual ["tab2.com"], results.map (tab) -> tab.url assert.arrayEqual [2], results.map (tab) -> tab.tabId context "search engines", setup -> searchEngines = "foo: bar?q=%s\n# comment\nbaz: qux?q=%s baz description" Settings.set 'searchEngines', searchEngines @completer = new SearchEngineCompleter() # note, I couldn't just call @completer.refresh() here as I couldn't set root.Settings without errors # workaround is below, would be good for someone that understands the testing system better than me to improve @completer.searchEngines = Settings.getSearchEngines() should "return search engine suggestion without description", -> results = filterCompleter(@completer, ["foo", "hello"]) assert.arrayEqual ["bar?q=hello"], results.map (result) -> result.url assert.arrayEqual ["foo: hello"], results.map (result) -> result.title assert.arrayEqual ["search"], results.map (result) -> result.type should "return search engine suggestion with description", -> results = filterCompleter(@completer, ["baz", "hello"]) assert.arrayEqual ["qux?q=hello"], results.map (result) -> result.url assert.arrayEqual ["hello"], results.map (result) -> result.title assert.arrayEqual ["baz description"], results.map (result) -> result.type context "suggestions", should "escape html in page titles", -> suggestion = new Suggestion(["queryterm"], "tab", "url", "title <span>", returns(1)) assert.isTrue suggestion.generateHtml().indexOf("title &lt;span&gt;") >= 0 should "highlight query words", -> suggestion = new Suggestion(["ninj", "words"], "tab", "url", "ninjawords", returns(1)) expected = "<span class='vomnibarMatch'>ninj</span>a<span class='vomnibarMatch'>words</span>" assert.isTrue suggestion.generateHtml().indexOf(expected) >= 0 should "highlight query words correctly when whey they overlap", -> suggestion = new Suggestion(["ninj", "jaword"], "tab", "url", "ninjawords", returns(1)) expected = "<span class='vomnibarMatch'>ninjaword</span>s" assert.isTrue suggestion.generateHtml().indexOf(expected) >= 0 should "shorten urls", -> suggestion = new Suggestion(["queryterm"], "tab", "http://ninjawords.com", "ninjawords", returns(1)) assert.equal -1, suggestion.generateHtml().indexOf("http://ninjawords.com") context "RankingUtils.wordRelevancy", should "score higher in shorter URLs", -> highScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/short", "a-title") lowScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/longer", "a-title") assert.isTrue highScore > lowScore should "score higher in shorter titles", -> highScore = RankingUtils.wordRelevancy(["coffee"], "a-url", "Coffeescript") lowScore = RankingUtils.wordRelevancy(["coffee"], "a-url", "Coffeescript rocks") assert.isTrue highScore > lowScore should "score higher for matching the start of a word (in a URL)", -> lowScore = RankingUtils.wordRelevancy(["stack"], "http://Xstackoverflow.com/same", "a-title") highScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflowX.com/same", "a-title") assert.isTrue highScore > lowScore should "score higher for matching the start of a word (in a title)", -> lowScore = RankingUtils.wordRelevancy(["te"], "a-url", "Dist racted") highScore = RankingUtils.wordRelevancy(["te"], "a-url", "Distrac ted") assert.isTrue highScore > lowScore should "score higher for matching a whole word (in a URL)", -> lowScore = RankingUtils.wordRelevancy(["com"], "http://stackoverflow.comX/same", "a-title") highScore = RankingUtils.wordRelevancy(["com"], "http://stackoverflowX.com/same", "a-title") assert.isTrue highScore > lowScore should "score higher for matching a whole word (in a title)", -> lowScore = RankingUtils.wordRelevancy(["com"], "a-url", "abc comX") highScore = RankingUtils.wordRelevancy(["com"], "a-url", "abcX com") assert.isTrue highScore > lowScore # # TODO: (smblott) # # Word relevancy should take into account the number of matches (it doesn't currently). # should "score higher for multiple matches (in a URL)", -> # lowScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/Xxxxxx", "a-title") # highScore = RankingUtils.wordRelevancy(["stack"], "http://stackoverflow.com/Xstack", "a-title") # assert.isTrue highScore > lowScore # should "score higher for multiple matches (in a title)", -> # lowScore = RankingUtils.wordRelevancy(["bbc"], "http://stackoverflow.com/same", "BBC Radio 4 (XBCr4)") # highScore = RankingUtils.wordRelevancy(["bbc"], "http://stackoverflow.com/same", "BBC Radio 4 (BBCr4)") # assert.isTrue highScore > lowScore context "Suggestion.pushMatchingRanges", should "extract ranges matching term (simple case, two matches)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{one}#{two}#{three}#{two}#{one}", two, ranges) assert.equal 2, Utils.zip([ ranges, [ [3,6], [11,14] ] ]).filter((pair) -> pair[0][0] == pair[1][0] and pair[0][1] == pair[1][1]).length should "extract ranges matching term (two matches, one at start of string)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{two}#{three}#{two}#{one}", two, ranges) assert.equal 2, Utils.zip([ ranges, [ [0,3], [8,11] ] ]).filter((pair) -> pair[0][0] == pair[1][0] and pair[0][1] == pair[1][1]).length should "extract ranges matching term (two matches, one at end of string)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{one}#{two}#{three}#{two}", two, ranges) assert.equal 2, Utils.zip([ ranges, [ [3,6], [11,14] ] ]).filter((pair) -> pair[0][0] == pair[1][0] and pair[0][1] == pair[1][1]).length should "extract ranges matching term (no matches)", -> ranges = [] [ one, two, three ] = [ "one", "two", "three" ] suggestion = new Suggestion([], "", "", "", returns(1)) suggestion.pushMatchingRanges("#{one}#{two}#{three}#{two}#{one}", "does-not-match", ranges) assert.equal 0, ranges.length context "RankingUtils", should "do a case insensitive match", -> assert.isTrue RankingUtils.matches(["ari"], "maRio") should "do a case insensitive match on full term", -> assert.isTrue RankingUtils.matches(["mario"], "PI:NAME:<NAME>END_PIio") should "do a case insensitive match on several terms", -> assert.isTrue RankingUtils.matches(["ari"], "DOES_NOT_MATCH", "DOES_NOT_MATCH_EITHER", "PI:NAME:<NAME>END_PIio") should "do a smartcase match (positive)", -> assert.isTrue RankingUtils.matches(["PI:NAME:<NAME>END_PI"], "PI:NAME:<NAME>END_PI") should "do a smartcase match (negative)", -> assert.isFalse RankingUtils.matches(["PI:NAME:<NAME>END_PI"], "PI:NAME:<NAME>END_PI") should "do a match with regexp meta-characters (positive)", -> assert.isTrue RankingUtils.matches(["ma.io"], "ma.io") should "do a match with regexp meta-characters (negative)", -> assert.isFalse RankingUtils.matches(["ma.io"], "mario") should "do a smartcase match on full term", -> assert.isTrue RankingUtils.matches(["PI:NAME:<NAME>END_PI"], "PI:NAME:<NAME>END_PI") assert.isFalse RankingUtils.matches(["PI:NAME:<NAME>END_PI"], "mario") should "do case insensitive word relevancy (matching)", -> assert.isTrue RankingUtils.wordRelevancy(["ari"], "PI:NAME:<NAME>END_PIIO", "MARio") > 0.0 should "do case insensitive word relevancy (not matching)", -> assert.isTrue RankingUtils.wordRelevancy(["DOES_NOT_MATCH"], "MARIO", "MARio") == 0.0 should "every query term must match at least one thing (matching)", -> assert.isTrue RankingUtils.matches(["cat", "dog"], "catapult", "hound dog") should "every query term must match at least one thing (not matching)", -> assert.isTrue not RankingUtils.matches(["cat", "dog", "wolf"], "catapult", "hound dog") context "RegexpCache", should "RegexpCache is in fact caching (positive case)", -> assert.isTrue RegexpCache.get("this") is RegexpCache.get("this") should "RegexpCache is in fact caching (negative case)", -> assert.isTrue RegexpCache.get("this") isnt RegexpCache.get("that") should "RegexpCache prefix/suffix wrapping is working (positive case)", -> assert.isTrue RegexpCache.get("this", "(", ")") is RegexpCache.get("this", "(", ")") should "RegexpCache prefix/suffix wrapping is working (negative case)", -> assert.isTrue RegexpCache.get("this", "(", ")") isnt RegexpCache.get("this") should "search for a string", -> assert.isTrue "hound dog".search(RegexpCache.get("dog")) == 6 should "search for a string which isn't there", -> assert.isTrue "hound dog".search(RegexpCache.get("cat")) == -1 should "search for a string with a prefix/suffix (positive case)", -> assert.isTrue "hound dog".search(RegexpCache.get("dog", "\\b", "\\b")) == 6 should "search for a string with a prefix/suffix (negative case)", -> assert.isTrue "hound dog".search(RegexpCache.get("do", "\\b", "\\b")) == -1 fakeTimeDeltaElapsing = -> context "TabRecency", setup -> @tabRecency = new TabRecency() fakeTimeDeltaElapsing = => if @tabRecency.lastVisitedTime? @tabRecency.lastVisitedTime = new Date(@tabRecency.lastVisitedTime - @tabRecency.timeDelta) @tabRecency.register 3 fakeTimeDeltaElapsing() @tabRecency.register 2 fakeTimeDeltaElapsing() @tabRecency.register 9 fakeTimeDeltaElapsing() @tabRecency.register 1 @tabRecency.deregister 9 fakeTimeDeltaElapsing() @tabRecency.register 4 fakeTimeDeltaElapsing() should "have entries for recently active tabs", -> assert.isTrue @tabRecency.cache[1] assert.isTrue @tabRecency.cache[2] assert.isTrue @tabRecency.cache[3] should "not have entries for removed tabs", -> assert.isFalse @tabRecency.cache[9] should "give a high score to the most recent tab", -> assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 1 assert.isTrue @tabRecency.recencyScore(3) < @tabRecency.recencyScore 1 assert.isTrue @tabRecency.recencyScore(2) < @tabRecency.recencyScore 1 should "give a low score to the current tab", -> assert.isTrue @tabRecency.recencyScore(1) > @tabRecency.recencyScore 4 assert.isTrue @tabRecency.recencyScore(2) > @tabRecency.recencyScore 4 assert.isTrue @tabRecency.recencyScore(3) > @tabRecency.recencyScore 4 should "rank tabs by recency", -> assert.isTrue @tabRecency.recencyScore(3) < @tabRecency.recencyScore 2 assert.isTrue @tabRecency.recencyScore(2) < @tabRecency.recencyScore 1 @tabRecency.register 3 fakeTimeDeltaElapsing() @tabRecency.register 4 # Making 3 the most recent tab which isn't the current tab. assert.isTrue @tabRecency.recencyScore(1) < @tabRecency.recencyScore 3 assert.isTrue @tabRecency.recencyScore(2) < @tabRecency.recencyScore 3 assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 3 assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 1 assert.isTrue @tabRecency.recencyScore(4) < @tabRecency.recencyScore 2 # A convenience wrapper around completer.filter() so it can be called synchronously in tests. filterCompleter = (completer, queryTerms) -> results = [] completer.filter(queryTerms, (completionResults) -> results = completionResults) results hours = (n) -> 1000 * 60 * 60 * n
[ { "context": "nter'\n# class: 'counting-number'\n# name: 'Counter'\n# style:\n# textAlign: 'center'\n# ", "end": 474, "score": 0.9494551420211792, "start": 467, "tag": "NAME", "value": "Counter" }, { "context": " data:\n# count: count\n# countName...
test/browser/main.coffee
jgoizueta/reactive-builder
0
# To test in browser: # grunt coffee # browserify -t coffeeify main.coffee > bundle.js # open index.html # # This requires: # # npm install -g browserify ReactiveBuilder = require '../../lib/reactive-builder' # double_view = (_, count) -> # _.p class: 'doubler', => # _.text String(count*2) # # count = 0 # reactive = ReactiveBuilder.external (_, count) -> # _.div String(count), # id: 'counter' # class: 'counting-number' # name: 'Counter' # style: # textAlign: 'center' # lineHeight: 100 + count + 'px' # border: '1px solid red' # width: 100 + count + 'px' # height: 100 + count + 'px' # data: # count: count # countName: 'xyz' # abc: '123' # _.div class: 'doubler-container', => # double_view _, count double_view = (count) -> @p class: 'doubler', => @text String(count*2) count = 0 reactive = new ReactiveBuilder (count) -> @div String(count), id: 'counter' class: 'counting-number' name: 'Counter' style: textAlign: 'center' lineHeight: 100 + count + 'px' border: '1px solid red' width: 100 + count + 'px' height: 100 + count + 'px' data: count: count countName: 'xyz' abc: '123' @div class: 'doubler-container', => @render double_view, count document.body.appendChild reactive.update count setInterval (-> count++ reactive.update count ), 1000
30734
# To test in browser: # grunt coffee # browserify -t coffeeify main.coffee > bundle.js # open index.html # # This requires: # # npm install -g browserify ReactiveBuilder = require '../../lib/reactive-builder' # double_view = (_, count) -> # _.p class: 'doubler', => # _.text String(count*2) # # count = 0 # reactive = ReactiveBuilder.external (_, count) -> # _.div String(count), # id: 'counter' # class: 'counting-number' # name: '<NAME>' # style: # textAlign: 'center' # lineHeight: 100 + count + 'px' # border: '1px solid red' # width: 100 + count + 'px' # height: 100 + count + 'px' # data: # count: count # countName: '<NAME>' # abc: '123' # _.div class: 'doubler-container', => # double_view _, count double_view = (count) -> @p class: 'doubler', => @text String(count*2) count = 0 reactive = new ReactiveBuilder (count) -> @div String(count), id: 'counter' class: 'counting-number' name: '<NAME>' style: textAlign: 'center' lineHeight: 100 + count + 'px' border: '1px solid red' width: 100 + count + 'px' height: 100 + count + 'px' data: count: count countName: '<NAME>' abc: '123' @div class: 'doubler-container', => @render double_view, count document.body.appendChild reactive.update count setInterval (-> count++ reactive.update count ), 1000
true
# To test in browser: # grunt coffee # browserify -t coffeeify main.coffee > bundle.js # open index.html # # This requires: # # npm install -g browserify ReactiveBuilder = require '../../lib/reactive-builder' # double_view = (_, count) -> # _.p class: 'doubler', => # _.text String(count*2) # # count = 0 # reactive = ReactiveBuilder.external (_, count) -> # _.div String(count), # id: 'counter' # class: 'counting-number' # name: 'PI:NAME:<NAME>END_PI' # style: # textAlign: 'center' # lineHeight: 100 + count + 'px' # border: '1px solid red' # width: 100 + count + 'px' # height: 100 + count + 'px' # data: # count: count # countName: 'PI:NAME:<NAME>END_PI' # abc: '123' # _.div class: 'doubler-container', => # double_view _, count double_view = (count) -> @p class: 'doubler', => @text String(count*2) count = 0 reactive = new ReactiveBuilder (count) -> @div String(count), id: 'counter' class: 'counting-number' name: 'PI:NAME:<NAME>END_PI' style: textAlign: 'center' lineHeight: 100 + count + 'px' border: '1px solid red' width: 100 + count + 'px' height: 100 + count + 'px' data: count: count countName: 'PI:NAME:<NAME>END_PI' abc: '123' @div class: 'doubler-container', => @render double_view, count document.body.appendChild reactive.update count setInterval (-> count++ reactive.update count ), 1000
[ { "context": "roduct) ->\n expect(-> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 27, to: 'backstock'})).to.throw 'Reques", "end": 3412, "score": 0.7683230638504028, "start": 3389, "tag": "KEY", "value": "5a620bf8850c0bb45f323e6" }, { "context": " expect(-> Product.m...
test/test.coffee
goodeggs/angular-validated-resource
1
# TODO: fix attaching this to window here. geomoment = require 'geomoment' require 'angular-resource' describe 'validatedResource', -> beforeEach -> angular.mock.module(require('./product.coffee')) angular.mock.module ($provide) -> $provide.constant '$window', settings: { env: 'test' } document: window.document null # https://groups.google.com/forum/#!msg/angular/gCGF_B4eQkc/XjkvbgE9iMcJ describe 'validating queryParamsSchema', -> describe 'class method', -> it 'fails if param invalid', inject (Product) -> expect(-> Product.query({isActive: true})).to.throw 'Query validation failed for action \'query\': Missing required property: foodhubSlug' it 'fails if there is an extra param (for test env only)', inject (Product) -> expect(-> Product.query({foodhubSlug: 'sfbay', state: 'lost'})).to.throw 'Query validation failed for action \'query\': Unknown property (not in schema) at /state' it 'succeeds if valid', inject (Product, $httpBackend) -> geomoment.stubTime '2015-11-11 09:00:00' $httpBackend.expectGET('http://api.test.com/products?day=2015-11-11&foodhubSlug=sfbay&isActive=true') .respond 200, [{_id: '55a620bf8850c0bb45f323e6', name: 'apple'}] # undefined fields should be stripped first... expect(-> Product.query({foodhubSlug: 'sfbay', isActive: true, randomField: undefined}).$promise.then(->)).not.to.throw() $httpBackend.flush() geomoment.restoreTime() it 'does not include @ url params if not in body', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/generate').respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} expect(-> Product.generate().$promise.then(->)).not.to.throw() $httpBackend.flush() it 'does include @ url params if in body', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/generate?name=apple').respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} expect(-> Product.generate({}, {name: 'apple'}).$promise.then(->)).not.to.throw() $httpBackend.flush() describe 'instance method', -> beforeEach inject (Product) -> @product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) it 'fails if param invalid', inject (Product) -> expect(=> @product.$update({$select: true})).to.throw 'Query validation failed for action \'$update\': Invalid type: boolean (expected string) at /$select' it 'fails if there is an extra param (for test env only)', inject (Product) -> expect(=> @product.$update({$select: 'name', deactivate: true})).to.throw 'Query validation failed for action \'$update\': Unknown property (not in schema) at /deactivate' it 'succeeds if valid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6?$select=name') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} # should still return a promise expect(=> @product.$update({$select: 'name'}).then(->)).not.to.throw() $httpBackend.flush() describe 'validating requestBodySchema', -> describe 'class method', -> it 'fails if body invalid', inject (Product) -> expect(-> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 27, to: 'backstock'})).to.throw 'Request body validation failed for action \'move\': Invalid type: number (expected string) at /from' it 'fails if there is an extra property (for test env only)', inject (Product) -> expect(-> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock', notify: true})).to.throw 'Request body validation failed for action \'move\': Unknown property (not in schema) at /notify' it 'succeeds if valid (for class method)', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} expect(-> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}).$promise.then(->)).not.to.throw() $httpBackend.flush() describe 'instance method', -> it 'fails if param invalid', inject (Product) -> product = new Product({_id: '123', name: 'apple'}) expect(=> product.$update()).to.throw 'Request body validation failed for action \'$update\': Format validation failed (objectid expected) at /_id' it 'fails if there is an extra param (for test env only)', inject (Product) -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple', active: true}) expect(=> product.$update()).to.throw 'Request body validation failed for action \'$update\': Unknown property (not in schema) at /active' it 'succeeds if valid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) expect(=> product.$update().then(->)).not.to.throw() $httpBackend.flush() describe 'validating responseBodySchema', -> describe 'class method', -> it 'fails if body invalid', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, {name: 'apple'} fulfillRequest = -> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}) $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'move\': Missing required property: _id' it 'fails if there is an extra property (for test env only)', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, _id: '55a620bf8850c0bb45f323e6' name: 'cheese' price: 2 location: 'frontstock' active: false fulfillRequest = -> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}) $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'move\': Unknown property (not in schema) at /active' it 'succeeds if valid (for class method)', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, _id: '55a620bf8850c0bb45f323e6' name: 'cheese' fulfillRequest = -> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}).$promise.then(->) $httpBackend.flush() expect(fulfillRequest).not.to.throw() describe 'instance method', -> it 'fails if body invalid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6'} fulfillRequest = -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) product.$update() $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'$update\': Missing required property: name' it 'fails if there is an extra property (for test env only)', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple', active: true} fulfillRequest = -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) product.$update() $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'$update\': Unknown property (not in schema) at /active' it 'succeeds if valid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} fulfillInstanceRequest = -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) product.$update().then(->) $httpBackend.flush() expect(fulfillInstanceRequest).not.to.throw()
176398
# TODO: fix attaching this to window here. geomoment = require 'geomoment' require 'angular-resource' describe 'validatedResource', -> beforeEach -> angular.mock.module(require('./product.coffee')) angular.mock.module ($provide) -> $provide.constant '$window', settings: { env: 'test' } document: window.document null # https://groups.google.com/forum/#!msg/angular/gCGF_B4eQkc/XjkvbgE9iMcJ describe 'validating queryParamsSchema', -> describe 'class method', -> it 'fails if param invalid', inject (Product) -> expect(-> Product.query({isActive: true})).to.throw 'Query validation failed for action \'query\': Missing required property: foodhubSlug' it 'fails if there is an extra param (for test env only)', inject (Product) -> expect(-> Product.query({foodhubSlug: 'sfbay', state: 'lost'})).to.throw 'Query validation failed for action \'query\': Unknown property (not in schema) at /state' it 'succeeds if valid', inject (Product, $httpBackend) -> geomoment.stubTime '2015-11-11 09:00:00' $httpBackend.expectGET('http://api.test.com/products?day=2015-11-11&foodhubSlug=sfbay&isActive=true') .respond 200, [{_id: '55a620bf8850c0bb45f323e6', name: 'apple'}] # undefined fields should be stripped first... expect(-> Product.query({foodhubSlug: 'sfbay', isActive: true, randomField: undefined}).$promise.then(->)).not.to.throw() $httpBackend.flush() geomoment.restoreTime() it 'does not include @ url params if not in body', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/generate').respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} expect(-> Product.generate().$promise.then(->)).not.to.throw() $httpBackend.flush() it 'does include @ url params if in body', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/generate?name=apple').respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} expect(-> Product.generate({}, {name: 'apple'}).$promise.then(->)).not.to.throw() $httpBackend.flush() describe 'instance method', -> beforeEach inject (Product) -> @product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) it 'fails if param invalid', inject (Product) -> expect(=> @product.$update({$select: true})).to.throw 'Query validation failed for action \'$update\': Invalid type: boolean (expected string) at /$select' it 'fails if there is an extra param (for test env only)', inject (Product) -> expect(=> @product.$update({$select: 'name', deactivate: true})).to.throw 'Query validation failed for action \'$update\': Unknown property (not in schema) at /deactivate' it 'succeeds if valid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6?$select=name') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} # should still return a promise expect(=> @product.$update({$select: 'name'}).then(->)).not.to.throw() $httpBackend.flush() describe 'validating requestBodySchema', -> describe 'class method', -> it 'fails if body invalid', inject (Product) -> expect(-> Product.move({_id: '5<KEY>'}, {from: 27, to: 'backstock'})).to.throw 'Request body validation failed for action \'move\': Invalid type: number (expected string) at /from' it 'fails if there is an extra property (for test env only)', inject (Product) -> expect(-> Product.move({_id: '55a620bf8850c0bb45f<KEY>23e6'}, {from: 'frontstock', to: 'backstock', notify: true})).to.throw 'Request body validation failed for action \'move\': Unknown property (not in schema) at /notify' it 'succeeds if valid (for class method)', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} expect(-> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}).$promise.then(->)).not.to.throw() $httpBackend.flush() describe 'instance method', -> it 'fails if param invalid', inject (Product) -> product = new Product({_id: '123', name: 'apple'}) expect(=> product.$update()).to.throw 'Request body validation failed for action \'$update\': Format validation failed (objectid expected) at /_id' it 'fails if there is an extra param (for test env only)', inject (Product) -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple', active: true}) expect(=> product.$update()).to.throw 'Request body validation failed for action \'$update\': Unknown property (not in schema) at /active' it 'succeeds if valid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) expect(=> product.$update().then(->)).not.to.throw() $httpBackend.flush() describe 'validating responseBodySchema', -> describe 'class method', -> it 'fails if body invalid', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, {name: 'apple'} fulfillRequest = -> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}) $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'move\': Missing required property: _id' it 'fails if there is an extra property (for test env only)', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, _id: '55a620bf8850c0bb45f323e6' name: '<NAME>ese' price: 2 location: 'frontstock' active: false fulfillRequest = -> Product.move({_id: '55a620bf8850c0bb45f<KEY>2<KEY>e6'}, {from: 'frontstock', to: 'backstock'}) $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'move\': Unknown property (not in schema) at /active' it 'succeeds if valid (for class method)', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, _id: '55a620bf8850c0bb45f323e6' name: 'cheese' fulfillRequest = -> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}).$promise.then(->) $httpBackend.flush() expect(fulfillRequest).not.to.throw() describe 'instance method', -> it 'fails if body invalid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6'} fulfillRequest = -> product = new Product({_id: '55a620bf8850c0bb4<KEY>f<KEY>e6', name: 'apple'}) product.$update() $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'$update\': Missing required property: name' it 'fails if there is an extra property (for test env only)', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple', active: true} fulfillRequest = -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) product.$update() $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'$update\': Unknown property (not in schema) at /active' it 'succeeds if valid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} fulfillInstanceRequest = -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) product.$update().then(->) $httpBackend.flush() expect(fulfillInstanceRequest).not.to.throw()
true
# TODO: fix attaching this to window here. geomoment = require 'geomoment' require 'angular-resource' describe 'validatedResource', -> beforeEach -> angular.mock.module(require('./product.coffee')) angular.mock.module ($provide) -> $provide.constant '$window', settings: { env: 'test' } document: window.document null # https://groups.google.com/forum/#!msg/angular/gCGF_B4eQkc/XjkvbgE9iMcJ describe 'validating queryParamsSchema', -> describe 'class method', -> it 'fails if param invalid', inject (Product) -> expect(-> Product.query({isActive: true})).to.throw 'Query validation failed for action \'query\': Missing required property: foodhubSlug' it 'fails if there is an extra param (for test env only)', inject (Product) -> expect(-> Product.query({foodhubSlug: 'sfbay', state: 'lost'})).to.throw 'Query validation failed for action \'query\': Unknown property (not in schema) at /state' it 'succeeds if valid', inject (Product, $httpBackend) -> geomoment.stubTime '2015-11-11 09:00:00' $httpBackend.expectGET('http://api.test.com/products?day=2015-11-11&foodhubSlug=sfbay&isActive=true') .respond 200, [{_id: '55a620bf8850c0bb45f323e6', name: 'apple'}] # undefined fields should be stripped first... expect(-> Product.query({foodhubSlug: 'sfbay', isActive: true, randomField: undefined}).$promise.then(->)).not.to.throw() $httpBackend.flush() geomoment.restoreTime() it 'does not include @ url params if not in body', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/generate').respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} expect(-> Product.generate().$promise.then(->)).not.to.throw() $httpBackend.flush() it 'does include @ url params if in body', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/generate?name=apple').respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} expect(-> Product.generate({}, {name: 'apple'}).$promise.then(->)).not.to.throw() $httpBackend.flush() describe 'instance method', -> beforeEach inject (Product) -> @product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) it 'fails if param invalid', inject (Product) -> expect(=> @product.$update({$select: true})).to.throw 'Query validation failed for action \'$update\': Invalid type: boolean (expected string) at /$select' it 'fails if there is an extra param (for test env only)', inject (Product) -> expect(=> @product.$update({$select: 'name', deactivate: true})).to.throw 'Query validation failed for action \'$update\': Unknown property (not in schema) at /deactivate' it 'succeeds if valid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6?$select=name') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} # should still return a promise expect(=> @product.$update({$select: 'name'}).then(->)).not.to.throw() $httpBackend.flush() describe 'validating requestBodySchema', -> describe 'class method', -> it 'fails if body invalid', inject (Product) -> expect(-> Product.move({_id: '5PI:KEY:<KEY>END_PI'}, {from: 27, to: 'backstock'})).to.throw 'Request body validation failed for action \'move\': Invalid type: number (expected string) at /from' it 'fails if there is an extra property (for test env only)', inject (Product) -> expect(-> Product.move({_id: '55a620bf8850c0bb45fPI:KEY:<KEY>END_PI23e6'}, {from: 'frontstock', to: 'backstock', notify: true})).to.throw 'Request body validation failed for action \'move\': Unknown property (not in schema) at /notify' it 'succeeds if valid (for class method)', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} expect(-> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}).$promise.then(->)).not.to.throw() $httpBackend.flush() describe 'instance method', -> it 'fails if param invalid', inject (Product) -> product = new Product({_id: '123', name: 'apple'}) expect(=> product.$update()).to.throw 'Request body validation failed for action \'$update\': Format validation failed (objectid expected) at /_id' it 'fails if there is an extra param (for test env only)', inject (Product) -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple', active: true}) expect(=> product.$update()).to.throw 'Request body validation failed for action \'$update\': Unknown property (not in schema) at /active' it 'succeeds if valid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) expect(=> product.$update().then(->)).not.to.throw() $httpBackend.flush() describe 'validating responseBodySchema', -> describe 'class method', -> it 'fails if body invalid', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, {name: 'apple'} fulfillRequest = -> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}) $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'move\': Missing required property: _id' it 'fails if there is an extra property (for test env only)', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, _id: '55a620bf8850c0bb45f323e6' name: 'PI:NAME:<NAME>END_PIese' price: 2 location: 'frontstock' active: false fulfillRequest = -> Product.move({_id: '55a620bf8850c0bb45fPI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PIe6'}, {from: 'frontstock', to: 'backstock'}) $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'move\': Unknown property (not in schema) at /active' it 'succeeds if valid (for class method)', inject (Product, $httpBackend) -> $httpBackend.expectPOST('http://api.test.com/products/55a620bf8850c0bb45f323e6/move', {from: 'frontstock', to: 'backstock'}) .respond 200, _id: '55a620bf8850c0bb45f323e6' name: 'cheese' fulfillRequest = -> Product.move({_id: '55a620bf8850c0bb45f323e6'}, {from: 'frontstock', to: 'backstock'}).$promise.then(->) $httpBackend.flush() expect(fulfillRequest).not.to.throw() describe 'instance method', -> it 'fails if body invalid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6'} fulfillRequest = -> product = new Product({_id: '55a620bf8850c0bb4PI:KEY:<KEY>END_PIfPI:KEY:<KEY>END_PIe6', name: 'apple'}) product.$update() $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'$update\': Missing required property: name' it 'fails if there is an extra property (for test env only)', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple', active: true} fulfillRequest = -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) product.$update() $httpBackend.flush() expect(fulfillRequest).to.throw 'Response body validation failed for action \'$update\': Unknown property (not in schema) at /active' it 'succeeds if valid', inject (Product, $httpBackend) -> $httpBackend.expectPUT('http://api.test.com/products/55a620bf8850c0bb45f323e6') .respond 200, {_id: '55a620bf8850c0bb45f323e6', name: 'apple'} fulfillInstanceRequest = -> product = new Product({_id: '55a620bf8850c0bb45f323e6', name: 'apple'}) product.$update().then(->) $httpBackend.flush() expect(fulfillInstanceRequest).not.to.throw()
[ { "context": "e-ad:authenticator-service')\n\nDEFAULT_PASSWORD = 'no-need-for-this'\nPUBLIC_KEYS_URL = 'https://login.microsoftonlin", "end": 347, "score": 0.9993972778320312, "start": 331, "tag": "PASSWORD", "value": "no-need-for-this" }, { "context": "IC_KEYS_URL = 'https://login...
src/services/authenticator-service.coffee
octoblu/meshblu-authenticator-azure-ad
0
_ = require 'lodash' { DeviceAuthenticator } = require 'meshblu-authenticator-core' MeshbluHttp = require 'meshblu-http' verifyJWT = require 'verify-azure-ad-jwt' debug = require('debug')('meshblu-authenticator-azure-ad:authenticator-service') DEFAULT_PASSWORD = 'no-need-for-this' PUBLIC_KEYS_URL = 'https://login.microsoftonline.com/common/discovery/keys' class AuthenticatorService constructor: ({ meshbluConfig, @namespace, privateKey, @publicKeysUrl }={}) -> throw new Error 'Missing required parameter: meshbluConfig' unless meshbluConfig? throw new Error 'Missing required parameter: namespace' unless @namespace? throw new Error 'Missing required parameter: privateKey' unless privateKey? @publicKeysUrl ?= PUBLIC_KEYS_URL @meshbluHttp = new MeshbluHttp meshbluConfig @meshbluHttp.setPrivateKey privateKey @deviceModel = new DeviceAuthenticator { authenticatorUuid: meshbluConfig.uuid authenticatorName: 'Meshblu Authenticator Azure AD' meshbluHttp: @meshbluHttp } authenticate: (accessToken, refresh_token, params, callback) => verifyJWT accessToken, (error, profile) => return callback error if error? @_ensureUser { email: profile.unique_name firstName: profile.given_name lastName: profile.family_name }, callback _createSearchId: ({ email }) => debug '_createSearchId', { email } email = _.toLower email return "#{@authenticatorUuid}:#{@namespace}:#{email}" _createUserDevice: ({ email, firstName, lastName }, callback) => debug '_createUserDevice', { email, firstName, lastName } email = _.toLower email searchId = @_createSearchId { email } query = {} query['meshblu.search.terms'] = { $in: [searchId] } @deviceModel.create { query: query data: user: metadata: { firstName, lastName, email } email: email name: "#{firstName} #{lastName}" user_id: email secret: DEFAULT_PASSWORD }, (error, device) => return callback error if error? @_updateSearchTerms { device, searchId }, (error) => return callback error if error? callback null, device _ensureUser: ({ email, firstName, lastName }, callback) => debug '_ensureUser', { email, firstName, lastName } @_validateRequest { email, firstName, lastName }, (error) => return callback error if error? @_maybeCreateDevice { email, firstName, lastName }, (error, device) => return callback error if error? @_generateToken { device }, callback _findUserDevice: ({ email }, callback) => debug '_maybeCreateDevice', { email } searchId = @_createSearchId { email } query = {} query['meshblu.search.terms'] = { $in: [searchId] } @deviceModel.findVerified { query, password: DEFAULT_PASSWORD }, callback _generateToken: ({ device }, callback) => debug '_generateToken', { uuid: device.uuid } @meshbluHttp.generateAndStoreToken device.uuid, callback _maybeCreateDevice: ({ email, firstName, lastName }, callback) => debug '_maybeCreateDevice', { email, firstName, lastName } @_findUserDevice { email }, (error, device) => return callback error if error? return callback null, device if device? @_createUserDevice { email, firstName, lastName }, callback _updateSearchTerms: ({ device, searchId }, callback) => debug '_updateSearchTerms', { searchId } query = $addToSet: 'meshblu.search.terms': searchId @meshbluHttp.updateDangerously device.uuid, query, callback _validateRequest: ({ email, firstName, lastName }, callback) => debug '_validateRequest', { email, firstName, lastName } return callback @_createError 'Last Name required', 422 if _.isEmpty lastName return callback @_createError 'First Name required', 422 if _.isEmpty firstName return callback @_createError 'Email required', 422 if _.isEmpty email callback null module.exports = AuthenticatorService
58276
_ = require 'lodash' { DeviceAuthenticator } = require 'meshblu-authenticator-core' MeshbluHttp = require 'meshblu-http' verifyJWT = require 'verify-azure-ad-jwt' debug = require('debug')('meshblu-authenticator-azure-ad:authenticator-service') DEFAULT_PASSWORD = '<PASSWORD>' PUBLIC_KEYS_URL = 'https://login.microsoftonline.com/<KEY>' class AuthenticatorService constructor: ({ meshbluConfig, @namespace, privateKey, @publicKeysUrl }={}) -> throw new Error 'Missing required parameter: meshbluConfig' unless meshbluConfig? throw new Error 'Missing required parameter: namespace' unless @namespace? throw new Error 'Missing required parameter: privateKey' unless privateKey? @publicKeysUrl ?= PUBLIC_KEYS_URL @meshbluHttp = new MeshbluHttp meshbluConfig @meshbluHttp.setPrivateKey privateKey @deviceModel = new DeviceAuthenticator { authenticatorUuid: meshbluConfig.uuid authenticatorName: 'Meshblu Authenticator Azure AD' meshbluHttp: @meshbluHttp } authenticate: (accessToken, refresh_token, params, callback) => verifyJWT accessToken, (error, profile) => return callback error if error? @_ensureUser { email: profile.unique_name firstName: profile.given_name lastName: profile.family_name }, callback _createSearchId: ({ email }) => debug '_createSearchId', { email } email = _.toLower email return "#{@authenticatorUuid}:#{@namespace}:#{email}" _createUserDevice: ({ email, <NAME>, <NAME> }, callback) => debug '_createUserDevice', { email, <NAME>, <NAME> } email = _.toLower email searchId = @_createSearchId { email } query = {} query['meshblu.search.terms'] = { $in: [searchId] } @deviceModel.create { query: query data: user: metadata: { <NAME>, <NAME>, email } email: email name: "#{firstName} #{lastName}" user_id: email secret: DEFAULT_PASSWORD }, (error, device) => return callback error if error? @_updateSearchTerms { device, searchId }, (error) => return callback error if error? callback null, device _ensureUser: ({ email, <NAME>, <NAME> }, callback) => debug '_ensureUser', { email, <NAME>, <NAME> } @_validateRequest { email, <NAME>, <NAME> }, (error) => return callback error if error? @_maybeCreateDevice { email, <NAME>, <NAME> }, (error, device) => return callback error if error? @_generateToken { device }, callback _findUserDevice: ({ email }, callback) => debug '_maybeCreateDevice', { email } searchId = @_createSearchId { email } query = {} query['meshblu.search.terms'] = { $in: [searchId] } @deviceModel.findVerified { query, password: <PASSWORD> }, callback _generateToken: ({ device }, callback) => debug '_generateToken', { uuid: device.uuid } @meshbluHttp.generateAndStoreToken device.uuid, callback _maybeCreateDevice: ({ email, <NAME>, <NAME> }, callback) => debug '_maybeCreateDevice', { email, <NAME>, <NAME> } @_findUserDevice { email }, (error, device) => return callback error if error? return callback null, device if device? @_createUserDevice { email, <NAME>, <NAME> }, callback _updateSearchTerms: ({ device, searchId }, callback) => debug '_updateSearchTerms', { searchId } query = $addToSet: 'meshblu.search.terms': searchId @meshbluHttp.updateDangerously device.uuid, query, callback _validateRequest: ({ email, <NAME>, <NAME> }, callback) => debug '_validateRequest', { email, <NAME>, <NAME> } return callback @_createError 'Last Name required', 422 if _.isEmpty lastName return callback @_createError 'First Name required', 422 if _.isEmpty firstName return callback @_createError 'Email required', 422 if _.isEmpty email callback null module.exports = AuthenticatorService
true
_ = require 'lodash' { DeviceAuthenticator } = require 'meshblu-authenticator-core' MeshbluHttp = require 'meshblu-http' verifyJWT = require 'verify-azure-ad-jwt' debug = require('debug')('meshblu-authenticator-azure-ad:authenticator-service') DEFAULT_PASSWORD = 'PI:PASSWORD:<PASSWORD>END_PI' PUBLIC_KEYS_URL = 'https://login.microsoftonline.com/PI:KEY:<KEY>END_PI' class AuthenticatorService constructor: ({ meshbluConfig, @namespace, privateKey, @publicKeysUrl }={}) -> throw new Error 'Missing required parameter: meshbluConfig' unless meshbluConfig? throw new Error 'Missing required parameter: namespace' unless @namespace? throw new Error 'Missing required parameter: privateKey' unless privateKey? @publicKeysUrl ?= PUBLIC_KEYS_URL @meshbluHttp = new MeshbluHttp meshbluConfig @meshbluHttp.setPrivateKey privateKey @deviceModel = new DeviceAuthenticator { authenticatorUuid: meshbluConfig.uuid authenticatorName: 'Meshblu Authenticator Azure AD' meshbluHttp: @meshbluHttp } authenticate: (accessToken, refresh_token, params, callback) => verifyJWT accessToken, (error, profile) => return callback error if error? @_ensureUser { email: profile.unique_name firstName: profile.given_name lastName: profile.family_name }, callback _createSearchId: ({ email }) => debug '_createSearchId', { email } email = _.toLower email return "#{@authenticatorUuid}:#{@namespace}:#{email}" _createUserDevice: ({ email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI }, callback) => debug '_createUserDevice', { email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI } email = _.toLower email searchId = @_createSearchId { email } query = {} query['meshblu.search.terms'] = { $in: [searchId] } @deviceModel.create { query: query data: user: metadata: { PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, email } email: email name: "#{firstName} #{lastName}" user_id: email secret: DEFAULT_PASSWORD }, (error, device) => return callback error if error? @_updateSearchTerms { device, searchId }, (error) => return callback error if error? callback null, device _ensureUser: ({ email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI }, callback) => debug '_ensureUser', { email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI } @_validateRequest { email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI }, (error) => return callback error if error? @_maybeCreateDevice { email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI }, (error, device) => return callback error if error? @_generateToken { device }, callback _findUserDevice: ({ email }, callback) => debug '_maybeCreateDevice', { email } searchId = @_createSearchId { email } query = {} query['meshblu.search.terms'] = { $in: [searchId] } @deviceModel.findVerified { query, password: PI:PASSWORD:<PASSWORD>END_PI }, callback _generateToken: ({ device }, callback) => debug '_generateToken', { uuid: device.uuid } @meshbluHttp.generateAndStoreToken device.uuid, callback _maybeCreateDevice: ({ email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI }, callback) => debug '_maybeCreateDevice', { email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI } @_findUserDevice { email }, (error, device) => return callback error if error? return callback null, device if device? @_createUserDevice { email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI }, callback _updateSearchTerms: ({ device, searchId }, callback) => debug '_updateSearchTerms', { searchId } query = $addToSet: 'meshblu.search.terms': searchId @meshbluHttp.updateDangerously device.uuid, query, callback _validateRequest: ({ email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI }, callback) => debug '_validateRequest', { email, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI } return callback @_createError 'Last Name required', 422 if _.isEmpty lastName return callback @_createError 'First Name required', 422 if _.isEmpty firstName return callback @_createError 'Email required', 422 if _.isEmpty email callback null module.exports = AuthenticatorService
[ { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Cof", "end": 23, "score": 0.999889075756073, "start": 13, "tag": "NAME", "value": "Mat Groves" }, { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/te...
src/Coffixi/textures/RenderTexture.coffee
namuol/Coffixi
1
###* @author Mat Groves http://matgroves.com/ @Doormat23 ### define 'Coffixi/textures/RenderTexture', [ 'Coffixi/core/Rectangle' 'Coffixi/core/Point' 'Coffixi/core/Matrix' 'Coffixi/renderers/canvas/CanvasRenderer' 'Coffixi/renderers/webgl/GLESRenderer' './BaseTexture' './Texture' ], ( Rectangle Point Matrix CanvasRenderer GLESRenderer BaseTexture Texture ) -> GLESRenderGroup = GLESRenderer.GLESRenderGroup ###* A RenderTexture is a special texture that allows any pixi displayObject to be rendered to it. __Hint__: All DisplayObjects (exmpl. Sprites) that renders on RenderTexture should be preloaded. Otherwise black rectangles will be drawn instead. RenderTexture takes snapshot of DisplayObject passed to render method. If DisplayObject is passed to render method, position and rotation of it will be ignored. For example: var renderTexture = new RenderTexture(800, 600); var sprite = Sprite.fromImage("spinObj_01.png"); sprite.x = 800/2; sprite.y = 600/2; sprite.anchorX = 0.5; sprite.anchorY = 0.5; renderTexture.render(sprite); Sprite in this case will be rendered to 0,0 position. To render this sprite at center DisplayObjectContainer should be used: var doc = new DisplayObjectContainer(); doc.addChild(sprite); renderTexture.render(doc); // Renders to center of renderTexture @class RenderTexture @extends Texture @constructor @param width {Number} The width of the render texture @param height {Number} The height of the render texture ### class RenderTexture extends Texture constructor: (width, height, @textureFilter=BaseTexture.filterModes.LINEAR, @filterMode=BaseTexture.filterModes.LINEAR) -> @width = width or 100 @height = height or 100 @indetityMatrix = Matrix.mat3.create() @frame = new Rectangle(0, 0, @width, @height) if GLESRenderer.gl @initGLES() else @initCanvas() ###* Initializes the webgl data for this texture @method initGLES @private ### initGLES: -> gl = GLESRenderer.gl @glFramebuffer = gl.createFramebuffer() gl.bindFramebuffer gl.FRAMEBUFFER, @glFramebuffer # LOU TODO: Do we need this? # @glFramebuffer.width = @width # @glFramebuffer.height = @height @baseTexture = new BaseTexture() @baseTexture.width = @width @baseTexture.height = @height @baseTexture._glTexture = gl.createTexture() gl.bindTexture gl.TEXTURE_2D, @baseTexture._glTexture gl.texImage2D gl.TEXTURE_2D, 0, gl.RGBA, @width, @height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null glFilterMode = GLESRenderer.getGLFilterMode @filterMode gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilterMode gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glFilterMode gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE @baseTexture.isRender = true # gl.bindTexture gl.TEXTURE_2D, null # gl.bindFramebuffer gl.FRAMEBUFFER, @glFramebuffer gl.framebufferTexture2D gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, @baseTexture._glTexture, 0 # create a projection matrix.. @projection = new Point(@width / 2, @height / 2) @projectionMatrix = Matrix.mat4.create() @projectionMatrix[5] = 2 / @height # * 0.5; @projectionMatrix[13] = -1 @projectionMatrix[0] = 2 / @width @projectionMatrix[12] = -1 # set the correct render function.. @render = @renderGLES resize: (width, height) -> @width = width @height = height @projection = new Point(@width / 2, @height / 2) if GLESRenderer.gl gl = GLESRenderer.gl gl.bindTexture gl.TEXTURE_2D, @baseTexture._glTexture gl.texImage2D gl.TEXTURE_2D, 0, gl.RGBA, @width, @height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null else @frame.width = @width @frame.height = @height @renderer.resize @width, @height ###* Initializes the canvas data for this texture @method initCanvas @private ### initCanvas: -> @renderer = new CanvasRenderer(@width, @height, null, 0) @baseTexture = new BaseTexture(@renderer.view) @frame = new Rectangle(0, 0, @width, @height) @render = @renderCanvas ###* This function will draw the display object to the texture. @method renderGLES @param displayObject {DisplayObject} The display object to render this texture on @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn @private ### renderGLES: (displayObject, position, clear) -> gl = GLESRenderer.gl # enable the alpha color mask.. gl.colorMask true, true, true, true gl.viewport 0, 0, @width, @height gl.bindFramebuffer gl.FRAMEBUFFER, @glFramebuffer if clear gl.clearColor 0, 0, 0, 0 gl.clear gl.COLOR_BUFFER_BIT # THIS WILL MESS WITH HIT TESTING! children = displayObject.children #TODO -? create a new one??? dont think so! displayObject.worldTransform = Matrix.mat3.create() #sthis.indetityMatrix; # modify to flip... # LOU TODO: Don't think we really need this. # displayObject.worldTransform[4] = -1 # displayObject.worldTransform[5] = @projection.y * 2 # if position # displayObject.worldTransform[2] = position.x # displayObject.worldTransform[5] -= position.y i = 0 j = children.length while i < j children[i].updateTransform() i++ renderGroup = displayObject.__renderGroup if renderGroup if displayObject is renderGroup.root renderGroup.render @projection else renderGroup.renderSpecific displayObject, @projection else @renderGroup = new GLESRenderGroup(gl, @textureFilter) unless @renderGroup @renderGroup.setRenderable displayObject @renderGroup.render @projection ###* This function will draw the display object to the texture. @method renderCanvas @param displayObject {DisplayObject} The display object to render this texture on @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn @private ### renderCanvas: (displayObject, position, clear) -> children = displayObject.children displayObject.worldTransform = Matrix.mat3.create() if position displayObject.worldTransform[2] = position.x displayObject.worldTransform[5] = position.y i = 0 j = children.length while i < j children[i].updateTransform() i++ imageSmoothingEnabled = @textureFilter not in [BaseTexture.filterModes.NEAREST, 'nearest'] @renderer.context.imageSmoothingEnabled = imageSmoothingEnabled @renderer.context.webkitImageSmoothingEnabled = imageSmoothingEnabled @renderer.context.mozImageSmoothingEnabled = imageSmoothingEnabled @renderer.context.clearRect 0, 0, @width, @height if clear @renderer.renderDisplayObject displayObject @renderer.context.setTransform 1, 0, 0, 1, 0, 0
212816
###* @author <NAME> http://matgroves.com/ @Doormat23 ### define 'Coffixi/textures/RenderTexture', [ 'Coffixi/core/Rectangle' 'Coffixi/core/Point' 'Coffixi/core/Matrix' 'Coffixi/renderers/canvas/CanvasRenderer' 'Coffixi/renderers/webgl/GLESRenderer' './BaseTexture' './Texture' ], ( Rectangle Point Matrix CanvasRenderer GLESRenderer BaseTexture Texture ) -> GLESRenderGroup = GLESRenderer.GLESRenderGroup ###* A RenderTexture is a special texture that allows any pixi displayObject to be rendered to it. __Hint__: All DisplayObjects (exmpl. Sprites) that renders on RenderTexture should be preloaded. Otherwise black rectangles will be drawn instead. RenderTexture takes snapshot of DisplayObject passed to render method. If DisplayObject is passed to render method, position and rotation of it will be ignored. For example: var renderTexture = new RenderTexture(800, 600); var sprite = Sprite.fromImage("spinObj_01.png"); sprite.x = 800/2; sprite.y = 600/2; sprite.anchorX = 0.5; sprite.anchorY = 0.5; renderTexture.render(sprite); Sprite in this case will be rendered to 0,0 position. To render this sprite at center DisplayObjectContainer should be used: var doc = new DisplayObjectContainer(); doc.addChild(sprite); renderTexture.render(doc); // Renders to center of renderTexture @class RenderTexture @extends Texture @constructor @param width {Number} The width of the render texture @param height {Number} The height of the render texture ### class RenderTexture extends Texture constructor: (width, height, @textureFilter=BaseTexture.filterModes.LINEAR, @filterMode=BaseTexture.filterModes.LINEAR) -> @width = width or 100 @height = height or 100 @indetityMatrix = Matrix.mat3.create() @frame = new Rectangle(0, 0, @width, @height) if GLESRenderer.gl @initGLES() else @initCanvas() ###* Initializes the webgl data for this texture @method initGLES @private ### initGLES: -> gl = GLESRenderer.gl @glFramebuffer = gl.createFramebuffer() gl.bindFramebuffer gl.FRAMEBUFFER, @glFramebuffer # LOU TODO: Do we need this? # @glFramebuffer.width = @width # @glFramebuffer.height = @height @baseTexture = new BaseTexture() @baseTexture.width = @width @baseTexture.height = @height @baseTexture._glTexture = gl.createTexture() gl.bindTexture gl.TEXTURE_2D, @baseTexture._glTexture gl.texImage2D gl.TEXTURE_2D, 0, gl.RGBA, @width, @height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null glFilterMode = GLESRenderer.getGLFilterMode @filterMode gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilterMode gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glFilterMode gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE @baseTexture.isRender = true # gl.bindTexture gl.TEXTURE_2D, null # gl.bindFramebuffer gl.FRAMEBUFFER, @glFramebuffer gl.framebufferTexture2D gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, @baseTexture._glTexture, 0 # create a projection matrix.. @projection = new Point(@width / 2, @height / 2) @projectionMatrix = Matrix.mat4.create() @projectionMatrix[5] = 2 / @height # * 0.5; @projectionMatrix[13] = -1 @projectionMatrix[0] = 2 / @width @projectionMatrix[12] = -1 # set the correct render function.. @render = @renderGLES resize: (width, height) -> @width = width @height = height @projection = new Point(@width / 2, @height / 2) if GLESRenderer.gl gl = GLESRenderer.gl gl.bindTexture gl.TEXTURE_2D, @baseTexture._glTexture gl.texImage2D gl.TEXTURE_2D, 0, gl.RGBA, @width, @height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null else @frame.width = @width @frame.height = @height @renderer.resize @width, @height ###* Initializes the canvas data for this texture @method initCanvas @private ### initCanvas: -> @renderer = new CanvasRenderer(@width, @height, null, 0) @baseTexture = new BaseTexture(@renderer.view) @frame = new Rectangle(0, 0, @width, @height) @render = @renderCanvas ###* This function will draw the display object to the texture. @method renderGLES @param displayObject {DisplayObject} The display object to render this texture on @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn @private ### renderGLES: (displayObject, position, clear) -> gl = GLESRenderer.gl # enable the alpha color mask.. gl.colorMask true, true, true, true gl.viewport 0, 0, @width, @height gl.bindFramebuffer gl.FRAMEBUFFER, @glFramebuffer if clear gl.clearColor 0, 0, 0, 0 gl.clear gl.COLOR_BUFFER_BIT # THIS WILL MESS WITH HIT TESTING! children = displayObject.children #TODO -? create a new one??? dont think so! displayObject.worldTransform = Matrix.mat3.create() #sthis.indetityMatrix; # modify to flip... # LOU TODO: Don't think we really need this. # displayObject.worldTransform[4] = -1 # displayObject.worldTransform[5] = @projection.y * 2 # if position # displayObject.worldTransform[2] = position.x # displayObject.worldTransform[5] -= position.y i = 0 j = children.length while i < j children[i].updateTransform() i++ renderGroup = displayObject.__renderGroup if renderGroup if displayObject is renderGroup.root renderGroup.render @projection else renderGroup.renderSpecific displayObject, @projection else @renderGroup = new GLESRenderGroup(gl, @textureFilter) unless @renderGroup @renderGroup.setRenderable displayObject @renderGroup.render @projection ###* This function will draw the display object to the texture. @method renderCanvas @param displayObject {DisplayObject} The display object to render this texture on @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn @private ### renderCanvas: (displayObject, position, clear) -> children = displayObject.children displayObject.worldTransform = Matrix.mat3.create() if position displayObject.worldTransform[2] = position.x displayObject.worldTransform[5] = position.y i = 0 j = children.length while i < j children[i].updateTransform() i++ imageSmoothingEnabled = @textureFilter not in [BaseTexture.filterModes.NEAREST, 'nearest'] @renderer.context.imageSmoothingEnabled = imageSmoothingEnabled @renderer.context.webkitImageSmoothingEnabled = imageSmoothingEnabled @renderer.context.mozImageSmoothingEnabled = imageSmoothingEnabled @renderer.context.clearRect 0, 0, @width, @height if clear @renderer.renderDisplayObject displayObject @renderer.context.setTransform 1, 0, 0, 1, 0, 0
true
###* @author PI:NAME:<NAME>END_PI http://matgroves.com/ @Doormat23 ### define 'Coffixi/textures/RenderTexture', [ 'Coffixi/core/Rectangle' 'Coffixi/core/Point' 'Coffixi/core/Matrix' 'Coffixi/renderers/canvas/CanvasRenderer' 'Coffixi/renderers/webgl/GLESRenderer' './BaseTexture' './Texture' ], ( Rectangle Point Matrix CanvasRenderer GLESRenderer BaseTexture Texture ) -> GLESRenderGroup = GLESRenderer.GLESRenderGroup ###* A RenderTexture is a special texture that allows any pixi displayObject to be rendered to it. __Hint__: All DisplayObjects (exmpl. Sprites) that renders on RenderTexture should be preloaded. Otherwise black rectangles will be drawn instead. RenderTexture takes snapshot of DisplayObject passed to render method. If DisplayObject is passed to render method, position and rotation of it will be ignored. For example: var renderTexture = new RenderTexture(800, 600); var sprite = Sprite.fromImage("spinObj_01.png"); sprite.x = 800/2; sprite.y = 600/2; sprite.anchorX = 0.5; sprite.anchorY = 0.5; renderTexture.render(sprite); Sprite in this case will be rendered to 0,0 position. To render this sprite at center DisplayObjectContainer should be used: var doc = new DisplayObjectContainer(); doc.addChild(sprite); renderTexture.render(doc); // Renders to center of renderTexture @class RenderTexture @extends Texture @constructor @param width {Number} The width of the render texture @param height {Number} The height of the render texture ### class RenderTexture extends Texture constructor: (width, height, @textureFilter=BaseTexture.filterModes.LINEAR, @filterMode=BaseTexture.filterModes.LINEAR) -> @width = width or 100 @height = height or 100 @indetityMatrix = Matrix.mat3.create() @frame = new Rectangle(0, 0, @width, @height) if GLESRenderer.gl @initGLES() else @initCanvas() ###* Initializes the webgl data for this texture @method initGLES @private ### initGLES: -> gl = GLESRenderer.gl @glFramebuffer = gl.createFramebuffer() gl.bindFramebuffer gl.FRAMEBUFFER, @glFramebuffer # LOU TODO: Do we need this? # @glFramebuffer.width = @width # @glFramebuffer.height = @height @baseTexture = new BaseTexture() @baseTexture.width = @width @baseTexture.height = @height @baseTexture._glTexture = gl.createTexture() gl.bindTexture gl.TEXTURE_2D, @baseTexture._glTexture gl.texImage2D gl.TEXTURE_2D, 0, gl.RGBA, @width, @height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null glFilterMode = GLESRenderer.getGLFilterMode @filterMode gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, glFilterMode gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, glFilterMode gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE gl.texParameteri gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE @baseTexture.isRender = true # gl.bindTexture gl.TEXTURE_2D, null # gl.bindFramebuffer gl.FRAMEBUFFER, @glFramebuffer gl.framebufferTexture2D gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, @baseTexture._glTexture, 0 # create a projection matrix.. @projection = new Point(@width / 2, @height / 2) @projectionMatrix = Matrix.mat4.create() @projectionMatrix[5] = 2 / @height # * 0.5; @projectionMatrix[13] = -1 @projectionMatrix[0] = 2 / @width @projectionMatrix[12] = -1 # set the correct render function.. @render = @renderGLES resize: (width, height) -> @width = width @height = height @projection = new Point(@width / 2, @height / 2) if GLESRenderer.gl gl = GLESRenderer.gl gl.bindTexture gl.TEXTURE_2D, @baseTexture._glTexture gl.texImage2D gl.TEXTURE_2D, 0, gl.RGBA, @width, @height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null else @frame.width = @width @frame.height = @height @renderer.resize @width, @height ###* Initializes the canvas data for this texture @method initCanvas @private ### initCanvas: -> @renderer = new CanvasRenderer(@width, @height, null, 0) @baseTexture = new BaseTexture(@renderer.view) @frame = new Rectangle(0, 0, @width, @height) @render = @renderCanvas ###* This function will draw the display object to the texture. @method renderGLES @param displayObject {DisplayObject} The display object to render this texture on @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn @private ### renderGLES: (displayObject, position, clear) -> gl = GLESRenderer.gl # enable the alpha color mask.. gl.colorMask true, true, true, true gl.viewport 0, 0, @width, @height gl.bindFramebuffer gl.FRAMEBUFFER, @glFramebuffer if clear gl.clearColor 0, 0, 0, 0 gl.clear gl.COLOR_BUFFER_BIT # THIS WILL MESS WITH HIT TESTING! children = displayObject.children #TODO -? create a new one??? dont think so! displayObject.worldTransform = Matrix.mat3.create() #sthis.indetityMatrix; # modify to flip... # LOU TODO: Don't think we really need this. # displayObject.worldTransform[4] = -1 # displayObject.worldTransform[5] = @projection.y * 2 # if position # displayObject.worldTransform[2] = position.x # displayObject.worldTransform[5] -= position.y i = 0 j = children.length while i < j children[i].updateTransform() i++ renderGroup = displayObject.__renderGroup if renderGroup if displayObject is renderGroup.root renderGroup.render @projection else renderGroup.renderSpecific displayObject, @projection else @renderGroup = new GLESRenderGroup(gl, @textureFilter) unless @renderGroup @renderGroup.setRenderable displayObject @renderGroup.render @projection ###* This function will draw the display object to the texture. @method renderCanvas @param displayObject {DisplayObject} The display object to render this texture on @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn @private ### renderCanvas: (displayObject, position, clear) -> children = displayObject.children displayObject.worldTransform = Matrix.mat3.create() if position displayObject.worldTransform[2] = position.x displayObject.worldTransform[5] = position.y i = 0 j = children.length while i < j children[i].updateTransform() i++ imageSmoothingEnabled = @textureFilter not in [BaseTexture.filterModes.NEAREST, 'nearest'] @renderer.context.imageSmoothingEnabled = imageSmoothingEnabled @renderer.context.webkitImageSmoothingEnabled = imageSmoothingEnabled @renderer.context.mozImageSmoothingEnabled = imageSmoothingEnabled @renderer.context.clearRect 0, 0, @width, @height if clear @renderer.renderDisplayObject displayObject @renderer.context.setTransform 1, 0, 0, 1, 0, 0
[ { "context": "rbot\n# A NodeJS module for creating Twitter Bots\n# Nathaniel Kirby <nate@projectspong.com\n# https://github.com/nkirb", "end": 132, "score": 0.9998586773872375, "start": 117, "tag": "NAME", "value": "Nathaniel Kirby" }, { "context": "dule for creating Twitter Bots\n# ...
src/twitterbot_streamaction.coffee
nkirby/node-twitterbot
75
#################################################### # node-twitterbot # A NodeJS module for creating Twitter Bots # Nathaniel Kirby <nate@projectspong.com # https://github.com/nkirby/node-twitterbot #################################################### eventEmitter = require('events').EventEmitter class TwitterBotStreamAction extends TwitterBotAction init: () -> @streams = {} @on "start", () => @start() @on "stop", () => @stream.stop() @stream_path = "statuses/sample" start: () -> @stream = @owner.twitter.stream @stream_path @stream.on "tweet", (tweet) => for key, value of @streams if value(tweet) @emit "stream-#{key}", @owner.twitter, tweet tweet this stop: () -> @emit "stop" listen: (name, match, callback) -> action = new TwitterBotAction callback, @owner @streams[name] = match @on "stream-#{name}", (twitter, tweet) => action.emit "action", twitter, tweet setStreamPath: (@stream_path) -> this getStreamPath: () -> @stream_path module.exports.TwitterBotStreamAction = TwitterBotStreamAction
38392
#################################################### # node-twitterbot # A NodeJS module for creating Twitter Bots # <NAME> <<EMAIL> # https://github.com/nkirby/node-twitterbot #################################################### eventEmitter = require('events').EventEmitter class TwitterBotStreamAction extends TwitterBotAction init: () -> @streams = {} @on "start", () => @start() @on "stop", () => @stream.stop() @stream_path = "statuses/sample" start: () -> @stream = @owner.twitter.stream @stream_path @stream.on "tweet", (tweet) => for key, value of @streams if value(tweet) @emit "stream-#{key}", @owner.twitter, tweet tweet this stop: () -> @emit "stop" listen: (name, match, callback) -> action = new TwitterBotAction callback, @owner @streams[name] = match @on "stream-#{name}", (twitter, tweet) => action.emit "action", twitter, tweet setStreamPath: (@stream_path) -> this getStreamPath: () -> @stream_path module.exports.TwitterBotStreamAction = TwitterBotStreamAction
true
#################################################### # node-twitterbot # A NodeJS module for creating Twitter Bots # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI # https://github.com/nkirby/node-twitterbot #################################################### eventEmitter = require('events').EventEmitter class TwitterBotStreamAction extends TwitterBotAction init: () -> @streams = {} @on "start", () => @start() @on "stop", () => @stream.stop() @stream_path = "statuses/sample" start: () -> @stream = @owner.twitter.stream @stream_path @stream.on "tweet", (tweet) => for key, value of @streams if value(tweet) @emit "stream-#{key}", @owner.twitter, tweet tweet this stop: () -> @emit "stop" listen: (name, match, callback) -> action = new TwitterBotAction callback, @owner @streams[name] = match @on "stream-#{name}", (twitter, tweet) => action.emit "action", twitter, tweet setStreamPath: (@stream_path) -> this getStreamPath: () -> @stream_path module.exports.TwitterBotStreamAction = TwitterBotStreamAction
[ { "context": "ails](/install/rails)\n- [Roda](https://github.com/adam12/roda-unpoly)\n- [Rack](https://github.com/adam12/r", "end": 902, "score": 0.9996078610420227, "start": 896, "tag": "USERNAME", "value": "adam12" }, { "context": "m/adam12/roda-unpoly)\n- [Rack](https://github.com...
lib/assets/javascripts/unpoly/protocol.coffee
Dr4K4n/unpoly
0
###** Server protocol =============== You rarely need to change server-side code in order to use Unpoly. There is no need to provide a JSON API, or add extra routes for AJAX requests. The server simply renders a series of full HTML pages, just like it would without Unpoly. That said, there is an **optional** protocol your server can use to exchange additional information when Unpoly is [updating fragments](/up.link). While the protocol can help you optimize performance and handle some edge cases, implementing it is **entirely optional**. For instance, `unpoly.com` itself is a static site that uses Unpoly on the frontend and doesn't even have a server component. ## Existing implementations You should be able to implement the protocol in a very short time. There are existing implementations for various web frameworks: - [Ruby on Rails](/install/rails) - [Roda](https://github.com/adam12/roda-unpoly) - [Rack](https://github.com/adam12/rack-unpoly) (Sinatra, Padrino, Hanami, Cuba, ...) - [Phoenix](https://elixirforum.com/t/unpoly-a-framework-like-turbolinks/3614/15) (Elixir) ## Protocol details \#\#\# Redirect detection for IE11 On Internet Explorer 11, Unpoly cannot detect the final URL after a redirect. You can fix this edge case by delivering an additional HTTP header with the *last* response in a series of redirects: ```http X-Up-Location: /current-url ``` The **simplest implementation** is to set these headers for every request. \#\#\# Optimizing responses When [updating a fragment](/up.link), Unpoly will send an additional HTTP header containing the CSS selector that is being replaced: ```http X-Up-Target: .user-list ``` Server-side code is free to **optimize its response** by only returning HTML that matches the selector. For example, you might prefer to not render an expensive sidebar if the sidebar is not targeted. Unpoly will often update a different selector in case the request fails. This selector is also included as a HTTP header: ``` X-Up-Fail-Target: body ``` \#\#\# Pushing a document title to the client When [updating a fragment](/up.link), Unpoly will by default extract the `<title>` from the server response and update the document title accordingly. The server can also force Unpoly to set a document title by passing a HTTP header: ```http X-Up-Title: My server-pushed title ``` This is useful when you [optimize your response](#optimizing-responses) and not render the application layout unless it is targeted. Since your optimized response no longer includes a `<title>`, you can instead use the HTTP header to pass the document title. \#\#\# Signaling failed form submissions When [submitting a form via AJAX](/form-up-target) Unpoly needs to know whether the form submission has failed (to update the form with validation errors) or succeeded (to update the `up-target` selector). For Unpoly to be able to detect a failed form submission, the response must be return a non-200 HTTP status code. We recommend to use either 400 (bad request) or 422 (unprocessable entity). To do so in [Ruby on Rails](http://rubyonrails.org/), pass a [`:status` option to `render`](http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option): class UsersController < ApplicationController def create user_params = params[:user].permit(:email, :password) @user = User.new(user_params) if @user.save? sign_in @user else render 'form', status: :bad_request end end end \#\#\# Detecting live form validations When [validating a form](/input-up-validate), Unpoly will send an additional HTTP header containing a CSS selector for the form that is being updated: ```http X-Up-Validate: .user-form ``` When detecting a validation request, the server is expected to **validate (but not save)** the form submission and render a new copy of the form with validation errors. Below you will an example for a writing route that is aware of Unpoly's live form validations. The code is for [Ruby on Rails](http://rubyonrails.org/), but you can adapt it for other languages: class UsersController < ApplicationController def create user_params = params[:user].permit(:email, :password) @user = User.new(user_params) if request.headers['X-Up-Validate'] @user.valid? # run validations, but don't save to the database render 'form' # render form with error messages elsif @user.save? sign_in @user else render 'form', status: :bad_request end end end \#\#\# Signaling the initial request method If the initial page was loaded with a non-`GET` HTTP method, Unpoly prefers to make a full page load when you try to update a fragment. Once the next page was loaded with a `GET` method, Unpoly will restore its standard behavior. This fixes two edge cases you might or might not care about: 1. Unpoly replaces the initial page state so it can later restore it when the user goes back to that initial URL. However, if the initial request was a POST, Unpoly will wrongly assume that it can restore the state by reloading with GET. 2. Some browsers have a bug where the initial request method is used for all subsequently pushed states. That means if the user reloads the page on a later GET state, the browser will wrongly attempt a POST request. This issue affects Safari 9-12 (last tested in 2019-03). Modern Firefoxes, Chromes and IE10+ don't have this behavior. In order to allow Unpoly to detect the HTTP method of the initial page load, the server must set a cookie: ```http Set-Cookie: _up_method=POST ``` When Unpoly boots, it will look for this cookie and configure its behavior accordingly. The cookie is then deleted in order to not affect following requests. The **simplest implementation** is to set this cookie for every request that is neither `GET` nor contains an [`X-Up-Target` header](/#optimizing-responses). For all other requests an existing cookie should be deleted. @module up.protocol ### up.protocol = do -> u = up.util e = up.element ###** @function up.protocol.locationFromXhr @internal ### locationFromXhr = (xhr) -> xhr.getResponseHeader(config.locationHeader) || xhr.responseURL ###** @function up.protocol.titleFromXhr @internal ### titleFromXhr = (xhr) -> xhr.getResponseHeader(config.titleHeader) ###** @function up.protocol.methodFromXhr @internal ### methodFromXhr = (xhr) -> if method = xhr.getResponseHeader(config.methodHeader) u.normalizeMethod(method) ###** Server-side companion libraries like unpoly-rails set this cookie so we have a way to detect the request method of the initial page load. There is no JavaScript API for this. @function up.protocol.initialRequestMethod @internal ### initialRequestMethod = u.memoize -> methodFromServer = up.browser.popCookie(config.methodCookie) (methodFromServer || 'get').toLowerCase() # Remove the method cookie as soon as possible. # Don't wait until the first call to initialRequestMethod(), # which might be much later. up.on('up:framework:booted', initialRequestMethod) ###** Configures strings used in the optional [server protocol](/up.protocol). @property up.protocol.config @param {String} [config.targetHeader='X-Up-Target'] @param {String} [config.failTargetHeader='X-Up-Fail-Target'] @param {String} [config.locationHeader='X-Up-Location'] @param {String} [config.titleHeader='X-Up-Title'] @param {String} [config.validateHeader='X-Up-Validate'] @param {String} [config.methodHeader='X-Up-Method'] @param {String} [config.methodCookie='_up_method'] The name of the optional cookie the server can send to [signal the initial request method](/up.protocol#signaling-the-initial-request-method). @param {String} [config.methodParam='_method'] The name of the POST parameter when [wrapping HTTP methods](/up.proxy.config#config.wrapMethods) in a `POST` request. @param {String} [config.csrfHeader='X-CSRF-Token'] The name of the HTTP header that will include the [CSRF token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern) for AJAX requests. @param {string|Function(): string} [config.csrfParam] The `name` of the hidden `<input>` used for sending a [CSRF token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern) when submitting a default, non-AJAX form. For AJAX request the token is sent as an HTTP header instead. The parameter name can be configured as a string or as function that returns the parameter name. If no name is set, no token will be sent. Defaults to the `content` attribute of a `<meta>` tag named `csrf-param`: <meta name="csrf-param" content="authenticity_token" /> @param {string|Function(): string} [config.csrfToken] The [CSRF token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern) to send for unsafe requests. The token will be sent as either a HTTP header (for AJAX requests) or hidden form `<input>` (for default, non-AJAX form submissions). The token can either be configured as a string or as function that returns the token. If no token is set, no token will be sent. Defaults to the `content` attribute of a `<meta>` tag named `csrf-token`: <meta name='csrf-token' content='secret12345'> @experimental ### config = new up.Config targetHeader: 'X-Up-Target' failTargetHeader: 'X-Up-Fail-Target' locationHeader: 'X-Up-Location' validateHeader: 'X-Up-Validate' titleHeader: 'X-Up-Title' methodHeader: 'X-Up-Method' methodCookie: '_up_method' methodParam: '_method' csrfParam: -> e.metaContent('csrf-param') csrfToken: -> e.metaContent('csrf-token') csrfHeader: 'X-CSRF-Token' csrfParam = -> u.evalOption(config.csrfParam) csrfToken = -> u.evalOption(config.csrfToken) reset = -> config.reset() up.on 'up:framework:reset', reset config: config reset: reset locationFromXhr: locationFromXhr titleFromXhr: titleFromXhr methodFromXhr: methodFromXhr csrfParam :csrfParam csrfToken: csrfToken initialRequestMethod: initialRequestMethod
12396
###** Server protocol =============== You rarely need to change server-side code in order to use Unpoly. There is no need to provide a JSON API, or add extra routes for AJAX requests. The server simply renders a series of full HTML pages, just like it would without Unpoly. That said, there is an **optional** protocol your server can use to exchange additional information when Unpoly is [updating fragments](/up.link). While the protocol can help you optimize performance and handle some edge cases, implementing it is **entirely optional**. For instance, `unpoly.com` itself is a static site that uses Unpoly on the frontend and doesn't even have a server component. ## Existing implementations You should be able to implement the protocol in a very short time. There are existing implementations for various web frameworks: - [Ruby on Rails](/install/rails) - [Roda](https://github.com/adam12/roda-unpoly) - [Rack](https://github.com/adam12/rack-unpoly) (Sinatra, Padrino, Hanami, Cuba, ...) - [Phoenix](https://elixirforum.com/t/unpoly-a-framework-like-turbolinks/3614/15) (Elixir) ## Protocol details \#\#\# Redirect detection for IE11 On Internet Explorer 11, Unpoly cannot detect the final URL after a redirect. You can fix this edge case by delivering an additional HTTP header with the *last* response in a series of redirects: ```http X-Up-Location: /current-url ``` The **simplest implementation** is to set these headers for every request. \#\#\# Optimizing responses When [updating a fragment](/up.link), Unpoly will send an additional HTTP header containing the CSS selector that is being replaced: ```http X-Up-Target: .user-list ``` Server-side code is free to **optimize its response** by only returning HTML that matches the selector. For example, you might prefer to not render an expensive sidebar if the sidebar is not targeted. Unpoly will often update a different selector in case the request fails. This selector is also included as a HTTP header: ``` X-Up-Fail-Target: body ``` \#\#\# Pushing a document title to the client When [updating a fragment](/up.link), Unpoly will by default extract the `<title>` from the server response and update the document title accordingly. The server can also force Unpoly to set a document title by passing a HTTP header: ```http X-Up-Title: My server-pushed title ``` This is useful when you [optimize your response](#optimizing-responses) and not render the application layout unless it is targeted. Since your optimized response no longer includes a `<title>`, you can instead use the HTTP header to pass the document title. \#\#\# Signaling failed form submissions When [submitting a form via AJAX](/form-up-target) Unpoly needs to know whether the form submission has failed (to update the form with validation errors) or succeeded (to update the `up-target` selector). For Unpoly to be able to detect a failed form submission, the response must be return a non-200 HTTP status code. We recommend to use either 400 (bad request) or 422 (unprocessable entity). To do so in [Ruby on Rails](http://rubyonrails.org/), pass a [`:status` option to `render`](http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option): class UsersController < ApplicationController def create user_params = params[:user].permit(:email, :password) @user = User.new(user_params) if @user.save? sign_in @user else render 'form', status: :bad_request end end end \#\#\# Detecting live form validations When [validating a form](/input-up-validate), Unpoly will send an additional HTTP header containing a CSS selector for the form that is being updated: ```http X-Up-Validate: .user-form ``` When detecting a validation request, the server is expected to **validate (but not save)** the form submission and render a new copy of the form with validation errors. Below you will an example for a writing route that is aware of Unpoly's live form validations. The code is for [Ruby on Rails](http://rubyonrails.org/), but you can adapt it for other languages: class UsersController < ApplicationController def create user_params = params[:user].permit(:email, :password) @user = User.new(user_params) if request.headers['X-Up-Validate'] @user.valid? # run validations, but don't save to the database render 'form' # render form with error messages elsif @user.save? sign_in @user else render 'form', status: :bad_request end end end \#\#\# Signaling the initial request method If the initial page was loaded with a non-`GET` HTTP method, Unpoly prefers to make a full page load when you try to update a fragment. Once the next page was loaded with a `GET` method, Unpoly will restore its standard behavior. This fixes two edge cases you might or might not care about: 1. Unpoly replaces the initial page state so it can later restore it when the user goes back to that initial URL. However, if the initial request was a POST, Unpoly will wrongly assume that it can restore the state by reloading with GET. 2. Some browsers have a bug where the initial request method is used for all subsequently pushed states. That means if the user reloads the page on a later GET state, the browser will wrongly attempt a POST request. This issue affects Safari 9-12 (last tested in 2019-03). Modern Firefoxes, Chromes and IE10+ don't have this behavior. In order to allow Unpoly to detect the HTTP method of the initial page load, the server must set a cookie: ```http Set-Cookie: _up_method=POST ``` When Unpoly boots, it will look for this cookie and configure its behavior accordingly. The cookie is then deleted in order to not affect following requests. The **simplest implementation** is to set this cookie for every request that is neither `GET` nor contains an [`X-Up-Target` header](/#optimizing-responses). For all other requests an existing cookie should be deleted. @module up.protocol ### up.protocol = do -> u = up.util e = up.element ###** @function up.protocol.locationFromXhr @internal ### locationFromXhr = (xhr) -> xhr.getResponseHeader(config.locationHeader) || xhr.responseURL ###** @function up.protocol.titleFromXhr @internal ### titleFromXhr = (xhr) -> xhr.getResponseHeader(config.titleHeader) ###** @function up.protocol.methodFromXhr @internal ### methodFromXhr = (xhr) -> if method = xhr.getResponseHeader(config.methodHeader) u.normalizeMethod(method) ###** Server-side companion libraries like unpoly-rails set this cookie so we have a way to detect the request method of the initial page load. There is no JavaScript API for this. @function up.protocol.initialRequestMethod @internal ### initialRequestMethod = u.memoize -> methodFromServer = up.browser.popCookie(config.methodCookie) (methodFromServer || 'get').toLowerCase() # Remove the method cookie as soon as possible. # Don't wait until the first call to initialRequestMethod(), # which might be much later. up.on('up:framework:booted', initialRequestMethod) ###** Configures strings used in the optional [server protocol](/up.protocol). @property up.protocol.config @param {String} [config.targetHeader='X-Up-Target'] @param {String} [config.failTargetHeader='X-Up-Fail-Target'] @param {String} [config.locationHeader='X-Up-Location'] @param {String} [config.titleHeader='X-Up-Title'] @param {String} [config.validateHeader='X-Up-Validate'] @param {String} [config.methodHeader='X-Up-Method'] @param {String} [config.methodCookie='_up_method'] The name of the optional cookie the server can send to [signal the initial request method](/up.protocol#signaling-the-initial-request-method). @param {String} [config.methodParam='_method'] The name of the POST parameter when [wrapping HTTP methods](/up.proxy.config#config.wrapMethods) in a `POST` request. @param {String} [config.csrfHeader='X-CSRF-Token'] The name of the HTTP header that will include the [CSRF token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern) for AJAX requests. @param {string|Function(): string} [config.csrfParam] The `name` of the hidden `<input>` used for sending a [CSRF token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern) when submitting a default, non-AJAX form. For AJAX request the token is sent as an HTTP header instead. The parameter name can be configured as a string or as function that returns the parameter name. If no name is set, no token will be sent. Defaults to the `content` attribute of a `<meta>` tag named `csrf-param`: <meta name="csrf-param" content="authenticity_token" /> @param {string|Function(): string} [config.csrfToken] The [CSRF token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern) to send for unsafe requests. The token will be sent as either a HTTP header (for AJAX requests) or hidden form `<input>` (for default, non-AJAX form submissions). The token can either be configured as a string or as function that returns the token. If no token is set, no token will be sent. Defaults to the `content` attribute of a `<meta>` tag named `csrf-token`: <meta name='csrf-token' content='<PASSWORD>'> @experimental ### config = new up.Config targetHeader: 'X-Up-Target' failTargetHeader: 'X-Up-Fail-Target' locationHeader: 'X-Up-Location' validateHeader: 'X-Up-Validate' titleHeader: 'X-Up-Title' methodHeader: 'X-Up-Method' methodCookie: '_up_method' methodParam: '_method' csrfParam: -> e.metaContent('csrf-param') csrfToken: -> e.metaContent('csrf-token') csrfHeader: 'X-CSRF-Token' csrfParam = -> u.evalOption(config.csrfParam) csrfToken = -> u.evalOption(config.csrfToken) reset = -> config.reset() up.on 'up:framework:reset', reset config: config reset: reset locationFromXhr: locationFromXhr titleFromXhr: titleFromXhr methodFromXhr: methodFromXhr csrfParam :csrfParam csrfToken: csrfToken initialRequestMethod: initialRequestMethod
true
###** Server protocol =============== You rarely need to change server-side code in order to use Unpoly. There is no need to provide a JSON API, or add extra routes for AJAX requests. The server simply renders a series of full HTML pages, just like it would without Unpoly. That said, there is an **optional** protocol your server can use to exchange additional information when Unpoly is [updating fragments](/up.link). While the protocol can help you optimize performance and handle some edge cases, implementing it is **entirely optional**. For instance, `unpoly.com` itself is a static site that uses Unpoly on the frontend and doesn't even have a server component. ## Existing implementations You should be able to implement the protocol in a very short time. There are existing implementations for various web frameworks: - [Ruby on Rails](/install/rails) - [Roda](https://github.com/adam12/roda-unpoly) - [Rack](https://github.com/adam12/rack-unpoly) (Sinatra, Padrino, Hanami, Cuba, ...) - [Phoenix](https://elixirforum.com/t/unpoly-a-framework-like-turbolinks/3614/15) (Elixir) ## Protocol details \#\#\# Redirect detection for IE11 On Internet Explorer 11, Unpoly cannot detect the final URL after a redirect. You can fix this edge case by delivering an additional HTTP header with the *last* response in a series of redirects: ```http X-Up-Location: /current-url ``` The **simplest implementation** is to set these headers for every request. \#\#\# Optimizing responses When [updating a fragment](/up.link), Unpoly will send an additional HTTP header containing the CSS selector that is being replaced: ```http X-Up-Target: .user-list ``` Server-side code is free to **optimize its response** by only returning HTML that matches the selector. For example, you might prefer to not render an expensive sidebar if the sidebar is not targeted. Unpoly will often update a different selector in case the request fails. This selector is also included as a HTTP header: ``` X-Up-Fail-Target: body ``` \#\#\# Pushing a document title to the client When [updating a fragment](/up.link), Unpoly will by default extract the `<title>` from the server response and update the document title accordingly. The server can also force Unpoly to set a document title by passing a HTTP header: ```http X-Up-Title: My server-pushed title ``` This is useful when you [optimize your response](#optimizing-responses) and not render the application layout unless it is targeted. Since your optimized response no longer includes a `<title>`, you can instead use the HTTP header to pass the document title. \#\#\# Signaling failed form submissions When [submitting a form via AJAX](/form-up-target) Unpoly needs to know whether the form submission has failed (to update the form with validation errors) or succeeded (to update the `up-target` selector). For Unpoly to be able to detect a failed form submission, the response must be return a non-200 HTTP status code. We recommend to use either 400 (bad request) or 422 (unprocessable entity). To do so in [Ruby on Rails](http://rubyonrails.org/), pass a [`:status` option to `render`](http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option): class UsersController < ApplicationController def create user_params = params[:user].permit(:email, :password) @user = User.new(user_params) if @user.save? sign_in @user else render 'form', status: :bad_request end end end \#\#\# Detecting live form validations When [validating a form](/input-up-validate), Unpoly will send an additional HTTP header containing a CSS selector for the form that is being updated: ```http X-Up-Validate: .user-form ``` When detecting a validation request, the server is expected to **validate (but not save)** the form submission and render a new copy of the form with validation errors. Below you will an example for a writing route that is aware of Unpoly's live form validations. The code is for [Ruby on Rails](http://rubyonrails.org/), but you can adapt it for other languages: class UsersController < ApplicationController def create user_params = params[:user].permit(:email, :password) @user = User.new(user_params) if request.headers['X-Up-Validate'] @user.valid? # run validations, but don't save to the database render 'form' # render form with error messages elsif @user.save? sign_in @user else render 'form', status: :bad_request end end end \#\#\# Signaling the initial request method If the initial page was loaded with a non-`GET` HTTP method, Unpoly prefers to make a full page load when you try to update a fragment. Once the next page was loaded with a `GET` method, Unpoly will restore its standard behavior. This fixes two edge cases you might or might not care about: 1. Unpoly replaces the initial page state so it can later restore it when the user goes back to that initial URL. However, if the initial request was a POST, Unpoly will wrongly assume that it can restore the state by reloading with GET. 2. Some browsers have a bug where the initial request method is used for all subsequently pushed states. That means if the user reloads the page on a later GET state, the browser will wrongly attempt a POST request. This issue affects Safari 9-12 (last tested in 2019-03). Modern Firefoxes, Chromes and IE10+ don't have this behavior. In order to allow Unpoly to detect the HTTP method of the initial page load, the server must set a cookie: ```http Set-Cookie: _up_method=POST ``` When Unpoly boots, it will look for this cookie and configure its behavior accordingly. The cookie is then deleted in order to not affect following requests. The **simplest implementation** is to set this cookie for every request that is neither `GET` nor contains an [`X-Up-Target` header](/#optimizing-responses). For all other requests an existing cookie should be deleted. @module up.protocol ### up.protocol = do -> u = up.util e = up.element ###** @function up.protocol.locationFromXhr @internal ### locationFromXhr = (xhr) -> xhr.getResponseHeader(config.locationHeader) || xhr.responseURL ###** @function up.protocol.titleFromXhr @internal ### titleFromXhr = (xhr) -> xhr.getResponseHeader(config.titleHeader) ###** @function up.protocol.methodFromXhr @internal ### methodFromXhr = (xhr) -> if method = xhr.getResponseHeader(config.methodHeader) u.normalizeMethod(method) ###** Server-side companion libraries like unpoly-rails set this cookie so we have a way to detect the request method of the initial page load. There is no JavaScript API for this. @function up.protocol.initialRequestMethod @internal ### initialRequestMethod = u.memoize -> methodFromServer = up.browser.popCookie(config.methodCookie) (methodFromServer || 'get').toLowerCase() # Remove the method cookie as soon as possible. # Don't wait until the first call to initialRequestMethod(), # which might be much later. up.on('up:framework:booted', initialRequestMethod) ###** Configures strings used in the optional [server protocol](/up.protocol). @property up.protocol.config @param {String} [config.targetHeader='X-Up-Target'] @param {String} [config.failTargetHeader='X-Up-Fail-Target'] @param {String} [config.locationHeader='X-Up-Location'] @param {String} [config.titleHeader='X-Up-Title'] @param {String} [config.validateHeader='X-Up-Validate'] @param {String} [config.methodHeader='X-Up-Method'] @param {String} [config.methodCookie='_up_method'] The name of the optional cookie the server can send to [signal the initial request method](/up.protocol#signaling-the-initial-request-method). @param {String} [config.methodParam='_method'] The name of the POST parameter when [wrapping HTTP methods](/up.proxy.config#config.wrapMethods) in a `POST` request. @param {String} [config.csrfHeader='X-CSRF-Token'] The name of the HTTP header that will include the [CSRF token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern) for AJAX requests. @param {string|Function(): string} [config.csrfParam] The `name` of the hidden `<input>` used for sending a [CSRF token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern) when submitting a default, non-AJAX form. For AJAX request the token is sent as an HTTP header instead. The parameter name can be configured as a string or as function that returns the parameter name. If no name is set, no token will be sent. Defaults to the `content` attribute of a `<meta>` tag named `csrf-param`: <meta name="csrf-param" content="authenticity_token" /> @param {string|Function(): string} [config.csrfToken] The [CSRF token](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern) to send for unsafe requests. The token will be sent as either a HTTP header (for AJAX requests) or hidden form `<input>` (for default, non-AJAX form submissions). The token can either be configured as a string or as function that returns the token. If no token is set, no token will be sent. Defaults to the `content` attribute of a `<meta>` tag named `csrf-token`: <meta name='csrf-token' content='PI:PASSWORD:<PASSWORD>END_PI'> @experimental ### config = new up.Config targetHeader: 'X-Up-Target' failTargetHeader: 'X-Up-Fail-Target' locationHeader: 'X-Up-Location' validateHeader: 'X-Up-Validate' titleHeader: 'X-Up-Title' methodHeader: 'X-Up-Method' methodCookie: '_up_method' methodParam: '_method' csrfParam: -> e.metaContent('csrf-param') csrfToken: -> e.metaContent('csrf-token') csrfHeader: 'X-CSRF-Token' csrfParam = -> u.evalOption(config.csrfParam) csrfToken = -> u.evalOption(config.csrfToken) reset = -> config.reset() up.on 'up:framework:reset', reset config: config reset: reset locationFromXhr: locationFromXhr titleFromXhr: titleFromXhr methodFromXhr: methodFromXhr csrfParam :csrfParam csrfToken: csrfToken initialRequestMethod: initialRequestMethod
[ { "context": "dle redraw events from neovim\n# Copyright (c) 2015 Lu Wang <coolwanglu@gmail.com>\n\nshell = require 'shell'\nE", "end": 75, "score": 0.9963443875312805, "start": 68, "tag": "NAME", "value": "Lu Wang" }, { "context": " events from neovim\n# Copyright (c) 2015 Lu Wang <...
src/nvim/ui.coffee
coolwanglu/neovim-e
252
# ui.coffee # handle redraw events from neovim # Copyright (c) 2015 Lu Wang <coolwanglu@gmail.com> shell = require 'shell' EventEmitter = require('events').EventEmitter remote = require 'remote' config = require './config' {keystrokeForKeyboardEvent} = require './key_handler' MOUSE_BUTTON_NAME = [ 'Left', 'Middle', 'Right' ] # neovim/vim scrolls by 3 rows for every ScrollWheel{Up,Down} # and 6 colums per ScrollWheel{Left,Right} (:h scroll-mouse-wheel) ROWS_PER_SCROLL = 3 COLS_PER_SCROLL = 6 get_vim_button_name = (button, e) -> kn = '<' kn += 'S-' if e.shiftKey kn += 'C-' if e.ctrlKey kn += 'A-' if e.altKey kn += button + '>' kn # borrowed from underscore@acf826fa42ba6 debounce = (func, wait, immediate) -> timeout = undefined args = undefined context = undefined timestamp = undefined result = undefined later = -> last = Date.now() - timestamp if last < wait and last >= 0 timeout = setTimeout(later, wait - last) else timeout = null if !immediate result = func.apply(context, args) if !timeout context = args = null return -> context = this args = arguments timestamp = Date.now() callNow = immediate and !timeout if !timeout timeout = setTimeout(later, wait) if callNow result = func.apply(context, args) context = args = null result # visualize neovim's abstract-ui class UI extends EventEmitter constructor: (row, col)-> super() @init_DOM() @init_state() @init_font() @init_cursor() @init_event_handlers() @nv_resize col, row init_DOM: -> @canvas = document.getElementById 'nvas-canvas' @ctx = @canvas.getContext '2d' @cursor = document.getElementById 'nvas-cursor' @font_test_node = document.getElementById 'nvas-font-test' @devicePixelRatio = window.devicePixelRatio ? 1 init_state: -> # @total_row/col, @scroll_top/bottom/left/right will be set in @nv_resize @cursor_col = 0 @cursor_row = 0 @mouse_enabled = true @mouse_button_pressed = null @wheelDeltaY = 0 @wheelDeltaX = 0 @fg_color = '#fff' @bg_color = '#000' @sp_color = '#f00' @attrs = {} @resize_timer = null init_font: -> @font = config.font @font_test_node.style.font = @font @font_test_node.innerHTML = 'm' @char_width = Math.max 1, @font_test_node.clientWidth @char_height = Math.max 1, @font_test_node.clientHeight @canvas_char_width = @char_width * @devicePixelRatio @canvas_char_height = @char_height * @devicePixelRatio init_cursor: -> @cursor.style.width = @char_width + 'px' @cursor.style.height = @char_height + 'px' if config.blink_cursor @start_cursor_blink() else @stop_cursor_blink() start_cursor_blink: -> @cursor.classList.add 'blink' stop_cursor_blink: -> @cursor.classList.remove 'blink' init_event_handlers: -> resumeBlink = debounce (=> @start_cursor_blink()), 250 pause_blink = => @stop_cursor_blink() resumeBlink() document.addEventListener 'keydown', (e) => keystroke = keystrokeForKeyboardEvent(e) @emit 'input', keystroke if keystroke if config.blink_cursor pause_blink() document.addEventListener 'mousedown', (e) => return if not @mouse_enabled e.preventDefault() @mouse_button_pressed = MOUSE_BUTTON_NAME[e.button] @emit 'input', get_vim_button_name(@mouse_button_pressed + 'Mouse', e) \ + '<' + Math.floor(e.clientX / @char_width) \ + ',' + Math.floor(e.clientY / @char_height) \ + '>' if config.blink_cursor pause_blink() document.addEventListener 'mouseup', (e) => return if not @mouse_enabled e.preventDefault() @mouse_button_pressed = null document.addEventListener 'mousemove', (e) => return if not @mouse_enabled or not @mouse_button_pressed e.preventDefault() @emit 'input', get_vim_button_name(@mouse_button_pressed + 'Drag', e) \ + '<' + Math.floor(e.clientX / @char_width) \ + ',' + Math.floor(e.clientY / @char_height) \ + '>' if config.blink_cursor pause_blink() window.addEventListener 'resize', (e) => if not @resize_timer @resize_timer = setTimeout => @resize_timer = null col = Math.floor window.innerWidth / @char_width row = Math.floor window.innerHeight / @char_height if col != @total_col or row != @total_row @emit 'resize', col, row , 250 @canvas.addEventListener 'wheel', (e) => return if not @mouse_enabled e.preventDefault() # Total distance scrolled in pixels @wheelDeltaX += e.wheelDeltaX @wheelDeltaY += e.wheelDeltaY # Get the number of row/column scroll events to send. Reporting a single # row scrolled will actually scroll by ROWS_PER_SCROLL, so divide accordingly cols = Math.round(@wheelDeltaX / @char_width / COLS_PER_SCROLL) rows = Math.round(@wheelDeltaY / @char_height / ROWS_PER_SCROLL) if rows == 0 && cols == 0 return if cols != 0 @wheelDeltaX = 0 direction = if cols > 0 then 'Left' else 'Right' if rows != 0 @wheelDeltaY = 0 direction = if rows > 0 then 'Up' else 'Down' @emit 'input', get_vim_button_name('ScrollWheel' + direction, e) \ + '<' + Math.floor(e.clientX / @char_width) \ + ',' + Math.floor(e.clientY / @char_height) \ + '>' if config.blink_cursor pause_blink() get_color_string: (rgb) -> bgr = [] for i in [0...3] bgr.push rgb & 0xff rgb = rgb >> 8 'rgb('+bgr[2]+','+bgr[1]+','+bgr[0]+')' clear_block: (col, row, width, height) -> @fill_block(col, row, width, height, @get_cur_bg_color()) fill_block: (col, row, width, height, color) -> @ctx.fillStyle = color @ctx.fillRect \ col * @canvas_char_width, \ row * @canvas_char_height, \ width * @canvas_char_width, \ height * @canvas_char_height clear_all: -> document.body.style.background = @get_cur_bg_color() @ctx.fillStyle = @get_cur_bg_color() @ctx.fillRect 0, 0, @canvas.width, @canvas.height # the font set to canvas might need to be scaled # when devicePixelRatio != 1 get_canvas_font: -> font = @font if @attrs?.bold then font = 'bold ' + font if @attrs?.italic then font = 'italic ' + font try l = @font.split /([\d]+)(?=in|[cem]m|ex|p[ctx])/ l[1] = parseFloat(l[1]) * @devicePixelRatio l.join '' catch @font get_cur_fg_color: -> if @attrs.reverse then @attrs.bg_color ? @bg_color else @attrs.fg_color ? @fg_color get_cur_bg_color: -> if @attrs.reverse then @attrs.fg_color ? @fg_color else @attrs.bg_color ? @bg_color update_cursor: -> @cursor.style.top = (@cursor_row * @char_height) + 'px' @cursor.style.left = (@cursor_col * @char_width) + 'px' ##################### # neovim redraw events # in alphabetical order handle_redraw: (events) -> for e in events try handler = @['nv_'+e[0]] if handler? # optimize for put, we group the chars together if e[0].toString() == 'put' handler.call @, e[1..] else for args in e[1..] handler.apply @, args else console.log 'Redraw event not handled: ' + e.toString() catch ex console.log 'Error when processing event!' console.log e.toString() console.log ex.stack || ex @update_cursor() nv_bell: -> shell.beep() nv_busy_start: -> @cursor.style.display = 'none' nv_busy_stop: -> @cursor.style.display = 'block' nv_clear: -> @clear_all() nv_cursor_goto: (row, col) -> @cursor_row = row @cursor_col = col nv_eol_clear: -> @clear_block @cursor_col, @cursor_row, @total_col - @cursor_col + 1, 1 nv_highlight_set: (attrs) -> @attrs = {} @attrs.bold = attrs.bold @attrs.italic = attrs.italic @attrs.reverse = attrs.reverse @attrs.underline = attrs.underline @attrs.undercurl = attrs.undercurl if attrs.foreground? then @attrs.fg_color = @get_color_string(attrs.foreground) if attrs.background? then @attrs.bg_color = @get_color_string(attrs.background) nv_mouse_off: -> @mouse_enabled = false nv_mouse_on: -> @mouse_enabled = true nv_mode_change: (mode) -> document.body.className = "#{mode}-mode" nv_put: (chars) -> return if chars.length == 0 # paint background @clear_block @cursor_col, @cursor_row, chars.length, 1 # paint string @ctx.font = @get_canvas_font() @ctx.textBaseline = 'bottom' x = @cursor_col * @canvas_char_width y = (@cursor_row + 1) * @canvas_char_height w = chars.length * @canvas_char_width @ctx.fillStyle = @get_cur_fg_color() # Paint each char individually in order to ensure they # line up as expected char_x = x for char in chars @ctx.fillText char, char_x, y char_x += @canvas_char_width if @attrs.underline @ctx.strokeStyle = @get_cur_fg_color() @ctx.lineWidth = @devicePixelRatio @ctx.beginPath() @ctx.moveTo x, y - @devicePixelRatio / 2 @ctx.lineTo x + w, y - @devicePixelRatio / 2 @ctx.stroke() if @attrs.undercurl offs = [1.5, 0.8, 0.5, 0.8, 1.5, 2.2, 2.5, 2.2] # should use sp_color, but neovim does not support it @ctx.strokeStyle = @get_cur_fg_color() @ctx.lineWidth = @devicePixelRatio @ctx.beginPath() @ctx.moveTo x, y - @devicePixelRatio * offs[(x / @devicePixelRatio) % 8] for xx in [x+@devicePixelRatio..x+w] by @devicePixelRatio @ctx.lineTo xx, y - @devicePixelRatio * offs[(xx / @devicePixelRatio) % 8] @ctx.stroke() @cursor_col += chars.length nv_resize: (col, row) -> @total_col = col @total_row = row @scroll_top = 0 @scroll_bottom = @total_row - 1 @scroll_left = 0 @scroll_right = @total_col - 1 @canvas.width = @canvas_char_width * col @canvas.height = @canvas_char_height * row @canvas.style.width = @char_width * col + "px" @canvas.style.height = @char_height * row + "px" window_col = Math.floor window.innerWidth / @char_width window_row = Math.floor window.innerHeight / @char_height if col != window_col || row != window_row window.resizeTo \ @char_width * col + window.outerWidth - window.innerWidth, \ @char_height * row + window.outerHeight - window.innerHeight # adapted from neovim/python-client nv_scroll: (row_count) -> src_top = dst_top = @scroll_top src_bottom = dst_bottom = @scroll_bottom if row_count > 0 # move up src_top += row_count dst_bottom -= row_count clr_top = dst_bottom + 1 clr_bottom = src_bottom else src_bottom += row_count dst_top -= row_count clr_top = src_top clr_bottom = dst_top - 1 img = @ctx.getImageData \ @scroll_left * @canvas_char_width, \ src_top * @canvas_char_height, \ (@scroll_right - @scroll_left + 1) * @canvas_char_width, \ (src_bottom - src_top + 1) * @canvas_char_height @ctx.putImageData img, \ @scroll_left * @canvas_char_width, \ dst_top * @canvas_char_height @fill_block \ @scroll_left, \ clr_top, \ @scroll_right - @scroll_left + 1, \ clr_bottom - clr_top + 1, \ @bg_color nv_set_icon: (icon) -> remote.getCurrentWindow().setRepresentedFilename? icon.toString() nv_set_title: (title) -> title = title.toString() match = /(.*) - VIM$/.exec(title) document.title = if match? then match[1] + ' - Neovim.AS' else title nv_set_scroll_region: (top, bottom, left, right) -> @scroll_top = top @scroll_bottom = bottom @scroll_left = left @scroll_right = right nv_update_fg: (rgb) -> @cursor.style.borderColor = @fg_color = if rgb == -1 then config.fg_color else @get_color_string(rgb) nv_update_bg: (rgb) -> @bg_color = if rgb == -1 then config.bg_color else @get_color_string(rgb) module.exports = UI
171848
# ui.coffee # handle redraw events from neovim # Copyright (c) 2015 <NAME> <<EMAIL>> shell = require 'shell' EventEmitter = require('events').EventEmitter remote = require 'remote' config = require './config' {keystrokeForKeyboardEvent} = require './key_handler' MOUSE_BUTTON_NAME = [ 'Left', 'Middle', 'Right' ] # neovim/vim scrolls by 3 rows for every ScrollWheel{Up,Down} # and 6 colums per ScrollWheel{Left,Right} (:h scroll-mouse-wheel) ROWS_PER_SCROLL = 3 COLS_PER_SCROLL = 6 get_vim_button_name = (button, e) -> kn = '<' kn += 'S-' if e.shiftKey kn += 'C-' if e.ctrlKey kn += 'A-' if e.altKey kn += button + '>' kn # borrowed from underscore@acf826fa42ba6 debounce = (func, wait, immediate) -> timeout = undefined args = undefined context = undefined timestamp = undefined result = undefined later = -> last = Date.now() - timestamp if last < wait and last >= 0 timeout = setTimeout(later, wait - last) else timeout = null if !immediate result = func.apply(context, args) if !timeout context = args = null return -> context = this args = arguments timestamp = Date.now() callNow = immediate and !timeout if !timeout timeout = setTimeout(later, wait) if callNow result = func.apply(context, args) context = args = null result # visualize neovim's abstract-ui class UI extends EventEmitter constructor: (row, col)-> super() @init_DOM() @init_state() @init_font() @init_cursor() @init_event_handlers() @nv_resize col, row init_DOM: -> @canvas = document.getElementById 'nvas-canvas' @ctx = @canvas.getContext '2d' @cursor = document.getElementById 'nvas-cursor' @font_test_node = document.getElementById 'nvas-font-test' @devicePixelRatio = window.devicePixelRatio ? 1 init_state: -> # @total_row/col, @scroll_top/bottom/left/right will be set in @nv_resize @cursor_col = 0 @cursor_row = 0 @mouse_enabled = true @mouse_button_pressed = null @wheelDeltaY = 0 @wheelDeltaX = 0 @fg_color = '#fff' @bg_color = '#000' @sp_color = '#f00' @attrs = {} @resize_timer = null init_font: -> @font = config.font @font_test_node.style.font = @font @font_test_node.innerHTML = 'm' @char_width = Math.max 1, @font_test_node.clientWidth @char_height = Math.max 1, @font_test_node.clientHeight @canvas_char_width = @char_width * @devicePixelRatio @canvas_char_height = @char_height * @devicePixelRatio init_cursor: -> @cursor.style.width = @char_width + 'px' @cursor.style.height = @char_height + 'px' if config.blink_cursor @start_cursor_blink() else @stop_cursor_blink() start_cursor_blink: -> @cursor.classList.add 'blink' stop_cursor_blink: -> @cursor.classList.remove 'blink' init_event_handlers: -> resumeBlink = debounce (=> @start_cursor_blink()), 250 pause_blink = => @stop_cursor_blink() resumeBlink() document.addEventListener 'keydown', (e) => keystroke = keystrokeForKeyboardEvent(e) @emit 'input', keystroke if keystroke if config.blink_cursor pause_blink() document.addEventListener 'mousedown', (e) => return if not @mouse_enabled e.preventDefault() @mouse_button_pressed = MOUSE_BUTTON_NAME[e.button] @emit 'input', get_vim_button_name(@mouse_button_pressed + 'Mouse', e) \ + '<' + Math.floor(e.clientX / @char_width) \ + ',' + Math.floor(e.clientY / @char_height) \ + '>' if config.blink_cursor pause_blink() document.addEventListener 'mouseup', (e) => return if not @mouse_enabled e.preventDefault() @mouse_button_pressed = null document.addEventListener 'mousemove', (e) => return if not @mouse_enabled or not @mouse_button_pressed e.preventDefault() @emit 'input', get_vim_button_name(@mouse_button_pressed + 'Drag', e) \ + '<' + Math.floor(e.clientX / @char_width) \ + ',' + Math.floor(e.clientY / @char_height) \ + '>' if config.blink_cursor pause_blink() window.addEventListener 'resize', (e) => if not @resize_timer @resize_timer = setTimeout => @resize_timer = null col = Math.floor window.innerWidth / @char_width row = Math.floor window.innerHeight / @char_height if col != @total_col or row != @total_row @emit 'resize', col, row , 250 @canvas.addEventListener 'wheel', (e) => return if not @mouse_enabled e.preventDefault() # Total distance scrolled in pixels @wheelDeltaX += e.wheelDeltaX @wheelDeltaY += e.wheelDeltaY # Get the number of row/column scroll events to send. Reporting a single # row scrolled will actually scroll by ROWS_PER_SCROLL, so divide accordingly cols = Math.round(@wheelDeltaX / @char_width / COLS_PER_SCROLL) rows = Math.round(@wheelDeltaY / @char_height / ROWS_PER_SCROLL) if rows == 0 && cols == 0 return if cols != 0 @wheelDeltaX = 0 direction = if cols > 0 then 'Left' else 'Right' if rows != 0 @wheelDeltaY = 0 direction = if rows > 0 then 'Up' else 'Down' @emit 'input', get_vim_button_name('ScrollWheel' + direction, e) \ + '<' + Math.floor(e.clientX / @char_width) \ + ',' + Math.floor(e.clientY / @char_height) \ + '>' if config.blink_cursor pause_blink() get_color_string: (rgb) -> bgr = [] for i in [0...3] bgr.push rgb & 0xff rgb = rgb >> 8 'rgb('+bgr[2]+','+bgr[1]+','+bgr[0]+')' clear_block: (col, row, width, height) -> @fill_block(col, row, width, height, @get_cur_bg_color()) fill_block: (col, row, width, height, color) -> @ctx.fillStyle = color @ctx.fillRect \ col * @canvas_char_width, \ row * @canvas_char_height, \ width * @canvas_char_width, \ height * @canvas_char_height clear_all: -> document.body.style.background = @get_cur_bg_color() @ctx.fillStyle = @get_cur_bg_color() @ctx.fillRect 0, 0, @canvas.width, @canvas.height # the font set to canvas might need to be scaled # when devicePixelRatio != 1 get_canvas_font: -> font = @font if @attrs?.bold then font = 'bold ' + font if @attrs?.italic then font = 'italic ' + font try l = @font.split /([\d]+)(?=in|[cem]m|ex|p[ctx])/ l[1] = parseFloat(l[1]) * @devicePixelRatio l.join '' catch @font get_cur_fg_color: -> if @attrs.reverse then @attrs.bg_color ? @bg_color else @attrs.fg_color ? @fg_color get_cur_bg_color: -> if @attrs.reverse then @attrs.fg_color ? @fg_color else @attrs.bg_color ? @bg_color update_cursor: -> @cursor.style.top = (@cursor_row * @char_height) + 'px' @cursor.style.left = (@cursor_col * @char_width) + 'px' ##################### # neovim redraw events # in alphabetical order handle_redraw: (events) -> for e in events try handler = @['nv_'+e[0]] if handler? # optimize for put, we group the chars together if e[0].toString() == 'put' handler.call @, e[1..] else for args in e[1..] handler.apply @, args else console.log 'Redraw event not handled: ' + e.toString() catch ex console.log 'Error when processing event!' console.log e.toString() console.log ex.stack || ex @update_cursor() nv_bell: -> shell.beep() nv_busy_start: -> @cursor.style.display = 'none' nv_busy_stop: -> @cursor.style.display = 'block' nv_clear: -> @clear_all() nv_cursor_goto: (row, col) -> @cursor_row = row @cursor_col = col nv_eol_clear: -> @clear_block @cursor_col, @cursor_row, @total_col - @cursor_col + 1, 1 nv_highlight_set: (attrs) -> @attrs = {} @attrs.bold = attrs.bold @attrs.italic = attrs.italic @attrs.reverse = attrs.reverse @attrs.underline = attrs.underline @attrs.undercurl = attrs.undercurl if attrs.foreground? then @attrs.fg_color = @get_color_string(attrs.foreground) if attrs.background? then @attrs.bg_color = @get_color_string(attrs.background) nv_mouse_off: -> @mouse_enabled = false nv_mouse_on: -> @mouse_enabled = true nv_mode_change: (mode) -> document.body.className = "#{mode}-mode" nv_put: (chars) -> return if chars.length == 0 # paint background @clear_block @cursor_col, @cursor_row, chars.length, 1 # paint string @ctx.font = @get_canvas_font() @ctx.textBaseline = 'bottom' x = @cursor_col * @canvas_char_width y = (@cursor_row + 1) * @canvas_char_height w = chars.length * @canvas_char_width @ctx.fillStyle = @get_cur_fg_color() # Paint each char individually in order to ensure they # line up as expected char_x = x for char in chars @ctx.fillText char, char_x, y char_x += @canvas_char_width if @attrs.underline @ctx.strokeStyle = @get_cur_fg_color() @ctx.lineWidth = @devicePixelRatio @ctx.beginPath() @ctx.moveTo x, y - @devicePixelRatio / 2 @ctx.lineTo x + w, y - @devicePixelRatio / 2 @ctx.stroke() if @attrs.undercurl offs = [1.5, 0.8, 0.5, 0.8, 1.5, 2.2, 2.5, 2.2] # should use sp_color, but neovim does not support it @ctx.strokeStyle = @get_cur_fg_color() @ctx.lineWidth = @devicePixelRatio @ctx.beginPath() @ctx.moveTo x, y - @devicePixelRatio * offs[(x / @devicePixelRatio) % 8] for xx in [x+@devicePixelRatio..x+w] by @devicePixelRatio @ctx.lineTo xx, y - @devicePixelRatio * offs[(xx / @devicePixelRatio) % 8] @ctx.stroke() @cursor_col += chars.length nv_resize: (col, row) -> @total_col = col @total_row = row @scroll_top = 0 @scroll_bottom = @total_row - 1 @scroll_left = 0 @scroll_right = @total_col - 1 @canvas.width = @canvas_char_width * col @canvas.height = @canvas_char_height * row @canvas.style.width = @char_width * col + "px" @canvas.style.height = @char_height * row + "px" window_col = Math.floor window.innerWidth / @char_width window_row = Math.floor window.innerHeight / @char_height if col != window_col || row != window_row window.resizeTo \ @char_width * col + window.outerWidth - window.innerWidth, \ @char_height * row + window.outerHeight - window.innerHeight # adapted from neovim/python-client nv_scroll: (row_count) -> src_top = dst_top = @scroll_top src_bottom = dst_bottom = @scroll_bottom if row_count > 0 # move up src_top += row_count dst_bottom -= row_count clr_top = dst_bottom + 1 clr_bottom = src_bottom else src_bottom += row_count dst_top -= row_count clr_top = src_top clr_bottom = dst_top - 1 img = @ctx.getImageData \ @scroll_left * @canvas_char_width, \ src_top * @canvas_char_height, \ (@scroll_right - @scroll_left + 1) * @canvas_char_width, \ (src_bottom - src_top + 1) * @canvas_char_height @ctx.putImageData img, \ @scroll_left * @canvas_char_width, \ dst_top * @canvas_char_height @fill_block \ @scroll_left, \ clr_top, \ @scroll_right - @scroll_left + 1, \ clr_bottom - clr_top + 1, \ @bg_color nv_set_icon: (icon) -> remote.getCurrentWindow().setRepresentedFilename? icon.toString() nv_set_title: (title) -> title = title.toString() match = /(.*) - VIM$/.exec(title) document.title = if match? then match[1] + ' - Neovim.AS' else title nv_set_scroll_region: (top, bottom, left, right) -> @scroll_top = top @scroll_bottom = bottom @scroll_left = left @scroll_right = right nv_update_fg: (rgb) -> @cursor.style.borderColor = @fg_color = if rgb == -1 then config.fg_color else @get_color_string(rgb) nv_update_bg: (rgb) -> @bg_color = if rgb == -1 then config.bg_color else @get_color_string(rgb) module.exports = UI
true
# ui.coffee # handle redraw events from neovim # Copyright (c) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> shell = require 'shell' EventEmitter = require('events').EventEmitter remote = require 'remote' config = require './config' {keystrokeForKeyboardEvent} = require './key_handler' MOUSE_BUTTON_NAME = [ 'Left', 'Middle', 'Right' ] # neovim/vim scrolls by 3 rows for every ScrollWheel{Up,Down} # and 6 colums per ScrollWheel{Left,Right} (:h scroll-mouse-wheel) ROWS_PER_SCROLL = 3 COLS_PER_SCROLL = 6 get_vim_button_name = (button, e) -> kn = '<' kn += 'S-' if e.shiftKey kn += 'C-' if e.ctrlKey kn += 'A-' if e.altKey kn += button + '>' kn # borrowed from underscore@acf826fa42ba6 debounce = (func, wait, immediate) -> timeout = undefined args = undefined context = undefined timestamp = undefined result = undefined later = -> last = Date.now() - timestamp if last < wait and last >= 0 timeout = setTimeout(later, wait - last) else timeout = null if !immediate result = func.apply(context, args) if !timeout context = args = null return -> context = this args = arguments timestamp = Date.now() callNow = immediate and !timeout if !timeout timeout = setTimeout(later, wait) if callNow result = func.apply(context, args) context = args = null result # visualize neovim's abstract-ui class UI extends EventEmitter constructor: (row, col)-> super() @init_DOM() @init_state() @init_font() @init_cursor() @init_event_handlers() @nv_resize col, row init_DOM: -> @canvas = document.getElementById 'nvas-canvas' @ctx = @canvas.getContext '2d' @cursor = document.getElementById 'nvas-cursor' @font_test_node = document.getElementById 'nvas-font-test' @devicePixelRatio = window.devicePixelRatio ? 1 init_state: -> # @total_row/col, @scroll_top/bottom/left/right will be set in @nv_resize @cursor_col = 0 @cursor_row = 0 @mouse_enabled = true @mouse_button_pressed = null @wheelDeltaY = 0 @wheelDeltaX = 0 @fg_color = '#fff' @bg_color = '#000' @sp_color = '#f00' @attrs = {} @resize_timer = null init_font: -> @font = config.font @font_test_node.style.font = @font @font_test_node.innerHTML = 'm' @char_width = Math.max 1, @font_test_node.clientWidth @char_height = Math.max 1, @font_test_node.clientHeight @canvas_char_width = @char_width * @devicePixelRatio @canvas_char_height = @char_height * @devicePixelRatio init_cursor: -> @cursor.style.width = @char_width + 'px' @cursor.style.height = @char_height + 'px' if config.blink_cursor @start_cursor_blink() else @stop_cursor_blink() start_cursor_blink: -> @cursor.classList.add 'blink' stop_cursor_blink: -> @cursor.classList.remove 'blink' init_event_handlers: -> resumeBlink = debounce (=> @start_cursor_blink()), 250 pause_blink = => @stop_cursor_blink() resumeBlink() document.addEventListener 'keydown', (e) => keystroke = keystrokeForKeyboardEvent(e) @emit 'input', keystroke if keystroke if config.blink_cursor pause_blink() document.addEventListener 'mousedown', (e) => return if not @mouse_enabled e.preventDefault() @mouse_button_pressed = MOUSE_BUTTON_NAME[e.button] @emit 'input', get_vim_button_name(@mouse_button_pressed + 'Mouse', e) \ + '<' + Math.floor(e.clientX / @char_width) \ + ',' + Math.floor(e.clientY / @char_height) \ + '>' if config.blink_cursor pause_blink() document.addEventListener 'mouseup', (e) => return if not @mouse_enabled e.preventDefault() @mouse_button_pressed = null document.addEventListener 'mousemove', (e) => return if not @mouse_enabled or not @mouse_button_pressed e.preventDefault() @emit 'input', get_vim_button_name(@mouse_button_pressed + 'Drag', e) \ + '<' + Math.floor(e.clientX / @char_width) \ + ',' + Math.floor(e.clientY / @char_height) \ + '>' if config.blink_cursor pause_blink() window.addEventListener 'resize', (e) => if not @resize_timer @resize_timer = setTimeout => @resize_timer = null col = Math.floor window.innerWidth / @char_width row = Math.floor window.innerHeight / @char_height if col != @total_col or row != @total_row @emit 'resize', col, row , 250 @canvas.addEventListener 'wheel', (e) => return if not @mouse_enabled e.preventDefault() # Total distance scrolled in pixels @wheelDeltaX += e.wheelDeltaX @wheelDeltaY += e.wheelDeltaY # Get the number of row/column scroll events to send. Reporting a single # row scrolled will actually scroll by ROWS_PER_SCROLL, so divide accordingly cols = Math.round(@wheelDeltaX / @char_width / COLS_PER_SCROLL) rows = Math.round(@wheelDeltaY / @char_height / ROWS_PER_SCROLL) if rows == 0 && cols == 0 return if cols != 0 @wheelDeltaX = 0 direction = if cols > 0 then 'Left' else 'Right' if rows != 0 @wheelDeltaY = 0 direction = if rows > 0 then 'Up' else 'Down' @emit 'input', get_vim_button_name('ScrollWheel' + direction, e) \ + '<' + Math.floor(e.clientX / @char_width) \ + ',' + Math.floor(e.clientY / @char_height) \ + '>' if config.blink_cursor pause_blink() get_color_string: (rgb) -> bgr = [] for i in [0...3] bgr.push rgb & 0xff rgb = rgb >> 8 'rgb('+bgr[2]+','+bgr[1]+','+bgr[0]+')' clear_block: (col, row, width, height) -> @fill_block(col, row, width, height, @get_cur_bg_color()) fill_block: (col, row, width, height, color) -> @ctx.fillStyle = color @ctx.fillRect \ col * @canvas_char_width, \ row * @canvas_char_height, \ width * @canvas_char_width, \ height * @canvas_char_height clear_all: -> document.body.style.background = @get_cur_bg_color() @ctx.fillStyle = @get_cur_bg_color() @ctx.fillRect 0, 0, @canvas.width, @canvas.height # the font set to canvas might need to be scaled # when devicePixelRatio != 1 get_canvas_font: -> font = @font if @attrs?.bold then font = 'bold ' + font if @attrs?.italic then font = 'italic ' + font try l = @font.split /([\d]+)(?=in|[cem]m|ex|p[ctx])/ l[1] = parseFloat(l[1]) * @devicePixelRatio l.join '' catch @font get_cur_fg_color: -> if @attrs.reverse then @attrs.bg_color ? @bg_color else @attrs.fg_color ? @fg_color get_cur_bg_color: -> if @attrs.reverse then @attrs.fg_color ? @fg_color else @attrs.bg_color ? @bg_color update_cursor: -> @cursor.style.top = (@cursor_row * @char_height) + 'px' @cursor.style.left = (@cursor_col * @char_width) + 'px' ##################### # neovim redraw events # in alphabetical order handle_redraw: (events) -> for e in events try handler = @['nv_'+e[0]] if handler? # optimize for put, we group the chars together if e[0].toString() == 'put' handler.call @, e[1..] else for args in e[1..] handler.apply @, args else console.log 'Redraw event not handled: ' + e.toString() catch ex console.log 'Error when processing event!' console.log e.toString() console.log ex.stack || ex @update_cursor() nv_bell: -> shell.beep() nv_busy_start: -> @cursor.style.display = 'none' nv_busy_stop: -> @cursor.style.display = 'block' nv_clear: -> @clear_all() nv_cursor_goto: (row, col) -> @cursor_row = row @cursor_col = col nv_eol_clear: -> @clear_block @cursor_col, @cursor_row, @total_col - @cursor_col + 1, 1 nv_highlight_set: (attrs) -> @attrs = {} @attrs.bold = attrs.bold @attrs.italic = attrs.italic @attrs.reverse = attrs.reverse @attrs.underline = attrs.underline @attrs.undercurl = attrs.undercurl if attrs.foreground? then @attrs.fg_color = @get_color_string(attrs.foreground) if attrs.background? then @attrs.bg_color = @get_color_string(attrs.background) nv_mouse_off: -> @mouse_enabled = false nv_mouse_on: -> @mouse_enabled = true nv_mode_change: (mode) -> document.body.className = "#{mode}-mode" nv_put: (chars) -> return if chars.length == 0 # paint background @clear_block @cursor_col, @cursor_row, chars.length, 1 # paint string @ctx.font = @get_canvas_font() @ctx.textBaseline = 'bottom' x = @cursor_col * @canvas_char_width y = (@cursor_row + 1) * @canvas_char_height w = chars.length * @canvas_char_width @ctx.fillStyle = @get_cur_fg_color() # Paint each char individually in order to ensure they # line up as expected char_x = x for char in chars @ctx.fillText char, char_x, y char_x += @canvas_char_width if @attrs.underline @ctx.strokeStyle = @get_cur_fg_color() @ctx.lineWidth = @devicePixelRatio @ctx.beginPath() @ctx.moveTo x, y - @devicePixelRatio / 2 @ctx.lineTo x + w, y - @devicePixelRatio / 2 @ctx.stroke() if @attrs.undercurl offs = [1.5, 0.8, 0.5, 0.8, 1.5, 2.2, 2.5, 2.2] # should use sp_color, but neovim does not support it @ctx.strokeStyle = @get_cur_fg_color() @ctx.lineWidth = @devicePixelRatio @ctx.beginPath() @ctx.moveTo x, y - @devicePixelRatio * offs[(x / @devicePixelRatio) % 8] for xx in [x+@devicePixelRatio..x+w] by @devicePixelRatio @ctx.lineTo xx, y - @devicePixelRatio * offs[(xx / @devicePixelRatio) % 8] @ctx.stroke() @cursor_col += chars.length nv_resize: (col, row) -> @total_col = col @total_row = row @scroll_top = 0 @scroll_bottom = @total_row - 1 @scroll_left = 0 @scroll_right = @total_col - 1 @canvas.width = @canvas_char_width * col @canvas.height = @canvas_char_height * row @canvas.style.width = @char_width * col + "px" @canvas.style.height = @char_height * row + "px" window_col = Math.floor window.innerWidth / @char_width window_row = Math.floor window.innerHeight / @char_height if col != window_col || row != window_row window.resizeTo \ @char_width * col + window.outerWidth - window.innerWidth, \ @char_height * row + window.outerHeight - window.innerHeight # adapted from neovim/python-client nv_scroll: (row_count) -> src_top = dst_top = @scroll_top src_bottom = dst_bottom = @scroll_bottom if row_count > 0 # move up src_top += row_count dst_bottom -= row_count clr_top = dst_bottom + 1 clr_bottom = src_bottom else src_bottom += row_count dst_top -= row_count clr_top = src_top clr_bottom = dst_top - 1 img = @ctx.getImageData \ @scroll_left * @canvas_char_width, \ src_top * @canvas_char_height, \ (@scroll_right - @scroll_left + 1) * @canvas_char_width, \ (src_bottom - src_top + 1) * @canvas_char_height @ctx.putImageData img, \ @scroll_left * @canvas_char_width, \ dst_top * @canvas_char_height @fill_block \ @scroll_left, \ clr_top, \ @scroll_right - @scroll_left + 1, \ clr_bottom - clr_top + 1, \ @bg_color nv_set_icon: (icon) -> remote.getCurrentWindow().setRepresentedFilename? icon.toString() nv_set_title: (title) -> title = title.toString() match = /(.*) - VIM$/.exec(title) document.title = if match? then match[1] + ' - Neovim.AS' else title nv_set_scroll_region: (top, bottom, left, right) -> @scroll_top = top @scroll_bottom = bottom @scroll_left = left @scroll_right = right nv_update_fg: (rgb) -> @cursor.style.borderColor = @fg_color = if rgb == -1 then config.fg_color else @get_color_string(rgb) nv_update_bg: (rgb) -> @bg_color = if rgb == -1 then config.bg_color else @get_color_string(rgb) module.exports = UI
[ { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n#", "end": 21, "score": 0.9977009296417236, "start": 14, "tag": "USERNAME", "value": "iTonyYo" }, { "context": "###\n# Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo)\n# Last Update ...
node_modules/node-find-folder/gulp/coffeelint.coffee
long-grass/mikey
0
### # Author: iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <ceo@holaever.com> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() extend = require 'xtend' clp = require './clp' gulp.task 'coffeelint', -> gulp.src cfg.path.dev + 'node.find.folder.coffee' .pipe $.coffeelint 'coffeelint.json' .pipe $.coffeelint.reporter() .pipe $.if clp.notify, $.notify extend cfg.notify_opts, title: 'CoffeeScript' message: cfg.message.coffeelint
17055
### # Author: iTonyYo <<EMAIL>> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <<EMAIL>> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() extend = require 'xtend' clp = require './clp' gulp.task 'coffeelint', -> gulp.src cfg.path.dev + 'node.find.folder.coffee' .pipe $.coffeelint 'coffeelint.json' .pipe $.coffeelint.reporter() .pipe $.if clp.notify, $.notify extend cfg.notify_opts, title: 'CoffeeScript' message: cfg.message.coffeelint
true
### # Author: iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) # Last Update (author): iTonyYo <PI:EMAIL:<EMAIL>END_PI> (https://github.com/iTonyYo) ### 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() extend = require 'xtend' clp = require './clp' gulp.task 'coffeelint', -> gulp.src cfg.path.dev + 'node.find.folder.coffee' .pipe $.coffeelint 'coffeelint.json' .pipe $.coffeelint.reporter() .pipe $.if clp.notify, $.notify extend cfg.notify_opts, title: 'CoffeeScript' message: cfg.message.coffeelint
[ { "context": "ssageSender'\n\n\n\n\n\n# todo\napnCrt = 'abc'\napnKey = 'abc'\ngcmKey = 'AIzaSyBBh4ddPa96rQQNxqiq_qQj7sq1JdsNQU", "end": 135, "score": 0.9974343180656433, "start": 132, "tag": "KEY", "value": "abc" }, { "context": "\n\n\n# todo\napnCrt = 'abc'\napnKey = 'abc'\ngcmKey =...
service.coffee
derhuerst/shout-dispatch
0
redis = require 'redis' async = require 'async' MessageSender = require './MessageSender' # todo apnCrt = 'abc' apnKey = 'abc' gcmKey = 'AIzaSyBBh4ddPa96rQQNxqiq_qQj7sq1JdsNQUQ' # todo: replace by own; shamelessly taken from https://simple-push-demo.appspot.com/ systems = ios: 'apn' osx: 'apn' safari: 'apn' android: 'gcm' chrome: 'gcm' windows: 'mpns' wp: 'mpns' sub = redis.createClient() client = redis.createClient() dispatcher = Object.create(MessageSender).init apnCrt, apnKey, gcmKey sub.on 'message', (channel, key) -> groupId = key.split(':')[1] tokens = apn: [] gcm: [] mpns: [] client.get key, (err, message) -> if err then return # todo: error handling message = JSON.parse(message).b # get every user in the group client.keys "u:#{groupId}:*", (err, keys) -> if err then return # todo: error handling async.eachLimit keys, 50, ((key, cb) -> # todo: use [redis transactions](http://redis.io/topics/transactions) or at least [redis pipelining](http://redis.io/topics/pipelining) client.get key, (err, user) -> if err then return # todo: error handling user = JSON.parse user tokens[systems[user.s]].push user.t cb() ), () -> dispatcher.apn tokens.apn, groupId, message dispatcher.gcm tokens.gcm, groupId, message dispatcher.mpns tokens.mpns, groupId, message sub.subscribe 'm' # `m` is for messages console.log 'Message sender running.'
144204
redis = require 'redis' async = require 'async' MessageSender = require './MessageSender' # todo apnCrt = 'abc' apnKey = '<KEY>' gcmKey = '<KEY>' # todo: replace by own; shamelessly taken from https://simple-push-demo.appspot.com/ systems = ios: 'apn' osx: 'apn' safari: 'apn' android: 'gcm' chrome: 'gcm' windows: 'mpns' wp: 'mpns' sub = redis.createClient() client = redis.createClient() dispatcher = Object.create(MessageSender).init apnCrt, apnKey, gcmKey sub.on 'message', (channel, key) -> groupId = key.split(':')[1] tokens = apn: [] gcm: [] mpns: [] client.get key, (err, message) -> if err then return # todo: error handling message = JSON.parse(message).b # get every user in the group client.keys "u:#{groupId}:*", (err, keys) -> if err then return # todo: error handling async.eachLimit keys, 50, ((key, cb) -> # todo: use [redis transactions](http://redis.io/topics/transactions) or at least [redis pipelining](http://redis.io/topics/pipelining) client.get key, (err, user) -> if err then return # todo: error handling user = JSON.parse user tokens[systems[user.s]].push user.t cb() ), () -> dispatcher.apn tokens.apn, groupId, message dispatcher.gcm tokens.gcm, groupId, message dispatcher.mpns tokens.mpns, groupId, message sub.subscribe 'm' # `m` is for messages console.log 'Message sender running.'
true
redis = require 'redis' async = require 'async' MessageSender = require './MessageSender' # todo apnCrt = 'abc' apnKey = 'PI:KEY:<KEY>END_PI' gcmKey = 'PI:KEY:<KEY>END_PI' # todo: replace by own; shamelessly taken from https://simple-push-demo.appspot.com/ systems = ios: 'apn' osx: 'apn' safari: 'apn' android: 'gcm' chrome: 'gcm' windows: 'mpns' wp: 'mpns' sub = redis.createClient() client = redis.createClient() dispatcher = Object.create(MessageSender).init apnCrt, apnKey, gcmKey sub.on 'message', (channel, key) -> groupId = key.split(':')[1] tokens = apn: [] gcm: [] mpns: [] client.get key, (err, message) -> if err then return # todo: error handling message = JSON.parse(message).b # get every user in the group client.keys "u:#{groupId}:*", (err, keys) -> if err then return # todo: error handling async.eachLimit keys, 50, ((key, cb) -> # todo: use [redis transactions](http://redis.io/topics/transactions) or at least [redis pipelining](http://redis.io/topics/pipelining) client.get key, (err, user) -> if err then return # todo: error handling user = JSON.parse user tokens[systems[user.s]].push user.t cb() ), () -> dispatcher.apn tokens.apn, groupId, message dispatcher.gcm tokens.gcm, groupId, message dispatcher.mpns tokens.mpns, groupId, message sub.subscribe 'm' # `m` is for messages console.log 'Message sender running.'
[ { "context": "##\n * Federated Wiki : Node Server\n *\n * Copyright Ward Cunningham and other contributors\n * Licensed under the MIT ", "end": 67, "score": 0.9998744130134583, "start": 52, "tag": "NAME", "value": "Ward Cunningham" }, { "context": "nsed under the MIT license.\n * htt...
cli.coffee
rajivchugh/wiki
1
### * Federated Wiki : Node Server * * Copyright Ward Cunningham and other contributors * Licensed under the MIT license. * https://github.com/fedwiki/wiki/blob/master/LICENSE.txt ### # **cli.coffee** command line interface for the # Smallest-Federated-Wiki express server path = require 'path' optimist = require 'optimist' cc = require 'config-chain' glob = require 'glob' server = require 'wiki-server' farm = require './farm' getUserHome = -> process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE # Handle command line options argv = optimist .usage('Usage: $0') .options('url', alias : 'u' describe : 'Important: Your server URL, used as Persona audience during verification' ) .options('port', alias : 'p' describe : 'Port' ) .options('data', alias : 'd' describe : 'location of flat file data' ) .options('root', alias : 'r' describe : 'Application root folder' ) .options('farm', alias : 'f' describe : 'Turn on the farm?' ) .options('admin', describe : 'Wiki server administrator identity' ) .options('home', describe : 'The page to go to instead of index.html' ) .options('host', alias : 'o' describe : 'Host to accept connections on, falsy == any' ) .options('security_type', describe : 'The security plugin to use, see documentation for additional parameters' ) .options('secure_cookie', describe : 'When true, session cookie will only be sent over SSL.' boolean : false ) .options('session_duration', describe : 'The wiki logon, session, duration in days' ) .options('id', describe : 'Set the location of the owner identity file' ) .options('database', describe : 'JSON object for database config' ) .options('neighbors', describe : 'comma separated list of neighbor sites to seed' ) .options('autoseed', describe : 'Seed all sites in a farm to each other site in the farm.' boolean : true ) .options('allowed', describe : 'comma separated list of allowed host names for farm mode.' ) .options('wikiDomains', describe : 'use in farm mode to define allowed wiki domains and any wiki domain specific configuration, see documentation.' ) .options('uploadLimit', describe : 'Set the upload size limit, limits the size page content items, and pages that can be forked' ) .options('test', boolean : true describe : 'Set server to work with the rspec integration tests' ) .options('help', alias : 'h' boolean : true describe : 'Show this help info and exit' ) .options('config', alias : 'conf' describe : 'Optional config file.' ) .options('version', alias : 'v' describe : 'Show version number and exit' ) .argv config = cc(argv, argv.config, 'config.json', path.join(__dirname, '..', 'config.json'), path.join(getUserHome(), '.wiki', 'config.json'), cc.env('wiki_'), port: 3000 root: path.dirname(require.resolve('wiki-server')) home: 'welcome-visitors' security_type: './security' data: path.join(getUserHome(), '.wiki') # see also defaultargs packageDir: path.resolve(path.join(__dirname, 'node_modules')) cookieSecret: require('crypto').randomBytes(64).toString('hex') ).store # If h/help is set print the generated help message and exit. if argv.help optimist.showHelp() # If v/version is set print the version of the wiki components and exit. else if argv.version console.log('wiki: ' + require('./package').version) console.log('wiki-server: ' + require('wiki-server/package').version) console.log('wiki-client: ' + require('wiki-client/package').version) glob 'wiki-security-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ": " + require(plugin + "/package").version) glob 'wiki-plugin-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ': ' + require(plugin + '/package').version) else if argv.test console.log "WARNING: Server started in testing mode, other options ignored" server({port: 33333, data: path.join(argv.root, 'spec', 'data')}) # If f/farm is set call../lib/farm.coffee with argv object, else call # ../lib/server.coffee with argv object. else if config.farm console.log('Wiki starting in Farm mode, navigate to a specific server to start it.\n') if !argv.wikiDomains and !argv.allowed console.log 'WARNING : Starting Wiki Farm in promiscous mode\n' if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki Farm will be read-only\n' farm(config) else app = server(config) app.on 'owner-set', (e) -> serv = app.listen app.startOpts.port, app.startOpts.host console.log "Federated Wiki server listening on", app.startOpts.port, "in mode:", app.settings.env if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki will be read-only\n' app.emit 'running-serv', serv
207118
### * Federated Wiki : Node Server * * Copyright <NAME> and other contributors * Licensed under the MIT license. * https://github.com/fedwiki/wiki/blob/master/LICENSE.txt ### # **cli.coffee** command line interface for the # Smallest-Federated-Wiki express server path = require 'path' optimist = require 'optimist' cc = require 'config-chain' glob = require 'glob' server = require 'wiki-server' farm = require './farm' getUserHome = -> process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE # Handle command line options argv = optimist .usage('Usage: $0') .options('url', alias : 'u' describe : 'Important: Your server URL, used as Persona audience during verification' ) .options('port', alias : 'p' describe : 'Port' ) .options('data', alias : 'd' describe : 'location of flat file data' ) .options('root', alias : 'r' describe : 'Application root folder' ) .options('farm', alias : 'f' describe : 'Turn on the farm?' ) .options('admin', describe : 'Wiki server administrator identity' ) .options('home', describe : 'The page to go to instead of index.html' ) .options('host', alias : 'o' describe : 'Host to accept connections on, falsy == any' ) .options('security_type', describe : 'The security plugin to use, see documentation for additional parameters' ) .options('secure_cookie', describe : 'When true, session cookie will only be sent over SSL.' boolean : false ) .options('session_duration', describe : 'The wiki logon, session, duration in days' ) .options('id', describe : 'Set the location of the owner identity file' ) .options('database', describe : 'JSON object for database config' ) .options('neighbors', describe : 'comma separated list of neighbor sites to seed' ) .options('autoseed', describe : 'Seed all sites in a farm to each other site in the farm.' boolean : true ) .options('allowed', describe : 'comma separated list of allowed host names for farm mode.' ) .options('wikiDomains', describe : 'use in farm mode to define allowed wiki domains and any wiki domain specific configuration, see documentation.' ) .options('uploadLimit', describe : 'Set the upload size limit, limits the size page content items, and pages that can be forked' ) .options('test', boolean : true describe : 'Set server to work with the rspec integration tests' ) .options('help', alias : 'h' boolean : true describe : 'Show this help info and exit' ) .options('config', alias : 'conf' describe : 'Optional config file.' ) .options('version', alias : 'v' describe : 'Show version number and exit' ) .argv config = cc(argv, argv.config, 'config.json', path.join(__dirname, '..', 'config.json'), path.join(getUserHome(), '.wiki', 'config.json'), cc.env('wiki_'), port: 3000 root: path.dirname(require.resolve('wiki-server')) home: 'welcome-visitors' security_type: './security' data: path.join(getUserHome(), '.wiki') # see also defaultargs packageDir: path.resolve(path.join(__dirname, 'node_modules')) cookieSecret: require('crypto').randomBytes(64).toString('hex') ).store # If h/help is set print the generated help message and exit. if argv.help optimist.showHelp() # If v/version is set print the version of the wiki components and exit. else if argv.version console.log('wiki: ' + require('./package').version) console.log('wiki-server: ' + require('wiki-server/package').version) console.log('wiki-client: ' + require('wiki-client/package').version) glob 'wiki-security-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ": " + require(plugin + "/package").version) glob 'wiki-plugin-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ': ' + require(plugin + '/package').version) else if argv.test console.log "WARNING: Server started in testing mode, other options ignored" server({port: 33333, data: path.join(argv.root, 'spec', 'data')}) # If f/farm is set call../lib/farm.coffee with argv object, else call # ../lib/server.coffee with argv object. else if config.farm console.log('Wiki starting in Farm mode, navigate to a specific server to start it.\n') if !argv.wikiDomains and !argv.allowed console.log 'WARNING : Starting Wiki Farm in promiscous mode\n' if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki Farm will be read-only\n' farm(config) else app = server(config) app.on 'owner-set', (e) -> serv = app.listen app.startOpts.port, app.startOpts.host console.log "Federated Wiki server listening on", app.startOpts.port, "in mode:", app.settings.env if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki will be read-only\n' app.emit 'running-serv', serv
true
### * Federated Wiki : Node Server * * Copyright PI:NAME:<NAME>END_PI and other contributors * Licensed under the MIT license. * https://github.com/fedwiki/wiki/blob/master/LICENSE.txt ### # **cli.coffee** command line interface for the # Smallest-Federated-Wiki express server path = require 'path' optimist = require 'optimist' cc = require 'config-chain' glob = require 'glob' server = require 'wiki-server' farm = require './farm' getUserHome = -> process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE # Handle command line options argv = optimist .usage('Usage: $0') .options('url', alias : 'u' describe : 'Important: Your server URL, used as Persona audience during verification' ) .options('port', alias : 'p' describe : 'Port' ) .options('data', alias : 'd' describe : 'location of flat file data' ) .options('root', alias : 'r' describe : 'Application root folder' ) .options('farm', alias : 'f' describe : 'Turn on the farm?' ) .options('admin', describe : 'Wiki server administrator identity' ) .options('home', describe : 'The page to go to instead of index.html' ) .options('host', alias : 'o' describe : 'Host to accept connections on, falsy == any' ) .options('security_type', describe : 'The security plugin to use, see documentation for additional parameters' ) .options('secure_cookie', describe : 'When true, session cookie will only be sent over SSL.' boolean : false ) .options('session_duration', describe : 'The wiki logon, session, duration in days' ) .options('id', describe : 'Set the location of the owner identity file' ) .options('database', describe : 'JSON object for database config' ) .options('neighbors', describe : 'comma separated list of neighbor sites to seed' ) .options('autoseed', describe : 'Seed all sites in a farm to each other site in the farm.' boolean : true ) .options('allowed', describe : 'comma separated list of allowed host names for farm mode.' ) .options('wikiDomains', describe : 'use in farm mode to define allowed wiki domains and any wiki domain specific configuration, see documentation.' ) .options('uploadLimit', describe : 'Set the upload size limit, limits the size page content items, and pages that can be forked' ) .options('test', boolean : true describe : 'Set server to work with the rspec integration tests' ) .options('help', alias : 'h' boolean : true describe : 'Show this help info and exit' ) .options('config', alias : 'conf' describe : 'Optional config file.' ) .options('version', alias : 'v' describe : 'Show version number and exit' ) .argv config = cc(argv, argv.config, 'config.json', path.join(__dirname, '..', 'config.json'), path.join(getUserHome(), '.wiki', 'config.json'), cc.env('wiki_'), port: 3000 root: path.dirname(require.resolve('wiki-server')) home: 'welcome-visitors' security_type: './security' data: path.join(getUserHome(), '.wiki') # see also defaultargs packageDir: path.resolve(path.join(__dirname, 'node_modules')) cookieSecret: require('crypto').randomBytes(64).toString('hex') ).store # If h/help is set print the generated help message and exit. if argv.help optimist.showHelp() # If v/version is set print the version of the wiki components and exit. else if argv.version console.log('wiki: ' + require('./package').version) console.log('wiki-server: ' + require('wiki-server/package').version) console.log('wiki-client: ' + require('wiki-client/package').version) glob 'wiki-security-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ": " + require(plugin + "/package").version) glob 'wiki-plugin-*', {cwd: config.packageDir}, (e, plugins) -> plugins.map (plugin) -> console.log(plugin + ': ' + require(plugin + '/package').version) else if argv.test console.log "WARNING: Server started in testing mode, other options ignored" server({port: 33333, data: path.join(argv.root, 'spec', 'data')}) # If f/farm is set call../lib/farm.coffee with argv object, else call # ../lib/server.coffee with argv object. else if config.farm console.log('Wiki starting in Farm mode, navigate to a specific server to start it.\n') if !argv.wikiDomains and !argv.allowed console.log 'WARNING : Starting Wiki Farm in promiscous mode\n' if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki Farm will be read-only\n' farm(config) else app = server(config) app.on 'owner-set', (e) -> serv = app.listen app.startOpts.port, app.startOpts.host console.log "Federated Wiki server listening on", app.startOpts.port, "in mode:", app.settings.env if argv.security_type is './security' console.log 'INFORMATION : Using default security - Wiki will be read-only\n' app.emit 'running-serv', serv
[ { "context": "pattern: \"http*://www.facebook.com/*\", passKeys: \"abab\" }\n { pattern: \"http*://www.facebook.com/*", "end": 1128, "score": 0.9907262325286865, "start": 1124, "tag": "KEY", "value": "abab" }, { "context": "pattern: \"http*://www.facebook.com/*\", passKeys: \"...
tests/unit_tests/exclusion_test.coffee
liudonghua123/vimium
16
require "./test_helper.js" extend global, require "./test_chrome_stubs.js" # FIXME: # Would like to do: # extend(global, require "../../background_scripts/marks.js") # But it looks like marks.coffee has never been included in a test before! # Temporary fix... root.Marks = create: () -> true goto: bind: () -> true extend(global, require "../../lib/utils.js") Utils.getCurrentVersion = -> '1.44' extend(global,require "../../lib/settings.js") extend(global,require "../../lib/clipboard.js") extend(global, require "../../background_scripts/bg_utils.js") extend(global, require "../../background_scripts/exclusions.js") extend(global, require "../../background_scripts/commands.js") extend(global, require "../../background_scripts/main.js") isEnabledForUrl = (request) -> Exclusions.isEnabledForUrl request.url # These tests cover only the most basic aspects of excluded URLs and passKeys. # context "Excluded URLs and pass keys", setup -> Settings.set "exclusionRules", [ { pattern: "http*://mail.google.com/*", passKeys: "" } { pattern: "http*://www.facebook.com/*", passKeys: "abab" } { pattern: "http*://www.facebook.com/*", passKeys: "cdcd" } { pattern: "http*://www.bbc.com/*", passKeys: "" } { pattern: "http*://www.bbc.com/*", passKeys: "ab" } { pattern: "http*://www.example.com/*", passKeys: "a bb c bba a" } { pattern: "http*://www.duplicate.com/*", passKeys: "ace" } { pattern: "http*://www.duplicate.com/*", passKeys: "bdf" } ] Exclusions.postUpdateHook() should "be disabled for excluded sites", -> rule = isEnabledForUrl({ url: 'http://mail.google.com/calendar/page' }) assert.isFalse rule.isEnabledForUrl assert.isFalse rule.passKeys should "be disabled for excluded sites, one exclusion", -> rule = isEnabledForUrl({ url: 'http://www.bbc.com/calendar/page' }) assert.isFalse rule.isEnabledForUrl assert.isFalse rule.passKeys should "be enabled, but with pass keys", -> rule = isEnabledForUrl({ url: 'https://www.facebook.com/something' }) assert.isTrue rule.isEnabledForUrl assert.equal rule.passKeys, 'abcd' should "be enabled", -> rule = isEnabledForUrl({ url: 'http://www.twitter.com/pages' }) assert.isTrue rule.isEnabledForUrl assert.isFalse rule.passKeys should "handle spaces and duplicates in passkeys", -> rule = isEnabledForUrl({ url: 'http://www.example.com/pages' }) assert.isTrue rule.isEnabledForUrl assert.equal "abc", rule.passKeys should "handle multiple passkeys rules", -> rule = isEnabledForUrl({ url: 'http://www.duplicate.com/pages' }) assert.isTrue rule.isEnabledForUrl assert.equal "abcdef", rule.passKeys should "be enabled for malformed regular expressions", -> Exclusions.postUpdateHook [ { pattern: "http*://www.bad-regexp.com/*[a-", passKeys: "" } ] rule = isEnabledForUrl({ url: 'http://www.bad-regexp.com/pages' }) assert.isTrue rule.isEnabledForUrl
98423
require "./test_helper.js" extend global, require "./test_chrome_stubs.js" # FIXME: # Would like to do: # extend(global, require "../../background_scripts/marks.js") # But it looks like marks.coffee has never been included in a test before! # Temporary fix... root.Marks = create: () -> true goto: bind: () -> true extend(global, require "../../lib/utils.js") Utils.getCurrentVersion = -> '1.44' extend(global,require "../../lib/settings.js") extend(global,require "../../lib/clipboard.js") extend(global, require "../../background_scripts/bg_utils.js") extend(global, require "../../background_scripts/exclusions.js") extend(global, require "../../background_scripts/commands.js") extend(global, require "../../background_scripts/main.js") isEnabledForUrl = (request) -> Exclusions.isEnabledForUrl request.url # These tests cover only the most basic aspects of excluded URLs and passKeys. # context "Excluded URLs and pass keys", setup -> Settings.set "exclusionRules", [ { pattern: "http*://mail.google.com/*", passKeys: "" } { pattern: "http*://www.facebook.com/*", passKeys: "<KEY>" } { pattern: "http*://www.facebook.com/*", passKeys: "<KEY>" } { pattern: "http*://www.bbc.com/*", passKeys: "" } { pattern: "http*://www.bbc.com/*", passKeys: "<KEY>" } { pattern: "http*://www.example.com/*", passKeys: "<KEY>" } { pattern: "http*://www.duplicate.com/*", passKeys: "<KEY>" } { pattern: "http*://www.duplicate.com/*", passKeys: "<KEY>" } ] Exclusions.postUpdateHook() should "be disabled for excluded sites", -> rule = isEnabledForUrl({ url: 'http://mail.google.com/calendar/page' }) assert.isFalse rule.isEnabledForUrl assert.isFalse rule.passKeys should "be disabled for excluded sites, one exclusion", -> rule = isEnabledForUrl({ url: 'http://www.bbc.com/calendar/page' }) assert.isFalse rule.isEnabledForUrl assert.isFalse rule.passKeys should "be enabled, but with pass keys", -> rule = isEnabledForUrl({ url: 'https://www.facebook.com/something' }) assert.isTrue rule.isEnabledForUrl assert.equal rule.passKeys, 'abcd' should "be enabled", -> rule = isEnabledForUrl({ url: 'http://www.twitter.com/pages' }) assert.isTrue rule.isEnabledForUrl assert.isFalse rule.passKeys should "handle spaces and duplicates in passkeys", -> rule = isEnabledForUrl({ url: 'http://www.example.com/pages' }) assert.isTrue rule.isEnabledForUrl assert.equal "abc", rule.passKeys should "handle multiple passkeys rules", -> rule = isEnabledForUrl({ url: 'http://www.duplicate.com/pages' }) assert.isTrue rule.isEnabledForUrl assert.equal "abcdef", rule.passKeys should "be enabled for malformed regular expressions", -> Exclusions.postUpdateHook [ { pattern: "http*://www.bad-regexp.com/*[a-", passKeys: "" } ] rule = isEnabledForUrl({ url: 'http://www.bad-regexp.com/pages' }) assert.isTrue rule.isEnabledForUrl
true
require "./test_helper.js" extend global, require "./test_chrome_stubs.js" # FIXME: # Would like to do: # extend(global, require "../../background_scripts/marks.js") # But it looks like marks.coffee has never been included in a test before! # Temporary fix... root.Marks = create: () -> true goto: bind: () -> true extend(global, require "../../lib/utils.js") Utils.getCurrentVersion = -> '1.44' extend(global,require "../../lib/settings.js") extend(global,require "../../lib/clipboard.js") extend(global, require "../../background_scripts/bg_utils.js") extend(global, require "../../background_scripts/exclusions.js") extend(global, require "../../background_scripts/commands.js") extend(global, require "../../background_scripts/main.js") isEnabledForUrl = (request) -> Exclusions.isEnabledForUrl request.url # These tests cover only the most basic aspects of excluded URLs and passKeys. # context "Excluded URLs and pass keys", setup -> Settings.set "exclusionRules", [ { pattern: "http*://mail.google.com/*", passKeys: "" } { pattern: "http*://www.facebook.com/*", passKeys: "PI:KEY:<KEY>END_PI" } { pattern: "http*://www.facebook.com/*", passKeys: "PI:KEY:<KEY>END_PI" } { pattern: "http*://www.bbc.com/*", passKeys: "" } { pattern: "http*://www.bbc.com/*", passKeys: "PI:KEY:<KEY>END_PI" } { pattern: "http*://www.example.com/*", passKeys: "PI:KEY:<KEY>END_PI" } { pattern: "http*://www.duplicate.com/*", passKeys: "PI:KEY:<KEY>END_PI" } { pattern: "http*://www.duplicate.com/*", passKeys: "PI:KEY:<KEY>END_PI" } ] Exclusions.postUpdateHook() should "be disabled for excluded sites", -> rule = isEnabledForUrl({ url: 'http://mail.google.com/calendar/page' }) assert.isFalse rule.isEnabledForUrl assert.isFalse rule.passKeys should "be disabled for excluded sites, one exclusion", -> rule = isEnabledForUrl({ url: 'http://www.bbc.com/calendar/page' }) assert.isFalse rule.isEnabledForUrl assert.isFalse rule.passKeys should "be enabled, but with pass keys", -> rule = isEnabledForUrl({ url: 'https://www.facebook.com/something' }) assert.isTrue rule.isEnabledForUrl assert.equal rule.passKeys, 'abcd' should "be enabled", -> rule = isEnabledForUrl({ url: 'http://www.twitter.com/pages' }) assert.isTrue rule.isEnabledForUrl assert.isFalse rule.passKeys should "handle spaces and duplicates in passkeys", -> rule = isEnabledForUrl({ url: 'http://www.example.com/pages' }) assert.isTrue rule.isEnabledForUrl assert.equal "abc", rule.passKeys should "handle multiple passkeys rules", -> rule = isEnabledForUrl({ url: 'http://www.duplicate.com/pages' }) assert.isTrue rule.isEnabledForUrl assert.equal "abcdef", rule.passKeys should "be enabled for malformed regular expressions", -> Exclusions.postUpdateHook [ { pattern: "http*://www.bad-regexp.com/*[a-", passKeys: "" } ] rule = isEnabledForUrl({ url: 'http://www.bad-regexp.com/pages' }) assert.isTrue rule.isEnabledForUrl
[ { "context": "###\n * @author Robert Kolatzek\n * @version 1.0\n * The MIT License (MIT)\n *\n ", "end": 30, "score": 0.9998663067817688, "start": 15, "tag": "NAME", "value": "Robert Kolatzek" }, { "context": "he MIT License (MIT)\n *\n * Copyright (c) 2015 Dr. Robert Kolatzek\n...
src/GND.coffee
SULB/GNDcoffeine
0
### * @author Robert Kolatzek * @version 1.0 * The MIT License (MIT) * * Copyright (c) 2015 Dr. Robert Kolatzek * * 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. ### $=jQuery gndData = {} gndXhr = {} gndXhrType = 'exact' _SEPARATOR_ = ',' $ -> imFeld = $.trim($(swdId).val()) wortArr = imFeld.split("#{_SEPARATOR_}") for i in wortArr if $.trim(i) != "" str = coffeePrintf([ schlagwortSpanselected { schlagwort: $.trim(i.replace("<", "&lt;").replace("\"", "&quote;")) 'swdWortClass': swdWortClass } ]...) $(swdDivSammlungId).append $(str) $(".#{swdWortClass}").unbind 'click' $(".#{swdWortClass}").bind 'click', removeGngItem $(swdErsatzNachrichtId).empty() $(gndFormHtml).insertAfter gndDivInsertAfterId $(gndDivInsertAfterId).append $("<input type='text' id='#{swdId.replace('#', '')}' name='#{swdId.replace('#', '')}'/>") if exactSearchId.length > 0 $(exactSearchId).bind 'click',exactSearch $("<br/><div id='swd_div_sammlung'>#{schlagwortUebernehmen}</div>").insertAfter insertswdCollectionAfterId $(swdId).val appendSwdItem(swdId, '') $(xgndSearchFormId).fadeIn('slow') $("form#{xgndSearchFormId}").unbind('submit').bind 'submit',exactSearch $(partSearchButtonId).unbind('click').bind 'click',searchGND if typeof window.onpopstate != "undefined" window.onpopstate = (event) -> GNDcoffeineState = event.state if typeof GNDcoffeineState['swdsuche'] != 'undefined' $(suchwortId).val GNDcoffeineState['swdsuche'] $('html, body').animate {scrollTop: $(xgndSearchFormId).offset().top}, 100 searchGND() true true searchGND =-> try event.preventDefault() gndData = {} $(gndsDiv).html bitteWarten gndXhrType = 'part' ajaxGnd "pica.sw", $(suchwortId).val(), "pica.tbs=\"s\"", "listGndTypes", gndTimeoutWarning false listGndTypes = (txt) -> # dummy-Aufruf, damit die Daten der Funktion zur Verfügung stehen... #console.log(txt) window.clearTimeout window.gndLoadTimeout $(gndsDiv).empty() if gndXhrType == 'exact' $(gndsDiv).html exactSearchResultMsg else if gndXhrType == 'part' $(gndsDiv).html fuzzySearchResultMsg if typeof window.history.pushState != "undefined" document.title = "#{document.title.split('| ' + documentHistoryItem)[0]} | #{documentHistoryItem} #{$(suchwortId).val()}" history.pushState {swdsuche: $(suchwortId).val()}, "#{documentHistoryItem} #{$(suchwortId).val()}", "#"+encodeURIComponent($(suchwortId).val()) $(xgndSearchFormId).css('cursor','default') if txt txt.forEach (n) -> typ = n.Typ if not gndData[typ] gndData[typ] = [n] else gndData[typ] = gndData[typ].concat n for typ, i of gndData elems = {} for i, elem of gndData[typ] elems[elem.Ansetzung] = elem gndData[typ] = elems for typ, i of gndData str = coffeePrintf( [ zeigeListeDerGruppeTyp { "typ": typ } ]... ) $(gndsDiv).append $("<fieldset class='gnd_typ' data-typ='#{typ}' id='fieldset_#{typ}'><legend><a href='#' title='#{str}'>#{typ} (#{Object.keys(i).length})</a></legend></fieldset>") $('.gnd_typ a').unbind 'click' $('.gnd_typ a').bind 'click', openGndType if gndXhrType == 'exact' $("#fieldset_#{typ} a").click() else $(gndsDiv).append $(emptyResultWarning) false openGndType =-> typ = $(this).parent().parent().data 'typ' $("#fieldset_#{typ}").css 'cursor','wait' if typeof $(this).data('closed') is "undefined" or $(this).data('closed') is true $(this).data 'closed', false $(this).parent().parent().append $("<ul id='gnd_list_#{typ}' class='gnd_list'></ul>") if gndData[typ] gndSortedType = (k for k of gndData[typ]) gndSortedType.sort() gndSortedTypeObjects = {} for i,obj of gndData[typ] gndSortedTypeObjects[obj.Ansetzung] = obj for k in gndSortedType obj = gndSortedTypeObjects[k] $("#gnd_list_#{typ}").append $("<li id='gnd_list_item_#{obj.PPN}' data-gndppn='#{obj.PPN}' data-gndwort='#{obj.Ansetzung}' class='gnd_list_item'><a href='#' class='takeGndItem' title='#{schlagwortInFundListe}'>#{obj.Ansetzung}</a> <a href='#' class='getItemInfo' title='#{detailsHinweis}'>#{Details}</a> </li>") $('.gnd_list_item a').unbind 'click' $('.gnd_list_item a.takeGndItem').bind 'click', takeGndItem $('.gnd_list_item a.getItemInfo').bind 'click', getItemInfo else $(this).data 'closed', true $("#gnd_list_#{typ}").remove() $("#fieldset_#{typ}").css 'cursor','default' false takeGndItem =-> wort = $(this).parent().data('gndwort') imFeld = $.trim($(swdId).val()) wortArr = imFeld.split("#{_SEPARATOR_}") for i in wortArr if $.trim(wort) == $.trim(i) return false $(swdId).val appendSwdItem(swdId, wort) str = coffeePrintf( [ schlagwortSpanselected { schlagwort: wort.replace('<', '&lt;').replace("\"", "&quote;") 'swdWortClass': swdWortClass } ]... ) $(swdDivSammlungId).append $(str) $(".#{swdWortClass}").unbind 'click' $(".#{swdWortClass}").bind 'click', removeGngItem false getItemInfo = (event) -> try event.preventDefault() ppn = $(this).parent().data 'gndppn' if typeof $(this).data('closed') is 'undefined' or $(this).data('closed') == 1 $(this).data 'closed', 0 ajaxGnd "pica.ppn", ppn, encodeURIComponent('pica.tbs="s" and '), "zeigeRecord", infoGndTimeout else $(this).data 'closed', 1 $("#gnd_list_item_info_#{ppn}").remove() false removeGngItem =-> wort = $(this).data 'wort' swdArr = $(swdId).val().split " #{_SEPARATOR_} " swdNewArr = [] for w in swdArr if w not in swdNewArr and $.trim(w) != $.trim(wort) r = new RegExp("$\s*#{_SEPARATOR_}\s*$","g") swdNewArr.push $.trim(w).replace(r, '') swds = swdNewArr.join(" #{_SEPARATOR_} ") $(swdId).val(swds) $(this).remove() emptySwdList =-> $(swdId).val('') $(swdDivSammlungId).empty() zeigeRecord = (txt) -> window.clearTimeout window.gndLoadTimeout $(xgndSearchFormId).css 'cursor','default' $("#gnd_list_item_#{txt[0].PPN}").append $("<div id='gnd_list_item_info_#{txt[0].PPN}' class='gnd_list_item_info'></div>") str1 = coffeePrintf( [ detailsFuerSchlagwort { schlagwort: txt[0].Ansetzung } ]... ) tabelle = $("<table class='gnd_list_item_info_table'><caption>#{str1}</caption><thead><tr><td>#{Typ}</td><td>#{Inhalt}</td></tr></thead><tbody></tbody></table>") $("#gnd_list_item_info_#{txt[0].PPN}").append tabelle for n, v of txt[0] if n is 'Verweise' and typeof v != 'undefined' and v.length > 0 verweiseliste = $("<tr></tr>") verweiseliste.append "<td>#{n}</td>" liste = '' for i in v if i.feldname != "" liste += " <b>#{i.feldname}</b>: " if typeof i.ppn != 'undefined' liste += "<i><a href='#' class='item_link' data-ppn='#{i.ppn}'>#{i.linkname}</a></i><br>" else liste += "<i>#{i.linkname}</i><br>" verweiseliste.append($("<td>#{liste}</td>")) $("#gnd_list_item_info_#{txt[0].PPN} > table > tbody ").append verweiseliste $('.item_link').unbind 'click' $('.item_link').bind 'click', searchGndItemById else if n == 'Synonyme' and v != null and v.length > 0 $("#gnd_list_item_info_#{txt[0].PPN} > table > tbody ").append $("<tr><td>#{n}</td><td>#{v.join('; ')}</td></tr>") else if n != 'Typ' and n != 'Ansetzung' and n != 'PPN' and v != null and v.length > 0 $("#gnd_list_item_info_#{txt[0].PPN} > table > tbody ").append $("<tr><td>#{n}</td><td>#{v}</td></tr>") searchGndItemById =-> $(suchwortId).val $(this).text() $('html, body').animate {scrollTop: $(xgndSearchFormId).offset().top}, 100 gndData = {} ppn = $(this).data 'ppn' $(gndsDiv).html bitteWarten gndXhrType = 'exact' ajaxGnd "pica.ppn", ppn, encodeURIComponent('pica.tbs="s" and '), "listGndTypes", gndTimeoutWarning false exactSearch = -> try event.preventDefault() gndData = {} $(gndsDiv).html bitteWarten gndXhrType = 'exact' ajaxGnd "pica.swr", $(suchwortId).val(), 'pica.tbs="s"', "listGndTypes", gndTimeoutWarning false searchGndTimeout = ( jqXHR, textStatus, errorThrown )-> $(gndsDiv).html dataErrorWarning gndTimeoutWarning =-> $(gndsDiv).html timeoutWarning infoGndTimeout =-> $(this).append $("#{timeoutWarning}") ajaxGnd = (searchtype, suchwort, suchoptionen, callbackFunction, gndTimeoutWarningFunction)-> $(xgndSearchFormId).css 'cursor','wait' gndXhr = $.ajax({"url": 'https://xgnd.bsz-bw.de/Anfrage', "data": {"suchfeld": searchtype, "suchwort": encodeURIComponent(suchwort) ,"suchfilter": "000000", suchoptionen, "jsonpCallback": callbackFunction}, "dataType": "jsonp", "jsonpCallback": callbackFunction, "timeout": gndSearchTimeout, "error": "searchGndTimeout" }) window.gndLoadTimeout = window.setTimeout gndTimeoutWarningFunction, gndSearchTimeout coffeePrintf = (string, values) -> for r in string.match /#\{([^\}]+)\}/ig string = string.replace r, "#{values[r.replace('#{', '').replace('}', '')]}" string appendSwdItem = (swdId, item) -> swdlist = $.trim $(swdId).val() swdArr = swdlist.split(" #{_SEPARATOR_} ") swdNewArr = [] for w in swdArr if $.trim(w) not in swdNewArr and $.trim(w) != '' swdNewArr.push w if $.trim(item) != '' and item not in swdNewArr swdNewArr.push item swdNewArr.join(" #{_SEPARATOR_} ")
3133
### * @author <NAME> * @version 1.0 * The MIT License (MIT) * * Copyright (c) 2015 Dr. <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ### $=jQuery gndData = {} gndXhr = {} gndXhrType = 'exact' _SEPARATOR_ = ',' $ -> imFeld = $.trim($(swdId).val()) wortArr = imFeld.split("#{_SEPARATOR_}") for i in wortArr if $.trim(i) != "" str = coffeePrintf([ schlagwortSpanselected { schlagwort: $.trim(i.replace("<", "&lt;").replace("\"", "&quote;")) 'swdWortClass': swdWortClass } ]...) $(swdDivSammlungId).append $(str) $(".#{swdWortClass}").unbind 'click' $(".#{swdWortClass}").bind 'click', removeGngItem $(swdErsatzNachrichtId).empty() $(gndFormHtml).insertAfter gndDivInsertAfterId $(gndDivInsertAfterId).append $("<input type='text' id='#{swdId.replace('#', '')}' name='#{swdId.replace('#', '')}'/>") if exactSearchId.length > 0 $(exactSearchId).bind 'click',exactSearch $("<br/><div id='swd_div_sammlung'>#{schlagwortUebernehmen}</div>").insertAfter insertswdCollectionAfterId $(swdId).val appendSwdItem(swdId, '') $(xgndSearchFormId).fadeIn('slow') $("form#{xgndSearchFormId}").unbind('submit').bind 'submit',exactSearch $(partSearchButtonId).unbind('click').bind 'click',searchGND if typeof window.onpopstate != "undefined" window.onpopstate = (event) -> GNDcoffeineState = event.state if typeof GNDcoffeineState['swdsuche'] != 'undefined' $(suchwortId).val GNDcoffeineState['swdsuche'] $('html, body').animate {scrollTop: $(xgndSearchFormId).offset().top}, 100 searchGND() true true searchGND =-> try event.preventDefault() gndData = {} $(gndsDiv).html bitteWarten gndXhrType = 'part' ajaxGnd "pica.sw", $(suchwortId).val(), "pica.tbs=\"s\"", "listGndTypes", gndTimeoutWarning false listGndTypes = (txt) -> # dummy-Aufruf, damit die Daten der Funktion zur Verfügung stehen... #console.log(txt) window.clearTimeout window.gndLoadTimeout $(gndsDiv).empty() if gndXhrType == 'exact' $(gndsDiv).html exactSearchResultMsg else if gndXhrType == 'part' $(gndsDiv).html fuzzySearchResultMsg if typeof window.history.pushState != "undefined" document.title = "#{document.title.split('| ' + documentHistoryItem)[0]} | #{documentHistoryItem} #{$(suchwortId).val()}" history.pushState {swdsuche: $(suchwortId).val()}, "#{documentHistoryItem} #{$(suchwortId).val()}", "#"+encodeURIComponent($(suchwortId).val()) $(xgndSearchFormId).css('cursor','default') if txt txt.forEach (n) -> typ = n.Typ if not gndData[typ] gndData[typ] = [n] else gndData[typ] = gndData[typ].concat n for typ, i of gndData elems = {} for i, elem of gndData[typ] elems[elem.Ansetzung] = elem gndData[typ] = elems for typ, i of gndData str = coffeePrintf( [ zeigeListeDerGruppeTyp { "typ": typ } ]... ) $(gndsDiv).append $("<fieldset class='gnd_typ' data-typ='#{typ}' id='fieldset_#{typ}'><legend><a href='#' title='#{str}'>#{typ} (#{Object.keys(i).length})</a></legend></fieldset>") $('.gnd_typ a').unbind 'click' $('.gnd_typ a').bind 'click', openGndType if gndXhrType == 'exact' $("#fieldset_#{typ} a").click() else $(gndsDiv).append $(emptyResultWarning) false openGndType =-> typ = $(this).parent().parent().data 'typ' $("#fieldset_#{typ}").css 'cursor','wait' if typeof $(this).data('closed') is "undefined" or $(this).data('closed') is true $(this).data 'closed', false $(this).parent().parent().append $("<ul id='gnd_list_#{typ}' class='gnd_list'></ul>") if gndData[typ] gndSortedType = (k for k of gndData[typ]) gndSortedType.sort() gndSortedTypeObjects = {} for i,obj of gndData[typ] gndSortedTypeObjects[obj.Ansetzung] = obj for k in gndSortedType obj = gndSortedTypeObjects[k] $("#gnd_list_#{typ}").append $("<li id='gnd_list_item_#{obj.PPN}' data-gndppn='#{obj.PPN}' data-gndwort='#{obj.Ansetzung}' class='gnd_list_item'><a href='#' class='takeGndItem' title='#{schlagwortInFundListe}'>#{obj.Ansetzung}</a> <a href='#' class='getItemInfo' title='#{detailsHinweis}'>#{Details}</a> </li>") $('.gnd_list_item a').unbind 'click' $('.gnd_list_item a.takeGndItem').bind 'click', takeGndItem $('.gnd_list_item a.getItemInfo').bind 'click', getItemInfo else $(this).data 'closed', true $("#gnd_list_#{typ}").remove() $("#fieldset_#{typ}").css 'cursor','default' false takeGndItem =-> wort = $(this).parent().data('gndwort') imFeld = $.trim($(swdId).val()) wortArr = imFeld.split("#{_SEPARATOR_}") for i in wortArr if $.trim(wort) == $.trim(i) return false $(swdId).val appendSwdItem(swdId, wort) str = coffeePrintf( [ schlagwortSpanselected { schlagwort: wort.replace('<', '&lt;').replace("\"", "&quote;") 'swdWortClass': swdWortClass } ]... ) $(swdDivSammlungId).append $(str) $(".#{swdWortClass}").unbind 'click' $(".#{swdWortClass}").bind 'click', removeGngItem false getItemInfo = (event) -> try event.preventDefault() ppn = $(this).parent().data 'gndppn' if typeof $(this).data('closed') is 'undefined' or $(this).data('closed') == 1 $(this).data 'closed', 0 ajaxGnd "pica.ppn", ppn, encodeURIComponent('pica.tbs="s" and '), "zeigeRecord", infoGndTimeout else $(this).data 'closed', 1 $("#gnd_list_item_info_#{ppn}").remove() false removeGngItem =-> wort = $(this).data 'wort' swdArr = $(swdId).val().split " #{_SEPARATOR_} " swdNewArr = [] for w in swdArr if w not in swdNewArr and $.trim(w) != $.trim(wort) r = new RegExp("$\s*#{_SEPARATOR_}\s*$","g") swdNewArr.push $.trim(w).replace(r, '') swds = swdNewArr.join(" #{_SEPARATOR_} ") $(swdId).val(swds) $(this).remove() emptySwdList =-> $(swdId).val('') $(swdDivSammlungId).empty() zeigeRecord = (txt) -> window.clearTimeout window.gndLoadTimeout $(xgndSearchFormId).css 'cursor','default' $("#gnd_list_item_#{txt[0].PPN}").append $("<div id='gnd_list_item_info_#{txt[0].PPN}' class='gnd_list_item_info'></div>") str1 = coffeePrintf( [ detailsFuerSchlagwort { schlagwort: txt[0].Ansetzung } ]... ) tabelle = $("<table class='gnd_list_item_info_table'><caption>#{str1}</caption><thead><tr><td>#{Typ}</td><td>#{Inhalt}</td></tr></thead><tbody></tbody></table>") $("#gnd_list_item_info_#{txt[0].PPN}").append tabelle for n, v of txt[0] if n is 'Verweise' and typeof v != 'undefined' and v.length > 0 verweiseliste = $("<tr></tr>") verweiseliste.append "<td>#{n}</td>" liste = '' for i in v if i.feldname != "" liste += " <b>#{i.feldname}</b>: " if typeof i.ppn != 'undefined' liste += "<i><a href='#' class='item_link' data-ppn='#{i.ppn}'>#{i.linkname}</a></i><br>" else liste += "<i>#{i.linkname}</i><br>" verweiseliste.append($("<td>#{liste}</td>")) $("#gnd_list_item_info_#{txt[0].PPN} > table > tbody ").append verweiseliste $('.item_link').unbind 'click' $('.item_link').bind 'click', searchGndItemById else if n == 'Synonyme' and v != null and v.length > 0 $("#gnd_list_item_info_#{txt[0].PPN} > table > tbody ").append $("<tr><td>#{n}</td><td>#{v.join('; ')}</td></tr>") else if n != 'Typ' and n != 'Ansetzung' and n != 'PPN' and v != null and v.length > 0 $("#gnd_list_item_info_#{txt[0].PPN} > table > tbody ").append $("<tr><td>#{n}</td><td>#{v}</td></tr>") searchGndItemById =-> $(suchwortId).val $(this).text() $('html, body').animate {scrollTop: $(xgndSearchFormId).offset().top}, 100 gndData = {} ppn = $(this).data 'ppn' $(gndsDiv).html bitteWarten gndXhrType = 'exact' ajaxGnd "pica.ppn", ppn, encodeURIComponent('pica.tbs="s" and '), "listGndTypes", gndTimeoutWarning false exactSearch = -> try event.preventDefault() gndData = {} $(gndsDiv).html bitteWarten gndXhrType = 'exact' ajaxGnd "pica.swr", $(suchwortId).val(), 'pica.tbs="s"', "listGndTypes", gndTimeoutWarning false searchGndTimeout = ( jqXHR, textStatus, errorThrown )-> $(gndsDiv).html dataErrorWarning gndTimeoutWarning =-> $(gndsDiv).html timeoutWarning infoGndTimeout =-> $(this).append $("#{timeoutWarning}") ajaxGnd = (searchtype, suchwort, suchoptionen, callbackFunction, gndTimeoutWarningFunction)-> $(xgndSearchFormId).css 'cursor','wait' gndXhr = $.ajax({"url": 'https://xgnd.bsz-bw.de/Anfrage', "data": {"suchfeld": searchtype, "suchwort": encodeURIComponent(suchwort) ,"suchfilter": "000000", suchoptionen, "jsonpCallback": callbackFunction}, "dataType": "jsonp", "jsonpCallback": callbackFunction, "timeout": gndSearchTimeout, "error": "searchGndTimeout" }) window.gndLoadTimeout = window.setTimeout gndTimeoutWarningFunction, gndSearchTimeout coffeePrintf = (string, values) -> for r in string.match /#\{([^\}]+)\}/ig string = string.replace r, "#{values[r.replace('#{', '').replace('}', '')]}" string appendSwdItem = (swdId, item) -> swdlist = $.trim $(swdId).val() swdArr = swdlist.split(" #{_SEPARATOR_} ") swdNewArr = [] for w in swdArr if $.trim(w) not in swdNewArr and $.trim(w) != '' swdNewArr.push w if $.trim(item) != '' and item not in swdNewArr swdNewArr.push item swdNewArr.join(" #{_SEPARATOR_} ")
true
### * @author PI:NAME:<NAME>END_PI * @version 1.0 * The MIT License (MIT) * * Copyright (c) 2015 Dr. PI:NAME:<NAME>END_PI * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ### $=jQuery gndData = {} gndXhr = {} gndXhrType = 'exact' _SEPARATOR_ = ',' $ -> imFeld = $.trim($(swdId).val()) wortArr = imFeld.split("#{_SEPARATOR_}") for i in wortArr if $.trim(i) != "" str = coffeePrintf([ schlagwortSpanselected { schlagwort: $.trim(i.replace("<", "&lt;").replace("\"", "&quote;")) 'swdWortClass': swdWortClass } ]...) $(swdDivSammlungId).append $(str) $(".#{swdWortClass}").unbind 'click' $(".#{swdWortClass}").bind 'click', removeGngItem $(swdErsatzNachrichtId).empty() $(gndFormHtml).insertAfter gndDivInsertAfterId $(gndDivInsertAfterId).append $("<input type='text' id='#{swdId.replace('#', '')}' name='#{swdId.replace('#', '')}'/>") if exactSearchId.length > 0 $(exactSearchId).bind 'click',exactSearch $("<br/><div id='swd_div_sammlung'>#{schlagwortUebernehmen}</div>").insertAfter insertswdCollectionAfterId $(swdId).val appendSwdItem(swdId, '') $(xgndSearchFormId).fadeIn('slow') $("form#{xgndSearchFormId}").unbind('submit').bind 'submit',exactSearch $(partSearchButtonId).unbind('click').bind 'click',searchGND if typeof window.onpopstate != "undefined" window.onpopstate = (event) -> GNDcoffeineState = event.state if typeof GNDcoffeineState['swdsuche'] != 'undefined' $(suchwortId).val GNDcoffeineState['swdsuche'] $('html, body').animate {scrollTop: $(xgndSearchFormId).offset().top}, 100 searchGND() true true searchGND =-> try event.preventDefault() gndData = {} $(gndsDiv).html bitteWarten gndXhrType = 'part' ajaxGnd "pica.sw", $(suchwortId).val(), "pica.tbs=\"s\"", "listGndTypes", gndTimeoutWarning false listGndTypes = (txt) -> # dummy-Aufruf, damit die Daten der Funktion zur Verfügung stehen... #console.log(txt) window.clearTimeout window.gndLoadTimeout $(gndsDiv).empty() if gndXhrType == 'exact' $(gndsDiv).html exactSearchResultMsg else if gndXhrType == 'part' $(gndsDiv).html fuzzySearchResultMsg if typeof window.history.pushState != "undefined" document.title = "#{document.title.split('| ' + documentHistoryItem)[0]} | #{documentHistoryItem} #{$(suchwortId).val()}" history.pushState {swdsuche: $(suchwortId).val()}, "#{documentHistoryItem} #{$(suchwortId).val()}", "#"+encodeURIComponent($(suchwortId).val()) $(xgndSearchFormId).css('cursor','default') if txt txt.forEach (n) -> typ = n.Typ if not gndData[typ] gndData[typ] = [n] else gndData[typ] = gndData[typ].concat n for typ, i of gndData elems = {} for i, elem of gndData[typ] elems[elem.Ansetzung] = elem gndData[typ] = elems for typ, i of gndData str = coffeePrintf( [ zeigeListeDerGruppeTyp { "typ": typ } ]... ) $(gndsDiv).append $("<fieldset class='gnd_typ' data-typ='#{typ}' id='fieldset_#{typ}'><legend><a href='#' title='#{str}'>#{typ} (#{Object.keys(i).length})</a></legend></fieldset>") $('.gnd_typ a').unbind 'click' $('.gnd_typ a').bind 'click', openGndType if gndXhrType == 'exact' $("#fieldset_#{typ} a").click() else $(gndsDiv).append $(emptyResultWarning) false openGndType =-> typ = $(this).parent().parent().data 'typ' $("#fieldset_#{typ}").css 'cursor','wait' if typeof $(this).data('closed') is "undefined" or $(this).data('closed') is true $(this).data 'closed', false $(this).parent().parent().append $("<ul id='gnd_list_#{typ}' class='gnd_list'></ul>") if gndData[typ] gndSortedType = (k for k of gndData[typ]) gndSortedType.sort() gndSortedTypeObjects = {} for i,obj of gndData[typ] gndSortedTypeObjects[obj.Ansetzung] = obj for k in gndSortedType obj = gndSortedTypeObjects[k] $("#gnd_list_#{typ}").append $("<li id='gnd_list_item_#{obj.PPN}' data-gndppn='#{obj.PPN}' data-gndwort='#{obj.Ansetzung}' class='gnd_list_item'><a href='#' class='takeGndItem' title='#{schlagwortInFundListe}'>#{obj.Ansetzung}</a> <a href='#' class='getItemInfo' title='#{detailsHinweis}'>#{Details}</a> </li>") $('.gnd_list_item a').unbind 'click' $('.gnd_list_item a.takeGndItem').bind 'click', takeGndItem $('.gnd_list_item a.getItemInfo').bind 'click', getItemInfo else $(this).data 'closed', true $("#gnd_list_#{typ}").remove() $("#fieldset_#{typ}").css 'cursor','default' false takeGndItem =-> wort = $(this).parent().data('gndwort') imFeld = $.trim($(swdId).val()) wortArr = imFeld.split("#{_SEPARATOR_}") for i in wortArr if $.trim(wort) == $.trim(i) return false $(swdId).val appendSwdItem(swdId, wort) str = coffeePrintf( [ schlagwortSpanselected { schlagwort: wort.replace('<', '&lt;').replace("\"", "&quote;") 'swdWortClass': swdWortClass } ]... ) $(swdDivSammlungId).append $(str) $(".#{swdWortClass}").unbind 'click' $(".#{swdWortClass}").bind 'click', removeGngItem false getItemInfo = (event) -> try event.preventDefault() ppn = $(this).parent().data 'gndppn' if typeof $(this).data('closed') is 'undefined' or $(this).data('closed') == 1 $(this).data 'closed', 0 ajaxGnd "pica.ppn", ppn, encodeURIComponent('pica.tbs="s" and '), "zeigeRecord", infoGndTimeout else $(this).data 'closed', 1 $("#gnd_list_item_info_#{ppn}").remove() false removeGngItem =-> wort = $(this).data 'wort' swdArr = $(swdId).val().split " #{_SEPARATOR_} " swdNewArr = [] for w in swdArr if w not in swdNewArr and $.trim(w) != $.trim(wort) r = new RegExp("$\s*#{_SEPARATOR_}\s*$","g") swdNewArr.push $.trim(w).replace(r, '') swds = swdNewArr.join(" #{_SEPARATOR_} ") $(swdId).val(swds) $(this).remove() emptySwdList =-> $(swdId).val('') $(swdDivSammlungId).empty() zeigeRecord = (txt) -> window.clearTimeout window.gndLoadTimeout $(xgndSearchFormId).css 'cursor','default' $("#gnd_list_item_#{txt[0].PPN}").append $("<div id='gnd_list_item_info_#{txt[0].PPN}' class='gnd_list_item_info'></div>") str1 = coffeePrintf( [ detailsFuerSchlagwort { schlagwort: txt[0].Ansetzung } ]... ) tabelle = $("<table class='gnd_list_item_info_table'><caption>#{str1}</caption><thead><tr><td>#{Typ}</td><td>#{Inhalt}</td></tr></thead><tbody></tbody></table>") $("#gnd_list_item_info_#{txt[0].PPN}").append tabelle for n, v of txt[0] if n is 'Verweise' and typeof v != 'undefined' and v.length > 0 verweiseliste = $("<tr></tr>") verweiseliste.append "<td>#{n}</td>" liste = '' for i in v if i.feldname != "" liste += " <b>#{i.feldname}</b>: " if typeof i.ppn != 'undefined' liste += "<i><a href='#' class='item_link' data-ppn='#{i.ppn}'>#{i.linkname}</a></i><br>" else liste += "<i>#{i.linkname}</i><br>" verweiseliste.append($("<td>#{liste}</td>")) $("#gnd_list_item_info_#{txt[0].PPN} > table > tbody ").append verweiseliste $('.item_link').unbind 'click' $('.item_link').bind 'click', searchGndItemById else if n == 'Synonyme' and v != null and v.length > 0 $("#gnd_list_item_info_#{txt[0].PPN} > table > tbody ").append $("<tr><td>#{n}</td><td>#{v.join('; ')}</td></tr>") else if n != 'Typ' and n != 'Ansetzung' and n != 'PPN' and v != null and v.length > 0 $("#gnd_list_item_info_#{txt[0].PPN} > table > tbody ").append $("<tr><td>#{n}</td><td>#{v}</td></tr>") searchGndItemById =-> $(suchwortId).val $(this).text() $('html, body').animate {scrollTop: $(xgndSearchFormId).offset().top}, 100 gndData = {} ppn = $(this).data 'ppn' $(gndsDiv).html bitteWarten gndXhrType = 'exact' ajaxGnd "pica.ppn", ppn, encodeURIComponent('pica.tbs="s" and '), "listGndTypes", gndTimeoutWarning false exactSearch = -> try event.preventDefault() gndData = {} $(gndsDiv).html bitteWarten gndXhrType = 'exact' ajaxGnd "pica.swr", $(suchwortId).val(), 'pica.tbs="s"', "listGndTypes", gndTimeoutWarning false searchGndTimeout = ( jqXHR, textStatus, errorThrown )-> $(gndsDiv).html dataErrorWarning gndTimeoutWarning =-> $(gndsDiv).html timeoutWarning infoGndTimeout =-> $(this).append $("#{timeoutWarning}") ajaxGnd = (searchtype, suchwort, suchoptionen, callbackFunction, gndTimeoutWarningFunction)-> $(xgndSearchFormId).css 'cursor','wait' gndXhr = $.ajax({"url": 'https://xgnd.bsz-bw.de/Anfrage', "data": {"suchfeld": searchtype, "suchwort": encodeURIComponent(suchwort) ,"suchfilter": "000000", suchoptionen, "jsonpCallback": callbackFunction}, "dataType": "jsonp", "jsonpCallback": callbackFunction, "timeout": gndSearchTimeout, "error": "searchGndTimeout" }) window.gndLoadTimeout = window.setTimeout gndTimeoutWarningFunction, gndSearchTimeout coffeePrintf = (string, values) -> for r in string.match /#\{([^\}]+)\}/ig string = string.replace r, "#{values[r.replace('#{', '').replace('}', '')]}" string appendSwdItem = (swdId, item) -> swdlist = $.trim $(swdId).val() swdArr = swdlist.split(" #{_SEPARATOR_} ") swdNewArr = [] for w in swdArr if $.trim(w) not in swdNewArr and $.trim(w) != '' swdNewArr.push w if $.trim(item) != '' and item not in swdNewArr swdNewArr.push item swdNewArr.join(" #{_SEPARATOR_} ")
[ { "context": "dy driver\n # helpers.initNewPlayer driver1, 'potter'\n\n # # challenge\n # helpers.startNewGam", "end": 3977, "score": 0.9985982179641724, "start": 3971, "tag": "NAME", "value": "potter" }, { "context": " challenge\n # helpers.startNewGame driver2, ...
test/challenge_spec_wip.coffee
Socialsquare/Sound-Duel-Core
0
# test/challenge_spec.coffee webdriverjs = require 'webdriverjs' chai = require 'chai' expect = chai.expect helpers = require './spec_helpers' describe "Challenge:", -> # tests describe "Player", -> browser2 = {} browsers = [ browser, browser2 ] # hooks before (done) -> browser2 = webdriverjs.remote browser.options browser2.sessionId = browser.sessionId helpers.addCustomCommands(b) for b in [browser, browser2] #browsers browser2.init(done) beforeEach -> b.home() for b in [browser, browser2] afterEach -> b.logout() for b in [browser, browser2] after (done) -> browser2.end(done) # it 'testy', (done) -> # # console.log browser # # console.log '' # # console.log browser2 # browser2.call done # it 'testy2', (done) -> # # console.log browser # # console.log '' # # console.log browser2 # browser.call -> # browser2.url('google.com') # done() it "eventhandling", (done) -> browser .newPlayer({}, (err, username) -> browser2.emit 'challenge', username ) .on 'checkChallenge', -> browser .refresh() .pause(500) .getText('#popup-confirm', (err, text) -> expect(err).to.be.null expect(text).to.match /accepter/i ) .answerPopup(true) .pause(500) .answerPopup(true) .answerQuestions(all: true) # .call(done) browser2 .on 'challenge', (username) -> browser2 .newPlayer({}) .newGame({challenge: username}) .answerQuestions(all: true) .call(-> browser.emit 'checkChallenge') # it "should be notified when challenged", (done) -> # browser # .newPlayer({}, (err, username) -> # browser.emit 'challenge', username # ) # .on('checkChallenge', -> # browser # .refresh() # .pause(500) # .getText('#popup-confirm', (err, text) -> # expect(err).to.be.null # expect(text).to.match /accepter/i # ) # .call done # ) # browser2 # .on('challenge', (username) -> # browser2 # .newPlayer({}) # .newGame({challenge: username}) # .answerQuestions(all: true) # .call(-> browser2.emit 'checkChallenge') # ) # it "should be notified when challenged is declined", (done) -> # browsers[0] # .newPlayer({}, (err, username) -> # browsers[1].emit 'challenge', username # ) # .on('checkChallenge', -> # browsers[0] # .refresh() # .pause(500) # .getText('#popup-cancel', (err, text) -> # expect(err).to.be.null # expect(text).to.match /nej tak/i # ) # .buttonClick('#popup-cancel', (err) -> # expect(err).to.be.null # ) # .call(-> browsers[1].emit 'declined') # ) # .on('done', -> browsers[0].call done) # browsers[1] # .on('challenge', (username) -> # browsers[1] # .newPlayer({}) # .newGame({challenge: username}) # .answerQuestions(all: true) # .call(-> browsers[0].emit 'checkChallenge') # ) # .on('declined', -> # browsers[1] # .pause(2000) # .getText('#opponentStatus', (err,text) -> # expect(err).to.be.null # expect(text).to.match /afvist din udfordring/i # ) # .call(-> browsers[0].emit 'done') # ) # test.it "should be notified when challenged is declined", -> # # ready driver # helpers.initNewPlayer driver1, 'potter' # # challenge # helpers.startNewGame driver2, 'hagrid', challenge: 'potter' # helpers.answerQuestion driver2, all: true # # decline challenge # helpers.answerPopup driver1, false # # assert challenger is informed # driver2.wait( -> # driver2.findElement(id: 'opponentStatus').getText().then (text) -> # return not text.match /endnu ikke svaret på din udfordring./i # , 200) # driver2.findElement(id: 'opponentStatus').getText().then (text) -> # text.should.match /Din modstander har afvist din udfordring/i # test.it "should be notified of result when challenged is answered", -> # challengerGameId = null # # ready drivers # helpers.initNewPlayer driver1, 'jens' # # challenge and play game # helpers.startNewGame driver2, 'lise', challenge: 'jens' # helpers.answerQuestion driver2, all: true # # store url and go to lobby # driver2.getCurrentUrl().then (url) -> # challengerGameId = url # driver2.findElement(id: 'restart').click() # # answer challenge # helpers.answerPopup driver1, true # driver1.wait( -> # driver1.findElement id: 'popup-confirm' # , 500) # driver1.executeScript "setTimeout((function() { # document.getElementById('popup-confirm').click(); # }), 750);" # helpers.answerQuestion driver1, all:true # # wait for popup # driver2.wait( -> # driver2.findElement(id: 'popup-confirm').getText().then (text) -> # text.should.match /se resultat/i # , 500) # # se result and assert it's the same game # helpers.answerPopup driver2, true # driver2.wait( -> # driver2.findElement(id: 'ratio') # , 500) # driver2.getCurrentUrl().then (url) -> # url.should.match challengerGameId # test.it "should not be notified of seen result when", -> # # ready drivers # helpers.initNewPlayer driver1, 'alfred' # # challenge and play game # helpers.startNewGame driver2, 'magda', challenge: 'alfred' # helpers.answerQuestion driver2, all: true # # answer challenge # helpers.answerChallenge driver1, true # helpers.answerQuestion driver1, all:true # # assert opponents score appears when answered # driver2.findElement(id: 'opponentRatio').getText().then (text) -> # text.should.match /.+ \d\/\d.+/i # driver2.findElement(id: 'opponentPoints').getText().then (text) -> # text.should.match /point: \d/i # driver2.findElement(id: 'restart').click() # driver2.findElement(id: 'popup-confirm').getText().then (text) -> # text.should.not.match /aksepter/i # test.it "should see result when challenged is answered", -> # # ready drivers # helpers.initNewPlayer driver1, 'mobydick' # # challenge and play game # helpers.startNewGame driver2, 'dumbledor', challenge: 'mobydick' # helpers.answerQuestion driver2, all: true # # answer challenge # helpers.answerChallenge driver1, true # helpers.answerQuestion driver1, all:true # # assert opponents result appears when answered # driver1.findElement(id: 'opponentName').getText().then (text) -> # text.should.match /dumbledor/i # driver1.findElement(id: 'opponentRatio').getText().then (text) -> # text.should.match /.+ \d+\/\d+.+/i # driver1.findElement(id: 'opponentPoints').getText().then (text) -> # text.should.match /point: \d+/i # driver2.findElement(id: 'opponentName').getText().then (text) -> # text.should.match /mobydick/i # driver2.findElement(id: 'opponentRatio').getText().then (text) -> # text.should.match /.+ \d+\/\d+.+/i # driver2.findElement(id: 'opponentPoints').getText().then (text) -> # text.should.match /point: \d+/i
80544
# test/challenge_spec.coffee webdriverjs = require 'webdriverjs' chai = require 'chai' expect = chai.expect helpers = require './spec_helpers' describe "Challenge:", -> # tests describe "Player", -> browser2 = {} browsers = [ browser, browser2 ] # hooks before (done) -> browser2 = webdriverjs.remote browser.options browser2.sessionId = browser.sessionId helpers.addCustomCommands(b) for b in [browser, browser2] #browsers browser2.init(done) beforeEach -> b.home() for b in [browser, browser2] afterEach -> b.logout() for b in [browser, browser2] after (done) -> browser2.end(done) # it 'testy', (done) -> # # console.log browser # # console.log '' # # console.log browser2 # browser2.call done # it 'testy2', (done) -> # # console.log browser # # console.log '' # # console.log browser2 # browser.call -> # browser2.url('google.com') # done() it "eventhandling", (done) -> browser .newPlayer({}, (err, username) -> browser2.emit 'challenge', username ) .on 'checkChallenge', -> browser .refresh() .pause(500) .getText('#popup-confirm', (err, text) -> expect(err).to.be.null expect(text).to.match /accepter/i ) .answerPopup(true) .pause(500) .answerPopup(true) .answerQuestions(all: true) # .call(done) browser2 .on 'challenge', (username) -> browser2 .newPlayer({}) .newGame({challenge: username}) .answerQuestions(all: true) .call(-> browser.emit 'checkChallenge') # it "should be notified when challenged", (done) -> # browser # .newPlayer({}, (err, username) -> # browser.emit 'challenge', username # ) # .on('checkChallenge', -> # browser # .refresh() # .pause(500) # .getText('#popup-confirm', (err, text) -> # expect(err).to.be.null # expect(text).to.match /accepter/i # ) # .call done # ) # browser2 # .on('challenge', (username) -> # browser2 # .newPlayer({}) # .newGame({challenge: username}) # .answerQuestions(all: true) # .call(-> browser2.emit 'checkChallenge') # ) # it "should be notified when challenged is declined", (done) -> # browsers[0] # .newPlayer({}, (err, username) -> # browsers[1].emit 'challenge', username # ) # .on('checkChallenge', -> # browsers[0] # .refresh() # .pause(500) # .getText('#popup-cancel', (err, text) -> # expect(err).to.be.null # expect(text).to.match /nej tak/i # ) # .buttonClick('#popup-cancel', (err) -> # expect(err).to.be.null # ) # .call(-> browsers[1].emit 'declined') # ) # .on('done', -> browsers[0].call done) # browsers[1] # .on('challenge', (username) -> # browsers[1] # .newPlayer({}) # .newGame({challenge: username}) # .answerQuestions(all: true) # .call(-> browsers[0].emit 'checkChallenge') # ) # .on('declined', -> # browsers[1] # .pause(2000) # .getText('#opponentStatus', (err,text) -> # expect(err).to.be.null # expect(text).to.match /afvist din udfordring/i # ) # .call(-> browsers[0].emit 'done') # ) # test.it "should be notified when challenged is declined", -> # # ready driver # helpers.initNewPlayer driver1, '<NAME>' # # challenge # helpers.startNewGame driver2, '<NAME>', challenge: '<NAME>' # helpers.answerQuestion driver2, all: true # # decline challenge # helpers.answerPopup driver1, false # # assert challenger is informed # driver2.wait( -> # driver2.findElement(id: 'opponentStatus').getText().then (text) -> # return not text.match /endnu ikke svaret på din udfordring./i # , 200) # driver2.findElement(id: 'opponentStatus').getText().then (text) -> # text.should.match /Din modstander har afvist din udfordring/i # test.it "should be notified of result when challenged is answered", -> # challengerGameId = null # # ready drivers # helpers.initNewPlayer driver1, '<NAME>' # # challenge and play game # helpers.startNewGame driver2, '<NAME>', challenge: '<NAME>' # helpers.answerQuestion driver2, all: true # # store url and go to lobby # driver2.getCurrentUrl().then (url) -> # challengerGameId = url # driver2.findElement(id: 'restart').click() # # answer challenge # helpers.answerPopup driver1, true # driver1.wait( -> # driver1.findElement id: 'popup-confirm' # , 500) # driver1.executeScript "setTimeout((function() { # document.getElementById('popup-confirm').click(); # }), 750);" # helpers.answerQuestion driver1, all:true # # wait for popup # driver2.wait( -> # driver2.findElement(id: 'popup-confirm').getText().then (text) -> # text.should.match /se resultat/i # , 500) # # se result and assert it's the same game # helpers.answerPopup driver2, true # driver2.wait( -> # driver2.findElement(id: 'ratio') # , 500) # driver2.getCurrentUrl().then (url) -> # url.should.match challengerGameId # test.it "should not be notified of seen result when", -> # # ready drivers # helpers.initNewPlayer driver1, '<NAME>' # # challenge and play game # helpers.startNewGame driver2, '<NAME>', challenge: '<NAME>' # helpers.answerQuestion driver2, all: true # # answer challenge # helpers.answerChallenge driver1, true # helpers.answerQuestion driver1, all:true # # assert opponents score appears when answered # driver2.findElement(id: 'opponentRatio').getText().then (text) -> # text.should.match /.+ \d\/\d.+/i # driver2.findElement(id: 'opponentPoints').getText().then (text) -> # text.should.match /point: \d/i # driver2.findElement(id: 'restart').click() # driver2.findElement(id: 'popup-confirm').getText().then (text) -> # text.should.not.match /aksepter/i # test.it "should see result when challenged is answered", -> # # ready drivers # helpers.initNewPlayer driver1, '<NAME>' # # challenge and play game # helpers.startNewGame driver2, '<NAME>', challenge: '<NAME>' # helpers.answerQuestion driver2, all: true # # answer challenge # helpers.answerChallenge driver1, true # helpers.answerQuestion driver1, all:true # # assert opponents result appears when answered # driver1.findElement(id: 'opponentName').getText().then (text) -> # text.should.match /<NAME>/i # driver1.findElement(id: 'opponentRatio').getText().then (text) -> # text.should.match /.+ \d+\/\d+.+/i # driver1.findElement(id: 'opponentPoints').getText().then (text) -> # text.should.match /point: \d+/i # driver2.findElement(id: 'opponentName').getText().then (text) -> # text.should.match /<NAME>/i # driver2.findElement(id: 'opponentRatio').getText().then (text) -> # text.should.match /.+ \d+\/\d+.+/i # driver2.findElement(id: 'opponentPoints').getText().then (text) -> # text.should.match /point: \d+/i
true
# test/challenge_spec.coffee webdriverjs = require 'webdriverjs' chai = require 'chai' expect = chai.expect helpers = require './spec_helpers' describe "Challenge:", -> # tests describe "Player", -> browser2 = {} browsers = [ browser, browser2 ] # hooks before (done) -> browser2 = webdriverjs.remote browser.options browser2.sessionId = browser.sessionId helpers.addCustomCommands(b) for b in [browser, browser2] #browsers browser2.init(done) beforeEach -> b.home() for b in [browser, browser2] afterEach -> b.logout() for b in [browser, browser2] after (done) -> browser2.end(done) # it 'testy', (done) -> # # console.log browser # # console.log '' # # console.log browser2 # browser2.call done # it 'testy2', (done) -> # # console.log browser # # console.log '' # # console.log browser2 # browser.call -> # browser2.url('google.com') # done() it "eventhandling", (done) -> browser .newPlayer({}, (err, username) -> browser2.emit 'challenge', username ) .on 'checkChallenge', -> browser .refresh() .pause(500) .getText('#popup-confirm', (err, text) -> expect(err).to.be.null expect(text).to.match /accepter/i ) .answerPopup(true) .pause(500) .answerPopup(true) .answerQuestions(all: true) # .call(done) browser2 .on 'challenge', (username) -> browser2 .newPlayer({}) .newGame({challenge: username}) .answerQuestions(all: true) .call(-> browser.emit 'checkChallenge') # it "should be notified when challenged", (done) -> # browser # .newPlayer({}, (err, username) -> # browser.emit 'challenge', username # ) # .on('checkChallenge', -> # browser # .refresh() # .pause(500) # .getText('#popup-confirm', (err, text) -> # expect(err).to.be.null # expect(text).to.match /accepter/i # ) # .call done # ) # browser2 # .on('challenge', (username) -> # browser2 # .newPlayer({}) # .newGame({challenge: username}) # .answerQuestions(all: true) # .call(-> browser2.emit 'checkChallenge') # ) # it "should be notified when challenged is declined", (done) -> # browsers[0] # .newPlayer({}, (err, username) -> # browsers[1].emit 'challenge', username # ) # .on('checkChallenge', -> # browsers[0] # .refresh() # .pause(500) # .getText('#popup-cancel', (err, text) -> # expect(err).to.be.null # expect(text).to.match /nej tak/i # ) # .buttonClick('#popup-cancel', (err) -> # expect(err).to.be.null # ) # .call(-> browsers[1].emit 'declined') # ) # .on('done', -> browsers[0].call done) # browsers[1] # .on('challenge', (username) -> # browsers[1] # .newPlayer({}) # .newGame({challenge: username}) # .answerQuestions(all: true) # .call(-> browsers[0].emit 'checkChallenge') # ) # .on('declined', -> # browsers[1] # .pause(2000) # .getText('#opponentStatus', (err,text) -> # expect(err).to.be.null # expect(text).to.match /afvist din udfordring/i # ) # .call(-> browsers[0].emit 'done') # ) # test.it "should be notified when challenged is declined", -> # # ready driver # helpers.initNewPlayer driver1, 'PI:NAME:<NAME>END_PI' # # challenge # helpers.startNewGame driver2, 'PI:NAME:<NAME>END_PI', challenge: 'PI:NAME:<NAME>END_PI' # helpers.answerQuestion driver2, all: true # # decline challenge # helpers.answerPopup driver1, false # # assert challenger is informed # driver2.wait( -> # driver2.findElement(id: 'opponentStatus').getText().then (text) -> # return not text.match /endnu ikke svaret på din udfordring./i # , 200) # driver2.findElement(id: 'opponentStatus').getText().then (text) -> # text.should.match /Din modstander har afvist din udfordring/i # test.it "should be notified of result when challenged is answered", -> # challengerGameId = null # # ready drivers # helpers.initNewPlayer driver1, 'PI:NAME:<NAME>END_PI' # # challenge and play game # helpers.startNewGame driver2, 'PI:NAME:<NAME>END_PI', challenge: 'PI:NAME:<NAME>END_PI' # helpers.answerQuestion driver2, all: true # # store url and go to lobby # driver2.getCurrentUrl().then (url) -> # challengerGameId = url # driver2.findElement(id: 'restart').click() # # answer challenge # helpers.answerPopup driver1, true # driver1.wait( -> # driver1.findElement id: 'popup-confirm' # , 500) # driver1.executeScript "setTimeout((function() { # document.getElementById('popup-confirm').click(); # }), 750);" # helpers.answerQuestion driver1, all:true # # wait for popup # driver2.wait( -> # driver2.findElement(id: 'popup-confirm').getText().then (text) -> # text.should.match /se resultat/i # , 500) # # se result and assert it's the same game # helpers.answerPopup driver2, true # driver2.wait( -> # driver2.findElement(id: 'ratio') # , 500) # driver2.getCurrentUrl().then (url) -> # url.should.match challengerGameId # test.it "should not be notified of seen result when", -> # # ready drivers # helpers.initNewPlayer driver1, 'PI:NAME:<NAME>END_PI' # # challenge and play game # helpers.startNewGame driver2, 'PI:NAME:<NAME>END_PI', challenge: 'PI:NAME:<NAME>END_PI' # helpers.answerQuestion driver2, all: true # # answer challenge # helpers.answerChallenge driver1, true # helpers.answerQuestion driver1, all:true # # assert opponents score appears when answered # driver2.findElement(id: 'opponentRatio').getText().then (text) -> # text.should.match /.+ \d\/\d.+/i # driver2.findElement(id: 'opponentPoints').getText().then (text) -> # text.should.match /point: \d/i # driver2.findElement(id: 'restart').click() # driver2.findElement(id: 'popup-confirm').getText().then (text) -> # text.should.not.match /aksepter/i # test.it "should see result when challenged is answered", -> # # ready drivers # helpers.initNewPlayer driver1, 'PI:NAME:<NAME>END_PI' # # challenge and play game # helpers.startNewGame driver2, 'PI:NAME:<NAME>END_PI', challenge: 'PI:NAME:<NAME>END_PI' # helpers.answerQuestion driver2, all: true # # answer challenge # helpers.answerChallenge driver1, true # helpers.answerQuestion driver1, all:true # # assert opponents result appears when answered # driver1.findElement(id: 'opponentName').getText().then (text) -> # text.should.match /PI:NAME:<NAME>END_PI/i # driver1.findElement(id: 'opponentRatio').getText().then (text) -> # text.should.match /.+ \d+\/\d+.+/i # driver1.findElement(id: 'opponentPoints').getText().then (text) -> # text.should.match /point: \d+/i # driver2.findElement(id: 'opponentName').getText().then (text) -> # text.should.match /PI:NAME:<NAME>END_PI/i # driver2.findElement(id: 'opponentRatio').getText().then (text) -> # text.should.match /.+ \d+\/\d+.+/i # driver2.findElement(id: 'opponentPoints').getText().then (text) -> # text.should.match /point: \d+/i
[ { "context": "bluConfig =\n uuid: 'user-uuid'\n token: 'user-token'\n hostname: 'localhost'\n port: 0xd00d\n ", "end": 406, "score": 0.7480618357658386, "start": 396, "tag": "PASSWORD", "value": "user-token" } ]
test/get-monitored-devices-spec.coffee
octoblu/inquisitor
0
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' sinon = require 'sinon' _ = require 'lodash' enableDestroy = require 'server-destroy' shmock = require 'shmock' SocketIO = require 'socket.io' Inquisitor = require '..' describe 'getMonitoredDevices', -> beforeEach -> meshbluConfig = uuid: 'user-uuid' token: 'user-token' hostname: 'localhost' port: 0xd00d protocol: 'http' uuid = 'inquisitor-uuid' @userAuth = new Buffer('user-uuid:user-token').toString 'base64' @sut = new Inquisitor {meshbluConfig, uuid} it 'should exist', -> expect(@sut).to.exist describe '->getMonitoredDevices', -> beforeEach 'meshblu', -> @meshblu = shmock 0xd00d enableDestroy(@meshblu) afterEach (done) -> @meshblu.destroy done beforeEach -> @meshblu .get "/v2/devices/inquisitor-uuid/subscriptions" .set 'Authorization', "Basic #{@userAuth}" .reply 200, [ {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'device-1', type: 'configure.sent'} {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'inquisitor-uuid', type: 'configure.sent'} {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'device-2', type: 'configure.sent'} {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'status-device', type: 'configure.sent'} ] beforeEach 'search', -> @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .send uuid: $in: ['device-1', 'device-2', 'status-device'] .reply 200, [ {uuid: 'status-device', errors: ['look-an-error']} {uuid: 'device-1', statusDevice: 'status-device'} {uuid: 'device-2', errors: ['yet-another-error']} ] beforeEach (done) -> @sut.getMonitoredDevices (error, @devicesAndErrors) => done() return null it 'should return an array of objects containing errors associated with devices', -> expected = 'device-1': device: { uuid: 'device-1', statusDevice: 'status-device' } statusDevice: 'status-device' errors: ['look-an-error'] 'device-2': device: { uuid: 'device-2', errors: ['yet-another-error'] } statusDevice: 'device-2' errors: ['yet-another-error'] expect(@devicesAndErrors).to.deep.equal expected
73162
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' sinon = require 'sinon' _ = require 'lodash' enableDestroy = require 'server-destroy' shmock = require 'shmock' SocketIO = require 'socket.io' Inquisitor = require '..' describe 'getMonitoredDevices', -> beforeEach -> meshbluConfig = uuid: 'user-uuid' token: '<PASSWORD>' hostname: 'localhost' port: 0xd00d protocol: 'http' uuid = 'inquisitor-uuid' @userAuth = new Buffer('user-uuid:user-token').toString 'base64' @sut = new Inquisitor {meshbluConfig, uuid} it 'should exist', -> expect(@sut).to.exist describe '->getMonitoredDevices', -> beforeEach 'meshblu', -> @meshblu = shmock 0xd00d enableDestroy(@meshblu) afterEach (done) -> @meshblu.destroy done beforeEach -> @meshblu .get "/v2/devices/inquisitor-uuid/subscriptions" .set 'Authorization', "Basic #{@userAuth}" .reply 200, [ {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'device-1', type: 'configure.sent'} {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'inquisitor-uuid', type: 'configure.sent'} {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'device-2', type: 'configure.sent'} {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'status-device', type: 'configure.sent'} ] beforeEach 'search', -> @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .send uuid: $in: ['device-1', 'device-2', 'status-device'] .reply 200, [ {uuid: 'status-device', errors: ['look-an-error']} {uuid: 'device-1', statusDevice: 'status-device'} {uuid: 'device-2', errors: ['yet-another-error']} ] beforeEach (done) -> @sut.getMonitoredDevices (error, @devicesAndErrors) => done() return null it 'should return an array of objects containing errors associated with devices', -> expected = 'device-1': device: { uuid: 'device-1', statusDevice: 'status-device' } statusDevice: 'status-device' errors: ['look-an-error'] 'device-2': device: { uuid: 'device-2', errors: ['yet-another-error'] } statusDevice: 'device-2' errors: ['yet-another-error'] expect(@devicesAndErrors).to.deep.equal expected
true
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' sinon = require 'sinon' _ = require 'lodash' enableDestroy = require 'server-destroy' shmock = require 'shmock' SocketIO = require 'socket.io' Inquisitor = require '..' describe 'getMonitoredDevices', -> beforeEach -> meshbluConfig = uuid: 'user-uuid' token: 'PI:PASSWORD:<PASSWORD>END_PI' hostname: 'localhost' port: 0xd00d protocol: 'http' uuid = 'inquisitor-uuid' @userAuth = new Buffer('user-uuid:user-token').toString 'base64' @sut = new Inquisitor {meshbluConfig, uuid} it 'should exist', -> expect(@sut).to.exist describe '->getMonitoredDevices', -> beforeEach 'meshblu', -> @meshblu = shmock 0xd00d enableDestroy(@meshblu) afterEach (done) -> @meshblu.destroy done beforeEach -> @meshblu .get "/v2/devices/inquisitor-uuid/subscriptions" .set 'Authorization', "Basic #{@userAuth}" .reply 200, [ {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'device-1', type: 'configure.sent'} {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'inquisitor-uuid', type: 'configure.sent'} {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'device-2', type: 'configure.sent'} {subscriberUuid: 'inquisitor-uuid', emitterUuid: 'status-device', type: 'configure.sent'} ] beforeEach 'search', -> @meshblu .post '/search/devices' .set 'Authorization', "Basic #{@userAuth}" .send uuid: $in: ['device-1', 'device-2', 'status-device'] .reply 200, [ {uuid: 'status-device', errors: ['look-an-error']} {uuid: 'device-1', statusDevice: 'status-device'} {uuid: 'device-2', errors: ['yet-another-error']} ] beforeEach (done) -> @sut.getMonitoredDevices (error, @devicesAndErrors) => done() return null it 'should return an array of objects containing errors associated with devices', -> expected = 'device-1': device: { uuid: 'device-1', statusDevice: 'status-device' } statusDevice: 'status-device' errors: ['look-an-error'] 'device-2': device: { uuid: 'device-2', errors: ['yet-another-error'] } statusDevice: 'device-2' errors: ['yet-another-error'] expect(@devicesAndErrors).to.deep.equal expected
[ { "context": "n no at signs\", ->\n model.populate({ email: \"joe\" });\n expect(! model.isValid()).toBeTruthy()\n ", "end": 948, "score": 0.8565196394920349, "start": 947, "tag": "NAME", "value": "e" }, { "context": "ls when two ats\", ->\n model.populate({ email: \"joe@blo...
test/spec_coffee/email_validator_spec.coffee
kirkbowers/mvcoffee
0
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model theUser.validates "email", test: "email" describe "validates email", -> model = null beforeEach -> model = new User it "fails when undefined", -> model.validate(); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when null", -> model.populate({ email: null }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when blank", -> model.populate({ email: "" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no at signs", -> model.populate({ email: "joe" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no dot suffix", -> model.populate({ email: "joe@foo" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when two ats", -> model.populate({ email: "joe@blow@foo.com" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "succeeds with good email", -> model.populate({ email: "joe.blow@foo.com" }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) #------------------------------------------------------- theUser = class UserWithDisplay extends MVCoffee.Model theUser.displays "email", "Email Address" theUser.validates "email", test: "email" describe "email with display name", -> model = null beforeEach -> model = new UserWithDisplay it "fails when no at signs", -> model.populate({ email: "joe" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email Address must be a valid email address') #------------------------------------------------------- theUser = class UserWithMessage extends MVCoffee.Model theUser.validates "email", test: "email", message: "has a custom message" describe "email with custom message", -> model = null beforeEach -> model = new UserWithMessage it "fails when no at signs", -> model.populate({ email: "joe" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email has a custom message') #------------------------------------------------------- theUser = class UserAllowNull extends MVCoffee.Model theUser.validates "email", test: "email", allow_null: true describe "email allows null", -> model = null beforeEach -> model = new UserAllowNull it "passes when undefined", -> model.validate(); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) it "passes when null", -> model.populate({ email: null }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) it "fails when blank", -> model.populate({ email: "" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no at signs", -> model.populate({ email: "joe" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no dot suffix", -> model.populate({ email: "joe@foo" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when two ats", -> model.populate({ email: "joe@blow@foo.com" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "succeeds with good email", -> model.populate({ email: "joe.blow@foo.com" }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) #------------------------------------------------------- theUser = class UserWithPresenceTest extends MVCoffee.Model theUser.validates "email", test: "presence" theUser.validates "email", test: "email", allow_blank: true describe "email allows blank with presence test", -> model = null beforeEach -> model = new UserWithPresenceTest it "only one error when undefined", -> model.validate(); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual("Email can't be empty") it "only one error when null", -> model.populate({ email: null }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual("Email can't be empty") it "only one error when blank", -> model.populate({ email: "" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual("Email can't be empty") it "fails when no at signs", -> model.populate({ email: "joe" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "succeeds with good email", -> model.populate({ email: "joe.blow@foo.com" }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0)
59902
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model theUser.validates "email", test: "email" describe "validates email", -> model = null beforeEach -> model = new User it "fails when undefined", -> model.validate(); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when null", -> model.populate({ email: null }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when blank", -> model.populate({ email: "" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no at signs", -> model.populate({ email: "jo<NAME>" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no dot suffix", -> model.populate({ email: "joe@foo" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when two ats", -> model.populate({ email: "<EMAIL>" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "succeeds with good email", -> model.populate({ email: "<EMAIL>" }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) #------------------------------------------------------- theUser = class UserWithDisplay extends MVCoffee.Model theUser.displays "email", "Email Address" theUser.validates "email", test: "email" describe "email with display name", -> model = null beforeEach -> model = new UserWithDisplay it "fails when no at signs", -> model.populate({ email: "<NAME>" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email Address must be a valid email address') #------------------------------------------------------- theUser = class UserWithMessage extends MVCoffee.Model theUser.validates "email", test: "email", message: "has a custom message" describe "email with custom message", -> model = null beforeEach -> model = new UserWithMessage it "fails when no at signs", -> model.populate({ email: "jo<NAME>" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email has a custom message') #------------------------------------------------------- theUser = class UserAllowNull extends MVCoffee.Model theUser.validates "email", test: "email", allow_null: true describe "email allows null", -> model = null beforeEach -> model = new UserAllowNull it "passes when undefined", -> model.validate(); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) it "passes when null", -> model.populate({ email: null }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) it "fails when blank", -> model.populate({ email: "" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no at signs", -> model.populate({ email: "jo<NAME>" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no dot suffix", -> model.populate({ email: "joe@foo" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when two ats", -> model.populate({ email: "<EMAIL>" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "succeeds with good email", -> model.populate({ email: "<EMAIL>" }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) #------------------------------------------------------- theUser = class UserWithPresenceTest extends MVCoffee.Model theUser.validates "email", test: "presence" theUser.validates "email", test: "email", allow_blank: true describe "email allows blank with presence test", -> model = null beforeEach -> model = new UserWithPresenceTest it "only one error when undefined", -> model.validate(); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual("Email can't be empty") it "only one error when null", -> model.populate({ email: null }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual("Email can't be empty") it "only one error when blank", -> model.populate({ email: "" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual("Email can't be empty") it "fails when no at signs", -> model.populate({ email: "<NAME>" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "succeeds with good email", -> model.populate({ email: "<EMAIL>" }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0)
true
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model theUser.validates "email", test: "email" describe "validates email", -> model = null beforeEach -> model = new User it "fails when undefined", -> model.validate(); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when null", -> model.populate({ email: null }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when blank", -> model.populate({ email: "" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no at signs", -> model.populate({ email: "joPI:NAME:<NAME>END_PI" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no dot suffix", -> model.populate({ email: "joe@foo" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when two ats", -> model.populate({ email: "PI:EMAIL:<EMAIL>END_PI" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "succeeds with good email", -> model.populate({ email: "PI:EMAIL:<EMAIL>END_PI" }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) #------------------------------------------------------- theUser = class UserWithDisplay extends MVCoffee.Model theUser.displays "email", "Email Address" theUser.validates "email", test: "email" describe "email with display name", -> model = null beforeEach -> model = new UserWithDisplay it "fails when no at signs", -> model.populate({ email: "PI:NAME:<NAME>END_PI" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email Address must be a valid email address') #------------------------------------------------------- theUser = class UserWithMessage extends MVCoffee.Model theUser.validates "email", test: "email", message: "has a custom message" describe "email with custom message", -> model = null beforeEach -> model = new UserWithMessage it "fails when no at signs", -> model.populate({ email: "joPI:NAME:<NAME>END_PI" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email has a custom message') #------------------------------------------------------- theUser = class UserAllowNull extends MVCoffee.Model theUser.validates "email", test: "email", allow_null: true describe "email allows null", -> model = null beforeEach -> model = new UserAllowNull it "passes when undefined", -> model.validate(); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) it "passes when null", -> model.populate({ email: null }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) it "fails when blank", -> model.populate({ email: "" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no at signs", -> model.populate({ email: "joPI:NAME:<NAME>END_PI" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when no dot suffix", -> model.populate({ email: "joe@foo" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "fails when two ats", -> model.populate({ email: "PI:EMAIL:<EMAIL>END_PI" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "succeeds with good email", -> model.populate({ email: "PI:EMAIL:<EMAIL>END_PI" }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0) #------------------------------------------------------- theUser = class UserWithPresenceTest extends MVCoffee.Model theUser.validates "email", test: "presence" theUser.validates "email", test: "email", allow_blank: true describe "email allows blank with presence test", -> model = null beforeEach -> model = new UserWithPresenceTest it "only one error when undefined", -> model.validate(); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual("Email can't be empty") it "only one error when null", -> model.populate({ email: null }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual("Email can't be empty") it "only one error when blank", -> model.populate({ email: "" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual("Email can't be empty") it "fails when no at signs", -> model.populate({ email: "PI:NAME:<NAME>END_PI" }); expect(! model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(1) expect(model.errors[0]).toEqual('Email must be a valid email address') it "succeeds with good email", -> model.populate({ email: "PI:EMAIL:<EMAIL>END_PI" }); expect(model.isValid()).toBeTruthy() expect(model.errors.length).toEqual(0)
[ { "context": ".exist ticket\n comment =\n name : \"worker\"\n kind : \"info\"\n content : \"tes", "end": 3046, "score": 0.9686368107795715, "start": 3040, "tag": "NAME", "value": "worker" } ]
src/tests/ticket_test.coffee
poikilos/node-ticket-manager
0
### # test for models_ticket ### ## Module dependencies should = require "should" _ = require "underscore" debuglog = require("debug")("node-ticket-manager:test:ticket_test") STATUS = require "../enums/ticket_status" config = require("../config/config")['development'] mongoose = require('mongoose') mongoose.connect(config.db) mongoose.set('debug', true) require "../models/ticket" Ticket = mongoose.model('Ticket') SAMPLE_TITLE_1 = "test models/ticket 1" SAMPLE_TITLE_2 = "test models/ticket 2" SAMPLE_CONTENT_1 = itema : "is string" itemb : sub : "content" sub2 : "still" itemc : [ 1, 2, "three" ] itemd : true ## Test cases describe "test", -> after (done)-> mongoose.connection.db.dropCollection 'tickets', done describe "models/ticket", -> it "should able create doc", (done) -> ticket = new Ticket title : SAMPLE_TITLE_1 owner_id : 'test' category : 'test' content : SAMPLE_CONTENT_1 ticket.save (err)-> should.not.exist err ticket = new Ticket title : SAMPLE_TITLE_2 owner_id : 'test' category : 'test' content : SAMPLE_CONTENT_1 ticket.save (err)-> should.not.exist err done() it "should not allow alive ticket with duplicated title", (done) -> ticket = new Ticket title : SAMPLE_TITLE_1 owner_id : 'test' category : 'test' content : SAMPLE_CONTENT_1 ticket.save (err)-> debuglog "[models_ticket_test] err:#{err}" should.exist err done() it "should able to complete ticket", (done)-> Ticket.changeStatus {title:SAMPLE_TITLE_1}, STATUS.COMPLETE, (err, ticket)-> #Ticket.findOneAndUpdate {title:SAMPLE_TITLE_1}, {status: STATUS.COMPLETE}, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.status.should.eql(STATUS.COMPLETE) done() it "should not abandon a completed ticket", (done)-> Ticket.changeStatus {title:SAMPLE_TITLE_1}, STATUS.ABANDON, (err, ticket)-> #Ticket.findOneAndUpdate {title:SAMPLE_TITLE_1}, {status: STATUS.COMPLETE}, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist ticket done() it "should able to process a pending ticket", (done)-> Ticket.changeStatus {title:SAMPLE_TITLE_2}, STATUS.PROCESSING, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.status.should.eql(STATUS.PROCESSING) ticket.title.should.eql(SAMPLE_TITLE_2) done() it "should able to add comment to a ticket", (done)-> Ticket.findOne {title:SAMPLE_TITLE_2}, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket comment = name : "worker" kind : "info" content : "test comment" Ticket.addComment ticket.id, comment, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket _.last(ticket.comments).content.should.eql(comment.content) done() it "arrange nothing when no avaliable ticket", (done)-> workerOptions = worker : "assignment worker" category : "assignment" Ticket.arrangeAssignment workerOptions, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.not.exist ticket done() it "arrange assignment", (done)-> ticket = new Ticket title : "for assignment 01" owner_id : 'test' category : 'assignment' content : "for assignment 01" ticket.save (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err ticket = new Ticket title : "for assignment 02" owner_id : 'test' category : 'assignment' content : "for assignment 02" ticket.save (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err ticket = new Ticket title : "for assignment 03" owner_id : 'test' category : 'assignment' content : "for assignment 03" ticket.save (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err workerOptions = worker : "assignment worker" category : "assignment" Ticket.arrangeAssignment workerOptions, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.status.should.eql STATUS.PROCESSING ticket.title.should.eql "for assignment 01" done() it "always arrange eldest assignment", (done)-> workerOptions = worker : "assignment worker" category : "assignment" Ticket.arrangeAssignment workerOptions, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.title.should.eql "for assignment 02" ticket.status.should.eql STATUS.PROCESSING done()
16855
### # test for models_ticket ### ## Module dependencies should = require "should" _ = require "underscore" debuglog = require("debug")("node-ticket-manager:test:ticket_test") STATUS = require "../enums/ticket_status" config = require("../config/config")['development'] mongoose = require('mongoose') mongoose.connect(config.db) mongoose.set('debug', true) require "../models/ticket" Ticket = mongoose.model('Ticket') SAMPLE_TITLE_1 = "test models/ticket 1" SAMPLE_TITLE_2 = "test models/ticket 2" SAMPLE_CONTENT_1 = itema : "is string" itemb : sub : "content" sub2 : "still" itemc : [ 1, 2, "three" ] itemd : true ## Test cases describe "test", -> after (done)-> mongoose.connection.db.dropCollection 'tickets', done describe "models/ticket", -> it "should able create doc", (done) -> ticket = new Ticket title : SAMPLE_TITLE_1 owner_id : 'test' category : 'test' content : SAMPLE_CONTENT_1 ticket.save (err)-> should.not.exist err ticket = new Ticket title : SAMPLE_TITLE_2 owner_id : 'test' category : 'test' content : SAMPLE_CONTENT_1 ticket.save (err)-> should.not.exist err done() it "should not allow alive ticket with duplicated title", (done) -> ticket = new Ticket title : SAMPLE_TITLE_1 owner_id : 'test' category : 'test' content : SAMPLE_CONTENT_1 ticket.save (err)-> debuglog "[models_ticket_test] err:#{err}" should.exist err done() it "should able to complete ticket", (done)-> Ticket.changeStatus {title:SAMPLE_TITLE_1}, STATUS.COMPLETE, (err, ticket)-> #Ticket.findOneAndUpdate {title:SAMPLE_TITLE_1}, {status: STATUS.COMPLETE}, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.status.should.eql(STATUS.COMPLETE) done() it "should not abandon a completed ticket", (done)-> Ticket.changeStatus {title:SAMPLE_TITLE_1}, STATUS.ABANDON, (err, ticket)-> #Ticket.findOneAndUpdate {title:SAMPLE_TITLE_1}, {status: STATUS.COMPLETE}, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist ticket done() it "should able to process a pending ticket", (done)-> Ticket.changeStatus {title:SAMPLE_TITLE_2}, STATUS.PROCESSING, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.status.should.eql(STATUS.PROCESSING) ticket.title.should.eql(SAMPLE_TITLE_2) done() it "should able to add comment to a ticket", (done)-> Ticket.findOne {title:SAMPLE_TITLE_2}, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket comment = name : "<NAME>" kind : "info" content : "test comment" Ticket.addComment ticket.id, comment, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket _.last(ticket.comments).content.should.eql(comment.content) done() it "arrange nothing when no avaliable ticket", (done)-> workerOptions = worker : "assignment worker" category : "assignment" Ticket.arrangeAssignment workerOptions, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.not.exist ticket done() it "arrange assignment", (done)-> ticket = new Ticket title : "for assignment 01" owner_id : 'test' category : 'assignment' content : "for assignment 01" ticket.save (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err ticket = new Ticket title : "for assignment 02" owner_id : 'test' category : 'assignment' content : "for assignment 02" ticket.save (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err ticket = new Ticket title : "for assignment 03" owner_id : 'test' category : 'assignment' content : "for assignment 03" ticket.save (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err workerOptions = worker : "assignment worker" category : "assignment" Ticket.arrangeAssignment workerOptions, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.status.should.eql STATUS.PROCESSING ticket.title.should.eql "for assignment 01" done() it "always arrange eldest assignment", (done)-> workerOptions = worker : "assignment worker" category : "assignment" Ticket.arrangeAssignment workerOptions, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.title.should.eql "for assignment 02" ticket.status.should.eql STATUS.PROCESSING done()
true
### # test for models_ticket ### ## Module dependencies should = require "should" _ = require "underscore" debuglog = require("debug")("node-ticket-manager:test:ticket_test") STATUS = require "../enums/ticket_status" config = require("../config/config")['development'] mongoose = require('mongoose') mongoose.connect(config.db) mongoose.set('debug', true) require "../models/ticket" Ticket = mongoose.model('Ticket') SAMPLE_TITLE_1 = "test models/ticket 1" SAMPLE_TITLE_2 = "test models/ticket 2" SAMPLE_CONTENT_1 = itema : "is string" itemb : sub : "content" sub2 : "still" itemc : [ 1, 2, "three" ] itemd : true ## Test cases describe "test", -> after (done)-> mongoose.connection.db.dropCollection 'tickets', done describe "models/ticket", -> it "should able create doc", (done) -> ticket = new Ticket title : SAMPLE_TITLE_1 owner_id : 'test' category : 'test' content : SAMPLE_CONTENT_1 ticket.save (err)-> should.not.exist err ticket = new Ticket title : SAMPLE_TITLE_2 owner_id : 'test' category : 'test' content : SAMPLE_CONTENT_1 ticket.save (err)-> should.not.exist err done() it "should not allow alive ticket with duplicated title", (done) -> ticket = new Ticket title : SAMPLE_TITLE_1 owner_id : 'test' category : 'test' content : SAMPLE_CONTENT_1 ticket.save (err)-> debuglog "[models_ticket_test] err:#{err}" should.exist err done() it "should able to complete ticket", (done)-> Ticket.changeStatus {title:SAMPLE_TITLE_1}, STATUS.COMPLETE, (err, ticket)-> #Ticket.findOneAndUpdate {title:SAMPLE_TITLE_1}, {status: STATUS.COMPLETE}, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.status.should.eql(STATUS.COMPLETE) done() it "should not abandon a completed ticket", (done)-> Ticket.changeStatus {title:SAMPLE_TITLE_1}, STATUS.ABANDON, (err, ticket)-> #Ticket.findOneAndUpdate {title:SAMPLE_TITLE_1}, {status: STATUS.COMPLETE}, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist ticket done() it "should able to process a pending ticket", (done)-> Ticket.changeStatus {title:SAMPLE_TITLE_2}, STATUS.PROCESSING, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.status.should.eql(STATUS.PROCESSING) ticket.title.should.eql(SAMPLE_TITLE_2) done() it "should able to add comment to a ticket", (done)-> Ticket.findOne {title:SAMPLE_TITLE_2}, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket comment = name : "PI:NAME:<NAME>END_PI" kind : "info" content : "test comment" Ticket.addComment ticket.id, comment, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket _.last(ticket.comments).content.should.eql(comment.content) done() it "arrange nothing when no avaliable ticket", (done)-> workerOptions = worker : "assignment worker" category : "assignment" Ticket.arrangeAssignment workerOptions, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.not.exist ticket done() it "arrange assignment", (done)-> ticket = new Ticket title : "for assignment 01" owner_id : 'test' category : 'assignment' content : "for assignment 01" ticket.save (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err ticket = new Ticket title : "for assignment 02" owner_id : 'test' category : 'assignment' content : "for assignment 02" ticket.save (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err ticket = new Ticket title : "for assignment 03" owner_id : 'test' category : 'assignment' content : "for assignment 03" ticket.save (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err workerOptions = worker : "assignment worker" category : "assignment" Ticket.arrangeAssignment workerOptions, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.status.should.eql STATUS.PROCESSING ticket.title.should.eql "for assignment 01" done() it "always arrange eldest assignment", (done)-> workerOptions = worker : "assignment worker" category : "assignment" Ticket.arrangeAssignment workerOptions, (err, ticket)-> debuglog "[models_ticket_test] err:#{err}, ticket:%j", ticket should.not.exist err should.exist ticket ticket.title.should.eql "for assignment 02" ticket.status.should.eql STATUS.PROCESSING done()
[ { "context": "= Input(driver)\n selector = '.box'\n keys = 'puppies'\n\n it 'fails if selector is undefined', ->\n ", "end": 257, "score": 0.998537003993988, "start": 250, "tag": "KEY", "value": "puppies" }, { "context": "= Input(driver)\n selector = '.box'\n keys = ...
test/unit/api/input_test.coffee
johan/testium
2
Input = require '../../../lib/api/input' assert = require 'assertive' describe 'input api', -> describe '#type', -> element = type: -> driver = getElement: -> element input = Input(driver) selector = '.box' keys = 'puppies' it 'fails if selector is undefined', -> assert.throws -> input.type(undefined, keys) it 'fails if selector is not a String', -> assert.throws -> input.type(->, keys) it 'fails if keys is not defined', -> assert.throws -> input.type(selector) it 'succeeds if all conditions are met', -> input.type(selector, keys) describe '#clear', -> element = clear: -> driver = getElement: -> element input = Input(driver) selector = '.box' it 'fails if selector is undefined', -> assert.throws -> input.clear(undefined) it 'fails if selector is not a String', -> assert.throws -> input.clear(->) it 'succeeds if all conditions are met', -> input.clear(selector) describe '#clearAndType', -> element = clear: -> type: -> driver = getElement: -> element input = Input(driver) selector = '.box' keys = 'puppies' it 'fails if selector is undefined', -> assert.throws -> input.clearAndType(undefined, keys) it 'fails if selector is not a String', -> assert.throws -> input.clearAndType(->, keys) it 'fails if keys is not defined', -> assert.throws -> input.clearAndType(selector) it 'succeeds if all conditions are met', -> input.clearAndType(selector, keys)
180770
Input = require '../../../lib/api/input' assert = require 'assertive' describe 'input api', -> describe '#type', -> element = type: -> driver = getElement: -> element input = Input(driver) selector = '.box' keys = '<KEY>' it 'fails if selector is undefined', -> assert.throws -> input.type(undefined, keys) it 'fails if selector is not a String', -> assert.throws -> input.type(->, keys) it 'fails if keys is not defined', -> assert.throws -> input.type(selector) it 'succeeds if all conditions are met', -> input.type(selector, keys) describe '#clear', -> element = clear: -> driver = getElement: -> element input = Input(driver) selector = '.box' it 'fails if selector is undefined', -> assert.throws -> input.clear(undefined) it 'fails if selector is not a String', -> assert.throws -> input.clear(->) it 'succeeds if all conditions are met', -> input.clear(selector) describe '#clearAndType', -> element = clear: -> type: -> driver = getElement: -> element input = Input(driver) selector = '.box' keys = '<KEY>' it 'fails if selector is undefined', -> assert.throws -> input.clearAndType(undefined, keys) it 'fails if selector is not a String', -> assert.throws -> input.clearAndType(->, keys) it 'fails if keys is not defined', -> assert.throws -> input.clearAndType(selector) it 'succeeds if all conditions are met', -> input.clearAndType(selector, keys)
true
Input = require '../../../lib/api/input' assert = require 'assertive' describe 'input api', -> describe '#type', -> element = type: -> driver = getElement: -> element input = Input(driver) selector = '.box' keys = 'PI:KEY:<KEY>END_PI' it 'fails if selector is undefined', -> assert.throws -> input.type(undefined, keys) it 'fails if selector is not a String', -> assert.throws -> input.type(->, keys) it 'fails if keys is not defined', -> assert.throws -> input.type(selector) it 'succeeds if all conditions are met', -> input.type(selector, keys) describe '#clear', -> element = clear: -> driver = getElement: -> element input = Input(driver) selector = '.box' it 'fails if selector is undefined', -> assert.throws -> input.clear(undefined) it 'fails if selector is not a String', -> assert.throws -> input.clear(->) it 'succeeds if all conditions are met', -> input.clear(selector) describe '#clearAndType', -> element = clear: -> type: -> driver = getElement: -> element input = Input(driver) selector = '.box' keys = 'PI:KEY:<KEY>END_PI' it 'fails if selector is undefined', -> assert.throws -> input.clearAndType(undefined, keys) it 'fails if selector is not a String', -> assert.throws -> input.clearAndType(->, keys) it 'fails if keys is not defined', -> assert.throws -> input.clearAndType(selector) it 'succeeds if all conditions are met', -> input.clearAndType(selector, keys)
[ { "context": "yScheduler extends Base\n @extend()\n\n _key: -> \"#{@hour}:#{@min}\"\n\n _parseOptions: ->\n @hour = parseInt @", "end": 117, "score": 0.5924414992332458, "start": 112, "tag": "KEY", "value": "hour}" } ]
daily.coffee
pavanvidusankha/Archiver
0
Base = require './base' DAY = 24 * 60 * 60 * 1000 class DailyScheduler extends Base @extend() _key: -> "#{@hour}:#{@min}" _parseOptions: -> @hour = parseInt @opt.hour @min = parseInt @opt.minute if not @hour? or isNaN @hour throw new Error "Scheduler missing/invalid hour value in scheduler #{@id}" if not @min? or isNaN @min throw new Error "Scheduler missing/invalid minute value in scheduler #{@id}" @hour = @hour % 24 @min = @min % 60 _nextTime: (Time) -> cur = new Date Time next = new Date cur.getFullYear(), cur.getMonth(), cur.getDate(), @hour, @min time = next.getTime() if time <= cur.getTime() time += DAY return time _lastTime: (Time) -> (@_nextTime Time) - DAY module.exports = (Types) -> Types.daily = DailyScheduler
180085
Base = require './base' DAY = 24 * 60 * 60 * 1000 class DailyScheduler extends Base @extend() _key: -> "#{@<KEY>:#{@min}" _parseOptions: -> @hour = parseInt @opt.hour @min = parseInt @opt.minute if not @hour? or isNaN @hour throw new Error "Scheduler missing/invalid hour value in scheduler #{@id}" if not @min? or isNaN @min throw new Error "Scheduler missing/invalid minute value in scheduler #{@id}" @hour = @hour % 24 @min = @min % 60 _nextTime: (Time) -> cur = new Date Time next = new Date cur.getFullYear(), cur.getMonth(), cur.getDate(), @hour, @min time = next.getTime() if time <= cur.getTime() time += DAY return time _lastTime: (Time) -> (@_nextTime Time) - DAY module.exports = (Types) -> Types.daily = DailyScheduler
true
Base = require './base' DAY = 24 * 60 * 60 * 1000 class DailyScheduler extends Base @extend() _key: -> "#{@PI:KEY:<KEY>END_PI:#{@min}" _parseOptions: -> @hour = parseInt @opt.hour @min = parseInt @opt.minute if not @hour? or isNaN @hour throw new Error "Scheduler missing/invalid hour value in scheduler #{@id}" if not @min? or isNaN @min throw new Error "Scheduler missing/invalid minute value in scheduler #{@id}" @hour = @hour % 24 @min = @min % 60 _nextTime: (Time) -> cur = new Date Time next = new Date cur.getFullYear(), cur.getMonth(), cur.getDate(), @hour, @min time = next.getTime() if time <= cur.getTime() time += DAY return time _lastTime: (Time) -> (@_nextTime Time) - DAY module.exports = (Types) -> Types.daily = DailyScheduler
[ { "context": "###\nCopyright 2013 Simon Lydell\n\nThis file is part of parse-stack.\n\nparse-stack i", "end": 31, "score": 0.9998713731765747, "start": 19, "tag": "NAME", "value": "Simon Lydell" } ]
node_modules/parse-stack/test/parse-stack.coffee
KartikVashisth/Camper_Website
7
### Copyright 2013 Simon Lydell This file is part of parse-stack. parse-stack is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. parse-stack is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with parse-stack. If not, see <http://www.gnu.org/licenses/>. ### {assert, throws, equal} = require "./common" parseStack = require "../src/parse-stack" toString = -> if @message then "#{@name}: #{@message}" else @name describe "parseStack", -> it "is a function", -> assert typeof parseStack is "function" it "requires an object as argument", -> assert throws -> parseStack() assert throws -> parseStack(null) assert not throws -> parseStack({stack: "@:0"}) it "returns null unless the passed object has a `stack` property, which is a string", -> assert parseStack({}) is null assert parseStack({stack: undefined}) is null assert parseStack({stack: null}) is null assert parseStack({stack: 1}) is null assert parseStack({stack: [1, 2]}) is null assert parseStack({stack: {}}) is null assert parseStack({stack: "@:0"}) isnt null it "throws an error for invalid strings", -> assert throws Error("shouldn't parse"), -> parseStack({stack: "shouldn't parse"}) it """returns an array of objects with the `name`, `filepath`, `lineNumber` and `columnNumber` properties""", -> stack = parseStack({stack: "@:0"}) assert stack.length is 1 assert stack[0].hasOwnProperty("name") assert stack[0].hasOwnProperty("filepath") assert stack[0].hasOwnProperty("lineNumber") assert stack[0].hasOwnProperty("columnNumber") assert Object.keys(stack[0]).length is 4 describe "the at format", -> it """starts with some spaces, followed by the word 'at' and contains at least a line number and column number""", -> for spaces in [" ", " ", " "] stack = parseStack({stack: "#{spaces}at :0:1"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is 1 it "may also contain a file path", -> stack = parseStack stack: " at scheme://user:pass@domain:80/path?query=string#fragment_id:0:1" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 it "may also contain a function name", -> stack = parseStack({stack: " at functionName (:0:1)"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is undefined assert lineNumber is 0 assert columnNumber is 1 it "handles all of the above at once", -> stack = parseStack stack: " at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1)" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 it "handles an eval", -> stack = parseStack stack: " at eval (native)" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "eval" assert filepath is "native" assert lineNumber is undefined assert columnNumber is undefined it "handles a complex eval", -> stack = parseStack stack: " at eval (eval at <anonymous> (http://localhost/random/test/js/jquery-1.11.0.js:339:22), <anonymous>:3:1)" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "eval" assert filepath is "eval at <anonymous> (http://localhost/random/test/js/jquery-1.11.0.js:339:22), <anonymous>" assert lineNumber is 3 assert columnNumber is 1 it "parses a nice example", -> stack = parseStack stack: """ Error: test at assert (c:\\test.js:22:9) at c:\\test.js:84:6 at $ (c:\\test.js:75:3) at Object.<anonymous> (c:\\test.js:84:1) at Object.<anonymous> (c:\\test.js:1:1) at Module._compile (module.js:456:26) """ name: "Error" message: "test" toString: toString assert stack.length is 6 assert equal stack, [ {name: "assert", filepath: "c:\\test.js", lineNumber: 22, columnNumber: 9} {name: undefined, filepath: "c:\\test.js", lineNumber: 84, columnNumber: 6} {name: "$", filepath: "c:\\test.js", lineNumber: 75, columnNumber: 3} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 84, columnNumber: 1} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 1, columnNumber: 1} {name: "Module._compile", filepath: "module.js", lineNumber: 456, columnNumber: 26} ] describe "the @ format", -> it "contains the '@' symbol and then at least a line number", -> stack = parseStack({stack: "@:0"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "may also contain a file path", -> stack = parseStack stack: "@scheme://user:pass@domain:80/path?query=string#fragment_id:0" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is undefined it "may also contain a function name", -> stack = parseStack({stack: "functionName@:0"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "handles all of the above at once", -> stack = parseStack stack: "functionName@scheme://user:pass@domain:80/path?query=string#fragment_id:0" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is undefined it "parses a nice example", -> stack = parseStack stack: """ assert@c:\\test.js:22 @c:\\test.js:84 $@c:\\test.js:75 Object.<anonymous>@c:\\test.js:84 Object.<anonymous>@c:\\test.js:1 Module._compile@module.js:456 """ assert stack.length is 6 assert equal stack, [ {name: "assert", filepath: "c:\\test.js", lineNumber: 22, columnNumber: undefined} {name: undefined, filepath: "c:\\test.js", lineNumber: 84, columnNumber: undefined} {name: "$", filepath: "c:\\test.js", lineNumber: 75, columnNumber: undefined} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 84, columnNumber: undefined} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 1, columnNumber: undefined} {name: "Module._compile", filepath: "module.js", lineNumber: 456, columnNumber: undefined} ] describe "any format", -> it "cannot contain invalid lines", -> stackString = """ fn@http://example.com/script/fn.js:29 invalid line @http://example.com/script/fn.js:34 """ assert throws Error("stack line 2"), -> parseStack({stack: stackString}) it "cannot mix formats", -> stackString = """ fn@http://example.com/script/fn.js:29 at fn (http://example.com/script/fn.js:29:4) """ assert throws Error("stack line 2| at fn (http://example.com/script/fn.js:29:4)"), -> parseStack({stack: stackString}) it "can use either of \\r\\n, \\r and \\n as newline characters", -> stack = parseStack({stack: "@:0\r\n@:0\r@:0\n@:0"}) assert stack.length is 4 for {name, filepath, lineNumber, columnNumber} in stack assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "can contain blank lines", -> stack = parseStack stack: """ @:0 @:0 """ assert stack.length is 2 for {name, filepath, lineNumber, columnNumber} in stack assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "may start with 'ErrorType: message'", -> stack = parseStack stack: """ AssertionError at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ name: "AssertionError" toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 stack = parseStack stack: """ AssertionError: assert(false); at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ name: "AssertionError" message: "assert(false);" toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 stack = parseStack stack: """ (Almost) anything is allowed as `name`!: The same is true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) at realStackLine (filepath:0:1) """ name: "(Almost) anything is allowed as `name`!" message: """ The same is true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "realStackLine" assert filepath is "filepath" assert lineNumber is 0 assert columnNumber is 1 stack = parseStack stack: """ Newlines \r\n works \r without \n trouble: The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) at realStackLine (filepath:0:1) """ name: "Newlines \r\n works \r without \n trouble" message: """ The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "realStackLine" assert filepath is "filepath" assert lineNumber is 0 assert columnNumber is 1 error = new Error """ The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ error.stack = """ Error: The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) at realStackLine (filepath:0:1) """ stack = parseStack(error) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "realStackLine" assert filepath is "filepath" assert lineNumber is 0 assert columnNumber is 1
144176
### Copyright 2013 <NAME> This file is part of parse-stack. parse-stack is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. parse-stack is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with parse-stack. If not, see <http://www.gnu.org/licenses/>. ### {assert, throws, equal} = require "./common" parseStack = require "../src/parse-stack" toString = -> if @message then "#{@name}: #{@message}" else @name describe "parseStack", -> it "is a function", -> assert typeof parseStack is "function" it "requires an object as argument", -> assert throws -> parseStack() assert throws -> parseStack(null) assert not throws -> parseStack({stack: "@:0"}) it "returns null unless the passed object has a `stack` property, which is a string", -> assert parseStack({}) is null assert parseStack({stack: undefined}) is null assert parseStack({stack: null}) is null assert parseStack({stack: 1}) is null assert parseStack({stack: [1, 2]}) is null assert parseStack({stack: {}}) is null assert parseStack({stack: "@:0"}) isnt null it "throws an error for invalid strings", -> assert throws Error("shouldn't parse"), -> parseStack({stack: "shouldn't parse"}) it """returns an array of objects with the `name`, `filepath`, `lineNumber` and `columnNumber` properties""", -> stack = parseStack({stack: "@:0"}) assert stack.length is 1 assert stack[0].hasOwnProperty("name") assert stack[0].hasOwnProperty("filepath") assert stack[0].hasOwnProperty("lineNumber") assert stack[0].hasOwnProperty("columnNumber") assert Object.keys(stack[0]).length is 4 describe "the at format", -> it """starts with some spaces, followed by the word 'at' and contains at least a line number and column number""", -> for spaces in [" ", " ", " "] stack = parseStack({stack: "#{spaces}at :0:1"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is 1 it "may also contain a file path", -> stack = parseStack stack: " at scheme://user:pass@domain:80/path?query=string#fragment_id:0:1" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 it "may also contain a function name", -> stack = parseStack({stack: " at functionName (:0:1)"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is undefined assert lineNumber is 0 assert columnNumber is 1 it "handles all of the above at once", -> stack = parseStack stack: " at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1)" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 it "handles an eval", -> stack = parseStack stack: " at eval (native)" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "eval" assert filepath is "native" assert lineNumber is undefined assert columnNumber is undefined it "handles a complex eval", -> stack = parseStack stack: " at eval (eval at <anonymous> (http://localhost/random/test/js/jquery-1.11.0.js:339:22), <anonymous>:3:1)" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "eval" assert filepath is "eval at <anonymous> (http://localhost/random/test/js/jquery-1.11.0.js:339:22), <anonymous>" assert lineNumber is 3 assert columnNumber is 1 it "parses a nice example", -> stack = parseStack stack: """ Error: test at assert (c:\\test.js:22:9) at c:\\test.js:84:6 at $ (c:\\test.js:75:3) at Object.<anonymous> (c:\\test.js:84:1) at Object.<anonymous> (c:\\test.js:1:1) at Module._compile (module.js:456:26) """ name: "Error" message: "test" toString: toString assert stack.length is 6 assert equal stack, [ {name: "assert", filepath: "c:\\test.js", lineNumber: 22, columnNumber: 9} {name: undefined, filepath: "c:\\test.js", lineNumber: 84, columnNumber: 6} {name: "$", filepath: "c:\\test.js", lineNumber: 75, columnNumber: 3} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 84, columnNumber: 1} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 1, columnNumber: 1} {name: "Module._compile", filepath: "module.js", lineNumber: 456, columnNumber: 26} ] describe "the @ format", -> it "contains the '@' symbol and then at least a line number", -> stack = parseStack({stack: "@:0"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "may also contain a file path", -> stack = parseStack stack: "@scheme://user:pass@domain:80/path?query=string#fragment_id:0" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is undefined it "may also contain a function name", -> stack = parseStack({stack: "functionName@:0"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "handles all of the above at once", -> stack = parseStack stack: "functionName@scheme://user:pass@domain:80/path?query=string#fragment_id:0" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is undefined it "parses a nice example", -> stack = parseStack stack: """ assert@c:\\test.js:22 @c:\\test.js:84 $@c:\\test.js:75 Object.<anonymous>@c:\\test.js:84 Object.<anonymous>@c:\\test.js:1 Module._compile@module.js:456 """ assert stack.length is 6 assert equal stack, [ {name: "assert", filepath: "c:\\test.js", lineNumber: 22, columnNumber: undefined} {name: undefined, filepath: "c:\\test.js", lineNumber: 84, columnNumber: undefined} {name: "$", filepath: "c:\\test.js", lineNumber: 75, columnNumber: undefined} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 84, columnNumber: undefined} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 1, columnNumber: undefined} {name: "Module._compile", filepath: "module.js", lineNumber: 456, columnNumber: undefined} ] describe "any format", -> it "cannot contain invalid lines", -> stackString = """ fn@http://example.com/script/fn.js:29 invalid line @http://example.com/script/fn.js:34 """ assert throws Error("stack line 2"), -> parseStack({stack: stackString}) it "cannot mix formats", -> stackString = """ fn@http://example.com/script/fn.js:29 at fn (http://example.com/script/fn.js:29:4) """ assert throws Error("stack line 2| at fn (http://example.com/script/fn.js:29:4)"), -> parseStack({stack: stackString}) it "can use either of \\r\\n, \\r and \\n as newline characters", -> stack = parseStack({stack: "@:0\r\n@:0\r@:0\n@:0"}) assert stack.length is 4 for {name, filepath, lineNumber, columnNumber} in stack assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "can contain blank lines", -> stack = parseStack stack: """ @:0 @:0 """ assert stack.length is 2 for {name, filepath, lineNumber, columnNumber} in stack assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "may start with 'ErrorType: message'", -> stack = parseStack stack: """ AssertionError at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ name: "AssertionError" toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 stack = parseStack stack: """ AssertionError: assert(false); at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ name: "AssertionError" message: "assert(false);" toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 stack = parseStack stack: """ (Almost) anything is allowed as `name`!: The same is true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) at realStackLine (filepath:0:1) """ name: "(Almost) anything is allowed as `name`!" message: """ The same is true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "realStackLine" assert filepath is "filepath" assert lineNumber is 0 assert columnNumber is 1 stack = parseStack stack: """ Newlines \r\n works \r without \n trouble: The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) at realStackLine (filepath:0:1) """ name: "Newlines \r\n works \r without \n trouble" message: """ The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "realStackLine" assert filepath is "filepath" assert lineNumber is 0 assert columnNumber is 1 error = new Error """ The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ error.stack = """ Error: The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) at realStackLine (filepath:0:1) """ stack = parseStack(error) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "realStackLine" assert filepath is "filepath" assert lineNumber is 0 assert columnNumber is 1
true
### Copyright 2013 PI:NAME:<NAME>END_PI This file is part of parse-stack. parse-stack is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. parse-stack is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with parse-stack. If not, see <http://www.gnu.org/licenses/>. ### {assert, throws, equal} = require "./common" parseStack = require "../src/parse-stack" toString = -> if @message then "#{@name}: #{@message}" else @name describe "parseStack", -> it "is a function", -> assert typeof parseStack is "function" it "requires an object as argument", -> assert throws -> parseStack() assert throws -> parseStack(null) assert not throws -> parseStack({stack: "@:0"}) it "returns null unless the passed object has a `stack` property, which is a string", -> assert parseStack({}) is null assert parseStack({stack: undefined}) is null assert parseStack({stack: null}) is null assert parseStack({stack: 1}) is null assert parseStack({stack: [1, 2]}) is null assert parseStack({stack: {}}) is null assert parseStack({stack: "@:0"}) isnt null it "throws an error for invalid strings", -> assert throws Error("shouldn't parse"), -> parseStack({stack: "shouldn't parse"}) it """returns an array of objects with the `name`, `filepath`, `lineNumber` and `columnNumber` properties""", -> stack = parseStack({stack: "@:0"}) assert stack.length is 1 assert stack[0].hasOwnProperty("name") assert stack[0].hasOwnProperty("filepath") assert stack[0].hasOwnProperty("lineNumber") assert stack[0].hasOwnProperty("columnNumber") assert Object.keys(stack[0]).length is 4 describe "the at format", -> it """starts with some spaces, followed by the word 'at' and contains at least a line number and column number""", -> for spaces in [" ", " ", " "] stack = parseStack({stack: "#{spaces}at :0:1"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is 1 it "may also contain a file path", -> stack = parseStack stack: " at scheme://user:pass@domain:80/path?query=string#fragment_id:0:1" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 it "may also contain a function name", -> stack = parseStack({stack: " at functionName (:0:1)"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is undefined assert lineNumber is 0 assert columnNumber is 1 it "handles all of the above at once", -> stack = parseStack stack: " at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1)" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 it "handles an eval", -> stack = parseStack stack: " at eval (native)" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "eval" assert filepath is "native" assert lineNumber is undefined assert columnNumber is undefined it "handles a complex eval", -> stack = parseStack stack: " at eval (eval at <anonymous> (http://localhost/random/test/js/jquery-1.11.0.js:339:22), <anonymous>:3:1)" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "eval" assert filepath is "eval at <anonymous> (http://localhost/random/test/js/jquery-1.11.0.js:339:22), <anonymous>" assert lineNumber is 3 assert columnNumber is 1 it "parses a nice example", -> stack = parseStack stack: """ Error: test at assert (c:\\test.js:22:9) at c:\\test.js:84:6 at $ (c:\\test.js:75:3) at Object.<anonymous> (c:\\test.js:84:1) at Object.<anonymous> (c:\\test.js:1:1) at Module._compile (module.js:456:26) """ name: "Error" message: "test" toString: toString assert stack.length is 6 assert equal stack, [ {name: "assert", filepath: "c:\\test.js", lineNumber: 22, columnNumber: 9} {name: undefined, filepath: "c:\\test.js", lineNumber: 84, columnNumber: 6} {name: "$", filepath: "c:\\test.js", lineNumber: 75, columnNumber: 3} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 84, columnNumber: 1} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 1, columnNumber: 1} {name: "Module._compile", filepath: "module.js", lineNumber: 456, columnNumber: 26} ] describe "the @ format", -> it "contains the '@' symbol and then at least a line number", -> stack = parseStack({stack: "@:0"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "may also contain a file path", -> stack = parseStack stack: "@scheme://user:pass@domain:80/path?query=string#fragment_id:0" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is undefined assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is undefined it "may also contain a function name", -> stack = parseStack({stack: "functionName@:0"}) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "handles all of the above at once", -> stack = parseStack stack: "functionName@scheme://user:pass@domain:80/path?query=string#fragment_id:0" assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is undefined it "parses a nice example", -> stack = parseStack stack: """ assert@c:\\test.js:22 @c:\\test.js:84 $@c:\\test.js:75 Object.<anonymous>@c:\\test.js:84 Object.<anonymous>@c:\\test.js:1 Module._compile@module.js:456 """ assert stack.length is 6 assert equal stack, [ {name: "assert", filepath: "c:\\test.js", lineNumber: 22, columnNumber: undefined} {name: undefined, filepath: "c:\\test.js", lineNumber: 84, columnNumber: undefined} {name: "$", filepath: "c:\\test.js", lineNumber: 75, columnNumber: undefined} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 84, columnNumber: undefined} {name: "Object.<anonymous>", filepath: "c:\\test.js", lineNumber: 1, columnNumber: undefined} {name: "Module._compile", filepath: "module.js", lineNumber: 456, columnNumber: undefined} ] describe "any format", -> it "cannot contain invalid lines", -> stackString = """ fn@http://example.com/script/fn.js:29 invalid line @http://example.com/script/fn.js:34 """ assert throws Error("stack line 2"), -> parseStack({stack: stackString}) it "cannot mix formats", -> stackString = """ fn@http://example.com/script/fn.js:29 at fn (http://example.com/script/fn.js:29:4) """ assert throws Error("stack line 2| at fn (http://example.com/script/fn.js:29:4)"), -> parseStack({stack: stackString}) it "can use either of \\r\\n, \\r and \\n as newline characters", -> stack = parseStack({stack: "@:0\r\n@:0\r@:0\n@:0"}) assert stack.length is 4 for {name, filepath, lineNumber, columnNumber} in stack assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "can contain blank lines", -> stack = parseStack stack: """ @:0 @:0 """ assert stack.length is 2 for {name, filepath, lineNumber, columnNumber} in stack assert name is undefined assert filepath is undefined assert lineNumber is 0 assert columnNumber is undefined it "may start with 'ErrorType: message'", -> stack = parseStack stack: """ AssertionError at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ name: "AssertionError" toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 stack = parseStack stack: """ AssertionError: assert(false); at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ name: "AssertionError" message: "assert(false);" toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "functionName" assert filepath is "scheme://user:pass@domain:80/path?query=string#fragment_id" assert lineNumber is 0 assert columnNumber is 1 stack = parseStack stack: """ (Almost) anything is allowed as `name`!: The same is true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) at realStackLine (filepath:0:1) """ name: "(Almost) anything is allowed as `name`!" message: """ The same is true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "realStackLine" assert filepath is "filepath" assert lineNumber is 0 assert columnNumber is 1 stack = parseStack stack: """ Newlines \r\n works \r without \n trouble: The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) at realStackLine (filepath:0:1) """ name: "Newlines \r\n works \r without \n trouble" message: """ The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ toString: toString assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "realStackLine" assert filepath is "filepath" assert lineNumber is 0 assert columnNumber is 1 error = new Error """ The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) """ error.stack = """ Error: The \r\n same \r is \n true for messages. The following line shouldn't be confused as a stack line: at functionName (scheme://user:pass@domain:80/path?query=string#fragment_id:0:1) at realStackLine (filepath:0:1) """ stack = parseStack(error) assert stack.length is 1 {name, filepath, lineNumber, columnNumber} = stack[0] assert name is "realStackLine" assert filepath is "filepath" assert lineNumber is 0 assert columnNumber is 1
[ { "context": " wrapper around Node.js 'http' module\n#\n# (C) 2011 Tristan Slominski\n#\nanode = require '../lib/anode'\nnodehttp = requi", "end": 91, "score": 0.9996641278266907, "start": 74, "tag": "NAME", "value": "Tristan Slominski" } ]
src/http.coffee
tristanls/anodejs
3
# # http.coffee : anode wrapper around Node.js 'http' module # # (C) 2011 Tristan Slominski # anode = require '../lib/anode' nodehttp = require 'http' # # Anode wrapper around the http.clientRequest # clientRequest_beh = anode.beh 'request' 'cust, #abort' : -> @request.abort() if @cust # ack requested @send( @, '#abort' ).to @cust 'cust, #end, [data], [encoding]' : -> @request.end @data, @encoding if @cust # ack requested @send( @, '#end' ).to @cust 'cust, #setNoDelay, noDelay' : -> @request.setNoDelay @noDelay if @cust # ack requested @send( @, '#setNoDelay' ).to @cust 'cust, #setSocketKeepAlive, enable, [initialDelay]' : -> @request.setSocketKeepAlive @enable, @initialDelay if @cust # ack requested @send( @, '#setSocketKeepAlive' ).to @cust 'cust, #setTimeout, timeout' : -> @request.setTimeout @timeout if @cust # ack requested @send( @, '#setTimeout' ).to @cust 'cust, #write, chunk, [encoding]' : -> @request.write chunk, @encoding if @cust # ack requested @send( @, '#write' ).to @cust # # Anode wrapper around the http.clientResponse # clientResponse_beh = anode.beh '_cust', 'response' 'cust, #headers' : -> @send( @, '#headers', @response.headers ).to @cust 'cust, #httpVersion' : -> @send( @, '#httpVersion', @response.httpVersion ).to @cust 'cust, #pause' : -> @response.pause() if @cust # ack requested @send( @, '#pause' ).to @cust 'cust, #resume' : -> @response.resume() if @cust # ack requested @send( @, '#resume' ).to @cust 'cust, #setEncoding, [encoding]' : -> @response.setEncoding( @encoding ) if @cust # ack requested @send( @, '#setEncoding' ).to @cust 'cust, #statusCode' : -> @send( @, '#statusCode', @response.statusCode ).to @cust 'cust, #trailers' : -> @send( @, '#trailers', @response.trailers ).to @cust '$response, #close, err' : -> @send( @, '#close', @err ).to @_cust '$response, #data, chunk' : -> @send( @, '#data', @chunk ).to @_cust '$response, #end' : -> @send( @, '#end' ).to @_cust # # Initialized http server beh wrapped around a created server # initializedServer_beh = anode.beh 'server', # stops the server from accepting new connections 'cust, #close' : -> @server.close() if @cust # ack requested @send( @, '#close' ).to @cust # # Actor wrapper around the request object that attaches the actor identity # with each message for distinction between messages from different # simultaneous requests # request_beh = anode.beh '_cust', 'req' # attempt to match the explicit $req first before trying generic 'cust' '$req, #close' : -> @send( @, '#close' ).to @_cust '$req, #data, chunk' : -> @send( @, '#data', @chunk ).to @_cust '$req, #end' : -> @send( @, '#end' ).to @_cust 'cust, #connection' : -> # TODO: implement net.Socket as actor @send( @, '#connection', @req.connection ).to @cust # headers 'cust, #headers' : -> @send( @, '#headers', @req.headers ).to @cust 'cust, #httpVersion' : -> @send( @, '#httpVersion', @req.httpVersion ).to @cust # the request method as a string 'cust, #method' : -> @send( @, '#method', @req.method ).to @cust # pauses request from emitting events 'cust, #pause' : -> @req.pause() if @cust # ack requested @send( @, '#pause' ).to @cust 'cust, #resume' : -> @req.resume() if @cust # ack requested @send( @, '#resume' ).to @cust 'cust, #setEncoding, encoding' : -> @req.setEncoding @encoding if @cust # ack requested @send( @, '#setEncoding' ).to @cust # trailers 'cust, #trailers' : -> @send( @, '#trailers', @req.trailers ).to @cust # requested URL string 'cust, #url' : -> @send( @, '#url', @req.url ).to @_cust # # An actor wrapper for the response object # response_beh = anode.beh 'res' 'cust, #addTrailers, headers' : -> @res.addTrailers @headers if @cust # ack requested @send( @, '#addTrailers' ).to @cust 'cust, #end, [data], [encoding]' : -> @res.end @data, @encoding if @cust # ack requested @send( @, '#end' ).to @cust 'cust, #getHeader, name' : -> @send( @, '#header', @res.getHeader @name ).to @cust 'cust, #removeHeader, name' : -> @res.removeHeader @name if @cust # ack requested @send( @, '#removeHeader' ). to @cust 'cust, #setHeader, name, value' : -> @res.setHeader @name, @value if @cust # ack requested @send( @, '#setHeader' ).to @cust 'cust, #statusCode, statusCode' : -> @res.statusCode @statusCode if @cust # ack requested @send( @, '#statusCode' ).to @cust 'cust, #write, chunk, [encoding]' : -> @res.write @chunk, @encoding if @cust # ack requested @send( @, '#write' ).to @cust 'cust, #writeContinue' : -> @res.writeContinue() if @cust # ack requested @send( @, '#writeContinue' ).to @cust 'cust, #writeHead, statusCode, [reasonPhrase], [headers]' : -> @res.writeHead @statusCode, @reasonPhrase, @headers if @cust # ack requested @send( @, '#writeHead' ).to @cust # # An http client beh that will execute client requests # client_beh = anode.beh # get convenience method, will create a request, set method to 'GET' # and automatically send '#end' message to request actor 'cust, #get, options' : -> # set method to GET @options.method = 'GET' # local aliases for use inside closures __httpClient = @ __cust = @cust __send = @send clientRequest = nodehttp.request @options request_actor = @create clientRequest_beh clientRequest # all clientRequest event bindings need to happen before nextTick clientRequest.on 'response', ( response ) -> response_actor = __create clientResponse_beh __cust, response response.on 'data', ( chunk ) -> __send( response, '#data', chunk ).to response_actor response.on 'end', -> __send( response, '#end' ).to response_actor response.on 'close', ( err ) -> __send( response, '#close', err ).to response_actor __send( __httpClient, '#response', response_actor ).to __cust clientRequest.on 'socket', ( socket ) -> # TODO clientRequest.on 'upgrade', ( response, socket, head ) -> # TODO clientRequest.on 'continue', -> __send( __httpClient, '#continue' ).to __cust # create 'callback' ack actor to execute once the 'get' request has been # sent, it matches this specific request_actor instance via $_request if @cust # ack requested ack = @create anode.beh( '_request' '$_request, #end' : -> __send( __httpClient, '#get', @_request ).to __cust )( request_actor ) ack = if ack then ack else undefined # send '#end' to request actor, executing the request, but give it # 'ack' actor ( if ack requested ) to listen for acknowledgment once '#end' # is executed, at which point, 'ack' will send an acknowledgment to the # customer of original '#get' request @send( ack, '#end' ).to request_actor # creates the request client 'cust, #request, options' : -> # local aliases for use inside closures __httpClient = @ __cust = @cust __send = @send clientRequest = nodehttp.request @options request_actor = @create clientRequest_beh clientRequest # all clientRequest event bindings need to happen before nextTick clientRequest.on 'response', ( response ) -> response_actor = __create clientResponse_beh __cust, response response.on 'data', ( chunk ) -> __send( response, '#data', chunk ).to response_actor response.on 'end', -> __send( response, '#end' ).to response_actor response.on 'close', ( err ) -> __send( response, '#close', err ).to response_actor __send( __httpClient, '#response', response_actor ).to __cust clientRequest.on 'socket', ( socket ) -> # TODO clientRequest.on 'upgrade', ( response, socket, head ) -> # TODO clientRequest.on 'continue', -> __send( __httpClient, '#continue' ).to __cust @send( @, '#request', request_actor ).to @cust # # An uninitialized http server beh that will lazy-initialize the server # and then become initialized http server beh # uninitializedServer_beh = anode.beh # creates the server and attempts to listen on given port and host 'cust, #listen, port, [host]' : -> # local aliases for use inside closures __create = @create __cust = @cust __host = @host __http = @ __port = @port __send = @send server = nodehttp.createServer() # all server event bindings need to happen before nextTick # on 'request' server.on 'request', ( req, res ) -> request_actor = __create request_beh __cust, req response_actor = __create response_beh res # all request binding needs to happen here before nextTick req.on 'data', ( chunk ) -> __send( req, '#data', chunk ).to request_actor req.on 'end', -> __send( req, '#end' ).to request_actor req.on 'close', -> __send( req, '#close' ).to request_actor __send( __http, '#request', request_actor, response_actor ).to __cust # on 'connection' server.on 'connection', ( socket ) -> # TODO # on 'close' server.on 'close', -> # TODO # on 'checkContinue' server.on 'checkContinue', ( req, res ) -> # TODO # on 'upgrade' server.on 'upgrade', ( request, socket, head ) -> # TODO # on clientError server.on 'clientError', ( exception ) -> # TODO # start listening if @cust # ack requested __callback = -> __send( __http, '#listen' ).to __cust @host = if @host then @host else undefined __callback = if __callback then __callback else undefined server.listen @port, @host, __callback @become initializedServer_beh server # # The request behavior for making http requests # exports.client_beh = client_beh # # The server behavior for serving http requests # exports.server_beh = uninitializedServer_beh
50523
# # http.coffee : anode wrapper around Node.js 'http' module # # (C) 2011 <NAME> # anode = require '../lib/anode' nodehttp = require 'http' # # Anode wrapper around the http.clientRequest # clientRequest_beh = anode.beh 'request' 'cust, #abort' : -> @request.abort() if @cust # ack requested @send( @, '#abort' ).to @cust 'cust, #end, [data], [encoding]' : -> @request.end @data, @encoding if @cust # ack requested @send( @, '#end' ).to @cust 'cust, #setNoDelay, noDelay' : -> @request.setNoDelay @noDelay if @cust # ack requested @send( @, '#setNoDelay' ).to @cust 'cust, #setSocketKeepAlive, enable, [initialDelay]' : -> @request.setSocketKeepAlive @enable, @initialDelay if @cust # ack requested @send( @, '#setSocketKeepAlive' ).to @cust 'cust, #setTimeout, timeout' : -> @request.setTimeout @timeout if @cust # ack requested @send( @, '#setTimeout' ).to @cust 'cust, #write, chunk, [encoding]' : -> @request.write chunk, @encoding if @cust # ack requested @send( @, '#write' ).to @cust # # Anode wrapper around the http.clientResponse # clientResponse_beh = anode.beh '_cust', 'response' 'cust, #headers' : -> @send( @, '#headers', @response.headers ).to @cust 'cust, #httpVersion' : -> @send( @, '#httpVersion', @response.httpVersion ).to @cust 'cust, #pause' : -> @response.pause() if @cust # ack requested @send( @, '#pause' ).to @cust 'cust, #resume' : -> @response.resume() if @cust # ack requested @send( @, '#resume' ).to @cust 'cust, #setEncoding, [encoding]' : -> @response.setEncoding( @encoding ) if @cust # ack requested @send( @, '#setEncoding' ).to @cust 'cust, #statusCode' : -> @send( @, '#statusCode', @response.statusCode ).to @cust 'cust, #trailers' : -> @send( @, '#trailers', @response.trailers ).to @cust '$response, #close, err' : -> @send( @, '#close', @err ).to @_cust '$response, #data, chunk' : -> @send( @, '#data', @chunk ).to @_cust '$response, #end' : -> @send( @, '#end' ).to @_cust # # Initialized http server beh wrapped around a created server # initializedServer_beh = anode.beh 'server', # stops the server from accepting new connections 'cust, #close' : -> @server.close() if @cust # ack requested @send( @, '#close' ).to @cust # # Actor wrapper around the request object that attaches the actor identity # with each message for distinction between messages from different # simultaneous requests # request_beh = anode.beh '_cust', 'req' # attempt to match the explicit $req first before trying generic 'cust' '$req, #close' : -> @send( @, '#close' ).to @_cust '$req, #data, chunk' : -> @send( @, '#data', @chunk ).to @_cust '$req, #end' : -> @send( @, '#end' ).to @_cust 'cust, #connection' : -> # TODO: implement net.Socket as actor @send( @, '#connection', @req.connection ).to @cust # headers 'cust, #headers' : -> @send( @, '#headers', @req.headers ).to @cust 'cust, #httpVersion' : -> @send( @, '#httpVersion', @req.httpVersion ).to @cust # the request method as a string 'cust, #method' : -> @send( @, '#method', @req.method ).to @cust # pauses request from emitting events 'cust, #pause' : -> @req.pause() if @cust # ack requested @send( @, '#pause' ).to @cust 'cust, #resume' : -> @req.resume() if @cust # ack requested @send( @, '#resume' ).to @cust 'cust, #setEncoding, encoding' : -> @req.setEncoding @encoding if @cust # ack requested @send( @, '#setEncoding' ).to @cust # trailers 'cust, #trailers' : -> @send( @, '#trailers', @req.trailers ).to @cust # requested URL string 'cust, #url' : -> @send( @, '#url', @req.url ).to @_cust # # An actor wrapper for the response object # response_beh = anode.beh 'res' 'cust, #addTrailers, headers' : -> @res.addTrailers @headers if @cust # ack requested @send( @, '#addTrailers' ).to @cust 'cust, #end, [data], [encoding]' : -> @res.end @data, @encoding if @cust # ack requested @send( @, '#end' ).to @cust 'cust, #getHeader, name' : -> @send( @, '#header', @res.getHeader @name ).to @cust 'cust, #removeHeader, name' : -> @res.removeHeader @name if @cust # ack requested @send( @, '#removeHeader' ). to @cust 'cust, #setHeader, name, value' : -> @res.setHeader @name, @value if @cust # ack requested @send( @, '#setHeader' ).to @cust 'cust, #statusCode, statusCode' : -> @res.statusCode @statusCode if @cust # ack requested @send( @, '#statusCode' ).to @cust 'cust, #write, chunk, [encoding]' : -> @res.write @chunk, @encoding if @cust # ack requested @send( @, '#write' ).to @cust 'cust, #writeContinue' : -> @res.writeContinue() if @cust # ack requested @send( @, '#writeContinue' ).to @cust 'cust, #writeHead, statusCode, [reasonPhrase], [headers]' : -> @res.writeHead @statusCode, @reasonPhrase, @headers if @cust # ack requested @send( @, '#writeHead' ).to @cust # # An http client beh that will execute client requests # client_beh = anode.beh # get convenience method, will create a request, set method to 'GET' # and automatically send '#end' message to request actor 'cust, #get, options' : -> # set method to GET @options.method = 'GET' # local aliases for use inside closures __httpClient = @ __cust = @cust __send = @send clientRequest = nodehttp.request @options request_actor = @create clientRequest_beh clientRequest # all clientRequest event bindings need to happen before nextTick clientRequest.on 'response', ( response ) -> response_actor = __create clientResponse_beh __cust, response response.on 'data', ( chunk ) -> __send( response, '#data', chunk ).to response_actor response.on 'end', -> __send( response, '#end' ).to response_actor response.on 'close', ( err ) -> __send( response, '#close', err ).to response_actor __send( __httpClient, '#response', response_actor ).to __cust clientRequest.on 'socket', ( socket ) -> # TODO clientRequest.on 'upgrade', ( response, socket, head ) -> # TODO clientRequest.on 'continue', -> __send( __httpClient, '#continue' ).to __cust # create 'callback' ack actor to execute once the 'get' request has been # sent, it matches this specific request_actor instance via $_request if @cust # ack requested ack = @create anode.beh( '_request' '$_request, #end' : -> __send( __httpClient, '#get', @_request ).to __cust )( request_actor ) ack = if ack then ack else undefined # send '#end' to request actor, executing the request, but give it # 'ack' actor ( if ack requested ) to listen for acknowledgment once '#end' # is executed, at which point, 'ack' will send an acknowledgment to the # customer of original '#get' request @send( ack, '#end' ).to request_actor # creates the request client 'cust, #request, options' : -> # local aliases for use inside closures __httpClient = @ __cust = @cust __send = @send clientRequest = nodehttp.request @options request_actor = @create clientRequest_beh clientRequest # all clientRequest event bindings need to happen before nextTick clientRequest.on 'response', ( response ) -> response_actor = __create clientResponse_beh __cust, response response.on 'data', ( chunk ) -> __send( response, '#data', chunk ).to response_actor response.on 'end', -> __send( response, '#end' ).to response_actor response.on 'close', ( err ) -> __send( response, '#close', err ).to response_actor __send( __httpClient, '#response', response_actor ).to __cust clientRequest.on 'socket', ( socket ) -> # TODO clientRequest.on 'upgrade', ( response, socket, head ) -> # TODO clientRequest.on 'continue', -> __send( __httpClient, '#continue' ).to __cust @send( @, '#request', request_actor ).to @cust # # An uninitialized http server beh that will lazy-initialize the server # and then become initialized http server beh # uninitializedServer_beh = anode.beh # creates the server and attempts to listen on given port and host 'cust, #listen, port, [host]' : -> # local aliases for use inside closures __create = @create __cust = @cust __host = @host __http = @ __port = @port __send = @send server = nodehttp.createServer() # all server event bindings need to happen before nextTick # on 'request' server.on 'request', ( req, res ) -> request_actor = __create request_beh __cust, req response_actor = __create response_beh res # all request binding needs to happen here before nextTick req.on 'data', ( chunk ) -> __send( req, '#data', chunk ).to request_actor req.on 'end', -> __send( req, '#end' ).to request_actor req.on 'close', -> __send( req, '#close' ).to request_actor __send( __http, '#request', request_actor, response_actor ).to __cust # on 'connection' server.on 'connection', ( socket ) -> # TODO # on 'close' server.on 'close', -> # TODO # on 'checkContinue' server.on 'checkContinue', ( req, res ) -> # TODO # on 'upgrade' server.on 'upgrade', ( request, socket, head ) -> # TODO # on clientError server.on 'clientError', ( exception ) -> # TODO # start listening if @cust # ack requested __callback = -> __send( __http, '#listen' ).to __cust @host = if @host then @host else undefined __callback = if __callback then __callback else undefined server.listen @port, @host, __callback @become initializedServer_beh server # # The request behavior for making http requests # exports.client_beh = client_beh # # The server behavior for serving http requests # exports.server_beh = uninitializedServer_beh
true
# # http.coffee : anode wrapper around Node.js 'http' module # # (C) 2011 PI:NAME:<NAME>END_PI # anode = require '../lib/anode' nodehttp = require 'http' # # Anode wrapper around the http.clientRequest # clientRequest_beh = anode.beh 'request' 'cust, #abort' : -> @request.abort() if @cust # ack requested @send( @, '#abort' ).to @cust 'cust, #end, [data], [encoding]' : -> @request.end @data, @encoding if @cust # ack requested @send( @, '#end' ).to @cust 'cust, #setNoDelay, noDelay' : -> @request.setNoDelay @noDelay if @cust # ack requested @send( @, '#setNoDelay' ).to @cust 'cust, #setSocketKeepAlive, enable, [initialDelay]' : -> @request.setSocketKeepAlive @enable, @initialDelay if @cust # ack requested @send( @, '#setSocketKeepAlive' ).to @cust 'cust, #setTimeout, timeout' : -> @request.setTimeout @timeout if @cust # ack requested @send( @, '#setTimeout' ).to @cust 'cust, #write, chunk, [encoding]' : -> @request.write chunk, @encoding if @cust # ack requested @send( @, '#write' ).to @cust # # Anode wrapper around the http.clientResponse # clientResponse_beh = anode.beh '_cust', 'response' 'cust, #headers' : -> @send( @, '#headers', @response.headers ).to @cust 'cust, #httpVersion' : -> @send( @, '#httpVersion', @response.httpVersion ).to @cust 'cust, #pause' : -> @response.pause() if @cust # ack requested @send( @, '#pause' ).to @cust 'cust, #resume' : -> @response.resume() if @cust # ack requested @send( @, '#resume' ).to @cust 'cust, #setEncoding, [encoding]' : -> @response.setEncoding( @encoding ) if @cust # ack requested @send( @, '#setEncoding' ).to @cust 'cust, #statusCode' : -> @send( @, '#statusCode', @response.statusCode ).to @cust 'cust, #trailers' : -> @send( @, '#trailers', @response.trailers ).to @cust '$response, #close, err' : -> @send( @, '#close', @err ).to @_cust '$response, #data, chunk' : -> @send( @, '#data', @chunk ).to @_cust '$response, #end' : -> @send( @, '#end' ).to @_cust # # Initialized http server beh wrapped around a created server # initializedServer_beh = anode.beh 'server', # stops the server from accepting new connections 'cust, #close' : -> @server.close() if @cust # ack requested @send( @, '#close' ).to @cust # # Actor wrapper around the request object that attaches the actor identity # with each message for distinction between messages from different # simultaneous requests # request_beh = anode.beh '_cust', 'req' # attempt to match the explicit $req first before trying generic 'cust' '$req, #close' : -> @send( @, '#close' ).to @_cust '$req, #data, chunk' : -> @send( @, '#data', @chunk ).to @_cust '$req, #end' : -> @send( @, '#end' ).to @_cust 'cust, #connection' : -> # TODO: implement net.Socket as actor @send( @, '#connection', @req.connection ).to @cust # headers 'cust, #headers' : -> @send( @, '#headers', @req.headers ).to @cust 'cust, #httpVersion' : -> @send( @, '#httpVersion', @req.httpVersion ).to @cust # the request method as a string 'cust, #method' : -> @send( @, '#method', @req.method ).to @cust # pauses request from emitting events 'cust, #pause' : -> @req.pause() if @cust # ack requested @send( @, '#pause' ).to @cust 'cust, #resume' : -> @req.resume() if @cust # ack requested @send( @, '#resume' ).to @cust 'cust, #setEncoding, encoding' : -> @req.setEncoding @encoding if @cust # ack requested @send( @, '#setEncoding' ).to @cust # trailers 'cust, #trailers' : -> @send( @, '#trailers', @req.trailers ).to @cust # requested URL string 'cust, #url' : -> @send( @, '#url', @req.url ).to @_cust # # An actor wrapper for the response object # response_beh = anode.beh 'res' 'cust, #addTrailers, headers' : -> @res.addTrailers @headers if @cust # ack requested @send( @, '#addTrailers' ).to @cust 'cust, #end, [data], [encoding]' : -> @res.end @data, @encoding if @cust # ack requested @send( @, '#end' ).to @cust 'cust, #getHeader, name' : -> @send( @, '#header', @res.getHeader @name ).to @cust 'cust, #removeHeader, name' : -> @res.removeHeader @name if @cust # ack requested @send( @, '#removeHeader' ). to @cust 'cust, #setHeader, name, value' : -> @res.setHeader @name, @value if @cust # ack requested @send( @, '#setHeader' ).to @cust 'cust, #statusCode, statusCode' : -> @res.statusCode @statusCode if @cust # ack requested @send( @, '#statusCode' ).to @cust 'cust, #write, chunk, [encoding]' : -> @res.write @chunk, @encoding if @cust # ack requested @send( @, '#write' ).to @cust 'cust, #writeContinue' : -> @res.writeContinue() if @cust # ack requested @send( @, '#writeContinue' ).to @cust 'cust, #writeHead, statusCode, [reasonPhrase], [headers]' : -> @res.writeHead @statusCode, @reasonPhrase, @headers if @cust # ack requested @send( @, '#writeHead' ).to @cust # # An http client beh that will execute client requests # client_beh = anode.beh # get convenience method, will create a request, set method to 'GET' # and automatically send '#end' message to request actor 'cust, #get, options' : -> # set method to GET @options.method = 'GET' # local aliases for use inside closures __httpClient = @ __cust = @cust __send = @send clientRequest = nodehttp.request @options request_actor = @create clientRequest_beh clientRequest # all clientRequest event bindings need to happen before nextTick clientRequest.on 'response', ( response ) -> response_actor = __create clientResponse_beh __cust, response response.on 'data', ( chunk ) -> __send( response, '#data', chunk ).to response_actor response.on 'end', -> __send( response, '#end' ).to response_actor response.on 'close', ( err ) -> __send( response, '#close', err ).to response_actor __send( __httpClient, '#response', response_actor ).to __cust clientRequest.on 'socket', ( socket ) -> # TODO clientRequest.on 'upgrade', ( response, socket, head ) -> # TODO clientRequest.on 'continue', -> __send( __httpClient, '#continue' ).to __cust # create 'callback' ack actor to execute once the 'get' request has been # sent, it matches this specific request_actor instance via $_request if @cust # ack requested ack = @create anode.beh( '_request' '$_request, #end' : -> __send( __httpClient, '#get', @_request ).to __cust )( request_actor ) ack = if ack then ack else undefined # send '#end' to request actor, executing the request, but give it # 'ack' actor ( if ack requested ) to listen for acknowledgment once '#end' # is executed, at which point, 'ack' will send an acknowledgment to the # customer of original '#get' request @send( ack, '#end' ).to request_actor # creates the request client 'cust, #request, options' : -> # local aliases for use inside closures __httpClient = @ __cust = @cust __send = @send clientRequest = nodehttp.request @options request_actor = @create clientRequest_beh clientRequest # all clientRequest event bindings need to happen before nextTick clientRequest.on 'response', ( response ) -> response_actor = __create clientResponse_beh __cust, response response.on 'data', ( chunk ) -> __send( response, '#data', chunk ).to response_actor response.on 'end', -> __send( response, '#end' ).to response_actor response.on 'close', ( err ) -> __send( response, '#close', err ).to response_actor __send( __httpClient, '#response', response_actor ).to __cust clientRequest.on 'socket', ( socket ) -> # TODO clientRequest.on 'upgrade', ( response, socket, head ) -> # TODO clientRequest.on 'continue', -> __send( __httpClient, '#continue' ).to __cust @send( @, '#request', request_actor ).to @cust # # An uninitialized http server beh that will lazy-initialize the server # and then become initialized http server beh # uninitializedServer_beh = anode.beh # creates the server and attempts to listen on given port and host 'cust, #listen, port, [host]' : -> # local aliases for use inside closures __create = @create __cust = @cust __host = @host __http = @ __port = @port __send = @send server = nodehttp.createServer() # all server event bindings need to happen before nextTick # on 'request' server.on 'request', ( req, res ) -> request_actor = __create request_beh __cust, req response_actor = __create response_beh res # all request binding needs to happen here before nextTick req.on 'data', ( chunk ) -> __send( req, '#data', chunk ).to request_actor req.on 'end', -> __send( req, '#end' ).to request_actor req.on 'close', -> __send( req, '#close' ).to request_actor __send( __http, '#request', request_actor, response_actor ).to __cust # on 'connection' server.on 'connection', ( socket ) -> # TODO # on 'close' server.on 'close', -> # TODO # on 'checkContinue' server.on 'checkContinue', ( req, res ) -> # TODO # on 'upgrade' server.on 'upgrade', ( request, socket, head ) -> # TODO # on clientError server.on 'clientError', ( exception ) -> # TODO # start listening if @cust # ack requested __callback = -> __send( __http, '#listen' ).to __cust @host = if @host then @host else undefined __callback = if __callback then __callback else undefined server.listen @port, @host, __callback @become initializedServer_beh server # # The request behavior for making http requests # exports.client_beh = client_beh # # The server behavior for serving http requests # exports.server_beh = uninitializedServer_beh
[ { "context": "# -*- coding: utf-8 -*-\n#\n# Copyright 2015 Roy Liu\n#\n# Licensed under the Apache License, Version 2.", "end": 50, "score": 0.9997628927230835, "start": 43, "tag": "NAME", "value": "Roy Liu" }, { "context": " @store.createRecord(\"spell\",\n name: \"Telep...
app/assets/javascripts/controllers/introduction_controller.coffee
carsomyr/nurf-stats
0
# -*- coding: utf-8 -*- # # Copyright 2015 Roy Liu # # 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. ((factory) -> if typeof define is "function" and define.amd? define ["ember", "application-base"], factory ).call(@, (Ember, # app) -> app.IntroductionController = Ember.Controller.extend fixtureAlistar: (-> @store.createRecord("champion", name: "Alistar" imagePath: "Alistar.png" ) ).property() fixtureBlitzcrank: (-> @store.createRecord("champion", name: "Blitzcrank" imagePath: "Blitzcrank.png" ) ).property() fixtureEzreal: (-> @store.createRecord("champion", name: "Ezreal" imagePath: "Ezreal.png" ) ).property() fixtureFlash: (-> @store.createRecord("spell", name: "Flash" imagePath: "SummonerFlash.png" ) ).property() fixtureLudensEcho: (-> @store.createRecord("item", name: "Luden's Echo" imagePath: "3285.png" ) ).property() fixtureNidalee: (-> @store.createRecord("champion", name: "Nidalee" imagePath: "Nidalee.png" ) ).property() fixtureShaco: (-> @store.createRecord("champion", name: "Shaco" imagePath: "Shaco.png" ) ).property() fixtureTeleport: (-> @store.createRecord("spell", name: "Teleport" imagePath: "SummonerTeleport.png" ) ).property() fixtureZed: (-> @store.createRecord("champion", name: "Zed" imagePath: "Zed.png" ) ).property() app.IntroductionController )
137168
# -*- coding: utf-8 -*- # # Copyright 2015 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. ((factory) -> if typeof define is "function" and define.amd? define ["ember", "application-base"], factory ).call(@, (Ember, # app) -> app.IntroductionController = Ember.Controller.extend fixtureAlistar: (-> @store.createRecord("champion", name: "Alistar" imagePath: "Alistar.png" ) ).property() fixtureBlitzcrank: (-> @store.createRecord("champion", name: "Blitzcrank" imagePath: "Blitzcrank.png" ) ).property() fixtureEzreal: (-> @store.createRecord("champion", name: "Ezreal" imagePath: "Ezreal.png" ) ).property() fixtureFlash: (-> @store.createRecord("spell", name: "Flash" imagePath: "SummonerFlash.png" ) ).property() fixtureLudensEcho: (-> @store.createRecord("item", name: "Luden's Echo" imagePath: "3285.png" ) ).property() fixtureNidalee: (-> @store.createRecord("champion", name: "Nidalee" imagePath: "Nidalee.png" ) ).property() fixtureShaco: (-> @store.createRecord("champion", name: "Shaco" imagePath: "Shaco.png" ) ).property() fixtureTeleport: (-> @store.createRecord("spell", name: "<NAME>" imagePath: "SummonerTeleport.png" ) ).property() fixtureZed: (-> @store.createRecord("champion", name: "<NAME>" imagePath: "Zed.png" ) ).property() app.IntroductionController )
true
# -*- coding: utf-8 -*- # # Copyright 2015 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. ((factory) -> if typeof define is "function" and define.amd? define ["ember", "application-base"], factory ).call(@, (Ember, # app) -> app.IntroductionController = Ember.Controller.extend fixtureAlistar: (-> @store.createRecord("champion", name: "Alistar" imagePath: "Alistar.png" ) ).property() fixtureBlitzcrank: (-> @store.createRecord("champion", name: "Blitzcrank" imagePath: "Blitzcrank.png" ) ).property() fixtureEzreal: (-> @store.createRecord("champion", name: "Ezreal" imagePath: "Ezreal.png" ) ).property() fixtureFlash: (-> @store.createRecord("spell", name: "Flash" imagePath: "SummonerFlash.png" ) ).property() fixtureLudensEcho: (-> @store.createRecord("item", name: "Luden's Echo" imagePath: "3285.png" ) ).property() fixtureNidalee: (-> @store.createRecord("champion", name: "Nidalee" imagePath: "Nidalee.png" ) ).property() fixtureShaco: (-> @store.createRecord("champion", name: "Shaco" imagePath: "Shaco.png" ) ).property() fixtureTeleport: (-> @store.createRecord("spell", name: "PI:NAME:<NAME>END_PI" imagePath: "SummonerTeleport.png" ) ).property() fixtureZed: (-> @store.createRecord("champion", name: "PI:NAME:<NAME>END_PI" imagePath: "Zed.png" ) ).property() app.IntroductionController )
[ { "context": "###################################\n# MINDAY 0.009 Lykia \n# sample-ishikawa.coffee\n# Пример применения диа", "end": 69, "score": 0.9145180583000183, "start": 64, "tag": "NAME", "value": "Lykia" }, { "context": "##################\n\nsample.gantt = ->\n\n\tgg = adf \"...
sample-gantt.coffee
agershun/minday
0
################################################ # MINDAY 0.009 Lykia # sample-ishikawa.coffee # Пример применения диаграммы ишикава ################################################ sample.gantt = -> gg = adf "Диаграмма Гантта" g=add "План работ",start:1,finish:10 gg.push g g.push add "Обследование",start:1,finish:3,result:(add "Отчет об обследовании") g.push add "Анализ",start:2,finish:4,result:(add "Отчет об анализе") g.push add "Дизайн",start:3,finish:5,result:(add "Прототип системы") g.push add "Разработка",start:4,finish:6,result:(add "Разработанная система") g.push add "Подготовка к запуску",start:5,finish:7,result:(add "План запуска") g.push add "Запуск",start:6,finish:8,result:(add "Работающая система") g.push add "Сопровождение",start:7,finish:9 g.push add "Поддержка",start:7,finish:10 g.phase = (gp=add "") gp.push add "Фаза 1",start:1,finish:5 gp.push add "Фаза 2",start:6,finish:10 g.kindGantt() gg
184069
################################################ # MINDAY 0.009 <NAME> # sample-ishikawa.coffee # Пример применения диаграммы ишикава ################################################ sample.gantt = -> gg = adf "<NAME>" g=add "План работ",start:1,finish:10 gg.push g g.push add "Обследование",start:1,finish:3,result:(add "Отчет об обследовании") g.push add "Анализ",start:2,finish:4,result:(add "Отчет об анализе") g.push add "Дизайн",start:3,finish:5,result:(add "Прототип системы") g.push add "Разработка",start:4,finish:6,result:(add "Разработанная система") g.push add "Подготовка к запуску",start:5,finish:7,result:(add "План запуска") g.push add "Запуск",start:6,finish:8,result:(add "Работающая система") g.push add "Сопровождение",start:7,finish:9 g.push add "Поддержка",start:7,finish:10 g.phase = (gp=add "") gp.push add "Фаза 1",start:1,finish:5 gp.push add "Фаза 2",start:6,finish:10 g.kindGantt() gg
true
################################################ # MINDAY 0.009 PI:NAME:<NAME>END_PI # sample-ishikawa.coffee # Пример применения диаграммы ишикава ################################################ sample.gantt = -> gg = adf "PI:NAME:<NAME>END_PI" g=add "План работ",start:1,finish:10 gg.push g g.push add "Обследование",start:1,finish:3,result:(add "Отчет об обследовании") g.push add "Анализ",start:2,finish:4,result:(add "Отчет об анализе") g.push add "Дизайн",start:3,finish:5,result:(add "Прототип системы") g.push add "Разработка",start:4,finish:6,result:(add "Разработанная система") g.push add "Подготовка к запуску",start:5,finish:7,result:(add "План запуска") g.push add "Запуск",start:6,finish:8,result:(add "Работающая система") g.push add "Сопровождение",start:7,finish:9 g.push add "Поддержка",start:7,finish:10 g.phase = (gp=add "") gp.push add "Фаза 1",start:1,finish:5 gp.push add "Фаза 2",start:6,finish:10 g.kindGantt() gg
[ { "context": "###\n mixin-js-flags.js 0.1.5\n (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/mixin/\n License: M", "end": 61, "score": 0.9997936487197876, "start": 47, "tag": "NAME", "value": "Kevin Malakoff" }, { "context": "js 0.1.5\n (c) 2011, 2012 Kevin Malakoff ...
src/lib/mixin-js-flags.coffee
kmalakoff/mixin
14
### mixin-js-flags.js 0.1.5 (c) 2011, 2012 Kevin Malakoff - http://kmalakoff.github.com/mixin/ License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Mixin.Core ### Mixin.Flags or= {} Mixin.Flags._mixin_info = mixin_name: 'Flags' initialize: (flags=0, change_callback) -> Mixin.instanceData(this, 'Flags', {flags: flags, change_callback: change_callback}) mixin_object: { flags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') # set if (flags != undefined) previous_flags = instance_data.flags instance_data.flags = flags instance_data.change_callback(instance_data.flags) if (instance_data.change_callback && (previous_flags!=instance_data.flags)) # get or set return instance_data.flags hasFlags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') return !!(instance_data.flags&flags) setFlags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') previous_flags = instance_data.flags instance_data.flags |= flags instance_data.change_callback(instance_data.flags) if (instance_data.change_callback && (previous_flags!=instance_data.flags)) return instance_data.flags resetFlags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') previous_flags = instance_data.flags instance_data.flags &= ~flags instance_data.change_callback(instance_data.flags) if (instance_data.change_callback && (previous_flags!=instance_data.flags)) return instance_data.flags } #################################################### # Make mixin available #################################################### Mixin.registerMixin(Mixin.Flags._mixin_info)
125603
### mixin-js-flags.js 0.1.5 (c) 2011, 2012 <NAME> - http://kmalakoff.github.com/mixin/ License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Mixin.Core ### Mixin.Flags or= {} Mixin.Flags._mixin_info = mixin_name: 'Flags' initialize: (flags=0, change_callback) -> Mixin.instanceData(this, 'Flags', {flags: flags, change_callback: change_callback}) mixin_object: { flags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') # set if (flags != undefined) previous_flags = instance_data.flags instance_data.flags = flags instance_data.change_callback(instance_data.flags) if (instance_data.change_callback && (previous_flags!=instance_data.flags)) # get or set return instance_data.flags hasFlags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') return !!(instance_data.flags&flags) setFlags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') previous_flags = instance_data.flags instance_data.flags |= flags instance_data.change_callback(instance_data.flags) if (instance_data.change_callback && (previous_flags!=instance_data.flags)) return instance_data.flags resetFlags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') previous_flags = instance_data.flags instance_data.flags &= ~flags instance_data.change_callback(instance_data.flags) if (instance_data.change_callback && (previous_flags!=instance_data.flags)) return instance_data.flags } #################################################### # Make mixin available #################################################### Mixin.registerMixin(Mixin.Flags._mixin_info)
true
### mixin-js-flags.js 0.1.5 (c) 2011, 2012 PI:NAME:<NAME>END_PI - http://kmalakoff.github.com/mixin/ License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Mixin.Core ### Mixin.Flags or= {} Mixin.Flags._mixin_info = mixin_name: 'Flags' initialize: (flags=0, change_callback) -> Mixin.instanceData(this, 'Flags', {flags: flags, change_callback: change_callback}) mixin_object: { flags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') # set if (flags != undefined) previous_flags = instance_data.flags instance_data.flags = flags instance_data.change_callback(instance_data.flags) if (instance_data.change_callback && (previous_flags!=instance_data.flags)) # get or set return instance_data.flags hasFlags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') return !!(instance_data.flags&flags) setFlags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') previous_flags = instance_data.flags instance_data.flags |= flags instance_data.change_callback(instance_data.flags) if (instance_data.change_callback && (previous_flags!=instance_data.flags)) return instance_data.flags resetFlags: (flags) -> instance_data = Mixin.instanceData(this, 'Flags') previous_flags = instance_data.flags instance_data.flags &= ~flags instance_data.change_callback(instance_data.flags) if (instance_data.change_callback && (previous_flags!=instance_data.flags)) return instance_data.flags } #################################################### # Make mixin available #################################################### Mixin.registerMixin(Mixin.Flags._mixin_info)
[ { "context": "body:\n essid: 'Testing'\n password: 'Testing'\n fetch '/sta', data\n .then ok\n\n it 'GET", "end": 191, "score": 0.9993703365325928, "start": 184, "tag": "PASSWORD", "value": "Testing" } ]
device/test/30-sta.coffee
twhtanghk/docker.esp8266
1
describe 'sta', -> it 'GET /sta', -> fetch '/sta' .then ok it 'PUT /sta', -> data = opts method: 'PUT' body: essid: 'Testing' password: 'Testing' fetch '/sta', data .then ok it 'GET /sta/scan', -> fetch '/sta/scan' .then ok
215240
describe 'sta', -> it 'GET /sta', -> fetch '/sta' .then ok it 'PUT /sta', -> data = opts method: 'PUT' body: essid: 'Testing' password: '<PASSWORD>' fetch '/sta', data .then ok it 'GET /sta/scan', -> fetch '/sta/scan' .then ok
true
describe 'sta', -> it 'GET /sta', -> fetch '/sta' .then ok it 'PUT /sta', -> data = opts method: 'PUT' body: essid: 'Testing' password: 'PI:PASSWORD:<PASSWORD>END_PI' fetch '/sta', data .then ok it 'GET /sta/scan', -> fetch '/sta/scan' .then ok
[ { "context": "(c) 2014 Klar Systems\n# License: MIT\n# Modified by Juha Tauriainen 2015\n###\n'use strict'\nangular.module('materialBat", "end": 105, "score": 0.9998960494995117, "start": 90, "tag": "NAME", "value": "Juha Tauriainen" } ]
src/angular-material-icons.coffee
purple-circle/battery-directive
4
### # angular-material-icons v0.4.0 # (c) 2014 Klar Systems # License: MIT # Modified by Juha Tauriainen 2015 ### 'use strict' angular.module('materialBatteryIcon', []).directive 'batteryIcon', -> shapes = 'battery_20': '<path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z"/><path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z"/>' 'battery_30': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V15h10V5.33z"/><path d="M7 15v5.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V15H7z"/>' 'battery_50': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"/><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"/>' 'battery_60': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h10V5.33z"/><path d="M7 11v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11H7z"/>' 'battery_80': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h10V5.33z"/><path d="M7 9v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9H7z"/>' 'battery_90': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/>' 'battery_alert': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM13 18h-2v-2h2v2zm0-4h-2V9h2v5z"/>' 'battery_charging_20': '<path d="M11 20v-3H7v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17h-4.4L11 20z"/><path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h4v-2.5H9L13 7v5.5h2L12.6 17H17V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_charging_30': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v9.17h2L13 7v5.5h2l-1.07 2H17V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M11 20v-5.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07L11 20z"/>' 'battery_charging_50': '<path d="M14.47 13.5L11 20v-5.5H9l.53-1H7v7.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13.5h-2.53z"/><path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v8.17h2.53L13 7v5.5h2l-.53 1H17V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_charging_60': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h3.87L13 7v4h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9l1.87-3.5H7v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11h-4v1.5z"/>' 'battery_charging_80': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z"/>' 'battery_charging_90': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h5.47L13 7v1h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L12.47 8H7v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8h-4v4.5z"/>' 'battery_charging_full': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM11 20v-5.5H9L13 7v5.5h2L11 20z"/>' 'battery_full': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_std': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_unknown': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zm-2.72 13.95h-1.9v-1.9h1.9v1.9zm1.35-5.26s-.38.42-.67.71c-.48.48-.83 1.15-.83 1.6h-1.6c0-.83.46-1.52.93-2l.93-.94c.27-.27.44-.65.44-1.06 0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5H9c0-1.66 1.34-3 3-3s3 1.34 3 3c0 .66-.27 1.26-.7 1.69z"/>' { restrict: 'E' link: (scope, element, attr) -> icon = undefined size = undefined render = -> # icon if attr.icon isnt undefined icon = attr.icon # Check for material-design-icons style name, and extract icon / size ss = icon.match(/ic_(.*)_([0-9]+)px.svg/m) if ss? icon = ss[1] size = ss[2] else icon = 'help' # validate if shapes[icon] == undefined icon = 'help' # size if attr.size? size = attr.size else if size isnt null size = 24 # render element.html '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="' + size + '" height="' + size + '">' + shapes[icon] + '</svg>' replace = (newicon) -> # validate if shapes[newicon] is undefined newicon = 'help' if newicon is icon return try # this block will succeed if SVGMorpheus is available # render new and old icons (old icon will be shown by default) element.html '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="' + size + '" height="' + size + '"><g id="' + newicon + '" style="display:none">' + shapes[newicon] + '</g><g id="' + icon + '" style="display:none">' + shapes[icon] + '</g></svg>' # morph new SVGMorpheus(element.children()[0]).to newicon, JSON.parse(attr.options or null) catch error # fallback element.html '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="' + size + '" height="' + size + '">' + shapes[newicon] + '</svg>' icon = newicon resize = (newsize) -> if newsize is size return children = element.children()[0] children.setAttribute 'width', newsize children.setAttribute 'height', newsize size = newsize # render the first time render() # watch for any changes if attr.icon isnt undefined attr.$observe 'icon', replace if attr.size isnt undefined attr.$observe 'size', resize }
34494
### # angular-material-icons v0.4.0 # (c) 2014 Klar Systems # License: MIT # Modified by <NAME> 2015 ### 'use strict' angular.module('materialBatteryIcon', []).directive 'batteryIcon', -> shapes = 'battery_20': '<path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z"/><path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z"/>' 'battery_30': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V15h10V5.33z"/><path d="M7 15v5.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V15H7z"/>' 'battery_50': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"/><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"/>' 'battery_60': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h10V5.33z"/><path d="M7 11v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11H7z"/>' 'battery_80': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h10V5.33z"/><path d="M7 9v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9H7z"/>' 'battery_90': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/>' 'battery_alert': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM13 18h-2v-2h2v2zm0-4h-2V9h2v5z"/>' 'battery_charging_20': '<path d="M11 20v-3H7v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17h-4.4L11 20z"/><path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h4v-2.5H9L13 7v5.5h2L12.6 17H17V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_charging_30': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v9.17h2L13 7v5.5h2l-1.07 2H17V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M11 20v-5.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07L11 20z"/>' 'battery_charging_50': '<path d="M14.47 13.5L11 20v-5.5H9l.53-1H7v7.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13.5h-2.53z"/><path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v8.17h2.53L13 7v5.5h2l-.53 1H17V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_charging_60': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h3.87L13 7v4h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9l1.87-3.5H7v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11h-4v1.5z"/>' 'battery_charging_80': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z"/>' 'battery_charging_90': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h5.47L13 7v1h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L12.47 8H7v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8h-4v4.5z"/>' 'battery_charging_full': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM11 20v-5.5H9L13 7v5.5h2L11 20z"/>' 'battery_full': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_std': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_unknown': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zm-2.72 13.95h-1.9v-1.9h1.9v1.9zm1.35-5.26s-.38.42-.67.71c-.48.48-.83 1.15-.83 1.6h-1.6c0-.83.46-1.52.93-2l.93-.94c.27-.27.44-.65.44-1.06 0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5H9c0-1.66 1.34-3 3-3s3 1.34 3 3c0 .66-.27 1.26-.7 1.69z"/>' { restrict: 'E' link: (scope, element, attr) -> icon = undefined size = undefined render = -> # icon if attr.icon isnt undefined icon = attr.icon # Check for material-design-icons style name, and extract icon / size ss = icon.match(/ic_(.*)_([0-9]+)px.svg/m) if ss? icon = ss[1] size = ss[2] else icon = 'help' # validate if shapes[icon] == undefined icon = 'help' # size if attr.size? size = attr.size else if size isnt null size = 24 # render element.html '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="' + size + '" height="' + size + '">' + shapes[icon] + '</svg>' replace = (newicon) -> # validate if shapes[newicon] is undefined newicon = 'help' if newicon is icon return try # this block will succeed if SVGMorpheus is available # render new and old icons (old icon will be shown by default) element.html '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="' + size + '" height="' + size + '"><g id="' + newicon + '" style="display:none">' + shapes[newicon] + '</g><g id="' + icon + '" style="display:none">' + shapes[icon] + '</g></svg>' # morph new SVGMorpheus(element.children()[0]).to newicon, JSON.parse(attr.options or null) catch error # fallback element.html '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="' + size + '" height="' + size + '">' + shapes[newicon] + '</svg>' icon = newicon resize = (newsize) -> if newsize is size return children = element.children()[0] children.setAttribute 'width', newsize children.setAttribute 'height', newsize size = newsize # render the first time render() # watch for any changes if attr.icon isnt undefined attr.$observe 'icon', replace if attr.size isnt undefined attr.$observe 'size', resize }
true
### # angular-material-icons v0.4.0 # (c) 2014 Klar Systems # License: MIT # Modified by PI:NAME:<NAME>END_PI 2015 ### 'use strict' angular.module('materialBatteryIcon', []).directive 'batteryIcon', -> shapes = 'battery_20': '<path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z"/><path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z"/>' 'battery_30': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V15h10V5.33z"/><path d="M7 15v5.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V15H7z"/>' 'battery_50': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"/><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"/>' 'battery_60': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h10V5.33z"/><path d="M7 11v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11H7z"/>' 'battery_80': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h10V5.33z"/><path d="M7 9v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9H7z"/>' 'battery_90': '<path fill-opacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/>' 'battery_alert': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM13 18h-2v-2h2v2zm0-4h-2V9h2v5z"/>' 'battery_charging_20': '<path d="M11 20v-3H7v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17h-4.4L11 20z"/><path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h4v-2.5H9L13 7v5.5h2L12.6 17H17V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_charging_30': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v9.17h2L13 7v5.5h2l-1.07 2H17V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M11 20v-5.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07L11 20z"/>' 'battery_charging_50': '<path d="M14.47 13.5L11 20v-5.5H9l.53-1H7v7.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13.5h-2.53z"/><path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v8.17h2.53L13 7v5.5h2l-.53 1H17V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_charging_60': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h3.87L13 7v4h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9l1.87-3.5H7v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11h-4v1.5z"/>' 'battery_charging_80': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z"/>' 'battery_charging_90': '<path fill-opacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h5.47L13 7v1h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L12.47 8H7v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8h-4v4.5z"/>' 'battery_charging_full': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zM11 20v-5.5H9L13 7v5.5h2L11 20z"/>' 'battery_full': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_std': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/>' 'battery_unknown': '<path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zm-2.72 13.95h-1.9v-1.9h1.9v1.9zm1.35-5.26s-.38.42-.67.71c-.48.48-.83 1.15-.83 1.6h-1.6c0-.83.46-1.52.93-2l.93-.94c.27-.27.44-.65.44-1.06 0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5H9c0-1.66 1.34-3 3-3s3 1.34 3 3c0 .66-.27 1.26-.7 1.69z"/>' { restrict: 'E' link: (scope, element, attr) -> icon = undefined size = undefined render = -> # icon if attr.icon isnt undefined icon = attr.icon # Check for material-design-icons style name, and extract icon / size ss = icon.match(/ic_(.*)_([0-9]+)px.svg/m) if ss? icon = ss[1] size = ss[2] else icon = 'help' # validate if shapes[icon] == undefined icon = 'help' # size if attr.size? size = attr.size else if size isnt null size = 24 # render element.html '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="' + size + '" height="' + size + '">' + shapes[icon] + '</svg>' replace = (newicon) -> # validate if shapes[newicon] is undefined newicon = 'help' if newicon is icon return try # this block will succeed if SVGMorpheus is available # render new and old icons (old icon will be shown by default) element.html '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="' + size + '" height="' + size + '"><g id="' + newicon + '" style="display:none">' + shapes[newicon] + '</g><g id="' + icon + '" style="display:none">' + shapes[icon] + '</g></svg>' # morph new SVGMorpheus(element.children()[0]).to newicon, JSON.parse(attr.options or null) catch error # fallback element.html '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="' + size + '" height="' + size + '">' + shapes[newicon] + '</svg>' icon = newicon resize = (newsize) -> if newsize is size return children = element.children()[0] children.setAttribute 'width', newsize children.setAttribute 'height', newsize size = newsize # render the first time render() # watch for any changes if attr.icon isnt undefined attr.$observe 'icon', replace if attr.size isnt undefined attr.$observe 'size', resize }
[ { "context": "\n window.print()\n\n userName: ->\n @name || \"Lorem Ipsum Name\"\n\n getCodeLanguageName: ->\n \"Python\"\n\n loadC", "end": 1895, "score": 0.8904175758361816, "start": 1879, "tag": "NAME", "value": "Lorem Ipsum Name" } ]
app/views/user/AnonCertificatesView.coffee
cihatislamdede/codecombat
4,858
require('app/styles/user/certificates-view.sass') RootView = require 'views/core/RootView' User = require 'models/User' LevelSession = require 'models/LevelSession' Levels = require 'collections/Levels' Level = require 'models/Level' utils = require 'core/utils' Campaign = require 'models/Campaign' # This certificate is generated anonymously. This requires the certificate # to be generated only from query params. # Requires campaign slug query param as well as username param. module.exports = class AnonCertificatesView extends RootView id: 'certificates-view' template: require 'templates/user/certificates-anon-view.pug' events: 'click .print-btn': 'onClickPrintButton' initialize: (options, userId) -> @loading = true user = new User _id:userId userPromise = user.fetch() campaignSlug = utils.getQueryVariable 'campaign' @name = utils.getQueryVariable 'username' levelsPromise = (new Levels()).fetchForCampaign(campaignSlug, {}) sessionsPromise = levelsPromise .then((l)=> return Promise.all( l.map((x)=>x._id) .map(@fetchLevelSession) ) ) # Initial data. @courseStats = { levels: { numDone: 0 }, linesOfCode: 0, courseComplete: true } Promise.all([userPromise, levelsPromise, sessionsPromise]) .then(([u, l, ls]) => ls = ls.map((data)=> new LevelSession(data)) l = l.map((data)=> new Level(data)) @concepts = @loadConcepts(l) @courseStats = @reduceSessionStats(ls, l) @loading = false @render() ) backgroundImage: -> "/images/pages/user/certificates/backgrounds/background-" + "hoc" + ".png" getMedallion: -> '/images/pages/user/certificates/medallions/medallion-' + 'gd3' + '.png' onClickPrintButton: -> window.print() userName: -> @name || "Lorem Ipsum Name" getCodeLanguageName: -> "Python" loadConcepts:(levels) -> allConcepts = levels .map((l)=>l.get("concepts")) .reduce((m, c) => return m.concat(c) , []) concepts = [] (new Set(allConcepts)) .forEach((v) => concepts.push(v)) return concepts getConcepts:-> @concepts fetchLevelSession:(levelID) -> url = "/db/level/#{levelID}/session" session = new LevelSession() return session.fetch({url: url}) reduceSessionStats: (sessions, levels) -> return sessions.reduce((stats, ls, i) => stats.levels.numDone += 1 stats.linesOfCode += ls.countOriginalLinesOfCode(levels[i]) return stats , @courseStats)
150848
require('app/styles/user/certificates-view.sass') RootView = require 'views/core/RootView' User = require 'models/User' LevelSession = require 'models/LevelSession' Levels = require 'collections/Levels' Level = require 'models/Level' utils = require 'core/utils' Campaign = require 'models/Campaign' # This certificate is generated anonymously. This requires the certificate # to be generated only from query params. # Requires campaign slug query param as well as username param. module.exports = class AnonCertificatesView extends RootView id: 'certificates-view' template: require 'templates/user/certificates-anon-view.pug' events: 'click .print-btn': 'onClickPrintButton' initialize: (options, userId) -> @loading = true user = new User _id:userId userPromise = user.fetch() campaignSlug = utils.getQueryVariable 'campaign' @name = utils.getQueryVariable 'username' levelsPromise = (new Levels()).fetchForCampaign(campaignSlug, {}) sessionsPromise = levelsPromise .then((l)=> return Promise.all( l.map((x)=>x._id) .map(@fetchLevelSession) ) ) # Initial data. @courseStats = { levels: { numDone: 0 }, linesOfCode: 0, courseComplete: true } Promise.all([userPromise, levelsPromise, sessionsPromise]) .then(([u, l, ls]) => ls = ls.map((data)=> new LevelSession(data)) l = l.map((data)=> new Level(data)) @concepts = @loadConcepts(l) @courseStats = @reduceSessionStats(ls, l) @loading = false @render() ) backgroundImage: -> "/images/pages/user/certificates/backgrounds/background-" + "hoc" + ".png" getMedallion: -> '/images/pages/user/certificates/medallions/medallion-' + 'gd3' + '.png' onClickPrintButton: -> window.print() userName: -> @name || "<NAME>" getCodeLanguageName: -> "Python" loadConcepts:(levels) -> allConcepts = levels .map((l)=>l.get("concepts")) .reduce((m, c) => return m.concat(c) , []) concepts = [] (new Set(allConcepts)) .forEach((v) => concepts.push(v)) return concepts getConcepts:-> @concepts fetchLevelSession:(levelID) -> url = "/db/level/#{levelID}/session" session = new LevelSession() return session.fetch({url: url}) reduceSessionStats: (sessions, levels) -> return sessions.reduce((stats, ls, i) => stats.levels.numDone += 1 stats.linesOfCode += ls.countOriginalLinesOfCode(levels[i]) return stats , @courseStats)
true
require('app/styles/user/certificates-view.sass') RootView = require 'views/core/RootView' User = require 'models/User' LevelSession = require 'models/LevelSession' Levels = require 'collections/Levels' Level = require 'models/Level' utils = require 'core/utils' Campaign = require 'models/Campaign' # This certificate is generated anonymously. This requires the certificate # to be generated only from query params. # Requires campaign slug query param as well as username param. module.exports = class AnonCertificatesView extends RootView id: 'certificates-view' template: require 'templates/user/certificates-anon-view.pug' events: 'click .print-btn': 'onClickPrintButton' initialize: (options, userId) -> @loading = true user = new User _id:userId userPromise = user.fetch() campaignSlug = utils.getQueryVariable 'campaign' @name = utils.getQueryVariable 'username' levelsPromise = (new Levels()).fetchForCampaign(campaignSlug, {}) sessionsPromise = levelsPromise .then((l)=> return Promise.all( l.map((x)=>x._id) .map(@fetchLevelSession) ) ) # Initial data. @courseStats = { levels: { numDone: 0 }, linesOfCode: 0, courseComplete: true } Promise.all([userPromise, levelsPromise, sessionsPromise]) .then(([u, l, ls]) => ls = ls.map((data)=> new LevelSession(data)) l = l.map((data)=> new Level(data)) @concepts = @loadConcepts(l) @courseStats = @reduceSessionStats(ls, l) @loading = false @render() ) backgroundImage: -> "/images/pages/user/certificates/backgrounds/background-" + "hoc" + ".png" getMedallion: -> '/images/pages/user/certificates/medallions/medallion-' + 'gd3' + '.png' onClickPrintButton: -> window.print() userName: -> @name || "PI:NAME:<NAME>END_PI" getCodeLanguageName: -> "Python" loadConcepts:(levels) -> allConcepts = levels .map((l)=>l.get("concepts")) .reduce((m, c) => return m.concat(c) , []) concepts = [] (new Set(allConcepts)) .forEach((v) => concepts.push(v)) return concepts getConcepts:-> @concepts fetchLevelSession:(levelID) -> url = "/db/level/#{levelID}/session" session = new LevelSession() return session.fetch({url: url}) reduceSessionStats: (sessions, levels) -> return sessions.reduce((stats, ls, i) => stats.levels.numDone += 1 stats.linesOfCode += ls.countOriginalLinesOfCode(levels[i]) return stats , @courseStats)
[ { "context": "###################################\n#\n# Created by Markus on 26/10/2017.\n#\n################################", "end": 101, "score": 0.9988530874252319, "start": 95, "tag": "NAME", "value": "Markus" } ]
server/3_database/modify.coffee
MooqitaSFH/worklearn
0
############################################################################### # # Created by Markus on 26/10/2017. # ############################################################################### ############################################################################### @set_field = (collection, item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.Error "Not permitted" if not collection throw new Meteor.Error "Collection undefined." type = Match.OneOf String, Number, Boolean array = [type] obj = Match.Where (x) -> l = Object.keys(x).length if l > 1000 return false for key, val of x check key, String check val, type return true check value, Match.OneOf type, array, obj check item_id, String check field, String csn = can_edit collection, item_id, user if not collection.findOne({owner_id: user._id}) throw new Meteor.Error("Not permitted.") res = modify_field_unprotected collection, item_id, field, value, user return res @set_challenge_field = (item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.Error "Not permitted" if not Challenges.findOne({_id: item_id, owner_id: user._id}) throw new Meteor.Error("Not permitted.") res = modify_field_unprotected Challenges, item_id, field, value, user return res @set_profile_field = (item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.Error "Not permitted" if not Profiles.findOne({_id: item_id, user_id: user._id}) throw new Meteor.Error("Not permitted.") res = modify_field_unprotected Profiles, item_id, field, value, user return res ############################################################################### @set_element = (collection, item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.error "Not permitted" if not collection throw new Meteor.Error "Collection undefined." check value, Match.OneOf String, Number, Boolean check item_id, String check field, String csn = can_edit collection, item_id, user if not csn throw new Meteor.Error "Not permitted." res = modify_field_unprotected collection, item_id, field, value return res ############################################################################### @modify_field_unprotected = (collection, id, field, value, user) -> if not collection throw new Meteor.Error "Collection undefined." check id, String s = {} s[field] = value s['modified'] = new Date mod = $set:s n = collection.update(id, mod) collection_name = get_collection_name collection #if typeof value == "string" # handle_text(collection_name, id, field, user) msg = "[" + collection_name + "] " msg += "[" + field + "] " msg += "[" + id + "] " msg += "set to [" + value.toString().substr(0, 30) + "]" log_event msg, event_db, event_edit return n
71793
############################################################################### # # Created by <NAME> on 26/10/2017. # ############################################################################### ############################################################################### @set_field = (collection, item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.Error "Not permitted" if not collection throw new Meteor.Error "Collection undefined." type = Match.OneOf String, Number, Boolean array = [type] obj = Match.Where (x) -> l = Object.keys(x).length if l > 1000 return false for key, val of x check key, String check val, type return true check value, Match.OneOf type, array, obj check item_id, String check field, String csn = can_edit collection, item_id, user if not collection.findOne({owner_id: user._id}) throw new Meteor.Error("Not permitted.") res = modify_field_unprotected collection, item_id, field, value, user return res @set_challenge_field = (item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.Error "Not permitted" if not Challenges.findOne({_id: item_id, owner_id: user._id}) throw new Meteor.Error("Not permitted.") res = modify_field_unprotected Challenges, item_id, field, value, user return res @set_profile_field = (item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.Error "Not permitted" if not Profiles.findOne({_id: item_id, user_id: user._id}) throw new Meteor.Error("Not permitted.") res = modify_field_unprotected Profiles, item_id, field, value, user return res ############################################################################### @set_element = (collection, item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.error "Not permitted" if not collection throw new Meteor.Error "Collection undefined." check value, Match.OneOf String, Number, Boolean check item_id, String check field, String csn = can_edit collection, item_id, user if not csn throw new Meteor.Error "Not permitted." res = modify_field_unprotected collection, item_id, field, value return res ############################################################################### @modify_field_unprotected = (collection, id, field, value, user) -> if not collection throw new Meteor.Error "Collection undefined." check id, String s = {} s[field] = value s['modified'] = new Date mod = $set:s n = collection.update(id, mod) collection_name = get_collection_name collection #if typeof value == "string" # handle_text(collection_name, id, field, user) msg = "[" + collection_name + "] " msg += "[" + field + "] " msg += "[" + id + "] " msg += "set to [" + value.toString().substr(0, 30) + "]" log_event msg, event_db, event_edit return n
true
############################################################################### # # Created by PI:NAME:<NAME>END_PI on 26/10/2017. # ############################################################################### ############################################################################### @set_field = (collection, item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.Error "Not permitted" if not collection throw new Meteor.Error "Collection undefined." type = Match.OneOf String, Number, Boolean array = [type] obj = Match.Where (x) -> l = Object.keys(x).length if l > 1000 return false for key, val of x check key, String check val, type return true check value, Match.OneOf type, array, obj check item_id, String check field, String csn = can_edit collection, item_id, user if not collection.findOne({owner_id: user._id}) throw new Meteor.Error("Not permitted.") res = modify_field_unprotected collection, item_id, field, value, user return res @set_challenge_field = (item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.Error "Not permitted" if not Challenges.findOne({_id: item_id, owner_id: user._id}) throw new Meteor.Error("Not permitted.") res = modify_field_unprotected Challenges, item_id, field, value, user return res @set_profile_field = (item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.Error "Not permitted" if not Profiles.findOne({_id: item_id, user_id: user._id}) throw new Meteor.Error("Not permitted.") res = modify_field_unprotected Profiles, item_id, field, value, user return res ############################################################################### @set_element = (collection, item_id, field, value) -> user = Meteor.user() if not user throw new Meteor.error "Not permitted" if not collection throw new Meteor.Error "Collection undefined." check value, Match.OneOf String, Number, Boolean check item_id, String check field, String csn = can_edit collection, item_id, user if not csn throw new Meteor.Error "Not permitted." res = modify_field_unprotected collection, item_id, field, value return res ############################################################################### @modify_field_unprotected = (collection, id, field, value, user) -> if not collection throw new Meteor.Error "Collection undefined." check id, String s = {} s[field] = value s['modified'] = new Date mod = $set:s n = collection.update(id, mod) collection_name = get_collection_name collection #if typeof value == "string" # handle_text(collection_name, id, field, user) msg = "[" + collection_name + "] " msg += "[" + field + "] " msg += "[" + id + "] " msg += "set to [" + value.toString().substr(0, 30) + "]" log_event msg, event_db, event_edit return n
[ { "context": "###\nNicholas Clawson -2014\n\nThe bottom toolbar. In charge handling use", "end": 20, "score": 0.9997664093971252, "start": 4, "tag": "NAME", "value": "Nicholas Clawson" }, { "context": ", borrowed from\n # https://github.com/Filirom1/stripcolorcodes (MIT l...
.atom/packages/grunt-runner/lib/grunt-runner-view.coffee
callistino/dotfiles
0
### Nicholas Clawson -2014 The bottom toolbar. In charge handling user input and implementing various commands. Creates a SelectListView and launches a task to discover the projects grunt commands. Logs errors and output. Also launches an Atom BufferedProcess to run grunt when needed. ### {View, BufferedProcess, Task} = require 'atom' ListView = require './task-list-view' module.exports = class ResultsView extends View path: null, process: null, taskList: null, # html layout @content: -> @div class: 'grunt-runner-results tool-panel panel-bottom native-key-bindings', => @div outlet:'status', class: 'grunt-panel-heading', => @div class: 'btn-group', => @button outlet:'startbtn', click:'toggleTaskList', class:'btn', 'Start Grunt' @button outlet:'stopbtn', click:'stopProcess', class:'btn', 'Stop Grunt' @button outlet:'logbtn', click:'toggleLog', class:'btn', 'Toggle Log' @button outlet:'panelbtn', click:'togglePanel', class:'btn', 'Hide' @div outlet:'panel', class: 'panel-body padded closed', => @ul outlet:'errors', class: 'list-group' # called after the view is constructed # gets the projects current path and launches a task # to parse the projects gruntfile if it exists initialize:(state = {}) -> @path = atom.project.getPath(); @taskList = new ListView @startProcess.bind(@), state.taskList view = @ Task.once require.resolve('./parse-config-task'), atom.project.getPath()+'/gruntfile', ({error, tasks})-> # now that we're ready, add some tooltips view.startbtn.setTooltip "", command: 'grunt-runner:run' view.stopbtn.setTooltip "", command: 'grunt-runner:stop' view.logbtn.setTooltip "", command: 'grunt-runner:toggle-log' view.panelbtn.setTooltip "", command: 'grunt-runner:toggle-panel' # log error or add panel to workspace if error console.warn "grunt-runner: #{error}" view.addLine "Error loading gruntfile: #{error}", "error" view.toggleLog() else view.togglePanel() view.taskList.addItems tasks # called to start the process # task name is gotten from the input element startProcess:(task) -> @stopProcess() @emptyPanel() @toggleLog() if @panel.hasClass 'closed' @status.attr 'data-status', 'loading' @addLine "Running : grunt #{task}", 'subtle' @gruntTask task, @path # stops the current process if it is running stopProcess: -> @addLine 'Grunt task was ended', 'warning' if @process and not @process?.killed @process?.kill() @process = null @status.attr 'data-status', null # toggles the visibility of the entire panel togglePanel: -> return atom.workspaceView.prependToBottom @ unless @.isOnDom() return @detach() if @.isOnDom() # toggles the visibility of the log toggleLog: -> @panel.toggleClass 'closed' # toggles the visibility of the tasklist toggleTaskList: -> return @taskList.attach() unless @taskList.isOnDom() return @taskList.cancel() # adds an entry to the log # converts all newlines to <br> addLine:(text, type = "plain") -> [panel, errorList] = [@panel, @errors] text = text.trim().replace /[\r\n]+/g, '<br />' stuckToBottom = errorList.height() - panel.height() - panel.scrollTop() == 0 errorList.append "<li class='text-#{type}'>#{text}</li>" panel.scrollTop errorList.height() if stuckToBottom # clears the log emptyPanel: -> @errors.empty() # returns a JSON object representing the state of the view serialize: -> return taskList: @taskList.serialize() # launches an Atom BufferedProcess gruntTask:(task, path) -> stdout = (out) -> # removed color commands, borrowed from # https://github.com/Filirom1/stripcolorcodes (MIT license) @addLine out.replace /\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, '' exit = (code) -> atom.beep() unless code == 0 @addLine "Grunt exited: code #{code}.", if code == 0 then 'success' else 'error' @status.attr 'data-status', if code == 0 then 'ready' else 'error' try @process = new BufferedProcess command: 'grunt' args: [task] options: {cwd: path} stdout: stdout.bind @ exit: exit.bind @ catch e # this never gets caught... @addLine "Could not find grunt command. Make sure to set the path in the configuration settings.", "error"
138152
### <NAME> -2014 The bottom toolbar. In charge handling user input and implementing various commands. Creates a SelectListView and launches a task to discover the projects grunt commands. Logs errors and output. Also launches an Atom BufferedProcess to run grunt when needed. ### {View, BufferedProcess, Task} = require 'atom' ListView = require './task-list-view' module.exports = class ResultsView extends View path: null, process: null, taskList: null, # html layout @content: -> @div class: 'grunt-runner-results tool-panel panel-bottom native-key-bindings', => @div outlet:'status', class: 'grunt-panel-heading', => @div class: 'btn-group', => @button outlet:'startbtn', click:'toggleTaskList', class:'btn', 'Start Grunt' @button outlet:'stopbtn', click:'stopProcess', class:'btn', 'Stop Grunt' @button outlet:'logbtn', click:'toggleLog', class:'btn', 'Toggle Log' @button outlet:'panelbtn', click:'togglePanel', class:'btn', 'Hide' @div outlet:'panel', class: 'panel-body padded closed', => @ul outlet:'errors', class: 'list-group' # called after the view is constructed # gets the projects current path and launches a task # to parse the projects gruntfile if it exists initialize:(state = {}) -> @path = atom.project.getPath(); @taskList = new ListView @startProcess.bind(@), state.taskList view = @ Task.once require.resolve('./parse-config-task'), atom.project.getPath()+'/gruntfile', ({error, tasks})-> # now that we're ready, add some tooltips view.startbtn.setTooltip "", command: 'grunt-runner:run' view.stopbtn.setTooltip "", command: 'grunt-runner:stop' view.logbtn.setTooltip "", command: 'grunt-runner:toggle-log' view.panelbtn.setTooltip "", command: 'grunt-runner:toggle-panel' # log error or add panel to workspace if error console.warn "grunt-runner: #{error}" view.addLine "Error loading gruntfile: #{error}", "error" view.toggleLog() else view.togglePanel() view.taskList.addItems tasks # called to start the process # task name is gotten from the input element startProcess:(task) -> @stopProcess() @emptyPanel() @toggleLog() if @panel.hasClass 'closed' @status.attr 'data-status', 'loading' @addLine "Running : grunt #{task}", 'subtle' @gruntTask task, @path # stops the current process if it is running stopProcess: -> @addLine 'Grunt task was ended', 'warning' if @process and not @process?.killed @process?.kill() @process = null @status.attr 'data-status', null # toggles the visibility of the entire panel togglePanel: -> return atom.workspaceView.prependToBottom @ unless @.isOnDom() return @detach() if @.isOnDom() # toggles the visibility of the log toggleLog: -> @panel.toggleClass 'closed' # toggles the visibility of the tasklist toggleTaskList: -> return @taskList.attach() unless @taskList.isOnDom() return @taskList.cancel() # adds an entry to the log # converts all newlines to <br> addLine:(text, type = "plain") -> [panel, errorList] = [@panel, @errors] text = text.trim().replace /[\r\n]+/g, '<br />' stuckToBottom = errorList.height() - panel.height() - panel.scrollTop() == 0 errorList.append "<li class='text-#{type}'>#{text}</li>" panel.scrollTop errorList.height() if stuckToBottom # clears the log emptyPanel: -> @errors.empty() # returns a JSON object representing the state of the view serialize: -> return taskList: @taskList.serialize() # launches an Atom BufferedProcess gruntTask:(task, path) -> stdout = (out) -> # removed color commands, borrowed from # https://github.com/Filirom1/stripcolorcodes (MIT license) @addLine out.replace /\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, '' exit = (code) -> atom.beep() unless code == 0 @addLine "Grunt exited: code #{code}.", if code == 0 then 'success' else 'error' @status.attr 'data-status', if code == 0 then 'ready' else 'error' try @process = new BufferedProcess command: 'grunt' args: [task] options: {cwd: path} stdout: stdout.bind @ exit: exit.bind @ catch e # this never gets caught... @addLine "Could not find grunt command. Make sure to set the path in the configuration settings.", "error"
true
### PI:NAME:<NAME>END_PI -2014 The bottom toolbar. In charge handling user input and implementing various commands. Creates a SelectListView and launches a task to discover the projects grunt commands. Logs errors and output. Also launches an Atom BufferedProcess to run grunt when needed. ### {View, BufferedProcess, Task} = require 'atom' ListView = require './task-list-view' module.exports = class ResultsView extends View path: null, process: null, taskList: null, # html layout @content: -> @div class: 'grunt-runner-results tool-panel panel-bottom native-key-bindings', => @div outlet:'status', class: 'grunt-panel-heading', => @div class: 'btn-group', => @button outlet:'startbtn', click:'toggleTaskList', class:'btn', 'Start Grunt' @button outlet:'stopbtn', click:'stopProcess', class:'btn', 'Stop Grunt' @button outlet:'logbtn', click:'toggleLog', class:'btn', 'Toggle Log' @button outlet:'panelbtn', click:'togglePanel', class:'btn', 'Hide' @div outlet:'panel', class: 'panel-body padded closed', => @ul outlet:'errors', class: 'list-group' # called after the view is constructed # gets the projects current path and launches a task # to parse the projects gruntfile if it exists initialize:(state = {}) -> @path = atom.project.getPath(); @taskList = new ListView @startProcess.bind(@), state.taskList view = @ Task.once require.resolve('./parse-config-task'), atom.project.getPath()+'/gruntfile', ({error, tasks})-> # now that we're ready, add some tooltips view.startbtn.setTooltip "", command: 'grunt-runner:run' view.stopbtn.setTooltip "", command: 'grunt-runner:stop' view.logbtn.setTooltip "", command: 'grunt-runner:toggle-log' view.panelbtn.setTooltip "", command: 'grunt-runner:toggle-panel' # log error or add panel to workspace if error console.warn "grunt-runner: #{error}" view.addLine "Error loading gruntfile: #{error}", "error" view.toggleLog() else view.togglePanel() view.taskList.addItems tasks # called to start the process # task name is gotten from the input element startProcess:(task) -> @stopProcess() @emptyPanel() @toggleLog() if @panel.hasClass 'closed' @status.attr 'data-status', 'loading' @addLine "Running : grunt #{task}", 'subtle' @gruntTask task, @path # stops the current process if it is running stopProcess: -> @addLine 'Grunt task was ended', 'warning' if @process and not @process?.killed @process?.kill() @process = null @status.attr 'data-status', null # toggles the visibility of the entire panel togglePanel: -> return atom.workspaceView.prependToBottom @ unless @.isOnDom() return @detach() if @.isOnDom() # toggles the visibility of the log toggleLog: -> @panel.toggleClass 'closed' # toggles the visibility of the tasklist toggleTaskList: -> return @taskList.attach() unless @taskList.isOnDom() return @taskList.cancel() # adds an entry to the log # converts all newlines to <br> addLine:(text, type = "plain") -> [panel, errorList] = [@panel, @errors] text = text.trim().replace /[\r\n]+/g, '<br />' stuckToBottom = errorList.height() - panel.height() - panel.scrollTop() == 0 errorList.append "<li class='text-#{type}'>#{text}</li>" panel.scrollTop errorList.height() if stuckToBottom # clears the log emptyPanel: -> @errors.empty() # returns a JSON object representing the state of the view serialize: -> return taskList: @taskList.serialize() # launches an Atom BufferedProcess gruntTask:(task, path) -> stdout = (out) -> # removed color commands, borrowed from # https://github.com/Filirom1/stripcolorcodes (MIT license) @addLine out.replace /\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, '' exit = (code) -> atom.beep() unless code == 0 @addLine "Grunt exited: code #{code}.", if code == 0 then 'success' else 'error' @status.attr 'data-status', if code == 0 then 'ready' else 'error' try @process = new BufferedProcess command: 'grunt' args: [task] options: {cwd: path} stdout: stdout.bind @ exit: exit.bind @ catch e # this never gets caught... @addLine "Could not find grunt command. Make sure to set the path in the configuration settings.", "error"
[ { "context": "ON.stringify({\n id: 100\n name: \"monster\"\n status: \"dead\"\n })\n }\n ", "end": 2220, "score": 0.9757388234138489, "start": 2213, "tag": "NAME", "value": "monster" }, { "context": " headers: {}\n petId: 1\n ...
src/swagger-http-spec.coffee
tinj/swagger-js
1
window.api_key = 'special-key' describe 'SwaggerHttp for version 1.2 spec', -> beforeEach -> success = -> log "success" window.authorizations.add "key", new ApiKeyAuthorization("api_key", "special-key", "header") window.swagger = new SwaggerApi({url: 'http://localhost:8002/api/api-docs', success: success}) waitsFor -> swagger.ready? describe "execute get operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a GET", -> params = { headers: {} petId: 1 } opts = { mock: true } window.response = swagger.pet.getPetById(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "GET" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/1") it "verifies the http request object for a GET with query params", -> params = { headers: {} status: "available" } opts = { mock: true } window.response = swagger.pet.findPetsByStatus(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "GET" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/findByStatus?status=available") describe "execute post operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a POST", -> params = { body: JSON.stringify({ id: 100 name: "monster" status: "dead" }) } opts = { mock: true } window.response = swagger.pet.addPet(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response log obj expect(obj.method).toBe "POST" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.headers["Content-Type"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet") it "verifies the http request object for a POST with form params", -> params = { headers: {} petId: 1 name: "dog" status: "very happy" } opts = { mock: true } window.response = swagger.pet.updatePetWithForm(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response log obj expect(obj.body).toBe "name=dog&status=very%20happy" expect(obj.method).toBe "POST" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/1") describe "execute put operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a PUT", -> params = { body: JSON.stringify({ id: 100 name: "monster" status: "dead" }) } opts = { mock: true } window.response = swagger.pet.updatePet(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "PUT" expect(obj.headers["Accept"]).toBe undefined expect(obj.headers["Content-Type"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet") describe "execute delete operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a DELETE", -> params = { petId: 100 } opts = { mock: true } window.response = swagger.pet.deletePet(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "DELETE" expect(obj.headers["Accept"]).toBe undefined expect(obj.headers["Content-Type"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/100") describe "query params should be single encoded", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a DELETE", -> params = { status: "a b c d e" } opts = { mock: true } window.response = swagger.pet.findPetsByStatus(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "GET" expect(obj.url).toBe ("http://localhost:8002/api/pet/findByStatus?status=a%20b%20c%20d%20e")
138926
window.api_key = 'special-key' describe 'SwaggerHttp for version 1.2 spec', -> beforeEach -> success = -> log "success" window.authorizations.add "key", new ApiKeyAuthorization("api_key", "special-key", "header") window.swagger = new SwaggerApi({url: 'http://localhost:8002/api/api-docs', success: success}) waitsFor -> swagger.ready? describe "execute get operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a GET", -> params = { headers: {} petId: 1 } opts = { mock: true } window.response = swagger.pet.getPetById(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "GET" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/1") it "verifies the http request object for a GET with query params", -> params = { headers: {} status: "available" } opts = { mock: true } window.response = swagger.pet.findPetsByStatus(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "GET" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/findByStatus?status=available") describe "execute post operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a POST", -> params = { body: JSON.stringify({ id: 100 name: "<NAME>" status: "dead" }) } opts = { mock: true } window.response = swagger.pet.addPet(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response log obj expect(obj.method).toBe "POST" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.headers["Content-Type"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet") it "verifies the http request object for a POST with form params", -> params = { headers: {} petId: 1 name: "<NAME>" status: "very happy" } opts = { mock: true } window.response = swagger.pet.updatePetWithForm(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response log obj expect(obj.body).toBe "name=dog&status=very%20happy" expect(obj.method).toBe "POST" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/1") describe "execute put operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a PUT", -> params = { body: JSON.stringify({ id: 100 name: "<NAME>" status: "dead" }) } opts = { mock: true } window.response = swagger.pet.updatePet(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "PUT" expect(obj.headers["Accept"]).toBe undefined expect(obj.headers["Content-Type"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet") describe "execute delete operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a DELETE", -> params = { petId: 100 } opts = { mock: true } window.response = swagger.pet.deletePet(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "DELETE" expect(obj.headers["Accept"]).toBe undefined expect(obj.headers["Content-Type"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/100") describe "query params should be single encoded", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a DELETE", -> params = { status: "a b c d e" } opts = { mock: true } window.response = swagger.pet.findPetsByStatus(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "GET" expect(obj.url).toBe ("http://localhost:8002/api/pet/findByStatus?status=a%20b%20c%20d%20e")
true
window.api_key = 'special-key' describe 'SwaggerHttp for version 1.2 spec', -> beforeEach -> success = -> log "success" window.authorizations.add "key", new ApiKeyAuthorization("api_key", "special-key", "header") window.swagger = new SwaggerApi({url: 'http://localhost:8002/api/api-docs', success: success}) waitsFor -> swagger.ready? describe "execute get operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a GET", -> params = { headers: {} petId: 1 } opts = { mock: true } window.response = swagger.pet.getPetById(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "GET" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/1") it "verifies the http request object for a GET with query params", -> params = { headers: {} status: "available" } opts = { mock: true } window.response = swagger.pet.findPetsByStatus(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "GET" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/findByStatus?status=available") describe "execute post operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a POST", -> params = { body: JSON.stringify({ id: 100 name: "PI:NAME:<NAME>END_PI" status: "dead" }) } opts = { mock: true } window.response = swagger.pet.addPet(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response log obj expect(obj.method).toBe "POST" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.headers["Content-Type"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet") it "verifies the http request object for a POST with form params", -> params = { headers: {} petId: 1 name: "PI:NAME:<NAME>END_PI" status: "very happy" } opts = { mock: true } window.response = swagger.pet.updatePetWithForm(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response log obj expect(obj.body).toBe "name=dog&status=very%20happy" expect(obj.method).toBe "POST" expect(obj.headers["Accept"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/1") describe "execute put operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a PUT", -> params = { body: JSON.stringify({ id: 100 name: "PI:NAME:<NAME>END_PI" status: "dead" }) } opts = { mock: true } window.response = swagger.pet.updatePet(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "PUT" expect(obj.headers["Accept"]).toBe undefined expect(obj.headers["Content-Type"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet") describe "execute delete operations", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a DELETE", -> params = { petId: 100 } opts = { mock: true } window.response = swagger.pet.deletePet(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "DELETE" expect(obj.headers["Accept"]).toBe undefined expect(obj.headers["Content-Type"]).toBe "application/json" expect(obj.url).toBe ("http://localhost:8002/api/pet/100") describe "query params should be single encoded", -> beforeEach -> window.body = null window.response = null window.callback = null window.error = null window.success_callback = (data) -> window.response = data window.error_callback = (data) -> window.error = data it "verifies the http request object for a DELETE", -> params = { status: "a b c d e" } opts = { mock: true } window.response = swagger.pet.findPetsByStatus(params, opts, success_callback, error_callback) waitsFor -> window.response? runs -> obj = window.response expect(obj.method).toBe "GET" expect(obj.url).toBe ("http://localhost:8002/api/pet/findByStatus?status=a%20b%20c%20d%20e")
[ { "context": "Loading = false\n return\n ,\n name: 'Vocaroo'\n style:\n border: 'none'\n widt", "end": 4400, "score": 0.9946165084838867, "start": 4393, "tag": "NAME", "value": "Vocaroo" }, { "context": " Embedding.cb.toggle @, el\n ,\n n...
src/Linkification/Embedding.coffee
ihavenoface/4chan-x
4
Embedding = init: -> return if g.VIEW is 'catalog' or !Conf['Embedding'] if Conf['Floating Embeds'] @dialog = UI.dialog 'embedding', 'top: 50px; right: 0px;', <%= importHTML('Linkification/Embed') %> @media = $ '#media-embed', @dialog $.on d, '4chanXInitFinished', @ready Post.callbacks.push name: 'Embedding' cb: @node node: -> anchors = $$ '.linkified', @nodes.comment return if !anchors.length or @isClone and !@origin.embeds for anchor in anchors for service in Embedding.services if result = service.regex.exec anchor.href break continue unless result embed = new Embed @, anchor, service, result do (embed) -> $.on embed.toggle, 'click', (e) -> Embedding.toggle embed, e return ready: -> $.off d, '4chanXInitFinished', Embedding.ready $.addClass Embedding.dialog, 'empty' $.on $('.close', Embedding.dialog), 'click', Embedding.toggleFloat $.on $('.move', Embedding.dialog), 'mousedown', Embedding.dragEmbed $.on $('.jump', Embedding.dialog), 'click', -> Header.scrollTo Embedding.lastEmbed.post.nodes.root $.add d.body, Embedding.dialog toggle: (embed, e) -> e.preventDefault() e.stopPropagation() return unless navigator.onLine if embed.isEmbedded embed.rmEmbed() embed.toggle.textContent = 'Embed' return else if embed.isLoading return embed.isLoading = true embed.service.embedURL.call embed toggleFloat: (e, embed) -> return unless div = Embedding.media.firstChild if el = embed?.el {href} = $ '[title="Link to this post"]', embed.post.nodes.info $.replace div, el Embedding.lastEmbed = embed $.rmClass Embedding.dialog, 'empty' return delete Embedding.lastEmbed $.addClass Embedding.dialog, 'empty' $.replace div, $.el 'div' dragEmbed: (e) -> # only webkit can handle a blocking div {style} = Embedding.media if Embedding.dragEmbed.mouseup $.off d, 'mouseup', Embedding.dragEmbed Embedding.dragEmbed.mouseup = false style.visibility = '' return $.on d, 'mouseup', Embedding.dragEmbed Embedding.dragEmbed.mouseup = true style.visibility = 'hidden' cb: toggle: (embed, el) -> embed.el = el {style} = embed.service if style $.extend el.style, style if Conf['Floating Embeds'] Embedding.toggleFloat null, embed embed.isLoading = false return div = $.el 'div', className: 'media-embed' $.add div, el $.after embed.span, div embed.toggle.textContent = 'Unembed' embed.isLoading = false embed.isEmbedded = true services: [ name: 'YouTube' style: border: 'none' width: '640px' height: '360px' regex: /^https?:\/\/(?:(?:www\.|m\.)?you.+v[=\/]|#p\/[a-z]\/.+\/|youtu\.be\/)([a-z0-9_-]+)(?:.*[#&\?]t=([0-9hms]+))?/i title: -> @entry.title.$t titleURL: -> "https://gdata.youtube.com/feeds/api/videos/#{@result[1]}?alt=json&fields=title/text(),yt:noembed,app:control/yt:state/@reasonCode" preview: -> "https://img.youtube.com/vi/#{@}/0.jpg" embedURL: -> [_, name, time] = @result time = if time match = /((\d+)h)?((\d+)m)?(\d+)?/.exec time time = parseInt(match[2] or 0) * 3600 + parseInt(match[4] or 0) * 60 + parseInt match[5] or 0 "&start=#{time}" else '' el = $.el 'iframe', src: "https://youtube.com/embed/#{name}?rel=1&autohide=1&iv_load_policy=3#{time}" Embedding.cb.toggle @, el , name: 'SoundCloud' regex: /(?:s(?:nd\.sc|oundcloud\.com)|www\.s(?:nd\.sc|oundcloud\.com)|m\.soundcloud\.com)\/([^#\&\?]+)/i title: -> @title titleURL: -> "https://soundcloud.com/oembed?&format=json&url=#{@anchor.href}" embedURL: -> url = "https://soundcloud.com/oembed?show_artwork=false&maxwidth=500px&show_comments=false&format=json&iframe=true&url=#{@anchor.href}" that = @ $.cache url, -> if @status in [200, 304] el = $.el 'div', innerHTML: JSON.parse(@response).html Embedding.cb.toggle that, el return that.isLoading = false return , name: 'Vocaroo' style: border: 'none' width: '150px' height: '45px' regex: /vocaroo\.com\/i\/([a-zA-Z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "http://vocaroo.com/player.swf?autoplay=0&playMediaID=#{@result[1]}" Embedding.cb.toggle @, el , name: 'Vimeo' style: border: 'none' width: '640px' height: '360px' regex: /vimeo\.com\/(?:m\/)?(\d+)(?:.*[#&\?](t=\d+))?/i title: -> @title titleURL: -> "https://vimeo.com/api/oembed.json?url=#{@anchor.href}" embedURL: -> el = $.el 'iframe', src: "https://player.vimeo.com/video/#{@result[1]}" Embedding.cb.toggle @, el , name: 'Pastebin' style: border: 'none' width: '640px' height: '500px' regex: /pastebin\.com\/(?!u\/)(?:raw.php\?i=)?([a-zA-Z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "http://pastebin.com/embed_iframe.php?i=#{@result[1]}" Embedding.cb.toggle @, el , name: 'Gist' style: border: 'none' width: '640px' height: '500px' regex: /gist\.github\.com\/\w+\/(\w+)/i title: -> response = @files return file for file of response when response.hasOwnProperty file titleURL: -> "https://api.github.com/gists/#{@result[1]}" embedURL: -> el = $.el 'iframe', src: "data:text/html,<script src='https://gist.github.com/#{@result[1]}.js'></script>" Embedding.cb.toggle @, el , name: 'InstallGentoo' style: border: 'none' width: '640px' height: '360px' regex: /paste\.installgentoo\.com\/view\/(?:raw\/)?([a-zA-Z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "http://paste.installgentoo.com/view/embed/#{@result[1]}" Embedding.cb.toggle @, el , name: 'imgur' style: border: 'none' cursor: 'pointer' regex: /imgur\.com\/(?!a\/)([a-zA-Z0-9]{7})(?:\.(?:a?png|jpg|gif))?/i embedURL: -> el = $.el 'img', # imgur/browser doesn't care about filetype so we # use this to embed files without type specified. src: "http://i.imgur.com/#{@result[1]}.png" className: 'image-embed' unless Embedding.style Embedding.style = $.addStyle null Embedding.services[7].resize() $.on window, 'resize', Embedding.services[7].resize {toggle} = @ unless Conf['Floating Embeds'] $.on el, 'click', -> $.rm el.parentNode toggle.textContent = 'Embed' Embedding.cb.toggle @, el resize: -> Embedding.style.textContent = ".media-embed .image-embed { max-height: #{parseInt innerHeight * .8}px; max-width: #{parseInt innerWidth * .8}px; }" , name: 'LiveLeak' style: border: 'none' width: '640px' height: '360px' regex: /liveleak\.com\/view.+i=([a-z0-9]{3}_\d+)/i embedURL: -> el = $.el 'iframe', src: "http://www.liveleak.com/e/#{@result[1]}" Embedding.cb.toggle @, el , name: 'TwitchTV' style: border: 'none' width: '640px' height: '360px' regex: /twitch\.tv\/(\w+)\/(?:b\/)?(\d+)/i embedURL: -> [_, channel, archive] = @result el = $.el 'object', data: 'http://www.twitch.tv/widgets/archive_embed_player.swf' innerHTML: """ <param name='allowFullScreen' value='true' /> <param name='flashvars' value='channel=#{channel}&start_volume=25&auto_play=false&archive_id=#{archive}' /> """ Embedding.cb.toggle @, el , name: 'Vine' style: border: 'none' width: '500px' height: '500px' regex: /vine\.co\/(v\/[a-z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "https://vine.co/#{@result[1]}/card" Embedding.cb.toggle @, el , name: 'Dailymotion' style: border: 'none' width: '620px' height: '352px' regex: /(?:dailymotion\.com\/video|dai.ly)\/([a-z0-9]+)(?:.+start=([0-9]+))?/i title: -> @title titleURL: -> "https://api.dailymotion.com/video/#{@result[1]}" embedURL: -> [_, name, time] = @result time = if time then time else '' el = $.el 'iframe', src: "https://www.dailymotion.com/embed/video/#{name}?logo=0#{time}" Embedding.cb.toggle @, el , name: 'StrawPoll' style: border: 'none' width: '600px' height: '406px' regex: /strawpoll\.me\/(?:embed_\d+\/)?(\d+)/i embedURL: -> el = $.el 'iframe', src: "http://strawpoll.me/embed_1/#{@result[1]}" Embedding.cb.toggle @, el ]
120263
Embedding = init: -> return if g.VIEW is 'catalog' or !Conf['Embedding'] if Conf['Floating Embeds'] @dialog = UI.dialog 'embedding', 'top: 50px; right: 0px;', <%= importHTML('Linkification/Embed') %> @media = $ '#media-embed', @dialog $.on d, '4chanXInitFinished', @ready Post.callbacks.push name: 'Embedding' cb: @node node: -> anchors = $$ '.linkified', @nodes.comment return if !anchors.length or @isClone and !@origin.embeds for anchor in anchors for service in Embedding.services if result = service.regex.exec anchor.href break continue unless result embed = new Embed @, anchor, service, result do (embed) -> $.on embed.toggle, 'click', (e) -> Embedding.toggle embed, e return ready: -> $.off d, '4chanXInitFinished', Embedding.ready $.addClass Embedding.dialog, 'empty' $.on $('.close', Embedding.dialog), 'click', Embedding.toggleFloat $.on $('.move', Embedding.dialog), 'mousedown', Embedding.dragEmbed $.on $('.jump', Embedding.dialog), 'click', -> Header.scrollTo Embedding.lastEmbed.post.nodes.root $.add d.body, Embedding.dialog toggle: (embed, e) -> e.preventDefault() e.stopPropagation() return unless navigator.onLine if embed.isEmbedded embed.rmEmbed() embed.toggle.textContent = 'Embed' return else if embed.isLoading return embed.isLoading = true embed.service.embedURL.call embed toggleFloat: (e, embed) -> return unless div = Embedding.media.firstChild if el = embed?.el {href} = $ '[title="Link to this post"]', embed.post.nodes.info $.replace div, el Embedding.lastEmbed = embed $.rmClass Embedding.dialog, 'empty' return delete Embedding.lastEmbed $.addClass Embedding.dialog, 'empty' $.replace div, $.el 'div' dragEmbed: (e) -> # only webkit can handle a blocking div {style} = Embedding.media if Embedding.dragEmbed.mouseup $.off d, 'mouseup', Embedding.dragEmbed Embedding.dragEmbed.mouseup = false style.visibility = '' return $.on d, 'mouseup', Embedding.dragEmbed Embedding.dragEmbed.mouseup = true style.visibility = 'hidden' cb: toggle: (embed, el) -> embed.el = el {style} = embed.service if style $.extend el.style, style if Conf['Floating Embeds'] Embedding.toggleFloat null, embed embed.isLoading = false return div = $.el 'div', className: 'media-embed' $.add div, el $.after embed.span, div embed.toggle.textContent = 'Unembed' embed.isLoading = false embed.isEmbedded = true services: [ name: 'YouTube' style: border: 'none' width: '640px' height: '360px' regex: /^https?:\/\/(?:(?:www\.|m\.)?you.+v[=\/]|#p\/[a-z]\/.+\/|youtu\.be\/)([a-z0-9_-]+)(?:.*[#&\?]t=([0-9hms]+))?/i title: -> @entry.title.$t titleURL: -> "https://gdata.youtube.com/feeds/api/videos/#{@result[1]}?alt=json&fields=title/text(),yt:noembed,app:control/yt:state/@reasonCode" preview: -> "https://img.youtube.com/vi/#{@}/0.jpg" embedURL: -> [_, name, time] = @result time = if time match = /((\d+)h)?((\d+)m)?(\d+)?/.exec time time = parseInt(match[2] or 0) * 3600 + parseInt(match[4] or 0) * 60 + parseInt match[5] or 0 "&start=#{time}" else '' el = $.el 'iframe', src: "https://youtube.com/embed/#{name}?rel=1&autohide=1&iv_load_policy=3#{time}" Embedding.cb.toggle @, el , name: 'SoundCloud' regex: /(?:s(?:nd\.sc|oundcloud\.com)|www\.s(?:nd\.sc|oundcloud\.com)|m\.soundcloud\.com)\/([^#\&\?]+)/i title: -> @title titleURL: -> "https://soundcloud.com/oembed?&format=json&url=#{@anchor.href}" embedURL: -> url = "https://soundcloud.com/oembed?show_artwork=false&maxwidth=500px&show_comments=false&format=json&iframe=true&url=#{@anchor.href}" that = @ $.cache url, -> if @status in [200, 304] el = $.el 'div', innerHTML: JSON.parse(@response).html Embedding.cb.toggle that, el return that.isLoading = false return , name: '<NAME>' style: border: 'none' width: '150px' height: '45px' regex: /vocaroo\.com\/i\/([a-zA-Z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "http://vocaroo.com/player.swf?autoplay=0&playMediaID=#{@result[1]}" Embedding.cb.toggle @, el , name: '<NAME>' style: border: 'none' width: '640px' height: '360px' regex: /vimeo\.com\/(?:m\/)?(\d+)(?:.*[#&\?](t=\d+))?/i title: -> @title titleURL: -> "https://vimeo.com/api/oembed.json?url=#{@anchor.href}" embedURL: -> el = $.el 'iframe', src: "https://player.vimeo.com/video/#{@result[1]}" Embedding.cb.toggle @, el , name: '<NAME>' style: border: 'none' width: '640px' height: '500px' regex: /pastebin\.com\/(?!u\/)(?:raw.php\?i=)?([a-zA-Z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "http://pastebin.com/embed_iframe.php?i=#{@result[1]}" Embedding.cb.toggle @, el , name: 'Gist' style: border: 'none' width: '640px' height: '500px' regex: /gist\.github\.com\/\w+\/(\w+)/i title: -> response = @files return file for file of response when response.hasOwnProperty file titleURL: -> "https://api.github.com/gists/#{@result[1]}" embedURL: -> el = $.el 'iframe', src: "data:text/html,<script src='https://gist.github.com/#{@result[1]}.js'></script>" Embedding.cb.toggle @, el , name: 'InstallGentoo' style: border: 'none' width: '640px' height: '360px' regex: /paste\.installgentoo\.com\/view\/(?:raw\/)?([a-zA-Z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "http://paste.installgentoo.com/view/embed/#{@result[1]}" Embedding.cb.toggle @, el , name: 'imgur' style: border: 'none' cursor: 'pointer' regex: /imgur\.com\/(?!a\/)([a-zA-Z0-9]{7})(?:\.(?:a?png|jpg|gif))?/i embedURL: -> el = $.el 'img', # imgur/browser doesn't care about filetype so we # use this to embed files without type specified. src: "http://i.imgur.com/#{@result[1]}.png" className: 'image-embed' unless Embedding.style Embedding.style = $.addStyle null Embedding.services[7].resize() $.on window, 'resize', Embedding.services[7].resize {toggle} = @ unless Conf['Floating Embeds'] $.on el, 'click', -> $.rm el.parentNode toggle.textContent = 'Embed' Embedding.cb.toggle @, el resize: -> Embedding.style.textContent = ".media-embed .image-embed { max-height: #{parseInt innerHeight * .8}px; max-width: #{parseInt innerWidth * .8}px; }" , name: 'LiveLeak' style: border: 'none' width: '640px' height: '360px' regex: /liveleak\.com\/view.+i=([a-z0-9]{3}_\d+)/i embedURL: -> el = $.el 'iframe', src: "http://www.liveleak.com/e/#{@result[1]}" Embedding.cb.toggle @, el , name: 'TwitchTV' style: border: 'none' width: '640px' height: '360px' regex: /twitch\.tv\/(\w+)\/(?:b\/)?(\d+)/i embedURL: -> [_, channel, archive] = @result el = $.el 'object', data: 'http://www.twitch.tv/widgets/archive_embed_player.swf' innerHTML: """ <param name='allowFullScreen' value='true' /> <param name='flashvars' value='channel=#{channel}&start_volume=25&auto_play=false&archive_id=#{archive}' /> """ Embedding.cb.toggle @, el , name: 'Vine' style: border: 'none' width: '500px' height: '500px' regex: /vine\.co\/(v\/[a-z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "https://vine.co/#{@result[1]}/card" Embedding.cb.toggle @, el , name: 'Dailymotion' style: border: 'none' width: '620px' height: '352px' regex: /(?:dailymotion\.com\/video|dai.ly)\/([a-z0-9]+)(?:.+start=([0-9]+))?/i title: -> @title titleURL: -> "https://api.dailymotion.com/video/#{@result[1]}" embedURL: -> [_, name, time] = @result time = if time then time else '' el = $.el 'iframe', src: "https://www.dailymotion.com/embed/video/#{name}?logo=0#{time}" Embedding.cb.toggle @, el , name: '<NAME>awPoll' style: border: 'none' width: '600px' height: '406px' regex: /strawpoll\.me\/(?:embed_\d+\/)?(\d+)/i embedURL: -> el = $.el 'iframe', src: "http://strawpoll.me/embed_1/#{@result[1]}" Embedding.cb.toggle @, el ]
true
Embedding = init: -> return if g.VIEW is 'catalog' or !Conf['Embedding'] if Conf['Floating Embeds'] @dialog = UI.dialog 'embedding', 'top: 50px; right: 0px;', <%= importHTML('Linkification/Embed') %> @media = $ '#media-embed', @dialog $.on d, '4chanXInitFinished', @ready Post.callbacks.push name: 'Embedding' cb: @node node: -> anchors = $$ '.linkified', @nodes.comment return if !anchors.length or @isClone and !@origin.embeds for anchor in anchors for service in Embedding.services if result = service.regex.exec anchor.href break continue unless result embed = new Embed @, anchor, service, result do (embed) -> $.on embed.toggle, 'click', (e) -> Embedding.toggle embed, e return ready: -> $.off d, '4chanXInitFinished', Embedding.ready $.addClass Embedding.dialog, 'empty' $.on $('.close', Embedding.dialog), 'click', Embedding.toggleFloat $.on $('.move', Embedding.dialog), 'mousedown', Embedding.dragEmbed $.on $('.jump', Embedding.dialog), 'click', -> Header.scrollTo Embedding.lastEmbed.post.nodes.root $.add d.body, Embedding.dialog toggle: (embed, e) -> e.preventDefault() e.stopPropagation() return unless navigator.onLine if embed.isEmbedded embed.rmEmbed() embed.toggle.textContent = 'Embed' return else if embed.isLoading return embed.isLoading = true embed.service.embedURL.call embed toggleFloat: (e, embed) -> return unless div = Embedding.media.firstChild if el = embed?.el {href} = $ '[title="Link to this post"]', embed.post.nodes.info $.replace div, el Embedding.lastEmbed = embed $.rmClass Embedding.dialog, 'empty' return delete Embedding.lastEmbed $.addClass Embedding.dialog, 'empty' $.replace div, $.el 'div' dragEmbed: (e) -> # only webkit can handle a blocking div {style} = Embedding.media if Embedding.dragEmbed.mouseup $.off d, 'mouseup', Embedding.dragEmbed Embedding.dragEmbed.mouseup = false style.visibility = '' return $.on d, 'mouseup', Embedding.dragEmbed Embedding.dragEmbed.mouseup = true style.visibility = 'hidden' cb: toggle: (embed, el) -> embed.el = el {style} = embed.service if style $.extend el.style, style if Conf['Floating Embeds'] Embedding.toggleFloat null, embed embed.isLoading = false return div = $.el 'div', className: 'media-embed' $.add div, el $.after embed.span, div embed.toggle.textContent = 'Unembed' embed.isLoading = false embed.isEmbedded = true services: [ name: 'YouTube' style: border: 'none' width: '640px' height: '360px' regex: /^https?:\/\/(?:(?:www\.|m\.)?you.+v[=\/]|#p\/[a-z]\/.+\/|youtu\.be\/)([a-z0-9_-]+)(?:.*[#&\?]t=([0-9hms]+))?/i title: -> @entry.title.$t titleURL: -> "https://gdata.youtube.com/feeds/api/videos/#{@result[1]}?alt=json&fields=title/text(),yt:noembed,app:control/yt:state/@reasonCode" preview: -> "https://img.youtube.com/vi/#{@}/0.jpg" embedURL: -> [_, name, time] = @result time = if time match = /((\d+)h)?((\d+)m)?(\d+)?/.exec time time = parseInt(match[2] or 0) * 3600 + parseInt(match[4] or 0) * 60 + parseInt match[5] or 0 "&start=#{time}" else '' el = $.el 'iframe', src: "https://youtube.com/embed/#{name}?rel=1&autohide=1&iv_load_policy=3#{time}" Embedding.cb.toggle @, el , name: 'SoundCloud' regex: /(?:s(?:nd\.sc|oundcloud\.com)|www\.s(?:nd\.sc|oundcloud\.com)|m\.soundcloud\.com)\/([^#\&\?]+)/i title: -> @title titleURL: -> "https://soundcloud.com/oembed?&format=json&url=#{@anchor.href}" embedURL: -> url = "https://soundcloud.com/oembed?show_artwork=false&maxwidth=500px&show_comments=false&format=json&iframe=true&url=#{@anchor.href}" that = @ $.cache url, -> if @status in [200, 304] el = $.el 'div', innerHTML: JSON.parse(@response).html Embedding.cb.toggle that, el return that.isLoading = false return , name: 'PI:NAME:<NAME>END_PI' style: border: 'none' width: '150px' height: '45px' regex: /vocaroo\.com\/i\/([a-zA-Z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "http://vocaroo.com/player.swf?autoplay=0&playMediaID=#{@result[1]}" Embedding.cb.toggle @, el , name: 'PI:NAME:<NAME>END_PI' style: border: 'none' width: '640px' height: '360px' regex: /vimeo\.com\/(?:m\/)?(\d+)(?:.*[#&\?](t=\d+))?/i title: -> @title titleURL: -> "https://vimeo.com/api/oembed.json?url=#{@anchor.href}" embedURL: -> el = $.el 'iframe', src: "https://player.vimeo.com/video/#{@result[1]}" Embedding.cb.toggle @, el , name: 'PI:NAME:<NAME>END_PI' style: border: 'none' width: '640px' height: '500px' regex: /pastebin\.com\/(?!u\/)(?:raw.php\?i=)?([a-zA-Z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "http://pastebin.com/embed_iframe.php?i=#{@result[1]}" Embedding.cb.toggle @, el , name: 'Gist' style: border: 'none' width: '640px' height: '500px' regex: /gist\.github\.com\/\w+\/(\w+)/i title: -> response = @files return file for file of response when response.hasOwnProperty file titleURL: -> "https://api.github.com/gists/#{@result[1]}" embedURL: -> el = $.el 'iframe', src: "data:text/html,<script src='https://gist.github.com/#{@result[1]}.js'></script>" Embedding.cb.toggle @, el , name: 'InstallGentoo' style: border: 'none' width: '640px' height: '360px' regex: /paste\.installgentoo\.com\/view\/(?:raw\/)?([a-zA-Z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "http://paste.installgentoo.com/view/embed/#{@result[1]}" Embedding.cb.toggle @, el , name: 'imgur' style: border: 'none' cursor: 'pointer' regex: /imgur\.com\/(?!a\/)([a-zA-Z0-9]{7})(?:\.(?:a?png|jpg|gif))?/i embedURL: -> el = $.el 'img', # imgur/browser doesn't care about filetype so we # use this to embed files without type specified. src: "http://i.imgur.com/#{@result[1]}.png" className: 'image-embed' unless Embedding.style Embedding.style = $.addStyle null Embedding.services[7].resize() $.on window, 'resize', Embedding.services[7].resize {toggle} = @ unless Conf['Floating Embeds'] $.on el, 'click', -> $.rm el.parentNode toggle.textContent = 'Embed' Embedding.cb.toggle @, el resize: -> Embedding.style.textContent = ".media-embed .image-embed { max-height: #{parseInt innerHeight * .8}px; max-width: #{parseInt innerWidth * .8}px; }" , name: 'LiveLeak' style: border: 'none' width: '640px' height: '360px' regex: /liveleak\.com\/view.+i=([a-z0-9]{3}_\d+)/i embedURL: -> el = $.el 'iframe', src: "http://www.liveleak.com/e/#{@result[1]}" Embedding.cb.toggle @, el , name: 'TwitchTV' style: border: 'none' width: '640px' height: '360px' regex: /twitch\.tv\/(\w+)\/(?:b\/)?(\d+)/i embedURL: -> [_, channel, archive] = @result el = $.el 'object', data: 'http://www.twitch.tv/widgets/archive_embed_player.swf' innerHTML: """ <param name='allowFullScreen' value='true' /> <param name='flashvars' value='channel=#{channel}&start_volume=25&auto_play=false&archive_id=#{archive}' /> """ Embedding.cb.toggle @, el , name: 'Vine' style: border: 'none' width: '500px' height: '500px' regex: /vine\.co\/(v\/[a-z0-9]+)/i embedURL: -> el = $.el 'iframe', src: "https://vine.co/#{@result[1]}/card" Embedding.cb.toggle @, el , name: 'Dailymotion' style: border: 'none' width: '620px' height: '352px' regex: /(?:dailymotion\.com\/video|dai.ly)\/([a-z0-9]+)(?:.+start=([0-9]+))?/i title: -> @title titleURL: -> "https://api.dailymotion.com/video/#{@result[1]}" embedURL: -> [_, name, time] = @result time = if time then time else '' el = $.el 'iframe', src: "https://www.dailymotion.com/embed/video/#{name}?logo=0#{time}" Embedding.cb.toggle @, el , name: 'PI:NAME:<NAME>END_PIawPoll' style: border: 'none' width: '600px' height: '406px' regex: /strawpoll\.me\/(?:embed_\d+\/)?(\d+)/i embedURL: -> el = $.el 'iframe', src: "http://strawpoll.me/embed_1/#{@result[1]}" Embedding.cb.toggle @, el ]
[ { "context": "PDFDocument - represents an entire PDF document\nBy Devon Govett\n###\n\nfs = require 'fs'\nPDFObjectStore = require '", "end": 67, "score": 0.999858021736145, "start": 55, "tag": "NAME", "value": "Devon Govett" } ]
lib/document.coffee
sax1johno/pdfkit
1
### PDFDocument - represents an entire PDF document By Devon Govett ### fs = require 'fs' PDFObjectStore = require './store' PDFObject = require './object' PDFReference = require './reference' PDFPage = require './page' class PDFDocument constructor: (@options = {}) -> # PDF version @version = 1.3 # Whether streams should be compressed @compress = yes # The PDF object store @store = new PDFObjectStore # A list of pages in this document @pages = [] # The current page @page = null # Initialize mixins @initColor() @initFonts() @initText() @initImages() # Create the metadata @_info = @ref Producer: 'PDFKit' Creator: 'PDFKit' CreationDate: new Date() @info = @_info.data if @options.info @info[key] = val for key, val of @options.info delete @options.info # Add the first page @addPage() mixin = (name) => methods = require './mixins/' + name for name, method of methods this::[name] = method # Load mixins mixin 'color' mixin 'vector' mixin 'fonts' mixin 'text' mixin 'images' mixin 'annotations' addPage: (options = @options) -> # create a page object @page = new PDFPage(this, options) # add the page to the object store @store.addPage @page @pages.push @page # reset x and y coordinates @x = @page.margins.left @y = @page.margins.top return this ref: (data) -> @store.ref(data) addContent: (str) -> @page.content.add str return this # make chaining possible write: (filename, fn) -> @output (out) -> fs.writeFile filename, out, 'binary', fn output: (fn) -> @finalize => out = [] @generateHeader out @generateBody out, => @generateXRef out @generateTrailer out fn out.join('\n') finalize: (fn) -> # convert strings in the info dictionary to literals for key, val of @info when typeof val is 'string' @info[key] = PDFObject.s val # embed the subsetted fonts @embedFonts => # embed the images @embedImages => done = 0 cb = => fn() if ++done is @pages.length # finalize each page for page in @pages page.finalize(cb) generateHeader: (out) -> # PDF version out.push "%PDF-#{@version}" # 4 binary chars, as recommended by the spec out.push "%\xFF\xFF\xFF\xFF\n" return out generateBody: (out, fn) -> offset = out.join('\n').length refs = (ref for id, ref of @store.objects) do proceed = => if ref = refs.shift() ref.object @compress, (object) -> ref.offset = offset out.push object offset += object.length + 1 proceed() else @xref_offset = offset fn() generateXRef: (out) -> len = @store.length + 1 out.push "xref" out.push "0 #{len}" out.push "0000000000 65535 f " for id, ref of @store.objects offset = ('0000000000' + ref.offset).slice(-10) out.push offset + ' 00000 n ' generateTrailer: (out) -> trailer = PDFObject.convert Size: @store.length Root: @store.root Info: @_info out.push 'trailer' out.push trailer out.push 'startxref' out.push @xref_offset out.push '%%EOF' toString: -> "[object PDFDocument]" module.exports = PDFDocument
42026
### PDFDocument - represents an entire PDF document By <NAME> ### fs = require 'fs' PDFObjectStore = require './store' PDFObject = require './object' PDFReference = require './reference' PDFPage = require './page' class PDFDocument constructor: (@options = {}) -> # PDF version @version = 1.3 # Whether streams should be compressed @compress = yes # The PDF object store @store = new PDFObjectStore # A list of pages in this document @pages = [] # The current page @page = null # Initialize mixins @initColor() @initFonts() @initText() @initImages() # Create the metadata @_info = @ref Producer: 'PDFKit' Creator: 'PDFKit' CreationDate: new Date() @info = @_info.data if @options.info @info[key] = val for key, val of @options.info delete @options.info # Add the first page @addPage() mixin = (name) => methods = require './mixins/' + name for name, method of methods this::[name] = method # Load mixins mixin 'color' mixin 'vector' mixin 'fonts' mixin 'text' mixin 'images' mixin 'annotations' addPage: (options = @options) -> # create a page object @page = new PDFPage(this, options) # add the page to the object store @store.addPage @page @pages.push @page # reset x and y coordinates @x = @page.margins.left @y = @page.margins.top return this ref: (data) -> @store.ref(data) addContent: (str) -> @page.content.add str return this # make chaining possible write: (filename, fn) -> @output (out) -> fs.writeFile filename, out, 'binary', fn output: (fn) -> @finalize => out = [] @generateHeader out @generateBody out, => @generateXRef out @generateTrailer out fn out.join('\n') finalize: (fn) -> # convert strings in the info dictionary to literals for key, val of @info when typeof val is 'string' @info[key] = PDFObject.s val # embed the subsetted fonts @embedFonts => # embed the images @embedImages => done = 0 cb = => fn() if ++done is @pages.length # finalize each page for page in @pages page.finalize(cb) generateHeader: (out) -> # PDF version out.push "%PDF-#{@version}" # 4 binary chars, as recommended by the spec out.push "%\xFF\xFF\xFF\xFF\n" return out generateBody: (out, fn) -> offset = out.join('\n').length refs = (ref for id, ref of @store.objects) do proceed = => if ref = refs.shift() ref.object @compress, (object) -> ref.offset = offset out.push object offset += object.length + 1 proceed() else @xref_offset = offset fn() generateXRef: (out) -> len = @store.length + 1 out.push "xref" out.push "0 #{len}" out.push "0000000000 65535 f " for id, ref of @store.objects offset = ('0000000000' + ref.offset).slice(-10) out.push offset + ' 00000 n ' generateTrailer: (out) -> trailer = PDFObject.convert Size: @store.length Root: @store.root Info: @_info out.push 'trailer' out.push trailer out.push 'startxref' out.push @xref_offset out.push '%%EOF' toString: -> "[object PDFDocument]" module.exports = PDFDocument
true
### PDFDocument - represents an entire PDF document By PI:NAME:<NAME>END_PI ### fs = require 'fs' PDFObjectStore = require './store' PDFObject = require './object' PDFReference = require './reference' PDFPage = require './page' class PDFDocument constructor: (@options = {}) -> # PDF version @version = 1.3 # Whether streams should be compressed @compress = yes # The PDF object store @store = new PDFObjectStore # A list of pages in this document @pages = [] # The current page @page = null # Initialize mixins @initColor() @initFonts() @initText() @initImages() # Create the metadata @_info = @ref Producer: 'PDFKit' Creator: 'PDFKit' CreationDate: new Date() @info = @_info.data if @options.info @info[key] = val for key, val of @options.info delete @options.info # Add the first page @addPage() mixin = (name) => methods = require './mixins/' + name for name, method of methods this::[name] = method # Load mixins mixin 'color' mixin 'vector' mixin 'fonts' mixin 'text' mixin 'images' mixin 'annotations' addPage: (options = @options) -> # create a page object @page = new PDFPage(this, options) # add the page to the object store @store.addPage @page @pages.push @page # reset x and y coordinates @x = @page.margins.left @y = @page.margins.top return this ref: (data) -> @store.ref(data) addContent: (str) -> @page.content.add str return this # make chaining possible write: (filename, fn) -> @output (out) -> fs.writeFile filename, out, 'binary', fn output: (fn) -> @finalize => out = [] @generateHeader out @generateBody out, => @generateXRef out @generateTrailer out fn out.join('\n') finalize: (fn) -> # convert strings in the info dictionary to literals for key, val of @info when typeof val is 'string' @info[key] = PDFObject.s val # embed the subsetted fonts @embedFonts => # embed the images @embedImages => done = 0 cb = => fn() if ++done is @pages.length # finalize each page for page in @pages page.finalize(cb) generateHeader: (out) -> # PDF version out.push "%PDF-#{@version}" # 4 binary chars, as recommended by the spec out.push "%\xFF\xFF\xFF\xFF\n" return out generateBody: (out, fn) -> offset = out.join('\n').length refs = (ref for id, ref of @store.objects) do proceed = => if ref = refs.shift() ref.object @compress, (object) -> ref.offset = offset out.push object offset += object.length + 1 proceed() else @xref_offset = offset fn() generateXRef: (out) -> len = @store.length + 1 out.push "xref" out.push "0 #{len}" out.push "0000000000 65535 f " for id, ref of @store.objects offset = ('0000000000' + ref.offset).slice(-10) out.push offset + ' 00000 n ' generateTrailer: (out) -> trailer = PDFObject.convert Size: @store.length Root: @store.root Info: @_info out.push 'trailer' out.push trailer out.push 'startxref' out.push @xref_offset out.push '%%EOF' toString: -> "[object PDFDocument]" module.exports = PDFDocument
[ { "context": "pts = {}) ->\n\n token = opts?.body?.email or 'someToken'\n body = generateResetRequestBody()\n\n params =", "end": 506, "score": 0.5193849802017212, "start": 501, "tag": "KEY", "value": "Token" } ]
servers/testhelper/handler/resethelper.coffee
ezgikaysi/koding
1
querystring = require 'querystring' { generateUrl deepObjectExtend generateRandomString generateRequestParamsEncodeBody } = require '../index' generateResetRequestBody = (opts = {}) -> defaultBodyObject = _csrf : generateRandomString() password : generateRandomString() recoveryToken : generateRandomString() deepObjectExtend defaultBodyObject, opts return defaultBodyObject generateResetRequestParams = (opts = {}) -> token = opts?.body?.email or 'someToken' body = generateResetRequestBody() params = url : generateUrl { route : "#{encodeURIComponent token}/Reset" } body : body csrfCookie : body._csrf requestParams = generateRequestParamsEncodeBody params, opts return requestParams module.exports = { generateResetRequestBody generateResetRequestParams }
142045
querystring = require 'querystring' { generateUrl deepObjectExtend generateRandomString generateRequestParamsEncodeBody } = require '../index' generateResetRequestBody = (opts = {}) -> defaultBodyObject = _csrf : generateRandomString() password : generateRandomString() recoveryToken : generateRandomString() deepObjectExtend defaultBodyObject, opts return defaultBodyObject generateResetRequestParams = (opts = {}) -> token = opts?.body?.email or 'some<KEY>' body = generateResetRequestBody() params = url : generateUrl { route : "#{encodeURIComponent token}/Reset" } body : body csrfCookie : body._csrf requestParams = generateRequestParamsEncodeBody params, opts return requestParams module.exports = { generateResetRequestBody generateResetRequestParams }
true
querystring = require 'querystring' { generateUrl deepObjectExtend generateRandomString generateRequestParamsEncodeBody } = require '../index' generateResetRequestBody = (opts = {}) -> defaultBodyObject = _csrf : generateRandomString() password : generateRandomString() recoveryToken : generateRandomString() deepObjectExtend defaultBodyObject, opts return defaultBodyObject generateResetRequestParams = (opts = {}) -> token = opts?.body?.email or 'somePI:KEY:<KEY>END_PI' body = generateResetRequestBody() params = url : generateUrl { route : "#{encodeURIComponent token}/Reset" } body : body csrfCookie : body._csrf requestParams = generateRequestParamsEncodeBody params, opts return requestParams module.exports = { generateResetRequestBody generateResetRequestParams }
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998884201049805, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright...
public/taiga-front/app/coffee/modules/search.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/search.coffee ### taiga = @.taiga groupBy = @.taiga.groupBy bindOnce = @.taiga.bindOnce mixOf = @.taiga.mixOf debounceLeading = @.taiga.debounceLeading trim = @.taiga.trim debounce = @.taiga.debounce module = angular.module("taigaSearch", []) ############################################################################# ## Search Controller ############################################################################# class SearchController extends mixOf(taiga.Controller, taiga.PageMixin) @.$inject = [ "$scope", "$tgRepo", "$tgResources", "$routeParams", "$q", "$tgLocation", "$appTitle", "$tgNavUrls", "tgLoader" ] constructor: (@scope, @repo, @rs, @params, @q, @location, @appTitle, @navUrls, @tgLoader) -> @scope.sectionName = "Search" promise = @.loadInitialData() promise.then () => @appTitle.set("Search") promise.then null, @.onInitialDataError.bind(@) # Search input watcher @scope.searchTerm = "" loadSearchData = debounceLeading(100, (t) => @.loadSearchData(t)) @scope.$watch "searchTerm", (term) => if not term @tgLoader.pageLoaded() else loadSearchData(term) loadFilters: -> defered = @q.defer() defered.resolve() return defered.promise loadProject: -> return @rs.projects.get(@scope.projectId).then (project) => @scope.project = project @scope.$emit('project:loaded', project) @scope.issueStatusById = groupBy(project.issue_statuses, (x) -> x.id) @scope.taskStatusById = groupBy(project.task_statuses, (x) -> x.id) @scope.severityById = groupBy(project.severities, (x) -> x.id) @scope.priorityById = groupBy(project.priorities, (x) -> x.id) @scope.membersById = groupBy(project.memberships, (x) -> x.user) @scope.usStatusById = groupBy(project.us_statuses, (x) -> x.id) return project loadSearchData: (term) -> promise = @rs.search.do(@scope.projectId, term).then (data) => @scope.searchResults = data @tgLoader.pageLoaded() return data return promise loadInitialData: -> promise = @repo.resolve({pslug: @params.pslug}).then (data) => @scope.projectId = data.project return data return promise.then(=> @.loadProject()) .then(=> @.loadUsersAndRoles()) module.controller("SearchController", SearchController) ############################################################################# ## Search box directive ############################################################################# SearchBoxDirective = ($lightboxService, $navurls, $location, $route)-> link = ($scope, $el, $attrs) -> project = null submit = debounce 2000, (event) => event.preventDefault() form = $el.find("form").checksley() if not form.validate() return text = $el.find("#search-text").val() url = $navurls.resolve("project-search", {project: project.slug}) $lightboxService.close($el) $scope.$apply -> $location.path(url) $location.search("text", text).path(url) $route.reload() $scope.$on "search-box:show", (ctx, newProject)-> project = newProject $lightboxService.open($el) $el.find("#search-text").val("") $el.on "submit", "form", submit $el.on "click", ".submit-button", submit return {link:link} module.directive("tgSearchBox", ["lightboxService", "$tgNavUrls", "$tgLocation", "$route", SearchBoxDirective]) ############################################################################# ## Search Directive ############################################################################# SearchDirective = ($log, $compile, $templatecache, $routeparams, $location) -> linkTable = ($scope, $el, $attrs, $ctrl) -> tabsDom = $el.find("section.search-filter") lastSeatchResults = null getActiveSection = (data) -> maxVal = 0 selectedSectionName = null selectedSectionData = null for name, value of data continue if name == "count" if value.length > maxVal maxVal = value.length selectedSectionName = name selectedSectionData = value if maxVal == 0 return {name: "userstories", value: []} return {name:selectedSectionName, value: selectedSectionData} renderFilterTabs = (data) -> for name, value of data continue if name == "count" tabsDom.find("li.#{name} .num").html(value.length) markSectionTabActive = (section) -> # Mark as active the item with max amount of results tabsDom.find("a.active").removeClass("active") tabsDom.find("li.#{section.name} a").addClass("active") templates = { issues: $templatecache.get("search-issues") tasks: $templatecache.get("search-tasks") userstories: $templatecache.get("search-userstories") wikipages: $templatecache.get("search-wikipages") } renderTableContent = (section) -> oldElements = $el.find(".search-result-table").children() oldScope = oldElements.scope() if oldScope oldScope.$destroy() oldElements.remove() scope = $scope.$new() scope[section.name] = section.value template = angular.element.parseHTML(trim(templates[section.name])) element = $compile(template)(scope) $el.find(".search-result-table").html(element) $scope.$watch "searchResults", (data) -> lastSeatchResults = data activeSection = getActiveSection(data) renderFilterTabs(data) renderTableContent(activeSection) markSectionTabActive(activeSection) $scope.$watch "searchTerm", (searchTerm) -> $location.search("text", searchTerm) if searchTerm $el.on "click", ".search-filter li > a", (event) -> event.preventDefault() target = angular.element(event.currentTarget) sectionName = target.parent().data("name") sectionData = lastSeatchResults[sectionName] section = { name: sectionName, value: sectionData } $scope.$apply -> renderTableContent(section) markSectionTabActive(section) link = ($scope, $el, $attrs) -> $ctrl = $el.controller() linkTable($scope, $el, $attrs, $ctrl) searchText = $routeparams.text $scope.$watch "projectId", (projectId) -> $scope.searchTerm = searchText if projectId? return {link:link} module.directive("tgSearch", ["$log", "$compile", "$templateCache", "$routeParams", "$tgLocation", SearchDirective])
17740
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/search.coffee ### taiga = @.taiga groupBy = @.taiga.groupBy bindOnce = @.taiga.bindOnce mixOf = @.taiga.mixOf debounceLeading = @.taiga.debounceLeading trim = @.taiga.trim debounce = @.taiga.debounce module = angular.module("taigaSearch", []) ############################################################################# ## Search Controller ############################################################################# class SearchController extends mixOf(taiga.Controller, taiga.PageMixin) @.$inject = [ "$scope", "$tgRepo", "$tgResources", "$routeParams", "$q", "$tgLocation", "$appTitle", "$tgNavUrls", "tgLoader" ] constructor: (@scope, @repo, @rs, @params, @q, @location, @appTitle, @navUrls, @tgLoader) -> @scope.sectionName = "Search" promise = @.loadInitialData() promise.then () => @appTitle.set("Search") promise.then null, @.onInitialDataError.bind(@) # Search input watcher @scope.searchTerm = "" loadSearchData = debounceLeading(100, (t) => @.loadSearchData(t)) @scope.$watch "searchTerm", (term) => if not term @tgLoader.pageLoaded() else loadSearchData(term) loadFilters: -> defered = @q.defer() defered.resolve() return defered.promise loadProject: -> return @rs.projects.get(@scope.projectId).then (project) => @scope.project = project @scope.$emit('project:loaded', project) @scope.issueStatusById = groupBy(project.issue_statuses, (x) -> x.id) @scope.taskStatusById = groupBy(project.task_statuses, (x) -> x.id) @scope.severityById = groupBy(project.severities, (x) -> x.id) @scope.priorityById = groupBy(project.priorities, (x) -> x.id) @scope.membersById = groupBy(project.memberships, (x) -> x.user) @scope.usStatusById = groupBy(project.us_statuses, (x) -> x.id) return project loadSearchData: (term) -> promise = @rs.search.do(@scope.projectId, term).then (data) => @scope.searchResults = data @tgLoader.pageLoaded() return data return promise loadInitialData: -> promise = @repo.resolve({pslug: @params.pslug}).then (data) => @scope.projectId = data.project return data return promise.then(=> @.loadProject()) .then(=> @.loadUsersAndRoles()) module.controller("SearchController", SearchController) ############################################################################# ## Search box directive ############################################################################# SearchBoxDirective = ($lightboxService, $navurls, $location, $route)-> link = ($scope, $el, $attrs) -> project = null submit = debounce 2000, (event) => event.preventDefault() form = $el.find("form").checksley() if not form.validate() return text = $el.find("#search-text").val() url = $navurls.resolve("project-search", {project: project.slug}) $lightboxService.close($el) $scope.$apply -> $location.path(url) $location.search("text", text).path(url) $route.reload() $scope.$on "search-box:show", (ctx, newProject)-> project = newProject $lightboxService.open($el) $el.find("#search-text").val("") $el.on "submit", "form", submit $el.on "click", ".submit-button", submit return {link:link} module.directive("tgSearchBox", ["lightboxService", "$tgNavUrls", "$tgLocation", "$route", SearchBoxDirective]) ############################################################################# ## Search Directive ############################################################################# SearchDirective = ($log, $compile, $templatecache, $routeparams, $location) -> linkTable = ($scope, $el, $attrs, $ctrl) -> tabsDom = $el.find("section.search-filter") lastSeatchResults = null getActiveSection = (data) -> maxVal = 0 selectedSectionName = null selectedSectionData = null for name, value of data continue if name == "count" if value.length > maxVal maxVal = value.length selectedSectionName = name selectedSectionData = value if maxVal == 0 return {name: "userstories", value: []} return {name:selectedSectionName, value: selectedSectionData} renderFilterTabs = (data) -> for name, value of data continue if name == "count" tabsDom.find("li.#{name} .num").html(value.length) markSectionTabActive = (section) -> # Mark as active the item with max amount of results tabsDom.find("a.active").removeClass("active") tabsDom.find("li.#{section.name} a").addClass("active") templates = { issues: $templatecache.get("search-issues") tasks: $templatecache.get("search-tasks") userstories: $templatecache.get("search-userstories") wikipages: $templatecache.get("search-wikipages") } renderTableContent = (section) -> oldElements = $el.find(".search-result-table").children() oldScope = oldElements.scope() if oldScope oldScope.$destroy() oldElements.remove() scope = $scope.$new() scope[section.name] = section.value template = angular.element.parseHTML(trim(templates[section.name])) element = $compile(template)(scope) $el.find(".search-result-table").html(element) $scope.$watch "searchResults", (data) -> lastSeatchResults = data activeSection = getActiveSection(data) renderFilterTabs(data) renderTableContent(activeSection) markSectionTabActive(activeSection) $scope.$watch "searchTerm", (searchTerm) -> $location.search("text", searchTerm) if searchTerm $el.on "click", ".search-filter li > a", (event) -> event.preventDefault() target = angular.element(event.currentTarget) sectionName = target.parent().data("name") sectionData = lastSeatchResults[sectionName] section = { name: sectionName, value: sectionData } $scope.$apply -> renderTableContent(section) markSectionTabActive(section) link = ($scope, $el, $attrs) -> $ctrl = $el.controller() linkTable($scope, $el, $attrs, $ctrl) searchText = $routeparams.text $scope.$watch "projectId", (projectId) -> $scope.searchTerm = searchText if projectId? return {link:link} module.directive("tgSearch", ["$log", "$compile", "$templateCache", "$routeParams", "$tgLocation", SearchDirective])
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/search.coffee ### taiga = @.taiga groupBy = @.taiga.groupBy bindOnce = @.taiga.bindOnce mixOf = @.taiga.mixOf debounceLeading = @.taiga.debounceLeading trim = @.taiga.trim debounce = @.taiga.debounce module = angular.module("taigaSearch", []) ############################################################################# ## Search Controller ############################################################################# class SearchController extends mixOf(taiga.Controller, taiga.PageMixin) @.$inject = [ "$scope", "$tgRepo", "$tgResources", "$routeParams", "$q", "$tgLocation", "$appTitle", "$tgNavUrls", "tgLoader" ] constructor: (@scope, @repo, @rs, @params, @q, @location, @appTitle, @navUrls, @tgLoader) -> @scope.sectionName = "Search" promise = @.loadInitialData() promise.then () => @appTitle.set("Search") promise.then null, @.onInitialDataError.bind(@) # Search input watcher @scope.searchTerm = "" loadSearchData = debounceLeading(100, (t) => @.loadSearchData(t)) @scope.$watch "searchTerm", (term) => if not term @tgLoader.pageLoaded() else loadSearchData(term) loadFilters: -> defered = @q.defer() defered.resolve() return defered.promise loadProject: -> return @rs.projects.get(@scope.projectId).then (project) => @scope.project = project @scope.$emit('project:loaded', project) @scope.issueStatusById = groupBy(project.issue_statuses, (x) -> x.id) @scope.taskStatusById = groupBy(project.task_statuses, (x) -> x.id) @scope.severityById = groupBy(project.severities, (x) -> x.id) @scope.priorityById = groupBy(project.priorities, (x) -> x.id) @scope.membersById = groupBy(project.memberships, (x) -> x.user) @scope.usStatusById = groupBy(project.us_statuses, (x) -> x.id) return project loadSearchData: (term) -> promise = @rs.search.do(@scope.projectId, term).then (data) => @scope.searchResults = data @tgLoader.pageLoaded() return data return promise loadInitialData: -> promise = @repo.resolve({pslug: @params.pslug}).then (data) => @scope.projectId = data.project return data return promise.then(=> @.loadProject()) .then(=> @.loadUsersAndRoles()) module.controller("SearchController", SearchController) ############################################################################# ## Search box directive ############################################################################# SearchBoxDirective = ($lightboxService, $navurls, $location, $route)-> link = ($scope, $el, $attrs) -> project = null submit = debounce 2000, (event) => event.preventDefault() form = $el.find("form").checksley() if not form.validate() return text = $el.find("#search-text").val() url = $navurls.resolve("project-search", {project: project.slug}) $lightboxService.close($el) $scope.$apply -> $location.path(url) $location.search("text", text).path(url) $route.reload() $scope.$on "search-box:show", (ctx, newProject)-> project = newProject $lightboxService.open($el) $el.find("#search-text").val("") $el.on "submit", "form", submit $el.on "click", ".submit-button", submit return {link:link} module.directive("tgSearchBox", ["lightboxService", "$tgNavUrls", "$tgLocation", "$route", SearchBoxDirective]) ############################################################################# ## Search Directive ############################################################################# SearchDirective = ($log, $compile, $templatecache, $routeparams, $location) -> linkTable = ($scope, $el, $attrs, $ctrl) -> tabsDom = $el.find("section.search-filter") lastSeatchResults = null getActiveSection = (data) -> maxVal = 0 selectedSectionName = null selectedSectionData = null for name, value of data continue if name == "count" if value.length > maxVal maxVal = value.length selectedSectionName = name selectedSectionData = value if maxVal == 0 return {name: "userstories", value: []} return {name:selectedSectionName, value: selectedSectionData} renderFilterTabs = (data) -> for name, value of data continue if name == "count" tabsDom.find("li.#{name} .num").html(value.length) markSectionTabActive = (section) -> # Mark as active the item with max amount of results tabsDom.find("a.active").removeClass("active") tabsDom.find("li.#{section.name} a").addClass("active") templates = { issues: $templatecache.get("search-issues") tasks: $templatecache.get("search-tasks") userstories: $templatecache.get("search-userstories") wikipages: $templatecache.get("search-wikipages") } renderTableContent = (section) -> oldElements = $el.find(".search-result-table").children() oldScope = oldElements.scope() if oldScope oldScope.$destroy() oldElements.remove() scope = $scope.$new() scope[section.name] = section.value template = angular.element.parseHTML(trim(templates[section.name])) element = $compile(template)(scope) $el.find(".search-result-table").html(element) $scope.$watch "searchResults", (data) -> lastSeatchResults = data activeSection = getActiveSection(data) renderFilterTabs(data) renderTableContent(activeSection) markSectionTabActive(activeSection) $scope.$watch "searchTerm", (searchTerm) -> $location.search("text", searchTerm) if searchTerm $el.on "click", ".search-filter li > a", (event) -> event.preventDefault() target = angular.element(event.currentTarget) sectionName = target.parent().data("name") sectionData = lastSeatchResults[sectionName] section = { name: sectionName, value: sectionData } $scope.$apply -> renderTableContent(section) markSectionTabActive(section) link = ($scope, $el, $attrs) -> $ctrl = $el.controller() linkTable($scope, $el, $attrs, $ctrl) searchText = $routeparams.text $scope.$watch "projectId", (projectId) -> $scope.searchTerm = searchText if projectId? return {link:link} module.directive("tgSearch", ["$log", "$compile", "$templateCache", "$routeParams", "$tgLocation", SearchDirective])
[ { "context": "bject\", ->\n result = @schema.process({name: \"Mathias\", age: 35})\n expect(Object.keys(result.doc))", "end": 722, "score": 0.9996310472488403, "start": 715, "tag": "NAME", "value": "Mathias" }, { "context": " \"alive\"])\n expect(result.doc.name).toEqu...
coffeescripts/json-schema-spec.coffee
webpop/json-schemer
1
describe "JsonSchema", -> describe "with a simple example schema from the ietf draft", -> beforeEach -> @schema = new JsonSchema description: "A person" type:"object" properties: name: {type: "string"} age: type: "integer" maximum: 125 alive: {type: "boolean"} it "should process an empty object", -> result = @schema.process({}) expect(Object.keys(result.doc)).toEqual(['name', 'age', 'alive']) expect(result.doc.name).toBe(undefined) expect(result.doc.age).toBe(undefined) expect(result.valid).toBe(true) it "should process a valid object", -> result = @schema.process({name: "Mathias", age: 35}) expect(Object.keys(result.doc)).toEqual(["name", "age", "alive"]) expect(result.doc.name).toEqual("Mathias") expect(result.doc.age).toEqual(35) expect(result.valid).toBe(true) it "should cast strings to numbers where needed", -> result = @schema.process({age: "35"}) expect(result.doc.age).toEqual(35) expect(result.valid).toBe(true) it "should validate the maximum for a number", -> result = @schema.process({age: 200}) expect(result.doc.age).toEqual(200) expect(result.valid).toBe(false) expect(result.errors.all()).toEqual([["age", ["maximum"]]]) it "should use a default value", -> @schema.properties.name.default = "Default" result = @schema.process({}) expect(result.doc.name).toEqual("Default") it "should not set an undefined boolean value", -> result = @schema.process({age: 200}) expect(result.doc.alive).toEqual(undefined) it "should set a boolean", -> result = @schema.process({alive: true}) expect(result.doc.alive).toEqual(true) result = @schema.process({alive: "true"}) expect(result.doc.alive).toEqual(true) result = @schema.process({alive: "false"}) expect(result.doc.alive).toEqual(false) describe "validations", -> describe "optional and required fields", -> beforeEach -> @schema = new JsonSchema type: "object" properties: optional: type: "string" required: type: "string" required: true it "should validate required fields", -> result = @schema.process({}) expect(result.valid).toBe(false) expect(result.errors.on("optional")).toBe(undefined) expect(result.errors.on("required")).toEqual(["required"]) describe "string validations", -> beforeEach -> @schema = new JsonSchema type: "object" properties: minlength: type: "string" minLength: 1 maxlength: type: "string" maxLength: 2 pattern: type: "string" pattern: "^[a-z]+$" enum: type: "string" enum: ["one", "two", "three"] it "should validate the minLength", -> result = @schema.process({minlength: ""}) expect(result.valid).toBe(false) expect(result.errors.on("minlength")).toEqual(["minLength"]) expect(@schema.process({minlength: "good"}).valid).toBe(true) it "should validate the maxLength", -> result = @schema.process({maxlength: "hello"}) expect(result.valid).toBe(false) expect(result.errors.on("maxlength")).toEqual(["maxLength"]) expect(@schema.process({maxlength: "It"}).valid).toBe(true) it "should validate the pattern", -> result = @schema.process({pattern: "Has Spaces"}) expect(result.valid).toBe(false) expect(result.errors.on("pattern")).toEqual(["pattern"]) expect(@schema.process({pattern: "nospaces"}).valid).toBe(true) it "should validate the enum", -> result = @schema.process({enum: "four"}) expect(result.valid).toBe(false) expect(result.errors.on("enum")).toEqual(["enum"]) expect(@schema.process({enum: "two"}).valid).toBe(true) describe "date and time", -> beforeEach -> @schema = new JsonSchema type: "object" properties: datetime: type: "string" format: "date-time" date: type: "string" format: "date" it "should process a date", -> result = @schema.process({date: "2012-07-09"}) expect(result.doc.date.getFullYear()).toEqual(2012) it "should process a date-time", -> result = @schema.process({datetime: "2012-07-09T12:09:18Z"}) expect(result.doc.datetime.getFullYear()).toEqual(2012) it "should validate a date", -> result = @schema.process({date: "09/09/2012"}) expect(result.valid).toBe(false) expect(result.errors.on("date")).toEqual(["format"]) describe "number validations", -> beforeEach -> @schema = new JsonSchema type: "object" properties: number: type: "integer" minimum: 10 maximum: 50 divisibleBy: 10 it "should not validate an empty value", -> result = @schema.process({divisibleBy: ""}) expect(result.valid).toBe(true) it "should validate maximum", -> result = @schema.process({number: 100}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["maximum"]) it "should accept a value equal to maximum", -> expect(@schema.process({number: 50}).valid).toBe(true) it "should validate minimum", -> result = @schema.process({number: 0}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["minimum"]) it "should accept a value equal to minimum", -> expect(@schema.process({number: 10}).valid).toBe(true) it "should validate divisibleBy" , -> result = @schema.process({number: 35}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["divisibleBy"]) it "should validate both divisibleBy and minimum", -> result = @schema.process({number: 5}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["minimum", "divisibleBy"]) it "should handle excludeMinimum", -> @schema.properties.number.excludeMinimum = true expect(@schema.process({number: 20}).valid).toBe(true) expect(@schema.process({number: 10}).valid).toBe(false) expect(@schema.process({number: 10}).errors.on("number")).toEqual(["minimum"]) it "should handle excludeMaximum", -> @schema.properties.number.excludeMaximum = true expect(@schema.process({number: 20}).valid).toBe(true) expect(@schema.process({number: 50}).valid).toBe(false) expect(@schema.process({number: 50}).errors.on("number")).toEqual(["maximum"]) describe "arrays", -> beforeEach -> @schema = new JsonSchema type: "object" properties: array: type: "array" it "should handle array values", -> result = @schema.process({array: [1,"2",3]}) expect(result.valid).toBe(true) expect(result.doc.array).toEqual([1,"2",3]) it "should validate minItems", -> @schema.properties.array.minItems = 3 result = @schema.process({array: [1,2]}) expect(result.valid).toBe(false) expect(result.errors.on("array")).toEqual(["minItems"]) expect(@schema.process({array: [1,2,3]}).valid).toBe(true) it "should validate maxItems", -> @schema.properties.array.maxItems = 3 result = @schema.process({array: [1,2,3,4]}) expect(result.valid).toBe(false) expect(result.errors.on("array")).toEqual(["maxItems"]) expect(@schema.process({array: [1,2,3]}).valid).toBe(true) describe "with numerical items", -> beforeEach -> @schema.properties.array.items = type: "integer" it "should cast array values", -> result = @schema.process({array: ["1", "2", "3"]}) expect(result.valid).toBe(true) expect(result.doc.array).toEqual([1,2,3]) it "should validate array values", -> @schema.properties.array.items.minimum = 3 result = @schema.process({array: [1, 2, 3]}) expect(result.valid).toBe(false) expect(result.errors.on("array.0")).toEqual(["minimum"]) expect(result.errors.on("array.1")).toEqual(["minimum"]) expect(result.errors.on("array.2")).toBe(undefined) describe "objects", -> beforeEach -> @schema = new JsonSchema type: "object" properties: object: type: "object" properties: test: type: "string" it "should process an object", -> result = @schema.process({object: {test: "Hello"}}) expect(result.doc.object.test).toEqual("Hello") it "should validate properties on the object", -> @schema.properties.object.properties.test.minLength = 8 result = @schema.process({object: {test: "Hello"}}) expect(result.valid).toBe(false) expect(result.errors.on("object.test")).toEqual(["minLength"]) it "should not make the object required when an property is required", -> @schema.properties.object.properties.test.required = true result = @schema.process({}) expect(result.valid).toBe(true) describe "resolving refs", -> beforeEach -> schemas = person: type: "object" properties: name: type: "string" required: true party: type: "object" properties: host: type: "object" properties: "$ref": "person#.properties" guests: type: "array" items: "$ref": "person" JsonSchema.resolver = (uri, current) -> attr = schemas[uri] new JsonSchema(attr) if attr @schema = JsonSchema.resolver("party") it "should resolve an object reference", -> result = @schema.process({host: {name: "Mathias"}}) expect(result.doc.host.name).toEqual("Mathias") expect(result.valid).toBe(true) bad = @schema.process({host: {}}) expect(bad.valid).toBe(false) expect(bad.errors.on("host.name")).toEqual(["required"]) it "should resolve array references", -> result = @schema.process({guests: [{name: "Irene"}, {name: "Julio"}]}) expect(result.doc.guests[0].name).toEqual("Irene") expect(result.doc.guests[1].name).toEqual("Julio") bad = @schema.process({guests: [{name: "Irene"}, {}]}) expect(bad.valid).toBe(false) expect(bad.errors.on("guests.1.name")).toEqual(["required"]) describe "JsonErrors", -> it "should handle merging nested error objects", -> errors = new JsonErrors errors.add("required") arrayErrors = new JsonErrors arrayErrors.add("minItems") arrayErrors.add("0", "numeric") errors.add("array", arrayErrors) expect(errors.on("")).toEqual(["required"]) expect(errors.on("array")).toEqual(["minItems"]) expect(errors.on("array.0")).toEqual(["numeric"])
193298
describe "JsonSchema", -> describe "with a simple example schema from the ietf draft", -> beforeEach -> @schema = new JsonSchema description: "A person" type:"object" properties: name: {type: "string"} age: type: "integer" maximum: 125 alive: {type: "boolean"} it "should process an empty object", -> result = @schema.process({}) expect(Object.keys(result.doc)).toEqual(['name', 'age', 'alive']) expect(result.doc.name).toBe(undefined) expect(result.doc.age).toBe(undefined) expect(result.valid).toBe(true) it "should process a valid object", -> result = @schema.process({name: "<NAME>", age: 35}) expect(Object.keys(result.doc)).toEqual(["name", "age", "alive"]) expect(result.doc.name).toEqual("<NAME>") expect(result.doc.age).toEqual(35) expect(result.valid).toBe(true) it "should cast strings to numbers where needed", -> result = @schema.process({age: "35"}) expect(result.doc.age).toEqual(35) expect(result.valid).toBe(true) it "should validate the maximum for a number", -> result = @schema.process({age: 200}) expect(result.doc.age).toEqual(200) expect(result.valid).toBe(false) expect(result.errors.all()).toEqual([["age", ["maximum"]]]) it "should use a default value", -> @schema.properties.name.default = "Default" result = @schema.process({}) expect(result.doc.name).toEqual("Default") it "should not set an undefined boolean value", -> result = @schema.process({age: 200}) expect(result.doc.alive).toEqual(undefined) it "should set a boolean", -> result = @schema.process({alive: true}) expect(result.doc.alive).toEqual(true) result = @schema.process({alive: "true"}) expect(result.doc.alive).toEqual(true) result = @schema.process({alive: "false"}) expect(result.doc.alive).toEqual(false) describe "validations", -> describe "optional and required fields", -> beforeEach -> @schema = new JsonSchema type: "object" properties: optional: type: "string" required: type: "string" required: true it "should validate required fields", -> result = @schema.process({}) expect(result.valid).toBe(false) expect(result.errors.on("optional")).toBe(undefined) expect(result.errors.on("required")).toEqual(["required"]) describe "string validations", -> beforeEach -> @schema = new JsonSchema type: "object" properties: minlength: type: "string" minLength: 1 maxlength: type: "string" maxLength: 2 pattern: type: "string" pattern: "^[a-z]+$" enum: type: "string" enum: ["one", "two", "three"] it "should validate the minLength", -> result = @schema.process({minlength: ""}) expect(result.valid).toBe(false) expect(result.errors.on("minlength")).toEqual(["minLength"]) expect(@schema.process({minlength: "good"}).valid).toBe(true) it "should validate the maxLength", -> result = @schema.process({maxlength: "hello"}) expect(result.valid).toBe(false) expect(result.errors.on("maxlength")).toEqual(["maxLength"]) expect(@schema.process({maxlength: "It"}).valid).toBe(true) it "should validate the pattern", -> result = @schema.process({pattern: "Has Spaces"}) expect(result.valid).toBe(false) expect(result.errors.on("pattern")).toEqual(["pattern"]) expect(@schema.process({pattern: "nospaces"}).valid).toBe(true) it "should validate the enum", -> result = @schema.process({enum: "four"}) expect(result.valid).toBe(false) expect(result.errors.on("enum")).toEqual(["enum"]) expect(@schema.process({enum: "two"}).valid).toBe(true) describe "date and time", -> beforeEach -> @schema = new JsonSchema type: "object" properties: datetime: type: "string" format: "date-time" date: type: "string" format: "date" it "should process a date", -> result = @schema.process({date: "2012-07-09"}) expect(result.doc.date.getFullYear()).toEqual(2012) it "should process a date-time", -> result = @schema.process({datetime: "2012-07-09T12:09:18Z"}) expect(result.doc.datetime.getFullYear()).toEqual(2012) it "should validate a date", -> result = @schema.process({date: "09/09/2012"}) expect(result.valid).toBe(false) expect(result.errors.on("date")).toEqual(["format"]) describe "number validations", -> beforeEach -> @schema = new JsonSchema type: "object" properties: number: type: "integer" minimum: 10 maximum: 50 divisibleBy: 10 it "should not validate an empty value", -> result = @schema.process({divisibleBy: ""}) expect(result.valid).toBe(true) it "should validate maximum", -> result = @schema.process({number: 100}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["maximum"]) it "should accept a value equal to maximum", -> expect(@schema.process({number: 50}).valid).toBe(true) it "should validate minimum", -> result = @schema.process({number: 0}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["minimum"]) it "should accept a value equal to minimum", -> expect(@schema.process({number: 10}).valid).toBe(true) it "should validate divisibleBy" , -> result = @schema.process({number: 35}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["divisibleBy"]) it "should validate both divisibleBy and minimum", -> result = @schema.process({number: 5}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["minimum", "divisibleBy"]) it "should handle excludeMinimum", -> @schema.properties.number.excludeMinimum = true expect(@schema.process({number: 20}).valid).toBe(true) expect(@schema.process({number: 10}).valid).toBe(false) expect(@schema.process({number: 10}).errors.on("number")).toEqual(["minimum"]) it "should handle excludeMaximum", -> @schema.properties.number.excludeMaximum = true expect(@schema.process({number: 20}).valid).toBe(true) expect(@schema.process({number: 50}).valid).toBe(false) expect(@schema.process({number: 50}).errors.on("number")).toEqual(["maximum"]) describe "arrays", -> beforeEach -> @schema = new JsonSchema type: "object" properties: array: type: "array" it "should handle array values", -> result = @schema.process({array: [1,"2",3]}) expect(result.valid).toBe(true) expect(result.doc.array).toEqual([1,"2",3]) it "should validate minItems", -> @schema.properties.array.minItems = 3 result = @schema.process({array: [1,2]}) expect(result.valid).toBe(false) expect(result.errors.on("array")).toEqual(["minItems"]) expect(@schema.process({array: [1,2,3]}).valid).toBe(true) it "should validate maxItems", -> @schema.properties.array.maxItems = 3 result = @schema.process({array: [1,2,3,4]}) expect(result.valid).toBe(false) expect(result.errors.on("array")).toEqual(["maxItems"]) expect(@schema.process({array: [1,2,3]}).valid).toBe(true) describe "with numerical items", -> beforeEach -> @schema.properties.array.items = type: "integer" it "should cast array values", -> result = @schema.process({array: ["1", "2", "3"]}) expect(result.valid).toBe(true) expect(result.doc.array).toEqual([1,2,3]) it "should validate array values", -> @schema.properties.array.items.minimum = 3 result = @schema.process({array: [1, 2, 3]}) expect(result.valid).toBe(false) expect(result.errors.on("array.0")).toEqual(["minimum"]) expect(result.errors.on("array.1")).toEqual(["minimum"]) expect(result.errors.on("array.2")).toBe(undefined) describe "objects", -> beforeEach -> @schema = new JsonSchema type: "object" properties: object: type: "object" properties: test: type: "string" it "should process an object", -> result = @schema.process({object: {test: "Hello"}}) expect(result.doc.object.test).toEqual("Hello") it "should validate properties on the object", -> @schema.properties.object.properties.test.minLength = 8 result = @schema.process({object: {test: "Hello"}}) expect(result.valid).toBe(false) expect(result.errors.on("object.test")).toEqual(["minLength"]) it "should not make the object required when an property is required", -> @schema.properties.object.properties.test.required = true result = @schema.process({}) expect(result.valid).toBe(true) describe "resolving refs", -> beforeEach -> schemas = person: type: "object" properties: name: type: "string" required: true party: type: "object" properties: host: type: "object" properties: "$ref": "person#.properties" guests: type: "array" items: "$ref": "person" JsonSchema.resolver = (uri, current) -> attr = schemas[uri] new JsonSchema(attr) if attr @schema = JsonSchema.resolver("party") it "should resolve an object reference", -> result = @schema.process({host: {name: "<NAME>"}}) expect(result.doc.host.name).toEqual("<NAME>") expect(result.valid).toBe(true) bad = @schema.process({host: {}}) expect(bad.valid).toBe(false) expect(bad.errors.on("host.name")).toEqual(["required"]) it "should resolve array references", -> result = @schema.process({guests: [{name: "<NAME>"}, {name: "<NAME>"}]}) expect(result.doc.guests[0].name).toEqual("<NAME>") expect(result.doc.guests[1].name).toEqual("<NAME>") bad = @schema.process({guests: [{name: "<NAME>"}, {}]}) expect(bad.valid).toBe(false) expect(bad.errors.on("guests.1.name")).toEqual(["required"]) describe "JsonErrors", -> it "should handle merging nested error objects", -> errors = new JsonErrors errors.add("required") arrayErrors = new JsonErrors arrayErrors.add("minItems") arrayErrors.add("0", "numeric") errors.add("array", arrayErrors) expect(errors.on("")).toEqual(["required"]) expect(errors.on("array")).toEqual(["minItems"]) expect(errors.on("array.0")).toEqual(["numeric"])
true
describe "JsonSchema", -> describe "with a simple example schema from the ietf draft", -> beforeEach -> @schema = new JsonSchema description: "A person" type:"object" properties: name: {type: "string"} age: type: "integer" maximum: 125 alive: {type: "boolean"} it "should process an empty object", -> result = @schema.process({}) expect(Object.keys(result.doc)).toEqual(['name', 'age', 'alive']) expect(result.doc.name).toBe(undefined) expect(result.doc.age).toBe(undefined) expect(result.valid).toBe(true) it "should process a valid object", -> result = @schema.process({name: "PI:NAME:<NAME>END_PI", age: 35}) expect(Object.keys(result.doc)).toEqual(["name", "age", "alive"]) expect(result.doc.name).toEqual("PI:NAME:<NAME>END_PI") expect(result.doc.age).toEqual(35) expect(result.valid).toBe(true) it "should cast strings to numbers where needed", -> result = @schema.process({age: "35"}) expect(result.doc.age).toEqual(35) expect(result.valid).toBe(true) it "should validate the maximum for a number", -> result = @schema.process({age: 200}) expect(result.doc.age).toEqual(200) expect(result.valid).toBe(false) expect(result.errors.all()).toEqual([["age", ["maximum"]]]) it "should use a default value", -> @schema.properties.name.default = "Default" result = @schema.process({}) expect(result.doc.name).toEqual("Default") it "should not set an undefined boolean value", -> result = @schema.process({age: 200}) expect(result.doc.alive).toEqual(undefined) it "should set a boolean", -> result = @schema.process({alive: true}) expect(result.doc.alive).toEqual(true) result = @schema.process({alive: "true"}) expect(result.doc.alive).toEqual(true) result = @schema.process({alive: "false"}) expect(result.doc.alive).toEqual(false) describe "validations", -> describe "optional and required fields", -> beforeEach -> @schema = new JsonSchema type: "object" properties: optional: type: "string" required: type: "string" required: true it "should validate required fields", -> result = @schema.process({}) expect(result.valid).toBe(false) expect(result.errors.on("optional")).toBe(undefined) expect(result.errors.on("required")).toEqual(["required"]) describe "string validations", -> beforeEach -> @schema = new JsonSchema type: "object" properties: minlength: type: "string" minLength: 1 maxlength: type: "string" maxLength: 2 pattern: type: "string" pattern: "^[a-z]+$" enum: type: "string" enum: ["one", "two", "three"] it "should validate the minLength", -> result = @schema.process({minlength: ""}) expect(result.valid).toBe(false) expect(result.errors.on("minlength")).toEqual(["minLength"]) expect(@schema.process({minlength: "good"}).valid).toBe(true) it "should validate the maxLength", -> result = @schema.process({maxlength: "hello"}) expect(result.valid).toBe(false) expect(result.errors.on("maxlength")).toEqual(["maxLength"]) expect(@schema.process({maxlength: "It"}).valid).toBe(true) it "should validate the pattern", -> result = @schema.process({pattern: "Has Spaces"}) expect(result.valid).toBe(false) expect(result.errors.on("pattern")).toEqual(["pattern"]) expect(@schema.process({pattern: "nospaces"}).valid).toBe(true) it "should validate the enum", -> result = @schema.process({enum: "four"}) expect(result.valid).toBe(false) expect(result.errors.on("enum")).toEqual(["enum"]) expect(@schema.process({enum: "two"}).valid).toBe(true) describe "date and time", -> beforeEach -> @schema = new JsonSchema type: "object" properties: datetime: type: "string" format: "date-time" date: type: "string" format: "date" it "should process a date", -> result = @schema.process({date: "2012-07-09"}) expect(result.doc.date.getFullYear()).toEqual(2012) it "should process a date-time", -> result = @schema.process({datetime: "2012-07-09T12:09:18Z"}) expect(result.doc.datetime.getFullYear()).toEqual(2012) it "should validate a date", -> result = @schema.process({date: "09/09/2012"}) expect(result.valid).toBe(false) expect(result.errors.on("date")).toEqual(["format"]) describe "number validations", -> beforeEach -> @schema = new JsonSchema type: "object" properties: number: type: "integer" minimum: 10 maximum: 50 divisibleBy: 10 it "should not validate an empty value", -> result = @schema.process({divisibleBy: ""}) expect(result.valid).toBe(true) it "should validate maximum", -> result = @schema.process({number: 100}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["maximum"]) it "should accept a value equal to maximum", -> expect(@schema.process({number: 50}).valid).toBe(true) it "should validate minimum", -> result = @schema.process({number: 0}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["minimum"]) it "should accept a value equal to minimum", -> expect(@schema.process({number: 10}).valid).toBe(true) it "should validate divisibleBy" , -> result = @schema.process({number: 35}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["divisibleBy"]) it "should validate both divisibleBy and minimum", -> result = @schema.process({number: 5}) expect(result.valid).toBe(false) expect(result.errors.on("number")).toEqual(["minimum", "divisibleBy"]) it "should handle excludeMinimum", -> @schema.properties.number.excludeMinimum = true expect(@schema.process({number: 20}).valid).toBe(true) expect(@schema.process({number: 10}).valid).toBe(false) expect(@schema.process({number: 10}).errors.on("number")).toEqual(["minimum"]) it "should handle excludeMaximum", -> @schema.properties.number.excludeMaximum = true expect(@schema.process({number: 20}).valid).toBe(true) expect(@schema.process({number: 50}).valid).toBe(false) expect(@schema.process({number: 50}).errors.on("number")).toEqual(["maximum"]) describe "arrays", -> beforeEach -> @schema = new JsonSchema type: "object" properties: array: type: "array" it "should handle array values", -> result = @schema.process({array: [1,"2",3]}) expect(result.valid).toBe(true) expect(result.doc.array).toEqual([1,"2",3]) it "should validate minItems", -> @schema.properties.array.minItems = 3 result = @schema.process({array: [1,2]}) expect(result.valid).toBe(false) expect(result.errors.on("array")).toEqual(["minItems"]) expect(@schema.process({array: [1,2,3]}).valid).toBe(true) it "should validate maxItems", -> @schema.properties.array.maxItems = 3 result = @schema.process({array: [1,2,3,4]}) expect(result.valid).toBe(false) expect(result.errors.on("array")).toEqual(["maxItems"]) expect(@schema.process({array: [1,2,3]}).valid).toBe(true) describe "with numerical items", -> beforeEach -> @schema.properties.array.items = type: "integer" it "should cast array values", -> result = @schema.process({array: ["1", "2", "3"]}) expect(result.valid).toBe(true) expect(result.doc.array).toEqual([1,2,3]) it "should validate array values", -> @schema.properties.array.items.minimum = 3 result = @schema.process({array: [1, 2, 3]}) expect(result.valid).toBe(false) expect(result.errors.on("array.0")).toEqual(["minimum"]) expect(result.errors.on("array.1")).toEqual(["minimum"]) expect(result.errors.on("array.2")).toBe(undefined) describe "objects", -> beforeEach -> @schema = new JsonSchema type: "object" properties: object: type: "object" properties: test: type: "string" it "should process an object", -> result = @schema.process({object: {test: "Hello"}}) expect(result.doc.object.test).toEqual("Hello") it "should validate properties on the object", -> @schema.properties.object.properties.test.minLength = 8 result = @schema.process({object: {test: "Hello"}}) expect(result.valid).toBe(false) expect(result.errors.on("object.test")).toEqual(["minLength"]) it "should not make the object required when an property is required", -> @schema.properties.object.properties.test.required = true result = @schema.process({}) expect(result.valid).toBe(true) describe "resolving refs", -> beforeEach -> schemas = person: type: "object" properties: name: type: "string" required: true party: type: "object" properties: host: type: "object" properties: "$ref": "person#.properties" guests: type: "array" items: "$ref": "person" JsonSchema.resolver = (uri, current) -> attr = schemas[uri] new JsonSchema(attr) if attr @schema = JsonSchema.resolver("party") it "should resolve an object reference", -> result = @schema.process({host: {name: "PI:NAME:<NAME>END_PI"}}) expect(result.doc.host.name).toEqual("PI:NAME:<NAME>END_PI") expect(result.valid).toBe(true) bad = @schema.process({host: {}}) expect(bad.valid).toBe(false) expect(bad.errors.on("host.name")).toEqual(["required"]) it "should resolve array references", -> result = @schema.process({guests: [{name: "PI:NAME:<NAME>END_PI"}, {name: "PI:NAME:<NAME>END_PI"}]}) expect(result.doc.guests[0].name).toEqual("PI:NAME:<NAME>END_PI") expect(result.doc.guests[1].name).toEqual("PI:NAME:<NAME>END_PI") bad = @schema.process({guests: [{name: "PI:NAME:<NAME>END_PI"}, {}]}) expect(bad.valid).toBe(false) expect(bad.errors.on("guests.1.name")).toEqual(["required"]) describe "JsonErrors", -> it "should handle merging nested error objects", -> errors = new JsonErrors errors.add("required") arrayErrors = new JsonErrors arrayErrors.add("minItems") arrayErrors.add("0", "numeric") errors.add("array", arrayErrors) expect(errors.on("")).toEqual(["required"]) expect(errors.on("array")).toEqual(["minItems"]) expect(errors.on("array.0")).toEqual(["numeric"])
[ { "context": "chargestatus']\n charge.pusher_channel_token = Math.random().toString(36).slice(2)\n\n pusher = ne", "end": 8788, "score": 0.941838800907135, "start": 8784, "tag": "KEY", "value": "Math" }, { "context": "status']\n charge.pusher_channel_token = Math.rando...
src/coffee/donations-form-model.coffee
controlshift/prague-client
3
cacheBust = '__rand__' class DonationsFormModel constructor: (jQuery, opts) -> try self = @ `$ = jQuery;` config = $.extend({}, { imgpath: 'praguecloudfronturl' + '/img', metaviewporttag: true }, opts, self.parseQueryString(document.URL.split("?")[1])) ko.validation.configure({ insertMessages: false }); ko.validation.rules['ccDate'] = { validator: (val, otherVal) -> return $.payment.validateCardExpiry(val.month, val.year); , message: 'Invalid date' } ko.validation.rules['ccNum'] = { validator: (val, otherVal) -> return $.payment.validateCardNumber(val); , message: 'Invalid credit card number' } ko.validation.rules['cvc'] = { validator: (val, otherVal) -> return $.payment.validateCardCVC(val); , message: 'Invalid CVC number' } ko.validation.registerExtenders() self.org = ko.observable(config['org']) self.countryCode = ko.observable(config['country'] ) self.imgPath = ko.observable(config['imgpath']) self.initializeIcons(self.imgPath()) self.seedAmount = config['seedamount'] || 100 self.seedValues = if config['seedvalues']? and /[0-9]+(,[0-9]+)*/.test(config['seedvalues']) then config['seedvalues'].split(",") else [15,35,50,100,250,500,1000] self.tags = if config['tags']? then config['tags'].replace(/\s/g, '').split(',') else [] self.currencies = { 'US' : 'USD', 'GB' : 'GBP', 'AU' : 'AUD', 'CA' : 'CAD', 'SE' : 'SEK', 'NO' : 'NOK', 'DK' : 'DKK', 'NZ' : 'NZD' } self.currenciesArray = ko.observableArray [ 'USD', 'GBP', 'CAD', 'AUD', 'EUR', 'NZD', 'SEK', 'NOK', 'DKK' ] self.currenciesEnabled = ko.observable(config['currencyconversion'] isnt "none") self.seededCurrency = config['seedcurrency'] or 'USD' self.formCurrency = config['formcurrency'] or self.seededCurrency initializeCurrency = -> unless config['currencyconversion'] in ["none", "choose"] return self.currencies[config['country']] else return self.formCurrency self.selectedCurrency = ko.observable(initializeCurrency()) self.currencySymbol = ko.computed(-> symbols = { 'USD' : '$', 'GBP' : '&pound;', 'EUR' : '&euro;', 'NZD' : 'NZ$', 'AUD' : 'AU$', 'CAD' : '$' } return symbols[self.selectedCurrency()] or self.selectedCurrency() , this) self.selectedBtn = ko.observable(-1) # Button amount self.selectedAmount = ko.observable("0") # Input amount self.inputtedAmount = ko.observable(null) self.displayAmount = ko.computed(-> self.inputtedAmount() or self.selectedAmount() , this).extend({ required: { message: "Please select an amount" }, min: 1 }) self.normalizedAmount = ko.computed(-> zeroDecimalCurrencies = ['BIF', 'CLP', 'JPY', 'KRW', 'PYG', 'VUV', 'XOF', 'CLP', 'GNF', 'KMF', 'MGA', 'RWF', 'XAF', 'XPF'] if self.selectedCurrency() in zeroDecimalCurrencies self.displayAmount() else self.displayAmount() + "00" , this) self.setActiveAmount = (index, amount) -> if index > -1 self.inputtedAmount(null) self.selectedAmount(self.amounts()[index]) self.selectedBtn(index) self.clearSelectedButton = -> self.selectedAmount(0) self.selectedBtn(-1) self.amounts = ko.computed(-> arr = [] for entry, count in self.seedValues baseAmount = parseInt(entry) / 100.0 * parseInt(self.seedAmount) if count < 7 # limit 7 buttons if self.currenciesEnabled() and config["rates"]? conversionRateToCurrency = config["rates"][self.selectedCurrency()] or 1 conversionRateFromCurrency = config["rates"][self.seededCurrency] or 1 arr.push(self.round(baseAmount * conversionRateToCurrency / conversionRateFromCurrency)) else arr.push(self.round(baseAmount)) return arr , this) self.amountsLength = ko.computed(-> self.amounts().length , this) self.visibleInputSet = ko.observable(0) self.incrementInputSet = -> gaDonations('send', 'event', 'next', 'click', "from-#{self.visibleInputSet()}-to-#{self.visibleInputSet()+1}") self.visibleInputSet(self.visibleInputSet() + 1) self.isAdvanceAllowed = (index) -> switch index when 1 self.inputSet1.isValid() when 2 self.inputSet1.isValid() && self.inputSet2.isValid() when 3 self.inputSet1.isValid() && self.inputSet2.isValid() && self.inputSet3.isValid() else true self.setInputSet = (index) -> if self.isAdvanceAllowed(index) gaDonations('send', 'event', 'navigation', 'click', "from-#{self.visibleInputSet()}-to-#{index}") self.visibleInputSet(index) self.firstName = ko.observable().extend({ required: { message: "Can't be blank" } }) self.lastName = ko.observable().extend({ required: { message: "Can't be blank" } }) self.email = ko.observable().extend({ required: { message: "Can't be blank" }, email: { message: "Invalid email" } }) self.cardNumber = ko.observable().extend({ required: { message: "Can't be blank" }, ccNum: true }) self.cardMonth = ko.observable() self.ccMonths = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] self.cardYear = ko.observable("#{new Date().getFullYear() + 1}") self.ccYears = (-> output = [] year = new Date().getFullYear() for yr in [year..year+19] output.push("#{yr}") return output )() self.cardDate = ko.computed(-> { month: self.cardMonth(), year: self.cardYear() } , this).extend({ ccDate: true, observable: true }) self.cvc = ko.observable().extend({ required: { message: "Can't be blank" }, digit: true, cvc: true }) $('#cc-num-input').payment('formatCardNumber') $('#cvc-num-input').payment('formatCardCVC') self.ccType = ko.observable() self.calcCardType = -> self.ccType($.payment.cardType($('#cc-num-input').val())) return true self.ccBackground = ko.computed(-> if self.ccType() in ['amex','mastercard','visa','discover','dinersclub'] return "url(#{self.imgPath()}/icon-cc-#{self.ccType()}.png)" else return "url(#{self.imgPath()}/icon-cc-none.png)" , this) self.inputSet1 = ko.validatedObservable({ amount: self.displayAmount }) self.inputSet2 = ko.validatedObservable({ firstName: self.firstName, lastName: self.lastName, email: self.email}) self.inputSet3 = ko.validatedObservable({ cardNumber: self.cardNumber, cardDate: self.cardDate, cvc: self.cvc}) self.stripeMessage = ko.observable("") self.connectToServer(config, self) catch e Honeybadger.notify e, {} parseQueryString: (q) -> hash = {} if q isnt `undefined` and q isnt "" q = q.split("&") i = 0 while i < q.length vars = q[i].split("=") hash[vars[0]] = vars[1] i++ return hash initializeIcons: (path) -> icons = { '#dnt-progress-amount' : 'icon-amount.png', '#dnt-progress-myinfo' : 'icon-myinfo.png', '#dnt-progress-payment' : 'icon-payment.png', '.donation-progress-arrow' : 'icon-arrow.png', '.donation-text-field[type="cc-num"]' : 'icon-cc-none.png', '.donation-select' : 'icon-dropdown-arrows.png', '.currency-select' : 'icon-dropdown-arrows.png', '.donation-loading-overlay' : '712.GIF' } for k, v of icons $(k).css('background-image', "url('#{path}/#{v}')") round: (number) -> temp = Math.round(parseFloat(number.toPrecision(2))) if temp == 0 then 1 else temp connectToServer: (opts, self) -> config = $.extend({}, { stripepublickey: "__praguestripepublickey__", stripepublictestkey: "__praguestripepublictestkey__", pusherpublickey: "__praguepusherpublickey__", pathtoserver: "__praguepathtoserver__" }, opts) keyToUse = if config['chargestatus'] == 'test' then config['stripepublictestkey'] else config['stripepublickey'] Stripe.setPublishableKey keyToUse subscribeToDonationChannel = (cardToken) -> $form = $("#donation-form") charge = {} charge.amount = self.normalizedAmount() charge.currency = self.selectedCurrency() if config['chargestatus']? charge.status = config['chargestatus'] charge.pusher_channel_token = Math.random().toString(36).slice(2) pusher = new Pusher(config['pusherpublickey']) channel = pusher.subscribe(charge.pusher_channel_token) channel.bind('pusher:subscription_succeeded', -> channel.bind "charge_completed", (data) -> $('.donation-loading-overlay').hide() pusher.disconnect() if data.status == "success" gaDonations('send', 'event', 'form', 'success') $("#donation-script").trigger("donations:success") if !!config['redirectto'] unless /^https?:\/\//.test(config['redirectto']) config['redirectto'] = "http://#{config['redirectto']}" window.location.replace(config['redirectto']) $("#donation-form").hide() $(".donations-callback-flash").show(0).delay(8000).hide(0) else gaDonations('send', 'event', 'form', 'error') $(".donation-payment-errors").text(data.message or "Something went wrong.").show() customer = {} customer.first_name = self.firstName() customer.last_name = self.lastName() customer.email = self.email() customer.country = self.countryCode() customer.charges_attributes = [charge] formPost = {} formPost.customer = customer formPost.card_token = cardToken formPost.config = $.extend(config, { 'calculatedAmounts' : self.amounts() }) formPost.organization_slug = self.org() formPost.tags = self.tags urlForCharges = if config['pathtoserver'].slice(-1) == "/" then config['pathtoserver'] + "charges" else config['pathtoserver'] + "/charges" $.ajax( url: urlForCharges type: "post" dataType: 'json' contentType: 'application/json' data: JSON.stringify(formPost) success: (response, textStatus, jqXHR) -> error: (response, textStatus, errorThrown) -> gaDonations('send', 'event', 'form', 'error', 'charge-error') $form.find(".donation-payment-errors").text(response.responseText or "Something went wrong.").show() $('.donation-loading-overlay').hide() $form.find("button").prop "disabled", false ) ) stripeResponseHandler = (status, response) -> $form = $("#donation-form") if response.error gaDonations('send', 'event', 'form', 'error', 'stripe-error') # Show the errors on the form $form.find("button").prop "disabled", false self.stripeMessage(response.error.message) $('.donation-loading-overlay').hide() else subscribeToDonationChannel(response.id, $form) false self.submitForm = -> gaDonations('send', 'event', 'submit', 'click') $form = $("#donation-form") $('.donation-loading-overlay').show() # Disable the submit button to prevent repeated clicks $form.find("button").prop "disabled", true Stripe.createToken $form, stripeResponseHandler # Prevent the form from submitting with the default action false
105226
cacheBust = '__rand__' class DonationsFormModel constructor: (jQuery, opts) -> try self = @ `$ = jQuery;` config = $.extend({}, { imgpath: 'praguecloudfronturl' + '/img', metaviewporttag: true }, opts, self.parseQueryString(document.URL.split("?")[1])) ko.validation.configure({ insertMessages: false }); ko.validation.rules['ccDate'] = { validator: (val, otherVal) -> return $.payment.validateCardExpiry(val.month, val.year); , message: 'Invalid date' } ko.validation.rules['ccNum'] = { validator: (val, otherVal) -> return $.payment.validateCardNumber(val); , message: 'Invalid credit card number' } ko.validation.rules['cvc'] = { validator: (val, otherVal) -> return $.payment.validateCardCVC(val); , message: 'Invalid CVC number' } ko.validation.registerExtenders() self.org = ko.observable(config['org']) self.countryCode = ko.observable(config['country'] ) self.imgPath = ko.observable(config['imgpath']) self.initializeIcons(self.imgPath()) self.seedAmount = config['seedamount'] || 100 self.seedValues = if config['seedvalues']? and /[0-9]+(,[0-9]+)*/.test(config['seedvalues']) then config['seedvalues'].split(",") else [15,35,50,100,250,500,1000] self.tags = if config['tags']? then config['tags'].replace(/\s/g, '').split(',') else [] self.currencies = { 'US' : 'USD', 'GB' : 'GBP', 'AU' : 'AUD', 'CA' : 'CAD', 'SE' : 'SEK', 'NO' : 'NOK', 'DK' : 'DKK', 'NZ' : 'NZD' } self.currenciesArray = ko.observableArray [ 'USD', 'GBP', 'CAD', 'AUD', 'EUR', 'NZD', 'SEK', 'NOK', 'DKK' ] self.currenciesEnabled = ko.observable(config['currencyconversion'] isnt "none") self.seededCurrency = config['seedcurrency'] or 'USD' self.formCurrency = config['formcurrency'] or self.seededCurrency initializeCurrency = -> unless config['currencyconversion'] in ["none", "choose"] return self.currencies[config['country']] else return self.formCurrency self.selectedCurrency = ko.observable(initializeCurrency()) self.currencySymbol = ko.computed(-> symbols = { 'USD' : '$', 'GBP' : '&pound;', 'EUR' : '&euro;', 'NZD' : 'NZ$', 'AUD' : 'AU$', 'CAD' : '$' } return symbols[self.selectedCurrency()] or self.selectedCurrency() , this) self.selectedBtn = ko.observable(-1) # Button amount self.selectedAmount = ko.observable("0") # Input amount self.inputtedAmount = ko.observable(null) self.displayAmount = ko.computed(-> self.inputtedAmount() or self.selectedAmount() , this).extend({ required: { message: "Please select an amount" }, min: 1 }) self.normalizedAmount = ko.computed(-> zeroDecimalCurrencies = ['BIF', 'CLP', 'JPY', 'KRW', 'PYG', 'VUV', 'XOF', 'CLP', 'GNF', 'KMF', 'MGA', 'RWF', 'XAF', 'XPF'] if self.selectedCurrency() in zeroDecimalCurrencies self.displayAmount() else self.displayAmount() + "00" , this) self.setActiveAmount = (index, amount) -> if index > -1 self.inputtedAmount(null) self.selectedAmount(self.amounts()[index]) self.selectedBtn(index) self.clearSelectedButton = -> self.selectedAmount(0) self.selectedBtn(-1) self.amounts = ko.computed(-> arr = [] for entry, count in self.seedValues baseAmount = parseInt(entry) / 100.0 * parseInt(self.seedAmount) if count < 7 # limit 7 buttons if self.currenciesEnabled() and config["rates"]? conversionRateToCurrency = config["rates"][self.selectedCurrency()] or 1 conversionRateFromCurrency = config["rates"][self.seededCurrency] or 1 arr.push(self.round(baseAmount * conversionRateToCurrency / conversionRateFromCurrency)) else arr.push(self.round(baseAmount)) return arr , this) self.amountsLength = ko.computed(-> self.amounts().length , this) self.visibleInputSet = ko.observable(0) self.incrementInputSet = -> gaDonations('send', 'event', 'next', 'click', "from-#{self.visibleInputSet()}-to-#{self.visibleInputSet()+1}") self.visibleInputSet(self.visibleInputSet() + 1) self.isAdvanceAllowed = (index) -> switch index when 1 self.inputSet1.isValid() when 2 self.inputSet1.isValid() && self.inputSet2.isValid() when 3 self.inputSet1.isValid() && self.inputSet2.isValid() && self.inputSet3.isValid() else true self.setInputSet = (index) -> if self.isAdvanceAllowed(index) gaDonations('send', 'event', 'navigation', 'click', "from-#{self.visibleInputSet()}-to-#{index}") self.visibleInputSet(index) self.firstName = ko.observable().extend({ required: { message: "Can't be blank" } }) self.lastName = ko.observable().extend({ required: { message: "Can't be blank" } }) self.email = ko.observable().extend({ required: { message: "Can't be blank" }, email: { message: "Invalid email" } }) self.cardNumber = ko.observable().extend({ required: { message: "Can't be blank" }, ccNum: true }) self.cardMonth = ko.observable() self.ccMonths = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] self.cardYear = ko.observable("#{new Date().getFullYear() + 1}") self.ccYears = (-> output = [] year = new Date().getFullYear() for yr in [year..year+19] output.push("#{yr}") return output )() self.cardDate = ko.computed(-> { month: self.cardMonth(), year: self.cardYear() } , this).extend({ ccDate: true, observable: true }) self.cvc = ko.observable().extend({ required: { message: "Can't be blank" }, digit: true, cvc: true }) $('#cc-num-input').payment('formatCardNumber') $('#cvc-num-input').payment('formatCardCVC') self.ccType = ko.observable() self.calcCardType = -> self.ccType($.payment.cardType($('#cc-num-input').val())) return true self.ccBackground = ko.computed(-> if self.ccType() in ['amex','mastercard','visa','discover','dinersclub'] return "url(#{self.imgPath()}/icon-cc-#{self.ccType()}.png)" else return "url(#{self.imgPath()}/icon-cc-none.png)" , this) self.inputSet1 = ko.validatedObservable({ amount: self.displayAmount }) self.inputSet2 = ko.validatedObservable({ firstName: self.firstName, lastName: self.lastName, email: self.email}) self.inputSet3 = ko.validatedObservable({ cardNumber: self.cardNumber, cardDate: self.cardDate, cvc: self.cvc}) self.stripeMessage = ko.observable("") self.connectToServer(config, self) catch e Honeybadger.notify e, {} parseQueryString: (q) -> hash = {} if q isnt `undefined` and q isnt "" q = q.split("&") i = 0 while i < q.length vars = q[i].split("=") hash[vars[0]] = vars[1] i++ return hash initializeIcons: (path) -> icons = { '#dnt-progress-amount' : 'icon-amount.png', '#dnt-progress-myinfo' : 'icon-myinfo.png', '#dnt-progress-payment' : 'icon-payment.png', '.donation-progress-arrow' : 'icon-arrow.png', '.donation-text-field[type="cc-num"]' : 'icon-cc-none.png', '.donation-select' : 'icon-dropdown-arrows.png', '.currency-select' : 'icon-dropdown-arrows.png', '.donation-loading-overlay' : '712.GIF' } for k, v of icons $(k).css('background-image', "url('#{path}/#{v}')") round: (number) -> temp = Math.round(parseFloat(number.toPrecision(2))) if temp == 0 then 1 else temp connectToServer: (opts, self) -> config = $.extend({}, { stripepublickey: "__praguestripepublickey__", stripepublictestkey: "__praguestripepublictestkey__", pusherpublickey: "__praguepusherpublickey__", pathtoserver: "__praguepathtoserver__" }, opts) keyToUse = if config['chargestatus'] == 'test' then config['stripepublictestkey'] else config['stripepublickey'] Stripe.setPublishableKey keyToUse subscribeToDonationChannel = (cardToken) -> $form = $("#donation-form") charge = {} charge.amount = self.normalizedAmount() charge.currency = self.selectedCurrency() if config['chargestatus']? charge.status = config['chargestatus'] charge.pusher_channel_token = <KEY>.<KEY>) pusher = new Pusher(config['pusherpublickey']) channel = pusher.subscribe(charge.pusher_channel_token) channel.bind('pusher:subscription_succeeded', -> channel.bind "charge_completed", (data) -> $('.donation-loading-overlay').hide() pusher.disconnect() if data.status == "success" gaDonations('send', 'event', 'form', 'success') $("#donation-script").trigger("donations:success") if !!config['redirectto'] unless /^https?:\/\//.test(config['redirectto']) config['redirectto'] = "http://#{config['redirectto']}" window.location.replace(config['redirectto']) $("#donation-form").hide() $(".donations-callback-flash").show(0).delay(8000).hide(0) else gaDonations('send', 'event', 'form', 'error') $(".donation-payment-errors").text(data.message or "Something went wrong.").show() customer = {} customer.first_name = self.firstName() customer.last_name = self.lastName() customer.email = self.email() customer.country = self.countryCode() customer.charges_attributes = [charge] formPost = {} formPost.customer = customer formPost.card_token = cardToken formPost.config = $.extend(config, { 'calculatedAmounts' : self.amounts() }) formPost.organization_slug = self.org() formPost.tags = self.tags urlForCharges = if config['pathtoserver'].slice(-1) == "/" then config['pathtoserver'] + "charges" else config['pathtoserver'] + "/charges" $.ajax( url: urlForCharges type: "post" dataType: 'json' contentType: 'application/json' data: JSON.stringify(formPost) success: (response, textStatus, jqXHR) -> error: (response, textStatus, errorThrown) -> gaDonations('send', 'event', 'form', 'error', 'charge-error') $form.find(".donation-payment-errors").text(response.responseText or "Something went wrong.").show() $('.donation-loading-overlay').hide() $form.find("button").prop "disabled", false ) ) stripeResponseHandler = (status, response) -> $form = $("#donation-form") if response.error gaDonations('send', 'event', 'form', 'error', 'stripe-error') # Show the errors on the form $form.find("button").prop "disabled", false self.stripeMessage(response.error.message) $('.donation-loading-overlay').hide() else subscribeToDonationChannel(response.id, $form) false self.submitForm = -> gaDonations('send', 'event', 'submit', 'click') $form = $("#donation-form") $('.donation-loading-overlay').show() # Disable the submit button to prevent repeated clicks $form.find("button").prop "disabled", true Stripe.createToken $form, stripeResponseHandler # Prevent the form from submitting with the default action false
true
cacheBust = '__rand__' class DonationsFormModel constructor: (jQuery, opts) -> try self = @ `$ = jQuery;` config = $.extend({}, { imgpath: 'praguecloudfronturl' + '/img', metaviewporttag: true }, opts, self.parseQueryString(document.URL.split("?")[1])) ko.validation.configure({ insertMessages: false }); ko.validation.rules['ccDate'] = { validator: (val, otherVal) -> return $.payment.validateCardExpiry(val.month, val.year); , message: 'Invalid date' } ko.validation.rules['ccNum'] = { validator: (val, otherVal) -> return $.payment.validateCardNumber(val); , message: 'Invalid credit card number' } ko.validation.rules['cvc'] = { validator: (val, otherVal) -> return $.payment.validateCardCVC(val); , message: 'Invalid CVC number' } ko.validation.registerExtenders() self.org = ko.observable(config['org']) self.countryCode = ko.observable(config['country'] ) self.imgPath = ko.observable(config['imgpath']) self.initializeIcons(self.imgPath()) self.seedAmount = config['seedamount'] || 100 self.seedValues = if config['seedvalues']? and /[0-9]+(,[0-9]+)*/.test(config['seedvalues']) then config['seedvalues'].split(",") else [15,35,50,100,250,500,1000] self.tags = if config['tags']? then config['tags'].replace(/\s/g, '').split(',') else [] self.currencies = { 'US' : 'USD', 'GB' : 'GBP', 'AU' : 'AUD', 'CA' : 'CAD', 'SE' : 'SEK', 'NO' : 'NOK', 'DK' : 'DKK', 'NZ' : 'NZD' } self.currenciesArray = ko.observableArray [ 'USD', 'GBP', 'CAD', 'AUD', 'EUR', 'NZD', 'SEK', 'NOK', 'DKK' ] self.currenciesEnabled = ko.observable(config['currencyconversion'] isnt "none") self.seededCurrency = config['seedcurrency'] or 'USD' self.formCurrency = config['formcurrency'] or self.seededCurrency initializeCurrency = -> unless config['currencyconversion'] in ["none", "choose"] return self.currencies[config['country']] else return self.formCurrency self.selectedCurrency = ko.observable(initializeCurrency()) self.currencySymbol = ko.computed(-> symbols = { 'USD' : '$', 'GBP' : '&pound;', 'EUR' : '&euro;', 'NZD' : 'NZ$', 'AUD' : 'AU$', 'CAD' : '$' } return symbols[self.selectedCurrency()] or self.selectedCurrency() , this) self.selectedBtn = ko.observable(-1) # Button amount self.selectedAmount = ko.observable("0") # Input amount self.inputtedAmount = ko.observable(null) self.displayAmount = ko.computed(-> self.inputtedAmount() or self.selectedAmount() , this).extend({ required: { message: "Please select an amount" }, min: 1 }) self.normalizedAmount = ko.computed(-> zeroDecimalCurrencies = ['BIF', 'CLP', 'JPY', 'KRW', 'PYG', 'VUV', 'XOF', 'CLP', 'GNF', 'KMF', 'MGA', 'RWF', 'XAF', 'XPF'] if self.selectedCurrency() in zeroDecimalCurrencies self.displayAmount() else self.displayAmount() + "00" , this) self.setActiveAmount = (index, amount) -> if index > -1 self.inputtedAmount(null) self.selectedAmount(self.amounts()[index]) self.selectedBtn(index) self.clearSelectedButton = -> self.selectedAmount(0) self.selectedBtn(-1) self.amounts = ko.computed(-> arr = [] for entry, count in self.seedValues baseAmount = parseInt(entry) / 100.0 * parseInt(self.seedAmount) if count < 7 # limit 7 buttons if self.currenciesEnabled() and config["rates"]? conversionRateToCurrency = config["rates"][self.selectedCurrency()] or 1 conversionRateFromCurrency = config["rates"][self.seededCurrency] or 1 arr.push(self.round(baseAmount * conversionRateToCurrency / conversionRateFromCurrency)) else arr.push(self.round(baseAmount)) return arr , this) self.amountsLength = ko.computed(-> self.amounts().length , this) self.visibleInputSet = ko.observable(0) self.incrementInputSet = -> gaDonations('send', 'event', 'next', 'click', "from-#{self.visibleInputSet()}-to-#{self.visibleInputSet()+1}") self.visibleInputSet(self.visibleInputSet() + 1) self.isAdvanceAllowed = (index) -> switch index when 1 self.inputSet1.isValid() when 2 self.inputSet1.isValid() && self.inputSet2.isValid() when 3 self.inputSet1.isValid() && self.inputSet2.isValid() && self.inputSet3.isValid() else true self.setInputSet = (index) -> if self.isAdvanceAllowed(index) gaDonations('send', 'event', 'navigation', 'click', "from-#{self.visibleInputSet()}-to-#{index}") self.visibleInputSet(index) self.firstName = ko.observable().extend({ required: { message: "Can't be blank" } }) self.lastName = ko.observable().extend({ required: { message: "Can't be blank" } }) self.email = ko.observable().extend({ required: { message: "Can't be blank" }, email: { message: "Invalid email" } }) self.cardNumber = ko.observable().extend({ required: { message: "Can't be blank" }, ccNum: true }) self.cardMonth = ko.observable() self.ccMonths = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] self.cardYear = ko.observable("#{new Date().getFullYear() + 1}") self.ccYears = (-> output = [] year = new Date().getFullYear() for yr in [year..year+19] output.push("#{yr}") return output )() self.cardDate = ko.computed(-> { month: self.cardMonth(), year: self.cardYear() } , this).extend({ ccDate: true, observable: true }) self.cvc = ko.observable().extend({ required: { message: "Can't be blank" }, digit: true, cvc: true }) $('#cc-num-input').payment('formatCardNumber') $('#cvc-num-input').payment('formatCardCVC') self.ccType = ko.observable() self.calcCardType = -> self.ccType($.payment.cardType($('#cc-num-input').val())) return true self.ccBackground = ko.computed(-> if self.ccType() in ['amex','mastercard','visa','discover','dinersclub'] return "url(#{self.imgPath()}/icon-cc-#{self.ccType()}.png)" else return "url(#{self.imgPath()}/icon-cc-none.png)" , this) self.inputSet1 = ko.validatedObservable({ amount: self.displayAmount }) self.inputSet2 = ko.validatedObservable({ firstName: self.firstName, lastName: self.lastName, email: self.email}) self.inputSet3 = ko.validatedObservable({ cardNumber: self.cardNumber, cardDate: self.cardDate, cvc: self.cvc}) self.stripeMessage = ko.observable("") self.connectToServer(config, self) catch e Honeybadger.notify e, {} parseQueryString: (q) -> hash = {} if q isnt `undefined` and q isnt "" q = q.split("&") i = 0 while i < q.length vars = q[i].split("=") hash[vars[0]] = vars[1] i++ return hash initializeIcons: (path) -> icons = { '#dnt-progress-amount' : 'icon-amount.png', '#dnt-progress-myinfo' : 'icon-myinfo.png', '#dnt-progress-payment' : 'icon-payment.png', '.donation-progress-arrow' : 'icon-arrow.png', '.donation-text-field[type="cc-num"]' : 'icon-cc-none.png', '.donation-select' : 'icon-dropdown-arrows.png', '.currency-select' : 'icon-dropdown-arrows.png', '.donation-loading-overlay' : '712.GIF' } for k, v of icons $(k).css('background-image', "url('#{path}/#{v}')") round: (number) -> temp = Math.round(parseFloat(number.toPrecision(2))) if temp == 0 then 1 else temp connectToServer: (opts, self) -> config = $.extend({}, { stripepublickey: "__praguestripepublickey__", stripepublictestkey: "__praguestripepublictestkey__", pusherpublickey: "__praguepusherpublickey__", pathtoserver: "__praguepathtoserver__" }, opts) keyToUse = if config['chargestatus'] == 'test' then config['stripepublictestkey'] else config['stripepublickey'] Stripe.setPublishableKey keyToUse subscribeToDonationChannel = (cardToken) -> $form = $("#donation-form") charge = {} charge.amount = self.normalizedAmount() charge.currency = self.selectedCurrency() if config['chargestatus']? charge.status = config['chargestatus'] charge.pusher_channel_token = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI) pusher = new Pusher(config['pusherpublickey']) channel = pusher.subscribe(charge.pusher_channel_token) channel.bind('pusher:subscription_succeeded', -> channel.bind "charge_completed", (data) -> $('.donation-loading-overlay').hide() pusher.disconnect() if data.status == "success" gaDonations('send', 'event', 'form', 'success') $("#donation-script").trigger("donations:success") if !!config['redirectto'] unless /^https?:\/\//.test(config['redirectto']) config['redirectto'] = "http://#{config['redirectto']}" window.location.replace(config['redirectto']) $("#donation-form").hide() $(".donations-callback-flash").show(0).delay(8000).hide(0) else gaDonations('send', 'event', 'form', 'error') $(".donation-payment-errors").text(data.message or "Something went wrong.").show() customer = {} customer.first_name = self.firstName() customer.last_name = self.lastName() customer.email = self.email() customer.country = self.countryCode() customer.charges_attributes = [charge] formPost = {} formPost.customer = customer formPost.card_token = cardToken formPost.config = $.extend(config, { 'calculatedAmounts' : self.amounts() }) formPost.organization_slug = self.org() formPost.tags = self.tags urlForCharges = if config['pathtoserver'].slice(-1) == "/" then config['pathtoserver'] + "charges" else config['pathtoserver'] + "/charges" $.ajax( url: urlForCharges type: "post" dataType: 'json' contentType: 'application/json' data: JSON.stringify(formPost) success: (response, textStatus, jqXHR) -> error: (response, textStatus, errorThrown) -> gaDonations('send', 'event', 'form', 'error', 'charge-error') $form.find(".donation-payment-errors").text(response.responseText or "Something went wrong.").show() $('.donation-loading-overlay').hide() $form.find("button").prop "disabled", false ) ) stripeResponseHandler = (status, response) -> $form = $("#donation-form") if response.error gaDonations('send', 'event', 'form', 'error', 'stripe-error') # Show the errors on the form $form.find("button").prop "disabled", false self.stripeMessage(response.error.message) $('.donation-loading-overlay').hide() else subscribeToDonationChannel(response.id, $form) false self.submitForm = -> gaDonations('send', 'event', 'submit', 'click') $form = $("#donation-form") $('.donation-loading-overlay').show() # Disable the submit button to prevent repeated clicks $form.find("button").prop "disabled", true Stripe.createToken $form, stripeResponseHandler # Prevent the form from submitting with the default action false
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9994345307350159, "start": 12, "tag": "NAME", "value": "Joyent" } ]
deps/npm/node_modules/sha/node_modules/readable-stream/lib/_stream_duplex.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # a duplex stream is just a stream that is both readable and writable. # Since JS doesn't have multiple prototypal inheritance, this class # prototypally inherits from Readable, and then parasitically from # Writable. #<replacement> #</replacement> #<replacement> #</replacement> Duplex = (options) -> return new Duplex(options) unless this instanceof Duplex Readable.call this, options Writable.call this, options @readable = false if options and options.readable is false @writable = false if options and options.writable is false @allowHalfOpen = true @allowHalfOpen = false if options and options.allowHalfOpen is false @once "end", onend return # the no-half-open enforcer onend = -> # if we allow half-open state, or if the writable side ended, # then we're ok. return if @allowHalfOpen or @_writableState.ended # no more data can be written. # But allow more writes to happen in this tick. process.nextTick @end.bind(this) return forEach = (xs, f) -> i = 0 l = xs.length while i < l f xs[i], i i++ return module.exports = Duplex objectKeys = Object.keys or (obj) -> keys = [] for key of obj keys.push key keys util = require("core-util-is") util.inherits = require("inherits") Readable = require("./_stream_readable") Writable = require("./_stream_writable") util.inherits Duplex, Readable forEach objectKeys(Writable::), (method) -> Duplex::[method] = Writable::[method] unless Duplex::[method] return
219814
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # a duplex stream is just a stream that is both readable and writable. # Since JS doesn't have multiple prototypal inheritance, this class # prototypally inherits from Readable, and then parasitically from # Writable. #<replacement> #</replacement> #<replacement> #</replacement> Duplex = (options) -> return new Duplex(options) unless this instanceof Duplex Readable.call this, options Writable.call this, options @readable = false if options and options.readable is false @writable = false if options and options.writable is false @allowHalfOpen = true @allowHalfOpen = false if options and options.allowHalfOpen is false @once "end", onend return # the no-half-open enforcer onend = -> # if we allow half-open state, or if the writable side ended, # then we're ok. return if @allowHalfOpen or @_writableState.ended # no more data can be written. # But allow more writes to happen in this tick. process.nextTick @end.bind(this) return forEach = (xs, f) -> i = 0 l = xs.length while i < l f xs[i], i i++ return module.exports = Duplex objectKeys = Object.keys or (obj) -> keys = [] for key of obj keys.push key keys util = require("core-util-is") util.inherits = require("inherits") Readable = require("./_stream_readable") Writable = require("./_stream_writable") util.inherits Duplex, Readable forEach objectKeys(Writable::), (method) -> Duplex::[method] = Writable::[method] unless Duplex::[method] return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # a duplex stream is just a stream that is both readable and writable. # Since JS doesn't have multiple prototypal inheritance, this class # prototypally inherits from Readable, and then parasitically from # Writable. #<replacement> #</replacement> #<replacement> #</replacement> Duplex = (options) -> return new Duplex(options) unless this instanceof Duplex Readable.call this, options Writable.call this, options @readable = false if options and options.readable is false @writable = false if options and options.writable is false @allowHalfOpen = true @allowHalfOpen = false if options and options.allowHalfOpen is false @once "end", onend return # the no-half-open enforcer onend = -> # if we allow half-open state, or if the writable side ended, # then we're ok. return if @allowHalfOpen or @_writableState.ended # no more data can be written. # But allow more writes to happen in this tick. process.nextTick @end.bind(this) return forEach = (xs, f) -> i = 0 l = xs.length while i < l f xs[i], i i++ return module.exports = Duplex objectKeys = Object.keys or (obj) -> keys = [] for key of obj keys.push key keys util = require("core-util-is") util.inherits = require("inherits") Readable = require("./_stream_readable") Writable = require("./_stream_writable") util.inherits Duplex, Readable forEach objectKeys(Writable::), (method) -> Duplex::[method] = Writable::[method] unless Duplex::[method] return
[ { "context": "gz'\n\n transbrute:\n docs:\n remote: 'git@github.com:chaplinjs/chaplin.git'\n branch: 'gh-pages'", "end": 2990, "score": 0.9997434616088867, "start": 2976, "tag": "EMAIL", "value": "git@github.com" }, { "context": "rute:\n docs:\n remo...
Gruntfile.coffee
timgates42/chaplin
406
'use strict' # Package # ======= pkg = require './package.json' banner = """ /*! * Chaplin #{pkg.version} * * Chaplin may be freely distributed under the MIT license. * For all details and documentation: * http://chaplinjs.org */ """ umdHead = ''' (function(root, factory) { if (typeof define === 'function' && define.amd) { define(['backbone', 'underscore'], factory); } else if (typeof module === 'object' && module && module.exports) { module.exports = factory(require('backbone'), require('underscore')); } else if (typeof require === 'function') { factory(window.Backbone, window._ || window.Backbone.utils); } else { throw new Error('Chaplin requires Common.js or AMD modules'); } }(this, function(Backbone, _) { function require(name) { return {backbone: Backbone, underscore: _}[name]; } require = ''' umdTail = ''' return require(1); })) ''' setupJSDOM = -> require('jsdom-global')(undefined, url: 'https://github.com' ) setupChai = -> chai = require 'chai' chai.use require 'sinon-chai' require 'chai/register-expect' module.exports = (grunt) -> # Configuration # ============= grunt.initConfig { # Package # ------- pkg coffeelint: src: 'src/**/*.coffee' test: 'test/*.coffee' grunt: 'Gruntfile.coffee' options: configFile: 'coffeelint.json' mochaTest: native: options: timeout: 1e5 reporter: 'spec' require: [ 'coffeescript/register' 'coffee-coverage/register-istanbul' setupJSDOM -> require.cache[require.resolve 'jquery'] = {} 'backbone.nativeview' setupChai ] src: 'test/*.coffee' jquery: options: timeout: 1e5 reporter: 'spec' require: [ 'coffeescript/register' setupJSDOM setupChai ] src: 'test/*.coffee' makeReport: src: 'coverage/coverage-coffee.json', options: type: 'html' dir: 'coverage' browserify: dist: files: 'build/chaplin.js': ['./src/chaplin.coffee'] options: { banner external: ['backbone', 'underscore'] transform: ['coffeeify'] browserifyOptions: debug: true bare: true extensions: ['.coffee'] postBundleCB: (err, src, next) -> if err next err else src = umdHead + src + umdTail next null, new Buffer src } # Minify # ====== uglify: options: mangle: true universal: files: 'build/chaplin.min.js': 'build/chaplin.js' # Compression # =========== compress: files: src: 'build/chaplin.min.js' dest: 'build/chaplin.min.js.gz' transbrute: docs: remote: 'git@github.com:chaplinjs/chaplin.git' branch: 'gh-pages' files: [ { expand: true, cwd: 'docs/', src: '**/*' } ] downloads: message: "Release #{pkg.version}." tag: pkg.version tagMessage: "Version #{pkg.version}." remote: 'git@github.com:chaplinjs/downloads.git' branch: 'gh-pages' files: [ { expand: true, cwd: 'build/', src: 'chaplin.{js,min.js}' }, { dest: 'bower.json', body: { name: 'chaplin', repo: 'chaplinjs/downloads', version: pkg.version, main: 'chaplin.js', scripts: ['chaplin.js'], dependencies: { backbone: '1.x' } } }, { dest: 'component.json', body: { name: 'chaplin', repo: 'chaplinjs/downloads', version: pkg.version, main: 'chaplin.js', scripts: ['chaplin.js'], dependencies: { 'bower_components/backbone': '1.x' } } }, { dest: 'package.json', body: { name: 'chaplin', version: pkg.version, description: 'Chaplin.js', main: 'chaplin.js', scripts: { test: 'echo "Error: no test specified" && exit 1' }, repository: { type: 'git', url: 'git://github.com/chaplinjs/downloads.git' }, author: 'Chaplin team', license: 'MIT', bugs: { url: 'https://github.com/chaplinjs/downloads/issues' }, dependencies: pkg.dependencies } } ] # Watching for changes # ==================== watch: coffee: files: ['src/**/*.coffee', 'test/*.coffee'] tasks: ['test'] } # Dependencies # ============ for name of pkg.devDependencies when name.startsWith 'grunt-' grunt.loadNpmTasks name # Releasing # ========= grunt.registerTask 'check:versions:component', 'Check that package.json and bower.json versions match', -> componentVersion = grunt.file.readJSON('bower.json').version unless componentVersion is pkg.version grunt.fail.warn "bower.json is version #{componentVersion}, package.json is #{pkg.version}." else grunt.log.ok() grunt.registerTask 'check:versions:changelog', 'Check that CHANGELOG.md is up to date', -> # Require CHANGELOG.md to contain "Chaplin VERSION (DIGIT" changelogMd = grunt.file.read('CHANGELOG.md') unless RegExp("Chaplin #{pkg.version} \\(\\d").test changelogMd grunt.fail.warn "CHANGELOG.md does not seem to be updated for #{pkg.version}." else grunt.log.ok() grunt.registerTask 'check:versions:docs', 'Check that package.json and docs versions match', -> template = grunt.file.read path.join('docs', '_layouts', 'default.html') match = template.match /^version: ((\d+)\.(\d+)\.(\d+)(?:-[\dA-Za-z\-]*)?)$/m unless match grunt.fail.warn "Version missing in docs layout." docsVersion = match[1] unless docsVersion is pkg.version grunt.fail.warn "Docs layout is version #{docsVersion}, package.json is #{pkg.version}." else grunt.log.ok() grunt.registerTask 'check:versions', [ 'check:versions:component', 'check:versions:changelog', 'check:versions:docs' ] grunt.registerTask 'release:git', 'Check context, commit and tag for release.', -> prompt = require 'prompt' prompt.start() prompt.message = prompt.delimiter = '' prompt.colors = false # Command/query wrapper, turns description object for `spawn` into runner command = (desc, message) -> (next) -> grunt.log.writeln message if message grunt.util.spawn desc, (err, result, code) -> next(err) query = (desc) -> (next) -> grunt.util.spawn desc, (err, result, code) -> next(err, result) # Help checking input from prompt. Returns a callback that calls the # original callback `next` only if the input was as expected checkInput = (expectation, next) -> (err, input) -> unless input and input.question is expectation grunt.fail.warn "Aborted: Expected #{expectation}, got #{input}" next() steps = [] continuation = this.async() # Check for master branch steps.push query(cmd: 'git', args: ['rev-parse', '--abbrev-ref', 'HEAD']) steps.push (result, next) -> result = result.toString().trim() if result is 'master' next() else prompt.get([ description: "Current branch is #{result}, not master. 'ok' to continue, Ctrl-C to quit." pattern: /^ok$/, required: true ], checkInput('ok', next) ) # List dirty files, ask for confirmation steps.push query(cmd: 'git', args: ['status', '--porcelain']) steps.push (result, next) -> grunt.fail.warn "Nothing to commit." unless result.toString().length grunt.log.writeln "The following dirty files will be committed:" grunt.log.writeln result prompt.get([ description: "Commit these files? 'ok' to continue, Ctrl-C to quit.", pattern: /^ok$/, required: true ], checkInput('ok', next) ) # Commit steps.push command(cmd: 'git', args: ['commit', '-a', '-m', "Release #{pkg.version}"]) # Tag steps.push command(cmd: 'git', args: ['tag', '-a', pkg.version, '-m', "Version #{pkg.version}"]) grunt.util.async.waterfall steps, continuation grunt.registerTask 'release', [ 'check:versions' 'release:git' 'build' 'transbrute:docs' 'transbrute:downloads' ] # Publish Documentation # ===================== grunt.registerTask 'docs:publish', ['check:versions:docs', 'transbrute:docs'] # Tests # ===== grunt.registerTask 'lint', 'coffeelint' grunt.registerTask 'test', 'mochaTest:native' grunt.registerTask 'test:jquery', 'mochaTest:jquery' # Coverage # ======== grunt.registerTask 'coverage', ['mochaTest:native', 'makeReport'] # Building # ======== grunt.registerTask 'build', ['browserify', 'uglify', 'compress'] # Default # ======= grunt.registerTask 'default', ['lint', 'test']
67098
'use strict' # Package # ======= pkg = require './package.json' banner = """ /*! * Chaplin #{pkg.version} * * Chaplin may be freely distributed under the MIT license. * For all details and documentation: * http://chaplinjs.org */ """ umdHead = ''' (function(root, factory) { if (typeof define === 'function' && define.amd) { define(['backbone', 'underscore'], factory); } else if (typeof module === 'object' && module && module.exports) { module.exports = factory(require('backbone'), require('underscore')); } else if (typeof require === 'function') { factory(window.Backbone, window._ || window.Backbone.utils); } else { throw new Error('Chaplin requires Common.js or AMD modules'); } }(this, function(Backbone, _) { function require(name) { return {backbone: Backbone, underscore: _}[name]; } require = ''' umdTail = ''' return require(1); })) ''' setupJSDOM = -> require('jsdom-global')(undefined, url: 'https://github.com' ) setupChai = -> chai = require 'chai' chai.use require 'sinon-chai' require 'chai/register-expect' module.exports = (grunt) -> # Configuration # ============= grunt.initConfig { # Package # ------- pkg coffeelint: src: 'src/**/*.coffee' test: 'test/*.coffee' grunt: 'Gruntfile.coffee' options: configFile: 'coffeelint.json' mochaTest: native: options: timeout: 1e5 reporter: 'spec' require: [ 'coffeescript/register' 'coffee-coverage/register-istanbul' setupJSDOM -> require.cache[require.resolve 'jquery'] = {} 'backbone.nativeview' setupChai ] src: 'test/*.coffee' jquery: options: timeout: 1e5 reporter: 'spec' require: [ 'coffeescript/register' setupJSDOM setupChai ] src: 'test/*.coffee' makeReport: src: 'coverage/coverage-coffee.json', options: type: 'html' dir: 'coverage' browserify: dist: files: 'build/chaplin.js': ['./src/chaplin.coffee'] options: { banner external: ['backbone', 'underscore'] transform: ['coffeeify'] browserifyOptions: debug: true bare: true extensions: ['.coffee'] postBundleCB: (err, src, next) -> if err next err else src = umdHead + src + umdTail next null, new Buffer src } # Minify # ====== uglify: options: mangle: true universal: files: 'build/chaplin.min.js': 'build/chaplin.js' # Compression # =========== compress: files: src: 'build/chaplin.min.js' dest: 'build/chaplin.min.js.gz' transbrute: docs: remote: '<EMAIL>:chaplinjs/chaplin.git' branch: 'gh-pages' files: [ { expand: true, cwd: 'docs/', src: '**/*' } ] downloads: message: "Release #{pkg.version}." tag: pkg.version tagMessage: "Version #{pkg.version}." remote: '<EMAIL>:chaplinjs/downloads.git' branch: 'gh-pages' files: [ { expand: true, cwd: 'build/', src: 'chaplin.{js,min.js}' }, { dest: 'bower.json', body: { name: 'chaplin', repo: 'chaplinjs/downloads', version: pkg.version, main: 'chaplin.js', scripts: ['chaplin.js'], dependencies: { backbone: '1.x' } } }, { dest: 'component.json', body: { name: 'chaplin', repo: 'chaplinjs/downloads', version: pkg.version, main: 'chaplin.js', scripts: ['chaplin.js'], dependencies: { 'bower_components/backbone': '1.x' } } }, { dest: 'package.json', body: { name: 'chaplin', version: pkg.version, description: 'Chaplin.js', main: 'chaplin.js', scripts: { test: 'echo "Error: no test specified" && exit 1' }, repository: { type: 'git', url: 'git://github.com/chaplinjs/downloads.git' }, author: 'Chaplin team', license: 'MIT', bugs: { url: 'https://github.com/chaplinjs/downloads/issues' }, dependencies: pkg.dependencies } } ] # Watching for changes # ==================== watch: coffee: files: ['src/**/*.coffee', 'test/*.coffee'] tasks: ['test'] } # Dependencies # ============ for name of pkg.devDependencies when name.startsWith 'grunt-' grunt.loadNpmTasks name # Releasing # ========= grunt.registerTask 'check:versions:component', 'Check that package.json and bower.json versions match', -> componentVersion = grunt.file.readJSON('bower.json').version unless componentVersion is pkg.version grunt.fail.warn "bower.json is version #{componentVersion}, package.json is #{pkg.version}." else grunt.log.ok() grunt.registerTask 'check:versions:changelog', 'Check that CHANGELOG.md is up to date', -> # Require CHANGELOG.md to contain "Chaplin VERSION (DIGIT" changelogMd = grunt.file.read('CHANGELOG.md') unless RegExp("Chaplin #{pkg.version} \\(\\d").test changelogMd grunt.fail.warn "CHANGELOG.md does not seem to be updated for #{pkg.version}." else grunt.log.ok() grunt.registerTask 'check:versions:docs', 'Check that package.json and docs versions match', -> template = grunt.file.read path.join('docs', '_layouts', 'default.html') match = template.match /^version: ((\d+)\.(\d+)\.(\d+)(?:-[\dA-Za-z\-]*)?)$/m unless match grunt.fail.warn "Version missing in docs layout." docsVersion = match[1] unless docsVersion is pkg.version grunt.fail.warn "Docs layout is version #{docsVersion}, package.json is #{pkg.version}." else grunt.log.ok() grunt.registerTask 'check:versions', [ 'check:versions:component', 'check:versions:changelog', 'check:versions:docs' ] grunt.registerTask 'release:git', 'Check context, commit and tag for release.', -> prompt = require 'prompt' prompt.start() prompt.message = prompt.delimiter = '' prompt.colors = false # Command/query wrapper, turns description object for `spawn` into runner command = (desc, message) -> (next) -> grunt.log.writeln message if message grunt.util.spawn desc, (err, result, code) -> next(err) query = (desc) -> (next) -> grunt.util.spawn desc, (err, result, code) -> next(err, result) # Help checking input from prompt. Returns a callback that calls the # original callback `next` only if the input was as expected checkInput = (expectation, next) -> (err, input) -> unless input and input.question is expectation grunt.fail.warn "Aborted: Expected #{expectation}, got #{input}" next() steps = [] continuation = this.async() # Check for master branch steps.push query(cmd: 'git', args: ['rev-parse', '--abbrev-ref', 'HEAD']) steps.push (result, next) -> result = result.toString().trim() if result is 'master' next() else prompt.get([ description: "Current branch is #{result}, not master. 'ok' to continue, Ctrl-C to quit." pattern: /^ok$/, required: true ], checkInput('ok', next) ) # List dirty files, ask for confirmation steps.push query(cmd: 'git', args: ['status', '--porcelain']) steps.push (result, next) -> grunt.fail.warn "Nothing to commit." unless result.toString().length grunt.log.writeln "The following dirty files will be committed:" grunt.log.writeln result prompt.get([ description: "Commit these files? 'ok' to continue, Ctrl-C to quit.", pattern: /^ok$/, required: true ], checkInput('ok', next) ) # Commit steps.push command(cmd: 'git', args: ['commit', '-a', '-m', "Release #{pkg.version}"]) # Tag steps.push command(cmd: 'git', args: ['tag', '-a', pkg.version, '-m', "Version #{pkg.version}"]) grunt.util.async.waterfall steps, continuation grunt.registerTask 'release', [ 'check:versions' 'release:git' 'build' 'transbrute:docs' 'transbrute:downloads' ] # Publish Documentation # ===================== grunt.registerTask 'docs:publish', ['check:versions:docs', 'transbrute:docs'] # Tests # ===== grunt.registerTask 'lint', 'coffeelint' grunt.registerTask 'test', 'mochaTest:native' grunt.registerTask 'test:jquery', 'mochaTest:jquery' # Coverage # ======== grunt.registerTask 'coverage', ['mochaTest:native', 'makeReport'] # Building # ======== grunt.registerTask 'build', ['browserify', 'uglify', 'compress'] # Default # ======= grunt.registerTask 'default', ['lint', 'test']
true
'use strict' # Package # ======= pkg = require './package.json' banner = """ /*! * Chaplin #{pkg.version} * * Chaplin may be freely distributed under the MIT license. * For all details and documentation: * http://chaplinjs.org */ """ umdHead = ''' (function(root, factory) { if (typeof define === 'function' && define.amd) { define(['backbone', 'underscore'], factory); } else if (typeof module === 'object' && module && module.exports) { module.exports = factory(require('backbone'), require('underscore')); } else if (typeof require === 'function') { factory(window.Backbone, window._ || window.Backbone.utils); } else { throw new Error('Chaplin requires Common.js or AMD modules'); } }(this, function(Backbone, _) { function require(name) { return {backbone: Backbone, underscore: _}[name]; } require = ''' umdTail = ''' return require(1); })) ''' setupJSDOM = -> require('jsdom-global')(undefined, url: 'https://github.com' ) setupChai = -> chai = require 'chai' chai.use require 'sinon-chai' require 'chai/register-expect' module.exports = (grunt) -> # Configuration # ============= grunt.initConfig { # Package # ------- pkg coffeelint: src: 'src/**/*.coffee' test: 'test/*.coffee' grunt: 'Gruntfile.coffee' options: configFile: 'coffeelint.json' mochaTest: native: options: timeout: 1e5 reporter: 'spec' require: [ 'coffeescript/register' 'coffee-coverage/register-istanbul' setupJSDOM -> require.cache[require.resolve 'jquery'] = {} 'backbone.nativeview' setupChai ] src: 'test/*.coffee' jquery: options: timeout: 1e5 reporter: 'spec' require: [ 'coffeescript/register' setupJSDOM setupChai ] src: 'test/*.coffee' makeReport: src: 'coverage/coverage-coffee.json', options: type: 'html' dir: 'coverage' browserify: dist: files: 'build/chaplin.js': ['./src/chaplin.coffee'] options: { banner external: ['backbone', 'underscore'] transform: ['coffeeify'] browserifyOptions: debug: true bare: true extensions: ['.coffee'] postBundleCB: (err, src, next) -> if err next err else src = umdHead + src + umdTail next null, new Buffer src } # Minify # ====== uglify: options: mangle: true universal: files: 'build/chaplin.min.js': 'build/chaplin.js' # Compression # =========== compress: files: src: 'build/chaplin.min.js' dest: 'build/chaplin.min.js.gz' transbrute: docs: remote: 'PI:EMAIL:<EMAIL>END_PI:chaplinjs/chaplin.git' branch: 'gh-pages' files: [ { expand: true, cwd: 'docs/', src: '**/*' } ] downloads: message: "Release #{pkg.version}." tag: pkg.version tagMessage: "Version #{pkg.version}." remote: 'PI:EMAIL:<EMAIL>END_PI:chaplinjs/downloads.git' branch: 'gh-pages' files: [ { expand: true, cwd: 'build/', src: 'chaplin.{js,min.js}' }, { dest: 'bower.json', body: { name: 'chaplin', repo: 'chaplinjs/downloads', version: pkg.version, main: 'chaplin.js', scripts: ['chaplin.js'], dependencies: { backbone: '1.x' } } }, { dest: 'component.json', body: { name: 'chaplin', repo: 'chaplinjs/downloads', version: pkg.version, main: 'chaplin.js', scripts: ['chaplin.js'], dependencies: { 'bower_components/backbone': '1.x' } } }, { dest: 'package.json', body: { name: 'chaplin', version: pkg.version, description: 'Chaplin.js', main: 'chaplin.js', scripts: { test: 'echo "Error: no test specified" && exit 1' }, repository: { type: 'git', url: 'git://github.com/chaplinjs/downloads.git' }, author: 'Chaplin team', license: 'MIT', bugs: { url: 'https://github.com/chaplinjs/downloads/issues' }, dependencies: pkg.dependencies } } ] # Watching for changes # ==================== watch: coffee: files: ['src/**/*.coffee', 'test/*.coffee'] tasks: ['test'] } # Dependencies # ============ for name of pkg.devDependencies when name.startsWith 'grunt-' grunt.loadNpmTasks name # Releasing # ========= grunt.registerTask 'check:versions:component', 'Check that package.json and bower.json versions match', -> componentVersion = grunt.file.readJSON('bower.json').version unless componentVersion is pkg.version grunt.fail.warn "bower.json is version #{componentVersion}, package.json is #{pkg.version}." else grunt.log.ok() grunt.registerTask 'check:versions:changelog', 'Check that CHANGELOG.md is up to date', -> # Require CHANGELOG.md to contain "Chaplin VERSION (DIGIT" changelogMd = grunt.file.read('CHANGELOG.md') unless RegExp("Chaplin #{pkg.version} \\(\\d").test changelogMd grunt.fail.warn "CHANGELOG.md does not seem to be updated for #{pkg.version}." else grunt.log.ok() grunt.registerTask 'check:versions:docs', 'Check that package.json and docs versions match', -> template = grunt.file.read path.join('docs', '_layouts', 'default.html') match = template.match /^version: ((\d+)\.(\d+)\.(\d+)(?:-[\dA-Za-z\-]*)?)$/m unless match grunt.fail.warn "Version missing in docs layout." docsVersion = match[1] unless docsVersion is pkg.version grunt.fail.warn "Docs layout is version #{docsVersion}, package.json is #{pkg.version}." else grunt.log.ok() grunt.registerTask 'check:versions', [ 'check:versions:component', 'check:versions:changelog', 'check:versions:docs' ] grunt.registerTask 'release:git', 'Check context, commit and tag for release.', -> prompt = require 'prompt' prompt.start() prompt.message = prompt.delimiter = '' prompt.colors = false # Command/query wrapper, turns description object for `spawn` into runner command = (desc, message) -> (next) -> grunt.log.writeln message if message grunt.util.spawn desc, (err, result, code) -> next(err) query = (desc) -> (next) -> grunt.util.spawn desc, (err, result, code) -> next(err, result) # Help checking input from prompt. Returns a callback that calls the # original callback `next` only if the input was as expected checkInput = (expectation, next) -> (err, input) -> unless input and input.question is expectation grunt.fail.warn "Aborted: Expected #{expectation}, got #{input}" next() steps = [] continuation = this.async() # Check for master branch steps.push query(cmd: 'git', args: ['rev-parse', '--abbrev-ref', 'HEAD']) steps.push (result, next) -> result = result.toString().trim() if result is 'master' next() else prompt.get([ description: "Current branch is #{result}, not master. 'ok' to continue, Ctrl-C to quit." pattern: /^ok$/, required: true ], checkInput('ok', next) ) # List dirty files, ask for confirmation steps.push query(cmd: 'git', args: ['status', '--porcelain']) steps.push (result, next) -> grunt.fail.warn "Nothing to commit." unless result.toString().length grunt.log.writeln "The following dirty files will be committed:" grunt.log.writeln result prompt.get([ description: "Commit these files? 'ok' to continue, Ctrl-C to quit.", pattern: /^ok$/, required: true ], checkInput('ok', next) ) # Commit steps.push command(cmd: 'git', args: ['commit', '-a', '-m', "Release #{pkg.version}"]) # Tag steps.push command(cmd: 'git', args: ['tag', '-a', pkg.version, '-m', "Version #{pkg.version}"]) grunt.util.async.waterfall steps, continuation grunt.registerTask 'release', [ 'check:versions' 'release:git' 'build' 'transbrute:docs' 'transbrute:downloads' ] # Publish Documentation # ===================== grunt.registerTask 'docs:publish', ['check:versions:docs', 'transbrute:docs'] # Tests # ===== grunt.registerTask 'lint', 'coffeelint' grunt.registerTask 'test', 'mochaTest:native' grunt.registerTask 'test:jquery', 'mochaTest:jquery' # Coverage # ======== grunt.registerTask 'coverage', ['mochaTest:native', 'makeReport'] # Building # ======== grunt.registerTask 'build', ['browserify', 'uglify', 'compress'] # Default # ======= grunt.registerTask 'default', ['lint', 'test']
[ { "context": "->\n SocialCalc ?= {}\n SocialCalc._username = Math.random().toString()\n SocialCalc.isConnected = true\n ", "end": 100, "score": 0.44269707798957825, "start": 89, "tag": "KEY", "value": "Math.random" }, { "context": "lc ?= {}\n SocialCalc._username = Math....
player.coffee
obra/ethercalc
1
@include = -> @client '/player.js': -> SocialCalc ?= {} SocialCalc._username = Math.random().toString() SocialCalc.isConnected = true SocialCalc.hadSnapshot = false SocialCalc._room = window.location.hash.replace('#', '') unless SocialCalc._room window.location = '/start' return try window.history.pushState {}, '', '/'+SocialCalc._room @connect() emit = (data) => @emit broadcast: data SocialCalc.Callbacks.broadcast = (type, data={}) => return unless SocialCalc.isConnected data.user = SocialCalc._username data.room = SocialCalc._room data.type = type emit data SocialCalc.isConnected = true SocialCalc.Callbacks.broadcast "ask.snapshot" @on broadcast: -> return unless SocialCalc?.isConnected return if @data.user == SocialCalc._username return if @data.to and @data.to != SocialCalc._username return if @data.room and @data.room != SocialCalc._room editor = SocialCalc.CurrentSpreadsheetControlObject.editor switch @data.type when "chat" window.addmsg @data.msg when "ecells" for user, ecell of @data.ecells continue if user == SocialCalc._username peerClass = " " + user + " defaultPeer" find = new RegExp(peerClass, "g") cr = SocialCalc.coordToCr(ecell) cell = SocialCalc.GetEditorCellElement(editor, cr.row, cr.col) cell.element.className += peerClass if cell.element.className.search(find) == -1 when "ecell" peerClass = " " + @data.user + " defaultPeer" find = new RegExp(peerClass, "g") if @data.original origCR = SocialCalc.coordToCr(@data.original) origCell = SocialCalc.GetEditorCellElement(editor, origCR.row, origCR.col) origCell.element.className = origCell.element.className.replace(find, "") cr = SocialCalc.coordToCr(@data.ecell) cell = SocialCalc.GetEditorCellElement(editor, cr.row, cr.col) cell.element.className += peerClass if cell.element.className.search(find) == -1 when "ask.snapshot" SocialCalc.Callbacks.broadcast "snapshot", to: @data.user snapshot: SocialCalc.CurrentSpreadsheetControlObject.CreateSpreadsheetSave() when "ask.ecell" SocialCalc.Callbacks.broadcast "ecell", to: @data.user ecell: editor.ecell.coord when "log" break if SocialCalc.hadSnapshot SocialCalc.hadSnapshot = true spreadsheet = SocialCalc.CurrentSpreadsheetControlObject window.addmsg @data.chat.join("\n"), true cmdstr = @data.log.join("\n") SocialCalc.CurrentSpreadsheetControlObject.context.sheetobj.ScheduleSheetCommands cmdstr, false, true editor = SocialCalc.CurrentSpreadsheetControlObject.editor # editor.MoveECellCallback.broadcast = (e) -> # SocialCalc.Callbacks.broadcast "my.ecell" # ecell: e.ecell.coord when "snapshot" break if SocialCalc.hadSnapshot SocialCalc.hadSnapshot = true spreadsheet = SocialCalc.CurrentSpreadsheetControlObject parts = spreadsheet.DecodeSpreadsheetSave(@data.snapshot) if parts if parts.sheet spreadsheet.sheet.ResetSheet() spreadsheet.ParseSheetSave @data.snapshot.substring(parts.sheet.start, parts.sheet.end) spreadsheet.editor.LoadEditorSettings @data.snapshot.substring(parts.edit.start, parts.edit.end) if parts.edit if spreadsheet.editor.context.sheetobj.attribs.recalc == "off" spreadsheet.ExecuteCommand "redisplay", "" spreadsheet.ExecuteCommand "set sheet defaulttextvalueformat text-wiki" else spreadsheet.ExecuteCommand "recalc", "" spreadsheet.ExecuteCommand "set sheet defaulttextvalueformat text-wiki" when "execute" SocialCalc.CurrentSpreadsheetControlObject.context.sheetobj.ScheduleSheetCommands @data.cmdstr, @data.saveundo, true return
210361
@include = -> @client '/player.js': -> SocialCalc ?= {} SocialCalc._username = <KEY>().<KEY>() SocialCalc.isConnected = true SocialCalc.hadSnapshot = false SocialCalc._room = window.location.hash.replace('#', '') unless SocialCalc._room window.location = '/start' return try window.history.pushState {}, '', '/'+SocialCalc._room @connect() emit = (data) => @emit broadcast: data SocialCalc.Callbacks.broadcast = (type, data={}) => return unless SocialCalc.isConnected data.user = SocialCalc._username data.room = SocialCalc._room data.type = type emit data SocialCalc.isConnected = true SocialCalc.Callbacks.broadcast "ask.snapshot" @on broadcast: -> return unless SocialCalc?.isConnected return if @data.user == SocialCalc._username return if @data.to and @data.to != SocialCalc._username return if @data.room and @data.room != SocialCalc._room editor = SocialCalc.CurrentSpreadsheetControlObject.editor switch @data.type when "chat" window.addmsg @data.msg when "ecells" for user, ecell of @data.ecells continue if user == SocialCalc._username peerClass = " " + user + " defaultPeer" find = new RegExp(peerClass, "g") cr = SocialCalc.coordToCr(ecell) cell = SocialCalc.GetEditorCellElement(editor, cr.row, cr.col) cell.element.className += peerClass if cell.element.className.search(find) == -1 when "ecell" peerClass = " " + @data.user + " defaultPeer" find = new RegExp(peerClass, "g") if @data.original origCR = SocialCalc.coordToCr(@data.original) origCell = SocialCalc.GetEditorCellElement(editor, origCR.row, origCR.col) origCell.element.className = origCell.element.className.replace(find, "") cr = SocialCalc.coordToCr(@data.ecell) cell = SocialCalc.GetEditorCellElement(editor, cr.row, cr.col) cell.element.className += peerClass if cell.element.className.search(find) == -1 when "ask.snapshot" SocialCalc.Callbacks.broadcast "snapshot", to: @data.user snapshot: SocialCalc.CurrentSpreadsheetControlObject.CreateSpreadsheetSave() when "ask.ecell" SocialCalc.Callbacks.broadcast "ecell", to: @data.user ecell: editor.ecell.coord when "log" break if SocialCalc.hadSnapshot SocialCalc.hadSnapshot = true spreadsheet = SocialCalc.CurrentSpreadsheetControlObject window.addmsg @data.chat.join("\n"), true cmdstr = @data.log.join("\n") SocialCalc.CurrentSpreadsheetControlObject.context.sheetobj.ScheduleSheetCommands cmdstr, false, true editor = SocialCalc.CurrentSpreadsheetControlObject.editor # editor.MoveECellCallback.broadcast = (e) -> # SocialCalc.Callbacks.broadcast "my.ecell" # ecell: e.ecell.coord when "snapshot" break if SocialCalc.hadSnapshot SocialCalc.hadSnapshot = true spreadsheet = SocialCalc.CurrentSpreadsheetControlObject parts = spreadsheet.DecodeSpreadsheetSave(@data.snapshot) if parts if parts.sheet spreadsheet.sheet.ResetSheet() spreadsheet.ParseSheetSave @data.snapshot.substring(parts.sheet.start, parts.sheet.end) spreadsheet.editor.LoadEditorSettings @data.snapshot.substring(parts.edit.start, parts.edit.end) if parts.edit if spreadsheet.editor.context.sheetobj.attribs.recalc == "off" spreadsheet.ExecuteCommand "redisplay", "" spreadsheet.ExecuteCommand "set sheet defaulttextvalueformat text-wiki" else spreadsheet.ExecuteCommand "recalc", "" spreadsheet.ExecuteCommand "set sheet defaulttextvalueformat text-wiki" when "execute" SocialCalc.CurrentSpreadsheetControlObject.context.sheetobj.ScheduleSheetCommands @data.cmdstr, @data.saveundo, true return
true
@include = -> @client '/player.js': -> SocialCalc ?= {} SocialCalc._username = PI:KEY:<KEY>END_PI().PI:KEY:<KEY>END_PI() SocialCalc.isConnected = true SocialCalc.hadSnapshot = false SocialCalc._room = window.location.hash.replace('#', '') unless SocialCalc._room window.location = '/start' return try window.history.pushState {}, '', '/'+SocialCalc._room @connect() emit = (data) => @emit broadcast: data SocialCalc.Callbacks.broadcast = (type, data={}) => return unless SocialCalc.isConnected data.user = SocialCalc._username data.room = SocialCalc._room data.type = type emit data SocialCalc.isConnected = true SocialCalc.Callbacks.broadcast "ask.snapshot" @on broadcast: -> return unless SocialCalc?.isConnected return if @data.user == SocialCalc._username return if @data.to and @data.to != SocialCalc._username return if @data.room and @data.room != SocialCalc._room editor = SocialCalc.CurrentSpreadsheetControlObject.editor switch @data.type when "chat" window.addmsg @data.msg when "ecells" for user, ecell of @data.ecells continue if user == SocialCalc._username peerClass = " " + user + " defaultPeer" find = new RegExp(peerClass, "g") cr = SocialCalc.coordToCr(ecell) cell = SocialCalc.GetEditorCellElement(editor, cr.row, cr.col) cell.element.className += peerClass if cell.element.className.search(find) == -1 when "ecell" peerClass = " " + @data.user + " defaultPeer" find = new RegExp(peerClass, "g") if @data.original origCR = SocialCalc.coordToCr(@data.original) origCell = SocialCalc.GetEditorCellElement(editor, origCR.row, origCR.col) origCell.element.className = origCell.element.className.replace(find, "") cr = SocialCalc.coordToCr(@data.ecell) cell = SocialCalc.GetEditorCellElement(editor, cr.row, cr.col) cell.element.className += peerClass if cell.element.className.search(find) == -1 when "ask.snapshot" SocialCalc.Callbacks.broadcast "snapshot", to: @data.user snapshot: SocialCalc.CurrentSpreadsheetControlObject.CreateSpreadsheetSave() when "ask.ecell" SocialCalc.Callbacks.broadcast "ecell", to: @data.user ecell: editor.ecell.coord when "log" break if SocialCalc.hadSnapshot SocialCalc.hadSnapshot = true spreadsheet = SocialCalc.CurrentSpreadsheetControlObject window.addmsg @data.chat.join("\n"), true cmdstr = @data.log.join("\n") SocialCalc.CurrentSpreadsheetControlObject.context.sheetobj.ScheduleSheetCommands cmdstr, false, true editor = SocialCalc.CurrentSpreadsheetControlObject.editor # editor.MoveECellCallback.broadcast = (e) -> # SocialCalc.Callbacks.broadcast "my.ecell" # ecell: e.ecell.coord when "snapshot" break if SocialCalc.hadSnapshot SocialCalc.hadSnapshot = true spreadsheet = SocialCalc.CurrentSpreadsheetControlObject parts = spreadsheet.DecodeSpreadsheetSave(@data.snapshot) if parts if parts.sheet spreadsheet.sheet.ResetSheet() spreadsheet.ParseSheetSave @data.snapshot.substring(parts.sheet.start, parts.sheet.end) spreadsheet.editor.LoadEditorSettings @data.snapshot.substring(parts.edit.start, parts.edit.end) if parts.edit if spreadsheet.editor.context.sheetobj.attribs.recalc == "off" spreadsheet.ExecuteCommand "redisplay", "" spreadsheet.ExecuteCommand "set sheet defaulttextvalueformat text-wiki" else spreadsheet.ExecuteCommand "recalc", "" spreadsheet.ExecuteCommand "set sheet defaulttextvalueformat text-wiki" when "execute" SocialCalc.CurrentSpreadsheetControlObject.context.sheetobj.ScheduleSheetCommands @data.cmdstr, @data.saveundo, true return
[ { "context": " o.body.track.id\n key : o.body.track.key.key_fingerprint?.toUpperCase()\n proofs : proofs\n ctime ", "end": 1911, "score": 0.4836783707141876, "start": 1900, "tag": "KEY", "value": "fingerprint" }, { "context": ".id\n key : o.body.track.key.key_fing...
src/command/list_tracking.iced
substack/keybase-client
1
{Base} = require './base' log = require '../log' {ArgumentParser} = require 'argparse' {add_option_dict} = require './argparse' {PackageJson} = require '../package' {session} = require '../session' {make_esc} = require 'iced-error' {env} = require '../env' log = require '../log' {User} = require '../user' {format_fingerprint} = require('pgp-utils').util util = require 'util' {E} = require '../err' ##======================================================================= ##======================================================================= exports.Command = class Command extends Base #---------- OPTS : v : alias : 'verbose' action : 'storeTrue' help : 'a full dump, with more gory details' j : alias : 'json' action : 'storeTrue' help : 'output in json format; default is simple text list' #---------- use_session : () -> true needs_configuration : () -> true #---------- add_subcommand_parser : (scp) -> opts = help : "list people you are tracking" aliases : [ ] name = "list-tracking" sub = scp.addParser name, opts sub.addArgument [ "filter" ], { nargs : '?', help : "a regex to filter by" } add_option_dict sub, @OPTS return [ name ].concat opts.aliases #---------- sort_list : (v) -> sort_fn = (a,b) -> a = ("" + a).toLowerCase() b = ("" + b).toLowerCase() if a < b then -1 else if a > b then 1 else 0 if not v? then {} else v = ( [ pj.body.track.basics.username, pj ] for pj in v) v.sort sort_fn out = {} for [k,val] in v out[k] = val out #---------- condense_record : (o) -> rps = [] unless (rps = o.body.track.remote_proofs)? proofs = (v for rp in rps when (v = rp?.remote_key_proof?.check_data_json)) out = uid : o.body.track.id key : o.body.track.key.key_fingerprint?.toUpperCase() proofs : proofs ctime : o.ctime return out #---------- condense_records : (d) -> out = {} for k,v of d out[k] = @condense_record v out #---------- display_json : (d) -> unless @argv.verbose d = @condense_records d JSON.stringify d, null, " " #---------- display : (v) -> if @argv.json then @display_json v else @display_text v #---------- display_text_line : (k,v) -> fields = [ k ] if @argv.verbose fields.push(v.key, v.ctime) proofs = [] for p in v.proofs if p.name? and p.username? proofs.push "#{p.name}:#{p.username}" proofs.sort() fields = fields.concat proofs fields.join("\t") #---------- display_text : (d) -> d = @condense_records d lines = (@display_text_line(k,v) for k,v of d) lines.join("\n") #---------- filter_list : (d) -> if @filter_rxx? out = {} for k,v of d if k.match(@filter_rxx) out[k] = v else if (rps = v.body?.track?.remote_proofs)? for proof in rps when (cd = proof?.remote_key_proof?.check_data_json)? if cd.username?.match(@filter_rxx) or cd.hostname?.match(@filter_rxx) out[k] = v break d = out d #---------- parse_filter : (cb) -> err = null if (f = @argv.filter)? and f.length try @filter_rxx = new RegExp(f, "i") catch e err = new E.ArgsError "Bad regex specified: #{e.message}" cb err #---------- run : (cb) -> esc = make_esc cb, "Command::run" await @parse_filter esc defer() if (un = env().get_username())? await session.check esc defer logged_in await User.load_me {secret : false}, esc defer me list = @sort_list me.list_trackees() list = @filter_list list log.console.log @display list else log.warn "Not logged in" cb null #----------------- ##=======================================================================
6234
{Base} = require './base' log = require '../log' {ArgumentParser} = require 'argparse' {add_option_dict} = require './argparse' {PackageJson} = require '../package' {session} = require '../session' {make_esc} = require 'iced-error' {env} = require '../env' log = require '../log' {User} = require '../user' {format_fingerprint} = require('pgp-utils').util util = require 'util' {E} = require '../err' ##======================================================================= ##======================================================================= exports.Command = class Command extends Base #---------- OPTS : v : alias : 'verbose' action : 'storeTrue' help : 'a full dump, with more gory details' j : alias : 'json' action : 'storeTrue' help : 'output in json format; default is simple text list' #---------- use_session : () -> true needs_configuration : () -> true #---------- add_subcommand_parser : (scp) -> opts = help : "list people you are tracking" aliases : [ ] name = "list-tracking" sub = scp.addParser name, opts sub.addArgument [ "filter" ], { nargs : '?', help : "a regex to filter by" } add_option_dict sub, @OPTS return [ name ].concat opts.aliases #---------- sort_list : (v) -> sort_fn = (a,b) -> a = ("" + a).toLowerCase() b = ("" + b).toLowerCase() if a < b then -1 else if a > b then 1 else 0 if not v? then {} else v = ( [ pj.body.track.basics.username, pj ] for pj in v) v.sort sort_fn out = {} for [k,val] in v out[k] = val out #---------- condense_record : (o) -> rps = [] unless (rps = o.body.track.remote_proofs)? proofs = (v for rp in rps when (v = rp?.remote_key_proof?.check_data_json)) out = uid : o.body.track.id key : o.body.track.key.key_<KEY>?.<KEY> proofs : proofs ctime : o.ctime return out #---------- condense_records : (d) -> out = {} for k,v of d out[k] = @condense_record v out #---------- display_json : (d) -> unless @argv.verbose d = @condense_records d JSON.stringify d, null, " " #---------- display : (v) -> if @argv.json then @display_json v else @display_text v #---------- display_text_line : (k,v) -> fields = [ k ] if @argv.verbose fields.push(v.key, v.ctime) proofs = [] for p in v.proofs if p.name? and p.username? proofs.push "#{p.name}:#{p.username}" proofs.sort() fields = fields.concat proofs fields.join("\t") #---------- display_text : (d) -> d = @condense_records d lines = (@display_text_line(k,v) for k,v of d) lines.join("\n") #---------- filter_list : (d) -> if @filter_rxx? out = {} for k,v of d if k.match(@filter_rxx) out[k] = v else if (rps = v.body?.track?.remote_proofs)? for proof in rps when (cd = proof?.remote_key_proof?.check_data_json)? if cd.username?.match(@filter_rxx) or cd.hostname?.match(@filter_rxx) out[k] = v break d = out d #---------- parse_filter : (cb) -> err = null if (f = @argv.filter)? and f.length try @filter_rxx = new RegExp(f, "i") catch e err = new E.ArgsError "Bad regex specified: #{e.message}" cb err #---------- run : (cb) -> esc = make_esc cb, "Command::run" await @parse_filter esc defer() if (un = env().get_username())? await session.check esc defer logged_in await User.load_me {secret : false}, esc defer me list = @sort_list me.list_trackees() list = @filter_list list log.console.log @display list else log.warn "Not logged in" cb null #----------------- ##=======================================================================
true
{Base} = require './base' log = require '../log' {ArgumentParser} = require 'argparse' {add_option_dict} = require './argparse' {PackageJson} = require '../package' {session} = require '../session' {make_esc} = require 'iced-error' {env} = require '../env' log = require '../log' {User} = require '../user' {format_fingerprint} = require('pgp-utils').util util = require 'util' {E} = require '../err' ##======================================================================= ##======================================================================= exports.Command = class Command extends Base #---------- OPTS : v : alias : 'verbose' action : 'storeTrue' help : 'a full dump, with more gory details' j : alias : 'json' action : 'storeTrue' help : 'output in json format; default is simple text list' #---------- use_session : () -> true needs_configuration : () -> true #---------- add_subcommand_parser : (scp) -> opts = help : "list people you are tracking" aliases : [ ] name = "list-tracking" sub = scp.addParser name, opts sub.addArgument [ "filter" ], { nargs : '?', help : "a regex to filter by" } add_option_dict sub, @OPTS return [ name ].concat opts.aliases #---------- sort_list : (v) -> sort_fn = (a,b) -> a = ("" + a).toLowerCase() b = ("" + b).toLowerCase() if a < b then -1 else if a > b then 1 else 0 if not v? then {} else v = ( [ pj.body.track.basics.username, pj ] for pj in v) v.sort sort_fn out = {} for [k,val] in v out[k] = val out #---------- condense_record : (o) -> rps = [] unless (rps = o.body.track.remote_proofs)? proofs = (v for rp in rps when (v = rp?.remote_key_proof?.check_data_json)) out = uid : o.body.track.id key : o.body.track.key.key_PI:KEY:<KEY>END_PI?.PI:KEY:<KEY>END_PI proofs : proofs ctime : o.ctime return out #---------- condense_records : (d) -> out = {} for k,v of d out[k] = @condense_record v out #---------- display_json : (d) -> unless @argv.verbose d = @condense_records d JSON.stringify d, null, " " #---------- display : (v) -> if @argv.json then @display_json v else @display_text v #---------- display_text_line : (k,v) -> fields = [ k ] if @argv.verbose fields.push(v.key, v.ctime) proofs = [] for p in v.proofs if p.name? and p.username? proofs.push "#{p.name}:#{p.username}" proofs.sort() fields = fields.concat proofs fields.join("\t") #---------- display_text : (d) -> d = @condense_records d lines = (@display_text_line(k,v) for k,v of d) lines.join("\n") #---------- filter_list : (d) -> if @filter_rxx? out = {} for k,v of d if k.match(@filter_rxx) out[k] = v else if (rps = v.body?.track?.remote_proofs)? for proof in rps when (cd = proof?.remote_key_proof?.check_data_json)? if cd.username?.match(@filter_rxx) or cd.hostname?.match(@filter_rxx) out[k] = v break d = out d #---------- parse_filter : (cb) -> err = null if (f = @argv.filter)? and f.length try @filter_rxx = new RegExp(f, "i") catch e err = new E.ArgsError "Bad regex specified: #{e.message}" cb err #---------- run : (cb) -> esc = make_esc cb, "Command::run" await @parse_filter esc defer() if (un = env().get_username())? await session.check esc defer logged_in await User.load_me {secret : false}, esc defer me list = @sort_list me.list_trackees() list = @filter_list list log.console.log @display list else log.warn "Not logged in" cb null #----------------- ##=======================================================================
[ { "context": "\tczech = {\n\t\t\tmeta: { Title: \"Desatero\", Author: \"Ví bůh\" }\n\t\t\tcontent: [\n\t\t\t\t{ section: \"1\", text: \"V jed", "end": 536, "score": 0.9994617700576782, "start": 530, "tag": "NAME", "value": "Ví bůh" }, { "context": "\tpolish = {\n\t\t\tmeta: { Title: ...
source/tests/services/transformer.js.coffee
tasuki/side-by-side
29
transformer = {} english = {} czech = {} polish = {} expected = {} module "transformer", { setup: -> transformer = getInjector().get 'transformer' english = { meta: { Title: "Ten Commandments", Author: "God knows" } content: [ { section: "1", text: "Thou shalt have no other gods before me" } { section: "2", text: "Thou shalt not take the name of the Lord thy God in vain" } { section: "3", text: "Remember the sabbath day, to keep it holy" } ] } czech = { meta: { Title: "Desatero", Author: "Ví bůh" } content: [ { section: "1", text: "V jednoho Boha věřiti budeš." } { section: "2", text: "Nevezmeš jména Božího nadarmo." } { section: "3", text: "Pomni, abys den sváteční světil." } ] } polish = { meta: { Title: "Dekalog", Author: "Bóg wie" } content: [ { section: "1", text: "Nie będziesz miał bogów cudzych przede mną." } { section: "2", text: "Nie będziesz wzywał imienia Boga twego nadaremno." } { section: "3", text: "Pamiętaj, abyś dzień święty święcił." } ] } expected = { meta: [ { Title: "Ten Commandments", Author: "God knows" } { Title: "Desatero", Author: "Ví bůh" } { Title: "Dekalog", Author: "Bóg wie" } ] verses: [[ { section: "1", text: "Thou shalt have no other gods before me" } { section: "1", text: "V jednoho Boha věřiti budeš." } { section: "1", text: "Nie będziesz miał bogów cudzych przede mną." } ], [ { section: "2", text: "Thou shalt not take the name of the Lord thy God in vain" } { section: "2", text: "Nevezmeš jména Božího nadarmo." } { section: "2", text: "Nie będziesz wzywał imienia Boga twego nadaremno." } ], [ { section: "3", text: "Remember the sabbath day, to keep it holy" } { section: "3", text: "Pomni, abys den sváteční světil." } { section: "3", text: "Pamiętaj, abyś dzień święty święcił." } ]] } } test "transforms", -> deepEqual transformer([english, czech, polish]), expected test "transforms with 2 items", -> expected.meta = expected.meta.slice(0, 2) expected.verses = _.map(expected.verses, (translations) -> return translations.slice(0, 2) ) deepEqual transformer([english, czech]), expected test "throws error on no param", -> throws -> transformer() , /no poems found/i test "throws error on empty array", -> throws -> transformer [] , /no poems found/i test "throws error on poem being too short", -> czech.content.pop() throws -> transformer [english, czech, polish] , /missing.*nevezmeš jména/i test "throws error on poem being too long", -> czech.content.pop() polish.content.pop() throws -> transformer [english, czech, polish] , /superfluous.*sabbath/i test "throws error on poems too short plus different lengths", -> czech.content.pop() polish.content.pop() polish.content.pop() throws -> transformer [english, czech, polish] , /missing.*bogów cudzych.*nevezmeš/i
46836
transformer = {} english = {} czech = {} polish = {} expected = {} module "transformer", { setup: -> transformer = getInjector().get 'transformer' english = { meta: { Title: "Ten Commandments", Author: "God knows" } content: [ { section: "1", text: "Thou shalt have no other gods before me" } { section: "2", text: "Thou shalt not take the name of the Lord thy God in vain" } { section: "3", text: "Remember the sabbath day, to keep it holy" } ] } czech = { meta: { Title: "Desatero", Author: "<NAME>" } content: [ { section: "1", text: "V jednoho Boha věřiti budeš." } { section: "2", text: "Nevezmeš jména Božího nadarmo." } { section: "3", text: "Pomni, abys den sváteční světil." } ] } polish = { meta: { Title: "Dekalog", Author: "<NAME>" } content: [ { section: "1", text: "Nie będziesz miał bogów cudzych przede mną." } { section: "2", text: "Nie będziesz wzywał imienia Boga twego nadaremno." } { section: "3", text: "Pamiętaj, abyś dzień święty święcił." } ] } expected = { meta: [ { Title: "Ten Commandments", Author: "God knows" } { Title: "Desatero", Author: "<NAME>" } { Title: "Dekalog", Author: "<NAME>" } ] verses: [[ { section: "1", text: "Thou shalt have no other gods before me" } { section: "1", text: "V jednoho Boha věřiti budeš." } { section: "1", text: "Nie będziesz miał bogów cudzych przede mną." } ], [ { section: "2", text: "Thou shalt not take the name of the Lord thy God in vain" } { section: "2", text: "Nevezmeš jména Božího nadarmo." } { section: "2", text: "Nie będziesz wzywał imienia Boga twego nadaremno." } ], [ { section: "3", text: "Remember the sabbath day, to keep it holy" } { section: "3", text: "Pomni, abys den sváteční světil." } { section: "3", text: "Pamiętaj, abyś dzień święty święcił." } ]] } } test "transforms", -> deepEqual transformer([english, czech, polish]), expected test "transforms with 2 items", -> expected.meta = expected.meta.slice(0, 2) expected.verses = _.map(expected.verses, (translations) -> return translations.slice(0, 2) ) deepEqual transformer([english, czech]), expected test "throws error on no param", -> throws -> transformer() , /no poems found/i test "throws error on empty array", -> throws -> transformer [] , /no poems found/i test "throws error on poem being too short", -> czech.content.pop() throws -> transformer [english, czech, polish] , /missing.*nevezmeš jména/i test "throws error on poem being too long", -> czech.content.pop() polish.content.pop() throws -> transformer [english, czech, polish] , /superfluous.*sabbath/i test "throws error on poems too short plus different lengths", -> czech.content.pop() polish.content.pop() polish.content.pop() throws -> transformer [english, czech, polish] , /missing.*bogów cudzych.*nevezmeš/i
true
transformer = {} english = {} czech = {} polish = {} expected = {} module "transformer", { setup: -> transformer = getInjector().get 'transformer' english = { meta: { Title: "Ten Commandments", Author: "God knows" } content: [ { section: "1", text: "Thou shalt have no other gods before me" } { section: "2", text: "Thou shalt not take the name of the Lord thy God in vain" } { section: "3", text: "Remember the sabbath day, to keep it holy" } ] } czech = { meta: { Title: "Desatero", Author: "PI:NAME:<NAME>END_PI" } content: [ { section: "1", text: "V jednoho Boha věřiti budeš." } { section: "2", text: "Nevezmeš jména Božího nadarmo." } { section: "3", text: "Pomni, abys den sváteční světil." } ] } polish = { meta: { Title: "Dekalog", Author: "PI:NAME:<NAME>END_PI" } content: [ { section: "1", text: "Nie będziesz miał bogów cudzych przede mną." } { section: "2", text: "Nie będziesz wzywał imienia Boga twego nadaremno." } { section: "3", text: "Pamiętaj, abyś dzień święty święcił." } ] } expected = { meta: [ { Title: "Ten Commandments", Author: "God knows" } { Title: "Desatero", Author: "PI:NAME:<NAME>END_PI" } { Title: "Dekalog", Author: "PI:NAME:<NAME>END_PI" } ] verses: [[ { section: "1", text: "Thou shalt have no other gods before me" } { section: "1", text: "V jednoho Boha věřiti budeš." } { section: "1", text: "Nie będziesz miał bogów cudzych przede mną." } ], [ { section: "2", text: "Thou shalt not take the name of the Lord thy God in vain" } { section: "2", text: "Nevezmeš jména Božího nadarmo." } { section: "2", text: "Nie będziesz wzywał imienia Boga twego nadaremno." } ], [ { section: "3", text: "Remember the sabbath day, to keep it holy" } { section: "3", text: "Pomni, abys den sváteční světil." } { section: "3", text: "Pamiętaj, abyś dzień święty święcił." } ]] } } test "transforms", -> deepEqual transformer([english, czech, polish]), expected test "transforms with 2 items", -> expected.meta = expected.meta.slice(0, 2) expected.verses = _.map(expected.verses, (translations) -> return translations.slice(0, 2) ) deepEqual transformer([english, czech]), expected test "throws error on no param", -> throws -> transformer() , /no poems found/i test "throws error on empty array", -> throws -> transformer [] , /no poems found/i test "throws error on poem being too short", -> czech.content.pop() throws -> transformer [english, czech, polish] , /missing.*nevezmeš jména/i test "throws error on poem being too long", -> czech.content.pop() polish.content.pop() throws -> transformer [english, czech, polish] , /superfluous.*sabbath/i test "throws error on poems too short plus different lengths", -> czech.content.pop() polish.content.pop() polish.content.pop() throws -> transformer [english, czech, polish] , /missing.*bogów cudzych.*nevezmeš/i
[ { "context": "nikita()\n .registry.register( 'level_1', key: 'value 1', handler: ->\n @call ({parent}) ->\n p", "end": 1120, "score": 0.934635579586029, "start": 1113, "tag": "KEY", "value": "value 1" }, { "context": "\n )\n .registry.register( 'level_2_2', key: ...
packages/core/test/action/parent.coffee
DanielJohnHarty/node-nikita
1
nikita = require '../../src' {tags} = require '../test' return unless tags.api describe 'action "parent"', -> it 'default values', -> nikita # First level .call ({parent}) -> (parent is undefined).should.be.true() # Second level .call -> @call ({parent}) -> (parent.parent is undefined).should.be.true() parent.metadata.disabled.should.be.false() # Third level .call -> @call -> @call ({parent}) -> (parent.parent.parent is undefined).should.be.true() parent.parent.metadata.disabled.should.be.false() .promise() it 'passed to action', -> nikita # Second level .call my_key: 'value 1', -> @call ({parent}) -> parent.options.my_key.should.eql 'value 1' # Third level .call my_key: 'value 1', -> @call my_key: 'value 2', -> @call ({parent}) -> parent.parent.options.my_key.should.eql 'value 1' parent.options.my_key.should.eql 'value 2' .promise() it 'defined in action', -> nikita() .registry.register( 'level_1', key: 'value 1', handler: -> @call ({parent}) -> parent.options.key.should.eql 'value 1' ) .registry.register( 'level_2_1', key: 'value 1', handler: -> @level_2_2() ) .registry.register( 'level_2_2', key: 'value 2', handler: -> @call ({parent}) -> parent.parent.options.key.should.eql 'value 1' parent.options.key.should.eql 'value 2' ) # Second level .level_1() # Third level .level_2_1() .promise()
72405
nikita = require '../../src' {tags} = require '../test' return unless tags.api describe 'action "parent"', -> it 'default values', -> nikita # First level .call ({parent}) -> (parent is undefined).should.be.true() # Second level .call -> @call ({parent}) -> (parent.parent is undefined).should.be.true() parent.metadata.disabled.should.be.false() # Third level .call -> @call -> @call ({parent}) -> (parent.parent.parent is undefined).should.be.true() parent.parent.metadata.disabled.should.be.false() .promise() it 'passed to action', -> nikita # Second level .call my_key: 'value 1', -> @call ({parent}) -> parent.options.my_key.should.eql 'value 1' # Third level .call my_key: 'value 1', -> @call my_key: 'value 2', -> @call ({parent}) -> parent.parent.options.my_key.should.eql 'value 1' parent.options.my_key.should.eql 'value 2' .promise() it 'defined in action', -> nikita() .registry.register( 'level_1', key: '<KEY>', handler: -> @call ({parent}) -> parent.options.key.should.eql 'value 1' ) .registry.register( 'level_2_1', key: 'value 1', handler: -> @level_2_2() ) .registry.register( 'level_2_2', key: '<KEY>', handler: -> @call ({parent}) -> parent.parent.options.key.should.eql 'value 1' parent.options.key.should.eql 'value 2' ) # Second level .level_1() # Third level .level_2_1() .promise()
true
nikita = require '../../src' {tags} = require '../test' return unless tags.api describe 'action "parent"', -> it 'default values', -> nikita # First level .call ({parent}) -> (parent is undefined).should.be.true() # Second level .call -> @call ({parent}) -> (parent.parent is undefined).should.be.true() parent.metadata.disabled.should.be.false() # Third level .call -> @call -> @call ({parent}) -> (parent.parent.parent is undefined).should.be.true() parent.parent.metadata.disabled.should.be.false() .promise() it 'passed to action', -> nikita # Second level .call my_key: 'value 1', -> @call ({parent}) -> parent.options.my_key.should.eql 'value 1' # Third level .call my_key: 'value 1', -> @call my_key: 'value 2', -> @call ({parent}) -> parent.parent.options.my_key.should.eql 'value 1' parent.options.my_key.should.eql 'value 2' .promise() it 'defined in action', -> nikita() .registry.register( 'level_1', key: 'PI:KEY:<KEY>END_PI', handler: -> @call ({parent}) -> parent.options.key.should.eql 'value 1' ) .registry.register( 'level_2_1', key: 'value 1', handler: -> @level_2_2() ) .registry.register( 'level_2_2', key: 'PI:KEY:<KEY>END_PI', handler: -> @call ({parent}) -> parent.parent.options.key.should.eql 'value 1' parent.options.key.should.eql 'value 2' ) # Second level .level_1() # Third level .level_2_1() .promise()
[ { "context": " #\n # Post.\n #\n # Created by hector spc <hector@aerstudio.com>\n # Aer Studio \n # http:/", "end": 41, "score": 0.9862385988235474, "start": 31, "tag": "NAME", "value": "hector spc" }, { "context": " #\n # Post.\n #\n # Created by hector spc <hector@aerstudio.c...
src/models/post_model.coffee
aerstudio/Phallanxpress
1
# # Post. # # Created by hector spc <hector@aerstudio.com> # Aer Studio # http://www.aerstudio.com # # Wed Feb 22 2012 # # models/post_model.js.coffee # class Phallanxpress.Post extends Phallanxpress.Model apiCommand: 'get_post' parseTag: 'post'
22251
# # Post. # # Created by <NAME> <<EMAIL>> # Aer Studio # http://www.aerstudio.com # # Wed Feb 22 2012 # # models/post_model.js.coffee # class Phallanxpress.Post extends Phallanxpress.Model apiCommand: 'get_post' parseTag: 'post'
true
# # Post. # # Created by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Aer Studio # http://www.aerstudio.com # # Wed Feb 22 2012 # # models/post_model.js.coffee # class Phallanxpress.Post extends Phallanxpress.Model apiCommand: 'get_post' parseTag: 'post'
[ { "context": " looks good moving #{meters}m.\"\n\nsam = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\nben = new C", "end": 626, "score": 0.7894735336303711, "start": 610, "tag": "NAME", "value": "Sammy the Python" }, { "context": "m = new Snake \"Sammy the P...
node_modules/YouAreDaChef/spec/YouAreDaChef.spec.coffee
raganwald/recursiveuniverse
4
YouAreDaChef = require('../lib/YouAreDaChef.coffee').YouAreDaChef _ = require 'underscore' ############ # preamble # ############ class Animal constructor: (@name) -> move: (meters) -> @name + " moved #{meters}m." class Hippo extends Animal move: (meters) -> @name + " lumbered #{meters}m." class Snake extends Animal move: -> super 5 class Horse extends Animal move: -> super 45 class Cheetah extends Animal class Monkey extends Animal class Lion extends Animal class Tiger extends Animal movie: (meters) -> @name + " looks good moving #{meters}m." sam = new Snake "Sammy the Python" tom = new Horse "Tommy the Palomino" ben = new Cheetah "Benny the Cheetah" poe = new Hippo "Poe the 'Potomous" moe = new Monkey "Moe the Marauder" leo = new Lion "Leo the Lionheart" kat = new Tiger "Kat the Big Cat" describe 'YouAreDaChef', -> it 'should allow before advice', -> expect(tom.move()).toBe('Tommy the Palomino moved 45m.') expect(tom.name).toBe("Tommy the Palomino") YouAreDaChef(Horse).before 'move', -> @name = "Harry the Hoofer" expect(tom.move()).toBe('Harry the Hoofer moved 45m.') expect(tom.name).toBe("Harry the Hoofer") it 'should allow guard advice', -> expect(leo.move(40)).toBe('Leo the Lionheart moved 40m.') expect(leo.move(400)).toBe('Leo the Lionheart moved 400m.') YouAreDaChef(Lion).guard 'move', (meters) -> meters < 100 expect(leo.move(40)).toBe('Leo the Lionheart moved 40m.') expect(leo.move(400)).toBeUndefined() it 'should allow after advice', -> expect(sam.move()).toBe('Sammy the Python moved 5m.') expect(sam.name).toBe("Sammy the Python") YouAreDaChef(Snake).after 'move', -> @name = 'Sly the Slitherer' expect(sam.move()).toBe('Sammy the Python moved 5m.') expect(sam.name).toBe("Sly the Slitherer") it 'should allow around advice', -> expect(poe.move(2)).toBe('Poe the \'Potomous lumbered 2m.') YouAreDaChef(Hippo).around 'move', (pointcut, by_how_much) -> pointcut(by_how_much * 2) expect(poe.move(2)).toBe('Poe the \'Potomous lumbered 4m.') it 'should handle methods not directly defined', -> expect(ben.move(7)).toBe('Benny the Cheetah moved 7m.') expect(moe.move(7)).toBe('Moe the Marauder moved 7m.') YouAreDaChef(Cheetah).around 'move', (pointcut, by_how_much) -> pointcut(by_how_much * 10) + ' That\'s great!' expect(ben.move(7)).toBe('Benny the Cheetah moved 70m. That\'s great!') expect(moe.move(7)).toBe('Moe the Marauder moved 7m.') it 'should allow specifying methods by regular expression', -> console?.log expect(kat.move(12)).toBe('Kat the Big Cat moved 12m.') expect(kat.movie(12)).toBe('Kat the Big Cat looks good moving 12m.') YouAreDaChef(Tiger).around /mo.*/, (pointcut, match, by_how_much) -> pointcut(by_how_much * 10) expect(kat.move(12)).toBe('Kat the Big Cat moved 120m.') expect(kat.movie(12)).toBe('Kat the Big Cat looks good moving 120m.')
23825
YouAreDaChef = require('../lib/YouAreDaChef.coffee').YouAreDaChef _ = require 'underscore' ############ # preamble # ############ class Animal constructor: (@name) -> move: (meters) -> @name + " moved #{meters}m." class Hippo extends Animal move: (meters) -> @name + " lumbered #{meters}m." class Snake extends Animal move: -> super 5 class Horse extends Animal move: -> super 45 class Cheetah extends Animal class Monkey extends Animal class Lion extends Animal class Tiger extends Animal movie: (meters) -> @name + " looks good moving #{meters}m." sam = new Snake "<NAME>" tom = new Horse "<NAME>" ben = new Cheetah "<NAME>" poe = new Hippo "Poe the 'Potomous" moe = new Monkey "Moe the Marauder" leo = new Lion "Leo the Lionheart" kat = new Tiger "Kat the Big Cat" describe 'YouAreDaChef', -> it 'should allow before advice', -> expect(tom.move()).toBe('Tommy the Palomino moved 45m.') expect(tom.name).toBe("<NAME>") YouAreDaChef(Horse).before 'move', -> @name = "<NAME>" expect(tom.move()).toBe('Harry the Hoofer moved 45m.') expect(tom.name).toBe("<NAME>") it 'should allow guard advice', -> expect(leo.move(40)).toBe('Leo the Lionheart moved 40m.') expect(leo.move(400)).toBe('Leo the Lionheart moved 400m.') YouAreDaChef(Lion).guard 'move', (meters) -> meters < 100 expect(leo.move(40)).toBe('Leo the Lionheart moved 40m.') expect(leo.move(400)).toBeUndefined() it 'should allow after advice', -> expect(sam.move()).toBe('<NAME> the Python moved 5m.') expect(sam.name).toBe("<NAME>") YouAreDaChef(Snake).after 'move', -> @name = '<NAME>' expect(sam.move()).toBe('<NAME> the Python moved 5m.') expect(sam.name).toBe("<NAME>") it 'should allow around advice', -> expect(poe.move(2)).toBe('Poe the \'Potomous lumbered 2m.') YouAreDaChef(Hippo).around 'move', (pointcut, by_how_much) -> pointcut(by_how_much * 2) expect(poe.move(2)).toBe('Poe the \'Potomous lumbered 4m.') it 'should handle methods not directly defined', -> expect(ben.move(7)).toBe('<NAME> the Cheetah moved 7m.') expect(moe.move(7)).toBe('Moe the Marauder moved 7m.') YouAreDaChef(Cheetah).around 'move', (pointcut, by_how_much) -> pointcut(by_how_much * 10) + ' That\'s great!' expect(ben.move(7)).toBe('<NAME> the Cheetah moved 70m. That\'s great!') expect(moe.move(7)).toBe('Moe the Marauder moved 7m.') it 'should allow specifying methods by regular expression', -> console?.log expect(kat.move(12)).toBe('Kat the Big Cat moved 12m.') expect(kat.movie(12)).toBe('Kat the Big Cat looks good moving 12m.') YouAreDaChef(Tiger).around /mo.*/, (pointcut, match, by_how_much) -> pointcut(by_how_much * 10) expect(kat.move(12)).toBe('Kat the Big Cat moved 120m.') expect(kat.movie(12)).toBe('Kat the Big Cat looks good moving 120m.')
true
YouAreDaChef = require('../lib/YouAreDaChef.coffee').YouAreDaChef _ = require 'underscore' ############ # preamble # ############ class Animal constructor: (@name) -> move: (meters) -> @name + " moved #{meters}m." class Hippo extends Animal move: (meters) -> @name + " lumbered #{meters}m." class Snake extends Animal move: -> super 5 class Horse extends Animal move: -> super 45 class Cheetah extends Animal class Monkey extends Animal class Lion extends Animal class Tiger extends Animal movie: (meters) -> @name + " looks good moving #{meters}m." sam = new Snake "PI:NAME:<NAME>END_PI" tom = new Horse "PI:NAME:<NAME>END_PI" ben = new Cheetah "PI:NAME:<NAME>END_PI" poe = new Hippo "Poe the 'Potomous" moe = new Monkey "Moe the Marauder" leo = new Lion "Leo the Lionheart" kat = new Tiger "Kat the Big Cat" describe 'YouAreDaChef', -> it 'should allow before advice', -> expect(tom.move()).toBe('Tommy the Palomino moved 45m.') expect(tom.name).toBe("PI:NAME:<NAME>END_PI") YouAreDaChef(Horse).before 'move', -> @name = "PI:NAME:<NAME>END_PI" expect(tom.move()).toBe('Harry the Hoofer moved 45m.') expect(tom.name).toBe("PI:NAME:<NAME>END_PI") it 'should allow guard advice', -> expect(leo.move(40)).toBe('Leo the Lionheart moved 40m.') expect(leo.move(400)).toBe('Leo the Lionheart moved 400m.') YouAreDaChef(Lion).guard 'move', (meters) -> meters < 100 expect(leo.move(40)).toBe('Leo the Lionheart moved 40m.') expect(leo.move(400)).toBeUndefined() it 'should allow after advice', -> expect(sam.move()).toBe('PI:NAME:<NAME>END_PI the Python moved 5m.') expect(sam.name).toBe("PI:NAME:<NAME>END_PI") YouAreDaChef(Snake).after 'move', -> @name = 'PI:NAME:<NAME>END_PI' expect(sam.move()).toBe('PI:NAME:<NAME>END_PI the Python moved 5m.') expect(sam.name).toBe("PI:NAME:<NAME>END_PI") it 'should allow around advice', -> expect(poe.move(2)).toBe('Poe the \'Potomous lumbered 2m.') YouAreDaChef(Hippo).around 'move', (pointcut, by_how_much) -> pointcut(by_how_much * 2) expect(poe.move(2)).toBe('Poe the \'Potomous lumbered 4m.') it 'should handle methods not directly defined', -> expect(ben.move(7)).toBe('PI:NAME:<NAME>END_PI the Cheetah moved 7m.') expect(moe.move(7)).toBe('Moe the Marauder moved 7m.') YouAreDaChef(Cheetah).around 'move', (pointcut, by_how_much) -> pointcut(by_how_much * 10) + ' That\'s great!' expect(ben.move(7)).toBe('PI:NAME:<NAME>END_PI the Cheetah moved 70m. That\'s great!') expect(moe.move(7)).toBe('Moe the Marauder moved 7m.') it 'should allow specifying methods by regular expression', -> console?.log expect(kat.move(12)).toBe('Kat the Big Cat moved 12m.') expect(kat.movie(12)).toBe('Kat the Big Cat looks good moving 12m.') YouAreDaChef(Tiger).around /mo.*/, (pointcut, match, by_how_much) -> pointcut(by_how_much * 10) expect(kat.move(12)).toBe('Kat the Big Cat moved 120m.') expect(kat.movie(12)).toBe('Kat the Big Cat looks good moving 120m.')
[ { "context": "atest/ for more info on available \n#\n# Author:\n# ParadoxGuitarist\n\nconfluence_user = process.env.HUBOT", "end": 992, "score": 0.7109500169754028, "start": 989, "tag": "NAME", "value": "Par" }, { "context": "t/ for more info on available \n#\n# Author:\n# Parado...
src/confluence-wiki.coffee
ParadoxGuitarist/hubot-confluence-wiki
1
# Description # Confluence/Wiki searches # # Configuration: # HUBOT_CONFLUENCE_USER - (required) # HUBOT_CONFLUENCE_PASSWORD - (required) # HUBOT_CONFLUENCE_HOST - (required) - confluence hostname or alias (wiki.example.com) # HUBOT_CONFLUENCE_PROTOCOL - defaults to https # HUBOT_CONFLUENCE_SEARCH_SPACE -(optional) limit searches to a particular space # HUBOT_CONFLUENCE_CONTEXT - (optional)- often '/wiki' - defaults to '' # HUBOT_CONFLUENCE_AUTH - (optional) defaults to 'basic' # HUBOT_CONFLUENCE_SEARCH_LIMIT - (optional) - max number of returned results - defaults to '5' # HUBOT_CONFLUENCE_HEARD_LIMIT - (optional) - max number of suggestions - defaults to '3' # HUBOT_CONFLUENCE_HIGHLIGHT_MARKDOWN_REPLACEMENT - (optional) - Replace the @@@hl@@@ markdown with something else. # # Commands: # hubot wiki <search term(s)> - Hubot provides pages # # Notes: # See https://docs.atlassian.com/confluence/REST/latest/ for more info on available # # Author: # ParadoxGuitarist confluence_user = process.env.HUBOT_CONFLUENCE_USER confluence_password = process.env.HUBOT_CONFLUENCE_PASSWORD confluence_host = process.env.HUBOT_CONFLUENCE_HOST confluence_context = process.env.HUBOT_CONFLUENCE_CONTEXT or '' confluence_protocol = process.env.HUBOT_CONFLUENCE_PROTOCOL or 'https' confluence_auth = process.env.HUBOT_CONFLUENCE_AUTH or 'basic' confluence_search_limit = process.env.HUBOT_CONFLUENCE_SEARCH_LIMIT or '5' confluence_heard_limit = process.env.HUBOT_CONFLUENCE_HEARD_LIMIT or '3' confluence_highlight = process.env.HUBOT_CONFLUENCE_HIGHLIGHT_MARKDOWN_REPLACEMENT or '' confluence_search_space = process.env.HUBOT_CONFLUENCE_SEARCH_SPACE or '' hellip = "[...]" searchspace = if confluence_search_space == '' searchspace = '' else searchspace = "AND(space+in+(#{confluence_search_space}))" ConfluenceBaseURL = "#{confluence_protocol}://#{confluence_host}#{confluence_context}" authsuffix = "os_authType=#{confluence_auth}" auth = 'Basic ' + new Buffer("#{confluence_user}:#{confluence_password}").toString('base64'); confluence_request = (msg, url, handler) -> msg.http("#{ConfluenceBaseURL}#{url}") .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> if err msg.send "Confluence reports error: #{err}" return if res.statusCode isnt 200 msg.send "Request Failed. Sorry." return content = JSON.parse(body) handler content module.exports = (robot) -> robot.respond /wiki (.*)$/i, (msg) -> search_term = msg.match[1] confluence_request msg, "/rest/api/search?#{authsuffix}&cql=(type=page)#{searchspace}AND(text~'#{search_term}')&limit=#{confluence_search_limit}", (result) -> if result.error msg.send result.description return message = "Showing #{result.size} results <#{result._links.base}/dosearchsite.action?cql=#{result.cqlQuery.replace /(\s)/g, '+'}|out of #{result.totalSize} total>" message += "\n<#{ConfluenceBaseURL}#{i.content._links.tinyui}|#{i.content.title}> \n>#{i.excerpt}" for i in result.results message = message.replace /@@@hl@@@|@@@endhl@@@/g, confluence_highlight message = message.replace /&hellip;/g, hellip message = message.replace /&#39;/g, "'" message = message.replace /&quot;/g, '"' msg.send message robot.hear /(?:how do i|how do you) (.*)$/i, (msg) -> search_term = msg.match[1].replace(/\s(the |and |on |like |as |a )|\?|\,|\./g, ' ') confluence_request msg, "/rest/api/search?#{authsuffix}&cql=(type=page)#{searchspace}AND(text~'#{search_term}')&limit=#{confluence_heard_limit}", (result) -> if result.error msg.send result.description return if result.size == '0' msg.send "Perhaps you could try: <http://lmgtfy.com/?q=#{search_term.replace /\s/g, '+'}|a google search>" return message = "Not sure I know how to do that, but this might help:" message += "\n<#{ConfluenceBaseURL}#{i.content._links.tinyui}|#{i.content.title}>\n>#{i.excerpt}" for i in result.results message = message.replace /@@@hl@@@|@@@endhl@@@/g, confluence_highlight message = message.replace /&hellip;/g, hellip message = message.replace /&#39;/g, "'" message = message.replace /&quot;/g, '"' message += "\n_You could always try searches here:_ <http://lmgtfy.com/?q=#{search_term.replace /(\s)/g, '+'}|google> or <#{result._links.base}/dosearchsite.action?cql=#{result.cqlQuery.replace /(\s)/g, '+'}|wiki> " msg.send message
112714
# Description # Confluence/Wiki searches # # Configuration: # HUBOT_CONFLUENCE_USER - (required) # HUBOT_CONFLUENCE_PASSWORD - (required) # HUBOT_CONFLUENCE_HOST - (required) - confluence hostname or alias (wiki.example.com) # HUBOT_CONFLUENCE_PROTOCOL - defaults to https # HUBOT_CONFLUENCE_SEARCH_SPACE -(optional) limit searches to a particular space # HUBOT_CONFLUENCE_CONTEXT - (optional)- often '/wiki' - defaults to '' # HUBOT_CONFLUENCE_AUTH - (optional) defaults to 'basic' # HUBOT_CONFLUENCE_SEARCH_LIMIT - (optional) - max number of returned results - defaults to '5' # HUBOT_CONFLUENCE_HEARD_LIMIT - (optional) - max number of suggestions - defaults to '3' # HUBOT_CONFLUENCE_HIGHLIGHT_MARKDOWN_REPLACEMENT - (optional) - Replace the @@@hl@@@ markdown with something else. # # Commands: # hubot wiki <search term(s)> - Hubot provides pages # # Notes: # See https://docs.atlassian.com/confluence/REST/latest/ for more info on available # # Author: # <NAME>adoxG<NAME> confluence_user = process.env.HUBOT_CONFLUENCE_USER confluence_password = process.env.HUBOT_CONFLUENCE_PASSWORD confluence_host = process.env.HUBOT_CONFLUENCE_HOST confluence_context = process.env.HUBOT_CONFLUENCE_CONTEXT or '' confluence_protocol = process.env.HUBOT_CONFLUENCE_PROTOCOL or 'https' confluence_auth = process.env.HUBOT_CONFLUENCE_AUTH or 'basic' confluence_search_limit = process.env.HUBOT_CONFLUENCE_SEARCH_LIMIT or '5' confluence_heard_limit = process.env.HUBOT_CONFLUENCE_HEARD_LIMIT or '3' confluence_highlight = process.env.HUBOT_CONFLUENCE_HIGHLIGHT_MARKDOWN_REPLACEMENT or '' confluence_search_space = process.env.HUBOT_CONFLUENCE_SEARCH_SPACE or '' hellip = "[...]" searchspace = if confluence_search_space == '' searchspace = '' else searchspace = "AND(space+in+(#{confluence_search_space}))" ConfluenceBaseURL = "#{confluence_protocol}://#{confluence_host}#{confluence_context}" authsuffix = "os_authType=#{confluence_auth}" auth = 'Basic ' + new Buffer("#{confluence_user}:#{confluence_password}").toString('base64'); confluence_request = (msg, url, handler) -> msg.http("#{ConfluenceBaseURL}#{url}") .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> if err msg.send "Confluence reports error: #{err}" return if res.statusCode isnt 200 msg.send "Request Failed. Sorry." return content = JSON.parse(body) handler content module.exports = (robot) -> robot.respond /wiki (.*)$/i, (msg) -> search_term = msg.match[1] confluence_request msg, "/rest/api/search?#{authsuffix}&cql=(type=page)#{searchspace}AND(text~'#{search_term}')&limit=#{confluence_search_limit}", (result) -> if result.error msg.send result.description return message = "Showing #{result.size} results <#{result._links.base}/dosearchsite.action?cql=#{result.cqlQuery.replace /(\s)/g, '+'}|out of #{result.totalSize} total>" message += "\n<#{ConfluenceBaseURL}#{i.content._links.tinyui}|#{i.content.title}> \n>#{i.excerpt}" for i in result.results message = message.replace /@@@hl@@@|@@@endhl@@@/g, confluence_highlight message = message.replace /&hellip;/g, hellip message = message.replace /&#39;/g, "'" message = message.replace /&quot;/g, '"' msg.send message robot.hear /(?:how do i|how do you) (.*)$/i, (msg) -> search_term = msg.match[1].replace(/\s(the |and |on |like |as |a )|\?|\,|\./g, ' ') confluence_request msg, "/rest/api/search?#{authsuffix}&cql=(type=page)#{searchspace}AND(text~'#{search_term}')&limit=#{confluence_heard_limit}", (result) -> if result.error msg.send result.description return if result.size == '0' msg.send "Perhaps you could try: <http://lmgtfy.com/?q=#{search_term.replace /\s/g, '+'}|a google search>" return message = "Not sure I know how to do that, but this might help:" message += "\n<#{ConfluenceBaseURL}#{i.content._links.tinyui}|#{i.content.title}>\n>#{i.excerpt}" for i in result.results message = message.replace /@@@hl@@@|@@@endhl@@@/g, confluence_highlight message = message.replace /&hellip;/g, hellip message = message.replace /&#39;/g, "'" message = message.replace /&quot;/g, '"' message += "\n_You could always try searches here:_ <http://lmgtfy.com/?q=#{search_term.replace /(\s)/g, '+'}|google> or <#{result._links.base}/dosearchsite.action?cql=#{result.cqlQuery.replace /(\s)/g, '+'}|wiki> " msg.send message
true
# Description # Confluence/Wiki searches # # Configuration: # HUBOT_CONFLUENCE_USER - (required) # HUBOT_CONFLUENCE_PASSWORD - (required) # HUBOT_CONFLUENCE_HOST - (required) - confluence hostname or alias (wiki.example.com) # HUBOT_CONFLUENCE_PROTOCOL - defaults to https # HUBOT_CONFLUENCE_SEARCH_SPACE -(optional) limit searches to a particular space # HUBOT_CONFLUENCE_CONTEXT - (optional)- often '/wiki' - defaults to '' # HUBOT_CONFLUENCE_AUTH - (optional) defaults to 'basic' # HUBOT_CONFLUENCE_SEARCH_LIMIT - (optional) - max number of returned results - defaults to '5' # HUBOT_CONFLUENCE_HEARD_LIMIT - (optional) - max number of suggestions - defaults to '3' # HUBOT_CONFLUENCE_HIGHLIGHT_MARKDOWN_REPLACEMENT - (optional) - Replace the @@@hl@@@ markdown with something else. # # Commands: # hubot wiki <search term(s)> - Hubot provides pages # # Notes: # See https://docs.atlassian.com/confluence/REST/latest/ for more info on available # # Author: # PI:NAME:<NAME>END_PIadoxGPI:NAME:<NAME>END_PI confluence_user = process.env.HUBOT_CONFLUENCE_USER confluence_password = process.env.HUBOT_CONFLUENCE_PASSWORD confluence_host = process.env.HUBOT_CONFLUENCE_HOST confluence_context = process.env.HUBOT_CONFLUENCE_CONTEXT or '' confluence_protocol = process.env.HUBOT_CONFLUENCE_PROTOCOL or 'https' confluence_auth = process.env.HUBOT_CONFLUENCE_AUTH or 'basic' confluence_search_limit = process.env.HUBOT_CONFLUENCE_SEARCH_LIMIT or '5' confluence_heard_limit = process.env.HUBOT_CONFLUENCE_HEARD_LIMIT or '3' confluence_highlight = process.env.HUBOT_CONFLUENCE_HIGHLIGHT_MARKDOWN_REPLACEMENT or '' confluence_search_space = process.env.HUBOT_CONFLUENCE_SEARCH_SPACE or '' hellip = "[...]" searchspace = if confluence_search_space == '' searchspace = '' else searchspace = "AND(space+in+(#{confluence_search_space}))" ConfluenceBaseURL = "#{confluence_protocol}://#{confluence_host}#{confluence_context}" authsuffix = "os_authType=#{confluence_auth}" auth = 'Basic ' + new Buffer("#{confluence_user}:#{confluence_password}").toString('base64'); confluence_request = (msg, url, handler) -> msg.http("#{ConfluenceBaseURL}#{url}") .headers(Authorization: auth, Accept: 'application/json') .get() (err, res, body) -> if err msg.send "Confluence reports error: #{err}" return if res.statusCode isnt 200 msg.send "Request Failed. Sorry." return content = JSON.parse(body) handler content module.exports = (robot) -> robot.respond /wiki (.*)$/i, (msg) -> search_term = msg.match[1] confluence_request msg, "/rest/api/search?#{authsuffix}&cql=(type=page)#{searchspace}AND(text~'#{search_term}')&limit=#{confluence_search_limit}", (result) -> if result.error msg.send result.description return message = "Showing #{result.size} results <#{result._links.base}/dosearchsite.action?cql=#{result.cqlQuery.replace /(\s)/g, '+'}|out of #{result.totalSize} total>" message += "\n<#{ConfluenceBaseURL}#{i.content._links.tinyui}|#{i.content.title}> \n>#{i.excerpt}" for i in result.results message = message.replace /@@@hl@@@|@@@endhl@@@/g, confluence_highlight message = message.replace /&hellip;/g, hellip message = message.replace /&#39;/g, "'" message = message.replace /&quot;/g, '"' msg.send message robot.hear /(?:how do i|how do you) (.*)$/i, (msg) -> search_term = msg.match[1].replace(/\s(the |and |on |like |as |a )|\?|\,|\./g, ' ') confluence_request msg, "/rest/api/search?#{authsuffix}&cql=(type=page)#{searchspace}AND(text~'#{search_term}')&limit=#{confluence_heard_limit}", (result) -> if result.error msg.send result.description return if result.size == '0' msg.send "Perhaps you could try: <http://lmgtfy.com/?q=#{search_term.replace /\s/g, '+'}|a google search>" return message = "Not sure I know how to do that, but this might help:" message += "\n<#{ConfluenceBaseURL}#{i.content._links.tinyui}|#{i.content.title}>\n>#{i.excerpt}" for i in result.results message = message.replace /@@@hl@@@|@@@endhl@@@/g, confluence_highlight message = message.replace /&hellip;/g, hellip message = message.replace /&#39;/g, "'" message = message.replace /&quot;/g, '"' message += "\n_You could always try searches here:_ <http://lmgtfy.com/?q=#{search_term.replace /(\s)/g, '+'}|google> or <#{result._links.base}/dosearchsite.action?cql=#{result.cqlQuery.replace /(\s)/g, '+'}|wiki> " msg.send message
[ { "context": "= null\n\n beforeEach ->\n creds = accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'sessi", "end": 905, "score": 0.9768177270889282, "start": 901, "tag": "KEY", "value": "akid" }, { "context": " creds = accessKeyId: 'akid', secretAccessKey: 'secret',...
test/signers/v4.spec.coffee
ilonabudapesti/aws-sdk-js
1
helpers = require('../helpers') AWS = helpers.AWS beforeEach -> spyOn(AWS.util, 'userAgent').andReturn('aws-sdk-js/0.1') buildRequest = -> ddb = new AWS.DynamoDB({region: 'region', endpoint: 'localhost', apiVersion: '2011-12-05'}) ddb.makeRequest('listTables', {foo: 'bår'}).build().httpRequest buildSigner = (request) -> return new AWS.Signers.V4(request || buildRequest(), 'dynamodb') describe 'AWS.Signers.V4', -> date = new Date(1935346573456) datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '') creds = null signature = '838c924736f5ce488c99f0955097c9571544d84968102543edc9b01dfaa7ef16' authorization = 'AWS4-HMAC-SHA256 Credential=akid/20310430/region/dynamodb/aws4_request, ' + 'SignedHeaders=content-length;host;x-amz-date;x-amz-security-token;x-amz-target, ' + 'Signature=' + signature signer = null beforeEach -> creds = accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session' signer = buildSigner() signer.addHeaders(creds, datetime) describe 'constructor', -> it 'can build a signer for a request object', -> req = buildRequest() signer = buildSigner(req) expect(signer.request).toBe(req) describe 'addAuthorization', -> headers = { 'Content-Type': 'application/x-amz-json-1.0', 'Content-Length': 14, 'X-Amz-Target': 'DynamoDB_20111205.ListTables', 'Host': 'localhost', 'X-Amz-Date': datetime, 'x-amz-security-token' : 'session', 'Authorization' : authorization } for key, value of headers it 'should add ' + key + ' header', -> signer.addAuthorization(creds, date) key = this.description.match(/(\S+) header/)[1] expect(signer.request.headers[key]).toEqual(headers[key]) describe 'authorization', -> it 'should return authorization part for signer', -> expect(signer.authorization(creds, datetime)).toEqual(authorization) describe 'signature', -> it 'should generate proper signature', -> expect(signer.signature(creds, datetime)).toEqual(signature) describe 'caching', -> callCount = null calls = null beforeEach -> spyOn(AWS.util.crypto, 'hmac') signer.signature(creds, datetime) calls = AWS.util.crypto.hmac.calls callCount = calls.length it 'caches subsequent requests', -> signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 1) signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 2) it 'busts cache if region changes', -> signer.request.region = 'new-region' signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 5) it 'busts cache if service changes', -> signer.serviceName = 'newService' signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 5) it 'busts cache if access key changes', -> creds.accessKeyId = 'NEWAKID' signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 5) it 'busts cache if date changes', -> newDate = new Date(date.getTime() + 1000000000) newDatetime = AWS.util.date.iso8601(newDate).replace(/[:\-]|\.\d{3}/g, '') signer.signature(creds, newDatetime) expect(calls.length).toEqual(callCount + 5) describe 'stringToSign', -> it 'should sign correctly generated input string', -> expect(signer.stringToSign(datetime)).toEqual 'AWS4-HMAC-SHA256\n' + datetime + '\n' + '20310430/region/dynamodb/aws4_request\n' + signer.hexEncodedHash(signer.canonicalString()) describe 'canonicalHeaders', -> it 'should return headers', -> expect(signer.canonicalHeaders()).toEqual [ 'content-length:14', 'host:localhost', 'x-amz-date:' + datetime, 'x-amz-security-token:session', 'x-amz-target:DynamoDB_20111205.ListTables' ].join('\n') it 'should ignore Authorization header', -> signer.request.headers = {'Authorization': 'foo'} expect(signer.canonicalHeaders()).toEqual('') it 'should lowercase all header names (not values)', -> signer.request.headers = {'FOO': 'BAR'} expect(signer.canonicalHeaders()).toEqual('foo:BAR') it 'should sort headers by key', -> signer.request.headers = {abc: 'a', bca: 'b', Qux: 'c', bar: 'd'} expect(signer.canonicalHeaders()).toEqual('abc:a\nbar:d\nbca:b\nqux:c') it 'should compact multiple spaces in keys/values to a single space', -> signer.request.headers = {'Header': 'Value with Multiple \t spaces'} expect(signer.canonicalHeaders()).toEqual('header:Value with Multiple spaces') it 'should strip starting and end of line spaces', -> signer.request.headers = {'Header': ' \t Value \t '} expect(signer.canonicalHeaders()).toEqual('header:Value')
125299
helpers = require('../helpers') AWS = helpers.AWS beforeEach -> spyOn(AWS.util, 'userAgent').andReturn('aws-sdk-js/0.1') buildRequest = -> ddb = new AWS.DynamoDB({region: 'region', endpoint: 'localhost', apiVersion: '2011-12-05'}) ddb.makeRequest('listTables', {foo: 'bår'}).build().httpRequest buildSigner = (request) -> return new AWS.Signers.V4(request || buildRequest(), 'dynamodb') describe 'AWS.Signers.V4', -> date = new Date(1935346573456) datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '') creds = null signature = '838c924736f5ce488c99f0955097c9571544d84968102543edc9b01dfaa7ef16' authorization = 'AWS4-HMAC-SHA256 Credential=akid/20310430/region/dynamodb/aws4_request, ' + 'SignedHeaders=content-length;host;x-amz-date;x-amz-security-token;x-amz-target, ' + 'Signature=' + signature signer = null beforeEach -> creds = accessKeyId: '<KEY>', secretAccessKey: '<KEY>', sessionToken: 'session' signer = buildSigner() signer.addHeaders(creds, datetime) describe 'constructor', -> it 'can build a signer for a request object', -> req = buildRequest() signer = buildSigner(req) expect(signer.request).toBe(req) describe 'addAuthorization', -> headers = { 'Content-Type': 'application/x-amz-json-1.0', 'Content-Length': 14, 'X-Amz-Target': 'DynamoDB_20111205.ListTables', 'Host': 'localhost', 'X-Amz-Date': datetime, 'x-amz-security-token' : '<KEY>', 'Authorization' : authorization } for key, value of headers it 'should add ' + key + ' header', -> signer.addAuthorization(creds, date) key = this.description.match(/(\S+) header/)[1] expect(signer.request.headers[key]).toEqual(headers[key]) describe 'authorization', -> it 'should return authorization part for signer', -> expect(signer.authorization(creds, datetime)).toEqual(authorization) describe 'signature', -> it 'should generate proper signature', -> expect(signer.signature(creds, datetime)).toEqual(signature) describe 'caching', -> callCount = null calls = null beforeEach -> spyOn(AWS.util.crypto, 'hmac') signer.signature(creds, datetime) calls = AWS.util.crypto.hmac.calls callCount = calls.length it 'caches subsequent requests', -> signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 1) signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 2) it 'busts cache if region changes', -> signer.request.region = 'new-region' signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 5) it 'busts cache if service changes', -> signer.serviceName = 'newService' signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 5) it 'busts cache if access key changes', -> creds.accessKeyId = '<KEY>' signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 5) it 'busts cache if date changes', -> newDate = new Date(date.getTime() + 1000000000) newDatetime = AWS.util.date.iso8601(newDate).replace(/[:\-]|\.\d{3}/g, '') signer.signature(creds, newDatetime) expect(calls.length).toEqual(callCount + 5) describe 'stringToSign', -> it 'should sign correctly generated input string', -> expect(signer.stringToSign(datetime)).toEqual 'AWS4-HMAC-SHA256\n' + datetime + '\n' + '20310430/region/dynamodb/aws4_request\n' + signer.hexEncodedHash(signer.canonicalString()) describe 'canonicalHeaders', -> it 'should return headers', -> expect(signer.canonicalHeaders()).toEqual [ 'content-length:14', 'host:localhost', 'x-amz-date:' + datetime, 'x-amz-security-token:session', 'x-amz-target:DynamoDB_20111205.ListTables' ].join('\n') it 'should ignore Authorization header', -> signer.request.headers = {'Authorization': 'foo'} expect(signer.canonicalHeaders()).toEqual('') it 'should lowercase all header names (not values)', -> signer.request.headers = {'FOO': 'BAR'} expect(signer.canonicalHeaders()).toEqual('foo:BAR') it 'should sort headers by key', -> signer.request.headers = {abc: 'a', bca: 'b', Qux: 'c', bar: 'd'} expect(signer.canonicalHeaders()).toEqual('abc:a\nbar:d\nbca:b\nqux:c') it 'should compact multiple spaces in keys/values to a single space', -> signer.request.headers = {'Header': 'Value with Multiple \t spaces'} expect(signer.canonicalHeaders()).toEqual('header:Value with Multiple spaces') it 'should strip starting and end of line spaces', -> signer.request.headers = {'Header': ' \t Value \t '} expect(signer.canonicalHeaders()).toEqual('header:Value')
true
helpers = require('../helpers') AWS = helpers.AWS beforeEach -> spyOn(AWS.util, 'userAgent').andReturn('aws-sdk-js/0.1') buildRequest = -> ddb = new AWS.DynamoDB({region: 'region', endpoint: 'localhost', apiVersion: '2011-12-05'}) ddb.makeRequest('listTables', {foo: 'bår'}).build().httpRequest buildSigner = (request) -> return new AWS.Signers.V4(request || buildRequest(), 'dynamodb') describe 'AWS.Signers.V4', -> date = new Date(1935346573456) datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '') creds = null signature = '838c924736f5ce488c99f0955097c9571544d84968102543edc9b01dfaa7ef16' authorization = 'AWS4-HMAC-SHA256 Credential=akid/20310430/region/dynamodb/aws4_request, ' + 'SignedHeaders=content-length;host;x-amz-date;x-amz-security-token;x-amz-target, ' + 'Signature=' + signature signer = null beforeEach -> creds = accessKeyId: 'PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI', sessionToken: 'session' signer = buildSigner() signer.addHeaders(creds, datetime) describe 'constructor', -> it 'can build a signer for a request object', -> req = buildRequest() signer = buildSigner(req) expect(signer.request).toBe(req) describe 'addAuthorization', -> headers = { 'Content-Type': 'application/x-amz-json-1.0', 'Content-Length': 14, 'X-Amz-Target': 'DynamoDB_20111205.ListTables', 'Host': 'localhost', 'X-Amz-Date': datetime, 'x-amz-security-token' : 'PI:KEY:<KEY>END_PI', 'Authorization' : authorization } for key, value of headers it 'should add ' + key + ' header', -> signer.addAuthorization(creds, date) key = this.description.match(/(\S+) header/)[1] expect(signer.request.headers[key]).toEqual(headers[key]) describe 'authorization', -> it 'should return authorization part for signer', -> expect(signer.authorization(creds, datetime)).toEqual(authorization) describe 'signature', -> it 'should generate proper signature', -> expect(signer.signature(creds, datetime)).toEqual(signature) describe 'caching', -> callCount = null calls = null beforeEach -> spyOn(AWS.util.crypto, 'hmac') signer.signature(creds, datetime) calls = AWS.util.crypto.hmac.calls callCount = calls.length it 'caches subsequent requests', -> signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 1) signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 2) it 'busts cache if region changes', -> signer.request.region = 'new-region' signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 5) it 'busts cache if service changes', -> signer.serviceName = 'newService' signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 5) it 'busts cache if access key changes', -> creds.accessKeyId = 'PI:KEY:<KEY>END_PI' signer.signature(creds, datetime) expect(calls.length).toEqual(callCount + 5) it 'busts cache if date changes', -> newDate = new Date(date.getTime() + 1000000000) newDatetime = AWS.util.date.iso8601(newDate).replace(/[:\-]|\.\d{3}/g, '') signer.signature(creds, newDatetime) expect(calls.length).toEqual(callCount + 5) describe 'stringToSign', -> it 'should sign correctly generated input string', -> expect(signer.stringToSign(datetime)).toEqual 'AWS4-HMAC-SHA256\n' + datetime + '\n' + '20310430/region/dynamodb/aws4_request\n' + signer.hexEncodedHash(signer.canonicalString()) describe 'canonicalHeaders', -> it 'should return headers', -> expect(signer.canonicalHeaders()).toEqual [ 'content-length:14', 'host:localhost', 'x-amz-date:' + datetime, 'x-amz-security-token:session', 'x-amz-target:DynamoDB_20111205.ListTables' ].join('\n') it 'should ignore Authorization header', -> signer.request.headers = {'Authorization': 'foo'} expect(signer.canonicalHeaders()).toEqual('') it 'should lowercase all header names (not values)', -> signer.request.headers = {'FOO': 'BAR'} expect(signer.canonicalHeaders()).toEqual('foo:BAR') it 'should sort headers by key', -> signer.request.headers = {abc: 'a', bca: 'b', Qux: 'c', bar: 'd'} expect(signer.canonicalHeaders()).toEqual('abc:a\nbar:d\nbca:b\nqux:c') it 'should compact multiple spaces in keys/values to a single space', -> signer.request.headers = {'Header': 'Value with Multiple \t spaces'} expect(signer.canonicalHeaders()).toEqual('header:Value with Multiple spaces') it 'should strip starting and end of line spaces', -> signer.request.headers = {'Header': ' \t Value \t '} expect(signer.canonicalHeaders()).toEqual('header:Value')
[ { "context": "options:\n coveralls:\n repoToken: \"9TE8NsKQWe94SUDmDeytRGcvuiYsYrabI\"\n require: ['coffee-script/register','shou", "end": 1126, "score": 0.958893895149231, "start": 1093, "tag": "KEY", "value": "9TE8NsKQWe94SUDmDeytRGcvuiYsYrabI" } ]
Gruntfile.coffee
codedoctor/hapi-routes-users-authorizations
1
_ = require 'underscore' coffeeRename = (destBase, destPath) -> destPath = destPath.replace 'src/','' destBase + destPath.replace /\.coffee$/, '.js' module.exports = (grunt) -> filterGrunt = -> gruntFiles = require("matchdep").filterDev("grunt-*") _.reject gruntFiles, (x) -> x is 'grunt-cli' filterGrunt().forEach grunt.loadNpmTasks config = coffee: compile: options: sourceMap: true files: grunt.file.expandMapping(['src/**/*.coffee'], 'lib/', {rename: coffeeRename }) shell: options: stdout: true npm_install: command: "npm install" release: {} env: dev: NODE_ENV: "development" test: NODE_ENV: "test" codo: options: undocumented: true private: true analytics: false src: ['src/**/*.coffee'] mochaTest: test: options: reporter: 'spec' require: 'coffee-script/register' src: ['test/**/*-tests.coffee'] mochacov: options: coveralls: repoToken: "9TE8NsKQWe94SUDmDeytRGcvuiYsYrabI" require: ['coffee-script/register','should'] all: ['test/**/*-tests.coffee'] config.watch = scripts: files: ['src/**/*.coffee'] tasks: ['build'] options: livereload: false tests: files: ['test/**/*.coffee'] tasks: ['build'] options: livereload: false grunt.initConfig config grunt.registerTask "install", [ "shell:npm_install" ] grunt.registerTask "build", [ 'env:dev' 'codo' 'coffee' 'test' ] grunt.registerTask "test", [ 'env:test' 'mochaTest:test' ] grunt.registerTask "testandcoverage", [ 'env:test' 'mochaTest:test' 'mochacov' ] grunt.registerTask 'deploy', [ 'build' 'release' ] grunt.registerTask 'default', ['build', 'watch']
13578
_ = require 'underscore' coffeeRename = (destBase, destPath) -> destPath = destPath.replace 'src/','' destBase + destPath.replace /\.coffee$/, '.js' module.exports = (grunt) -> filterGrunt = -> gruntFiles = require("matchdep").filterDev("grunt-*") _.reject gruntFiles, (x) -> x is 'grunt-cli' filterGrunt().forEach grunt.loadNpmTasks config = coffee: compile: options: sourceMap: true files: grunt.file.expandMapping(['src/**/*.coffee'], 'lib/', {rename: coffeeRename }) shell: options: stdout: true npm_install: command: "npm install" release: {} env: dev: NODE_ENV: "development" test: NODE_ENV: "test" codo: options: undocumented: true private: true analytics: false src: ['src/**/*.coffee'] mochaTest: test: options: reporter: 'spec' require: 'coffee-script/register' src: ['test/**/*-tests.coffee'] mochacov: options: coveralls: repoToken: "<KEY>" require: ['coffee-script/register','should'] all: ['test/**/*-tests.coffee'] config.watch = scripts: files: ['src/**/*.coffee'] tasks: ['build'] options: livereload: false tests: files: ['test/**/*.coffee'] tasks: ['build'] options: livereload: false grunt.initConfig config grunt.registerTask "install", [ "shell:npm_install" ] grunt.registerTask "build", [ 'env:dev' 'codo' 'coffee' 'test' ] grunt.registerTask "test", [ 'env:test' 'mochaTest:test' ] grunt.registerTask "testandcoverage", [ 'env:test' 'mochaTest:test' 'mochacov' ] grunt.registerTask 'deploy', [ 'build' 'release' ] grunt.registerTask 'default', ['build', 'watch']
true
_ = require 'underscore' coffeeRename = (destBase, destPath) -> destPath = destPath.replace 'src/','' destBase + destPath.replace /\.coffee$/, '.js' module.exports = (grunt) -> filterGrunt = -> gruntFiles = require("matchdep").filterDev("grunt-*") _.reject gruntFiles, (x) -> x is 'grunt-cli' filterGrunt().forEach grunt.loadNpmTasks config = coffee: compile: options: sourceMap: true files: grunt.file.expandMapping(['src/**/*.coffee'], 'lib/', {rename: coffeeRename }) shell: options: stdout: true npm_install: command: "npm install" release: {} env: dev: NODE_ENV: "development" test: NODE_ENV: "test" codo: options: undocumented: true private: true analytics: false src: ['src/**/*.coffee'] mochaTest: test: options: reporter: 'spec' require: 'coffee-script/register' src: ['test/**/*-tests.coffee'] mochacov: options: coveralls: repoToken: "PI:KEY:<KEY>END_PI" require: ['coffee-script/register','should'] all: ['test/**/*-tests.coffee'] config.watch = scripts: files: ['src/**/*.coffee'] tasks: ['build'] options: livereload: false tests: files: ['test/**/*.coffee'] tasks: ['build'] options: livereload: false grunt.initConfig config grunt.registerTask "install", [ "shell:npm_install" ] grunt.registerTask "build", [ 'env:dev' 'codo' 'coffee' 'test' ] grunt.registerTask "test", [ 'env:test' 'mochaTest:test' ] grunt.registerTask "testandcoverage", [ 'env:test' 'mochaTest:test' 'mochacov' ] grunt.registerTask 'deploy', [ 'build' 'release' ] grunt.registerTask 'default', ['build', 'watch']
[ { "context": "alOptions or= {}\n options =\n 'http-address': \"127.0.0.1:#{HTTP_PORT}\"\n 'tcp-address': \"127.0.0.1:#{TCP", "end": 364, "score": 0.9997307658195496, "start": 355, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ss': \"127.0.0.1:#{HTTP_PORT}\"\n '...
test/integration_test.coffee
upyun-dev/nsqjs
0
_ = require 'underscore' async = require 'async' child_process = require 'child_process' request = require 'request' should = require 'should' temp = require('temp').track() nsq = require '../src/nsq' TCP_PORT = 14150 HTTP_PORT = 14151 startNSQD = (dataPath, additionalOptions, callback) -> additionalOptions or= {} options = 'http-address': "127.0.0.1:#{HTTP_PORT}" 'tcp-address': "127.0.0.1:#{TCP_PORT}" 'data-path': dataPath 'tls-cert': './test/cert.pem' 'tls-key': './test/key.pem' _.extend options, additionalOptions options = ("-#{key}=#{value}" for key, value of options) process = child_process.spawn 'nsqd', options, stdio: ['ignore', 'ignore', 'ignore'] # Give nsqd a chance to startup successfully. setTimeout _.partial(callback, null, process), 500 topicOp = (op, topic, callback) -> options = method: 'POST' uri: "http://127.0.0.1:#{HTTP_PORT}/#{op}" qs: topic: topic request options, (err, res, body) -> callback err createTopic = _.partial topicOp, 'create_topic' deleteTopic = _.partial topicOp, 'delete_topic' # Publish a single message via HTTP publish = (topic, message, done) -> options = uri: "http://127.0.0.1:#{HTTP_PORT}/pub" method: 'POST' qs: topic: topic body: message request options, (err, res, body) -> done? err describe 'integration', -> nsqdProcess = null reader = null before (done) -> temp.mkdir '/nsq', (err, dirPath) -> startNSQD dirPath, {}, (err, process) -> nsqdProcess = process done err after (done) -> nsqdProcess.kill() # Give nsqd a chance to exit before it's data directory will be cleaned up. setTimeout done, 500 beforeEach (done) -> createTopic 'test', done afterEach (done) -> reader?.close() deleteTopic 'test', done describe 'stream compression and encryption', -> [ {deflate: true} {snappy: true} {tls: true, tlsVerification: false} {tls: true, tlsVerification: false, snappy: true} {tls: true, tlsVerification: false, deflate: true} ].forEach (options) -> # Figure out what compression is enabled compression = (key for key in ['deflate', 'snappy'] when key of options) compression.push 'none' description = "reader with compression (#{compression[0]}) and tls (#{options.tls?})" describe description, -> it 'should send and receive a message', (done) -> topic = 'test' channel = 'default' message = "a message for our reader" publish topic, message reader = new nsq.Reader topic, channel, _.extend {nsqdTCPAddresses: ["127.0.0.1:#{TCP_PORT}"]}, options reader.on 'message', (msg) -> msg.body.toString().should.eql message msg.finish() done() reader.connect() it 'should send and receive a large message', (done) -> topic = 'test' channel = 'default' message = ('a' for i in [0..100000]).join '' publish topic, message reader = new nsq.Reader topic, channel, _.extend {nsqdTCPAddresses: ["127.0.0.1:#{TCP_PORT}"]}, options reader.on 'message', (msg) -> msg.body.toString().should.eql message msg.finish() done() reader.connect() describe 'end to end', -> topic = 'test' channel = 'default' tcpAddress = "127.0.0.1:#{TCP_PORT}" writer = null reader = null beforeEach (done) -> writer = new nsq.Writer '127.0.0.1', TCP_PORT writer.on 'ready', -> reader = new nsq.Reader topic, channel, nsqdTCPAddresses: tcpAddress reader.connect() done() writer.connect() afterEach -> writer.close() it 'should send and receive a string', (done) -> message = 'hello world' writer.publish topic, message, (err) -> done err if err reader.on 'message', (msg) -> msg.body.toString().should.eql message msg.finish() done() it 'should send and receive a Buffer', (done) -> message = new Buffer [0x11, 0x22, 0x33] writer.publish topic, message reader.on 'message', (readMsg) -> readByte.should.equal message[i] for readByte, i in readMsg.body readMsg.finish() done() # TODO (Dudley): The behavior of nsqd seems to have changed around this. # This requires more investigation but not concerning at the moment. it.skip 'should not receive messages when immediately paused', (done) -> waitedLongEnough = false timeout = setTimeout -> reader.unpause() waitedLongEnough = true , 100 # Note: because NSQDConnection.connect() does most of it's work in # process.nextTick(), we're really pausing before the reader is # connected. # reader.pause() reader.on 'message', (msg) -> msg.finish() clearTimeout timeout waitedLongEnough.should.be.true done() writer.publish topic, 'pause test' it 'should not receive any new messages when paused', (done) -> writer.publish topic, messageShouldArrive: true reader.on 'message', (msg) -> # check the message msg.json().messageShouldArrive.should.be.true msg.finish() if reader.isPaused() then return done() reader.pause() process.nextTick -> # send it again, shouldn't get this one writer.publish topic, messageShouldArrive: false setTimeout done, 100 it 'should not receive any requeued messages when paused', (done) -> writer.publish topic, 'requeue me' id = '' reader.on 'message', (msg) -> # this will fail if the msg comes through again id.should.equal '' id = msg.id if reader.isPaused() then return done() reader.pause() process.nextTick -> # send it again, shouldn't get this one msg.requeue 0, false setTimeout done, 100 it 'should start receiving messages again after unpause', (done) -> shouldReceive = true writer.publish topic, sentWhilePaused: false reader.on 'message', (msg) -> shouldReceive.should.be.true reader.pause() msg.requeue() if msg.json().sentWhilePaused then return done() shouldReceive = false writer.publish topic, sentWhilePaused: true setTimeout -> shouldReceive = true reader.unpause() , 100 done() it 'should successfully publish a message before fully connected', (done) -> writer = new nsq.Writer '127.0.0.1', TCP_PORT writer.connect() # The writer is connecting, but it shouldn't be ready to publish. writer.ready.should.eql false # Publish the message. It should succeed since the writer will queue up # the message while connecting. writer.publish 'a_topic', 'a message', (err) -> should.not.exist err done() describe 'failures', -> before (done) -> temp.mkdir '/nsq', (err, dirPath) => startNSQD dirPath, {}, (err, process) => @nsqdProcess = process done err after (done) -> @nsqdProcess.kill() # Give nsqd a chance to exit before it's data directory will be cleaned up. setTimeout done, 500 describe 'Writer', -> describe 'nsqd disconnect before publish', -> it 'should fail to publish a message', (done) -> writer = new nsq.Writer '127.0.0.1', TCP_PORT async.series [ # Connect the writer to the nsqd. (callback) -> writer.connect() writer.on 'ready', -> callback() # Stop the nsqd process. (callback) => @nsqdProcess.kill() setTimeout callback, 200 # Attempt to publish a message. (callback) -> writer.publish 'test_topic', 'a message that should fail', (err) -> should.exist err callback() ], (err) -> done err
84190
_ = require 'underscore' async = require 'async' child_process = require 'child_process' request = require 'request' should = require 'should' temp = require('temp').track() nsq = require '../src/nsq' TCP_PORT = 14150 HTTP_PORT = 14151 startNSQD = (dataPath, additionalOptions, callback) -> additionalOptions or= {} options = 'http-address': "127.0.0.1:#{HTTP_PORT}" 'tcp-address': "127.0.0.1:#{TCP_PORT}" 'data-path': dataPath 'tls-cert': './test/cert.pem' 'tls-key': './test/key.pem' _.extend options, additionalOptions options = ("-#{key}=#{value}" for key, value of options) process = child_process.spawn 'nsqd', options, stdio: ['ignore', 'ignore', 'ignore'] # Give nsqd a chance to startup successfully. setTimeout _.partial(callback, null, process), 500 topicOp = (op, topic, callback) -> options = method: 'POST' uri: "http://127.0.0.1:#{HTTP_PORT}/#{op}" qs: topic: topic request options, (err, res, body) -> callback err createTopic = _.partial topicOp, 'create_topic' deleteTopic = _.partial topicOp, 'delete_topic' # Publish a single message via HTTP publish = (topic, message, done) -> options = uri: "http://127.0.0.1:#{HTTP_PORT}/pub" method: 'POST' qs: topic: topic body: message request options, (err, res, body) -> done? err describe 'integration', -> nsqdProcess = null reader = null before (done) -> temp.mkdir '/nsq', (err, dirPath) -> startNSQD dirPath, {}, (err, process) -> nsqdProcess = process done err after (done) -> nsqdProcess.kill() # Give nsqd a chance to exit before it's data directory will be cleaned up. setTimeout done, 500 beforeEach (done) -> createTopic 'test', done afterEach (done) -> reader?.close() deleteTopic 'test', done describe 'stream compression and encryption', -> [ {deflate: true} {snappy: true} {tls: true, tlsVerification: false} {tls: true, tlsVerification: false, snappy: true} {tls: true, tlsVerification: false, deflate: true} ].forEach (options) -> # Figure out what compression is enabled compression = (key for key in ['def<KEY>', 'sn<KEY>'] when key of options) compression.push 'none' description = "reader with compression (#{compression[0]}) and tls (#{options.tls?})" describe description, -> it 'should send and receive a message', (done) -> topic = 'test' channel = 'default' message = "a message for our reader" publish topic, message reader = new nsq.Reader topic, channel, _.extend {nsqdTCPAddresses: ["127.0.0.1:#{TCP_PORT}"]}, options reader.on 'message', (msg) -> msg.body.toString().should.eql message msg.finish() done() reader.connect() it 'should send and receive a large message', (done) -> topic = 'test' channel = 'default' message = ('a' for i in [0..100000]).join '' publish topic, message reader = new nsq.Reader topic, channel, _.extend {nsqdTCPAddresses: ["127.0.0.1:#{TCP_PORT}"]}, options reader.on 'message', (msg) -> msg.body.toString().should.eql message msg.finish() done() reader.connect() describe 'end to end', -> topic = 'test' channel = 'default' tcpAddress = "127.0.0.1:#{TCP_PORT}" writer = null reader = null beforeEach (done) -> writer = new nsq.Writer '1172.16.17.32', TCP_PORT writer.on 'ready', -> reader = new nsq.Reader topic, channel, nsqdTCPAddresses: tcpAddress reader.connect() done() writer.connect() afterEach -> writer.close() it 'should send and receive a string', (done) -> message = 'hello world' writer.publish topic, message, (err) -> done err if err reader.on 'message', (msg) -> msg.body.toString().should.eql message msg.finish() done() it 'should send and receive a Buffer', (done) -> message = new Buffer [0x11, 0x22, 0x33] writer.publish topic, message reader.on 'message', (readMsg) -> readByte.should.equal message[i] for readByte, i in readMsg.body readMsg.finish() done() # TODO (<NAME>): The behavior of nsqd seems to have changed around this. # This requires more investigation but not concerning at the moment. it.skip 'should not receive messages when immediately paused', (done) -> waitedLongEnough = false timeout = setTimeout -> reader.unpause() waitedLongEnough = true , 100 # Note: because NSQDConnection.connect() does most of it's work in # process.nextTick(), we're really pausing before the reader is # connected. # reader.pause() reader.on 'message', (msg) -> msg.finish() clearTimeout timeout waitedLongEnough.should.be.true done() writer.publish topic, 'pause test' it 'should not receive any new messages when paused', (done) -> writer.publish topic, messageShouldArrive: true reader.on 'message', (msg) -> # check the message msg.json().messageShouldArrive.should.be.true msg.finish() if reader.isPaused() then return done() reader.pause() process.nextTick -> # send it again, shouldn't get this one writer.publish topic, messageShouldArrive: false setTimeout done, 100 it 'should not receive any requeued messages when paused', (done) -> writer.publish topic, 'requeue me' id = '' reader.on 'message', (msg) -> # this will fail if the msg comes through again id.should.equal '' id = msg.id if reader.isPaused() then return done() reader.pause() process.nextTick -> # send it again, shouldn't get this one msg.requeue 0, false setTimeout done, 100 it 'should start receiving messages again after unpause', (done) -> shouldReceive = true writer.publish topic, sentWhilePaused: false reader.on 'message', (msg) -> shouldReceive.should.be.true reader.pause() msg.requeue() if msg.json().sentWhilePaused then return done() shouldReceive = false writer.publish topic, sentWhilePaused: true setTimeout -> shouldReceive = true reader.unpause() , 100 done() it 'should successfully publish a message before fully connected', (done) -> writer = new nsq.Writer '127.0.0.1', TCP_PORT writer.connect() # The writer is connecting, but it shouldn't be ready to publish. writer.ready.should.eql false # Publish the message. It should succeed since the writer will queue up # the message while connecting. writer.publish 'a_topic', 'a message', (err) -> should.not.exist err done() describe 'failures', -> before (done) -> temp.mkdir '/nsq', (err, dirPath) => startNSQD dirPath, {}, (err, process) => @nsqdProcess = process done err after (done) -> @nsqdProcess.kill() # Give nsqd a chance to exit before it's data directory will be cleaned up. setTimeout done, 500 describe 'Writer', -> describe 'nsqd disconnect before publish', -> it 'should fail to publish a message', (done) -> writer = new nsq.Writer '127.0.0.1', TCP_PORT async.series [ # Connect the writer to the nsqd. (callback) -> writer.connect() writer.on 'ready', -> callback() # Stop the nsqd process. (callback) => @nsqdProcess.kill() setTimeout callback, 200 # Attempt to publish a message. (callback) -> writer.publish 'test_topic', 'a message that should fail', (err) -> should.exist err callback() ], (err) -> done err
true
_ = require 'underscore' async = require 'async' child_process = require 'child_process' request = require 'request' should = require 'should' temp = require('temp').track() nsq = require '../src/nsq' TCP_PORT = 14150 HTTP_PORT = 14151 startNSQD = (dataPath, additionalOptions, callback) -> additionalOptions or= {} options = 'http-address': "127.0.0.1:#{HTTP_PORT}" 'tcp-address': "127.0.0.1:#{TCP_PORT}" 'data-path': dataPath 'tls-cert': './test/cert.pem' 'tls-key': './test/key.pem' _.extend options, additionalOptions options = ("-#{key}=#{value}" for key, value of options) process = child_process.spawn 'nsqd', options, stdio: ['ignore', 'ignore', 'ignore'] # Give nsqd a chance to startup successfully. setTimeout _.partial(callback, null, process), 500 topicOp = (op, topic, callback) -> options = method: 'POST' uri: "http://127.0.0.1:#{HTTP_PORT}/#{op}" qs: topic: topic request options, (err, res, body) -> callback err createTopic = _.partial topicOp, 'create_topic' deleteTopic = _.partial topicOp, 'delete_topic' # Publish a single message via HTTP publish = (topic, message, done) -> options = uri: "http://127.0.0.1:#{HTTP_PORT}/pub" method: 'POST' qs: topic: topic body: message request options, (err, res, body) -> done? err describe 'integration', -> nsqdProcess = null reader = null before (done) -> temp.mkdir '/nsq', (err, dirPath) -> startNSQD dirPath, {}, (err, process) -> nsqdProcess = process done err after (done) -> nsqdProcess.kill() # Give nsqd a chance to exit before it's data directory will be cleaned up. setTimeout done, 500 beforeEach (done) -> createTopic 'test', done afterEach (done) -> reader?.close() deleteTopic 'test', done describe 'stream compression and encryption', -> [ {deflate: true} {snappy: true} {tls: true, tlsVerification: false} {tls: true, tlsVerification: false, snappy: true} {tls: true, tlsVerification: false, deflate: true} ].forEach (options) -> # Figure out what compression is enabled compression = (key for key in ['defPI:KEY:<KEY>END_PI', 'snPI:KEY:<KEY>END_PI'] when key of options) compression.push 'none' description = "reader with compression (#{compression[0]}) and tls (#{options.tls?})" describe description, -> it 'should send and receive a message', (done) -> topic = 'test' channel = 'default' message = "a message for our reader" publish topic, message reader = new nsq.Reader topic, channel, _.extend {nsqdTCPAddresses: ["127.0.0.1:#{TCP_PORT}"]}, options reader.on 'message', (msg) -> msg.body.toString().should.eql message msg.finish() done() reader.connect() it 'should send and receive a large message', (done) -> topic = 'test' channel = 'default' message = ('a' for i in [0..100000]).join '' publish topic, message reader = new nsq.Reader topic, channel, _.extend {nsqdTCPAddresses: ["127.0.0.1:#{TCP_PORT}"]}, options reader.on 'message', (msg) -> msg.body.toString().should.eql message msg.finish() done() reader.connect() describe 'end to end', -> topic = 'test' channel = 'default' tcpAddress = "127.0.0.1:#{TCP_PORT}" writer = null reader = null beforeEach (done) -> writer = new nsq.Writer '1PI:IP_ADDRESS:172.16.17.32END_PI', TCP_PORT writer.on 'ready', -> reader = new nsq.Reader topic, channel, nsqdTCPAddresses: tcpAddress reader.connect() done() writer.connect() afterEach -> writer.close() it 'should send and receive a string', (done) -> message = 'hello world' writer.publish topic, message, (err) -> done err if err reader.on 'message', (msg) -> msg.body.toString().should.eql message msg.finish() done() it 'should send and receive a Buffer', (done) -> message = new Buffer [0x11, 0x22, 0x33] writer.publish topic, message reader.on 'message', (readMsg) -> readByte.should.equal message[i] for readByte, i in readMsg.body readMsg.finish() done() # TODO (PI:NAME:<NAME>END_PI): The behavior of nsqd seems to have changed around this. # This requires more investigation but not concerning at the moment. it.skip 'should not receive messages when immediately paused', (done) -> waitedLongEnough = false timeout = setTimeout -> reader.unpause() waitedLongEnough = true , 100 # Note: because NSQDConnection.connect() does most of it's work in # process.nextTick(), we're really pausing before the reader is # connected. # reader.pause() reader.on 'message', (msg) -> msg.finish() clearTimeout timeout waitedLongEnough.should.be.true done() writer.publish topic, 'pause test' it 'should not receive any new messages when paused', (done) -> writer.publish topic, messageShouldArrive: true reader.on 'message', (msg) -> # check the message msg.json().messageShouldArrive.should.be.true msg.finish() if reader.isPaused() then return done() reader.pause() process.nextTick -> # send it again, shouldn't get this one writer.publish topic, messageShouldArrive: false setTimeout done, 100 it 'should not receive any requeued messages when paused', (done) -> writer.publish topic, 'requeue me' id = '' reader.on 'message', (msg) -> # this will fail if the msg comes through again id.should.equal '' id = msg.id if reader.isPaused() then return done() reader.pause() process.nextTick -> # send it again, shouldn't get this one msg.requeue 0, false setTimeout done, 100 it 'should start receiving messages again after unpause', (done) -> shouldReceive = true writer.publish topic, sentWhilePaused: false reader.on 'message', (msg) -> shouldReceive.should.be.true reader.pause() msg.requeue() if msg.json().sentWhilePaused then return done() shouldReceive = false writer.publish topic, sentWhilePaused: true setTimeout -> shouldReceive = true reader.unpause() , 100 done() it 'should successfully publish a message before fully connected', (done) -> writer = new nsq.Writer '127.0.0.1', TCP_PORT writer.connect() # The writer is connecting, but it shouldn't be ready to publish. writer.ready.should.eql false # Publish the message. It should succeed since the writer will queue up # the message while connecting. writer.publish 'a_topic', 'a message', (err) -> should.not.exist err done() describe 'failures', -> before (done) -> temp.mkdir '/nsq', (err, dirPath) => startNSQD dirPath, {}, (err, process) => @nsqdProcess = process done err after (done) -> @nsqdProcess.kill() # Give nsqd a chance to exit before it's data directory will be cleaned up. setTimeout done, 500 describe 'Writer', -> describe 'nsqd disconnect before publish', -> it 'should fail to publish a message', (done) -> writer = new nsq.Writer '127.0.0.1', TCP_PORT async.series [ # Connect the writer to the nsqd. (callback) -> writer.connect() writer.on 'ready', -> callback() # Stop the nsqd process. (callback) => @nsqdProcess.kill() setTimeout callback, 200 # Attempt to publish a message. (callback) -> writer.publish 'test_topic', 'a message that should fail', (err) -> should.exist err callback() ], (err) -> done err
[ { "context": "#\n# Zoom main file\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\n\n# hook up dependencies\ncore = require('core", "end": 59, "score": 0.9998822212219238, "start": 42, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
ui/zoom/main.coffee
lovely-io/lovely.io-stl
2
# # Zoom main file # # Copyright (C) 2012 Nikolay Nemshilov # # hook up dependencies core = require('core') UI = require('ui') $ = Lovely.module('dom') # reusing UI's dom module # local variables assignments ext = core.ext Class = core.Class Options = core.Options Element = $.Element Locker = UI.Locker Modal = UI.Modal Icon = UI.Icon # glue in your files include 'src/zoom' include 'src/document' # export your objects in the module exports = ext(Zoom, { version: '%{version}' });
138078
# # Zoom main file # # Copyright (C) 2012 <NAME> # # hook up dependencies core = require('core') UI = require('ui') $ = Lovely.module('dom') # reusing UI's dom module # local variables assignments ext = core.ext Class = core.Class Options = core.Options Element = $.Element Locker = UI.Locker Modal = UI.Modal Icon = UI.Icon # glue in your files include 'src/zoom' include 'src/document' # export your objects in the module exports = ext(Zoom, { version: '%{version}' });
true
# # Zoom main file # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # # hook up dependencies core = require('core') UI = require('ui') $ = Lovely.module('dom') # reusing UI's dom module # local variables assignments ext = core.ext Class = core.Class Options = core.Options Element = $.Element Locker = UI.Locker Modal = UI.Modal Icon = UI.Icon # glue in your files include 'src/zoom' include 'src/document' # export your objects in the module exports = ext(Zoom, { version: '%{version}' });
[ { "context": "quest(@app).get('/api/posts').query\n\t\t\t\tpassword:'asdf'\n\t\t\t.end (err, res) ->\n\t\t\t\tres.status.should.equa", "end": 2576, "score": 0.9990381002426147, "start": 2572, "tag": "PASSWORD", "value": "asdf" }, { "context": "quest(@app).get('/api/posts').query\n\t\...
test/list.coffee
DailyFeats/mongoose-rest-endpoints
0
express = require 'express' bodyParser = require 'body-parser' methodOverride = require 'method-override' request = require 'supertest' should = require 'should' Q = require 'q' mongoose = require 'mongoose' require('../lib/log').verbose(true) moment = require 'moment' mre = require '../lib/endpoint' # Custom "Post" and "Comment" documents commentSchema = new mongoose.Schema comment:String _post: type:mongoose.Schema.Types.ObjectId ref:'Post' _author: type:mongoose.Schema.Types.ObjectId ref:'Author' postSchema = new mongoose.Schema date:Date number:Number string: type:String required:true _comments:[ type:mongoose.Schema.Types.ObjectId ref:'Comment' $through:'_post' ] foo: bar:Number otherField:mongoose.Schema.Types.Mixed authorSchema = new mongoose.Schema name:'String' # Custom middleware for testing requirePassword = (password) -> return (req, res, next) -> if req.query.password and req.query.password is password next() else res.send(401) createPost = (data) -> deferred = Q.defer() postClass = mongoose.model('Post') post = new postClass(data) post.save (err, res) -> if err return deferred.reject(err) return deferred.resolve() return deferred.promise mongoUrlCreds = if process.env.MONGO_USERNAME then "#{process.env.MONGO_USERNAME}:#{process.env.MONGO_PASSWORD}@" else "" mongoose.connect("mongodb://#{mongoUrlCreds}#{process.env.MONGO_HOST}/mre_test") mongoose.model('Post', postSchema) mongoose.model('Comment', commentSchema) mongoose.model('Author', authorSchema) mongoose.set 'debug', true describe 'List', -> describe 'Basics', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' otherField: foo:'bar' mod.save (err, res) => @mod = res done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should retrieve with no hooks', (done) -> @endpoint.register(@app) request(@app).get('/api/posts/').end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(1) res.body[0].number.should.equal(5) res.body[0].string.should.equal('Test') done() it 'should allow through with middleware', (done) -> @endpoint.addMiddleware('list', requirePassword('asdf')).register(@app) request(@app).get('/api/posts').query password:'asdf' .end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should prevent on bad middleware', (done) -> @endpoint.addMiddleware('list', requirePassword('asdf')).register(@app) request(@app).get('/api/posts').query password:'ffff' .end (err, res) -> res.status.should.equal(401) done() it 'should fetch only specified fields', (done) -> @endpoint.limitFields(['string', 'date']).register(@app) request(@app).get('/api/posts').end (err, res) -> res.body.length.should.equal(1) res.body[0].string.should.equal('Test') should.not.exist(res.body[0].number) done() it 'should work with default query hook', (done) -> @endpoint.allowQueryParam(['$gte_number', '$lte_number', '$gte_date', '$lte_date']).register(@app) request(@app).get('/api/posts/').query '$gte_number':6 .end (err, res) => console.log res.body res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').query '$lte_number':6 .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) request(@app).get('/api/posts/').query '$gte_date':moment().add('day', 1).toDate() .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').query '$lte_date':moment().add('day', 1).toDate() .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should work with pre_response hook', (done) -> @endpoint.tap 'pre_response', 'list', (req, collection, next) -> for col in collection col.number = 10 next(collection) .register(@app) request(@app).get('/api/posts/').end (err, res) => res.body.length.should.equal(1) res.body[0].number.should.equal(10) done() it 'should do a regex search', (done) -> @endpoint.allowQueryParam('$regex_string').register(@app) request(@app).get('/api/posts/').query '$regex_string':'tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').query '$regex_string':'Tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should do a case insensitive regex search', (done) -> @endpoint.allowQueryParam('$regexi_string').register(@app) request(@app).get('/api/posts/').query '$regexi_string':'tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) request(@app).get('/api/posts/').query '$regexi_string':'Tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should work with $exists', (done) -> @endpoint.allowQueryParam(['otherField.*']).register(@app) request(@app).get('/api/posts/').query 'otherField.foo':'$exists' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) request(@app).get('/api/posts/').query 'otherField.bar':'$exists' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) done() describe 'Populate', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' comment = new (mongoose.model('Comment'))() comment._post = mod._id comment.comment = 'Asdf1234' comment.otherField = 5 mod._comments = [comment._id] @mod = mod Q.all([mod.save(), comment.save()]).then -> done() .fail(done).done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should return populated data', (done) -> @endpoint.populate('_comments').register(@app) request(@app).get('/api/posts/').end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(1) res.body[0]._comments.length.should.equal(1) res.body[0]._comments[0].comment.should.equal('Asdf1234') done() describe 'Pagination', -> beforeEach (done) -> # set up endpoints @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) # Create a whole bunch of posts data = [ date:moment().add('days', 26).toDate() number:13 string:'a' , date:moment().add('days', 25).toDate() number:17 string:'c' , date:moment().add('days', 24).toDate() number:12 string:'f' , date:moment().add('days', 20).toDate() number:50 string:'z' ] promises = [] for post in data promises.push(createPost(post)) Q.all(promises).then => new mre('/api/posts', 'Post').paginate(2, 'string') .register(@app) done() afterEach (done) -> # clear out mongoose.connection.collections.posts.drop() done() it 'should give paginated results by default', (done) -> request(@app).get('/api/posts').end (err, res) -> res.body.length.should.equal(2) res.body[0].string.should.equal('a') res.body[1].string.should.equal('c') done() it 'should give you the total results in the header', (done) -> request(@app).get('/api/posts').end (err, res) -> res.header['record-count'].should.equal('4') done() it 'should take your custom pagination parameters', (done) -> request(@app).get('/api/posts').query page:2 perPage:1 sortField:'-number' .end (err, res) -> res.body.length.should.equal(1) res.body[0].string.should.equal('c') done() it 'should sort by date too!', (done) -> request(@app).get('/api/posts').query page:1 perPage:2 sortField:'date' .end (err, res) -> res.body.length.should.equal(2) res.body[0].string.should.equal('z') done() describe 'Deep querying', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' foo: bar:6 mod.save (err, res) => @mod = res done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should allow deep querying', (done) -> @endpoint.allowQueryParam(['foo.bar']).register(@app) request(@app).get('/api/posts/').query 'foo.bar':7 .end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(0) done() describe 'Alternator bug', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' foo: bar:6 mod.save (err, res) => @mod = res done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should allow deep querying', (done) -> @endpoint.tap 'pre_filter', 'list', (req, data, next) -> data.number = 6 console.log 'Set number to 6' next(data) .register(@app) request(@app).get('/api/posts/').end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(0) done()
124457
express = require 'express' bodyParser = require 'body-parser' methodOverride = require 'method-override' request = require 'supertest' should = require 'should' Q = require 'q' mongoose = require 'mongoose' require('../lib/log').verbose(true) moment = require 'moment' mre = require '../lib/endpoint' # Custom "Post" and "Comment" documents commentSchema = new mongoose.Schema comment:String _post: type:mongoose.Schema.Types.ObjectId ref:'Post' _author: type:mongoose.Schema.Types.ObjectId ref:'Author' postSchema = new mongoose.Schema date:Date number:Number string: type:String required:true _comments:[ type:mongoose.Schema.Types.ObjectId ref:'Comment' $through:'_post' ] foo: bar:Number otherField:mongoose.Schema.Types.Mixed authorSchema = new mongoose.Schema name:'String' # Custom middleware for testing requirePassword = (password) -> return (req, res, next) -> if req.query.password and req.query.password is password next() else res.send(401) createPost = (data) -> deferred = Q.defer() postClass = mongoose.model('Post') post = new postClass(data) post.save (err, res) -> if err return deferred.reject(err) return deferred.resolve() return deferred.promise mongoUrlCreds = if process.env.MONGO_USERNAME then "#{process.env.MONGO_USERNAME}:#{process.env.MONGO_PASSWORD}@" else "" mongoose.connect("mongodb://#{mongoUrlCreds}#{process.env.MONGO_HOST}/mre_test") mongoose.model('Post', postSchema) mongoose.model('Comment', commentSchema) mongoose.model('Author', authorSchema) mongoose.set 'debug', true describe 'List', -> describe 'Basics', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' otherField: foo:'bar' mod.save (err, res) => @mod = res done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should retrieve with no hooks', (done) -> @endpoint.register(@app) request(@app).get('/api/posts/').end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(1) res.body[0].number.should.equal(5) res.body[0].string.should.equal('Test') done() it 'should allow through with middleware', (done) -> @endpoint.addMiddleware('list', requirePassword('asdf')).register(@app) request(@app).get('/api/posts').query password:'<PASSWORD>' .end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should prevent on bad middleware', (done) -> @endpoint.addMiddleware('list', requirePassword('asdf')).register(@app) request(@app).get('/api/posts').query password:'<PASSWORD>' .end (err, res) -> res.status.should.equal(401) done() it 'should fetch only specified fields', (done) -> @endpoint.limitFields(['string', 'date']).register(@app) request(@app).get('/api/posts').end (err, res) -> res.body.length.should.equal(1) res.body[0].string.should.equal('Test') should.not.exist(res.body[0].number) done() it 'should work with default query hook', (done) -> @endpoint.allowQueryParam(['$gte_number', '$lte_number', '$gte_date', '$lte_date']).register(@app) request(@app).get('/api/posts/').query '$gte_number':6 .end (err, res) => console.log res.body res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').query '$lte_number':6 .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) request(@app).get('/api/posts/').query '$gte_date':moment().add('day', 1).toDate() .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').query '$lte_date':moment().add('day', 1).toDate() .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should work with pre_response hook', (done) -> @endpoint.tap 'pre_response', 'list', (req, collection, next) -> for col in collection col.number = 10 next(collection) .register(@app) request(@app).get('/api/posts/').end (err, res) => res.body.length.should.equal(1) res.body[0].number.should.equal(10) done() it 'should do a regex search', (done) -> @endpoint.allowQueryParam('$regex_string').register(@app) request(@app).get('/api/posts/').query '$regex_string':'tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').query '$regex_string':'Tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should do a case insensitive regex search', (done) -> @endpoint.allowQueryParam('$regexi_string').register(@app) request(@app).get('/api/posts/').query '$regexi_string':'tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) request(@app).get('/api/posts/').query '$regexi_string':'Tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should work with $exists', (done) -> @endpoint.allowQueryParam(['otherField.*']).register(@app) request(@app).get('/api/posts/').query 'otherField.foo':'$exists' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) request(@app).get('/api/posts/').query 'otherField.bar':'$exists' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) done() describe 'Populate', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' comment = new (mongoose.model('Comment'))() comment._post = mod._id comment.comment = '<PASSWORD>1234' comment.otherField = 5 mod._comments = [comment._id] @mod = mod Q.all([mod.save(), comment.save()]).then -> done() .fail(done).done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should return populated data', (done) -> @endpoint.populate('_comments').register(@app) request(@app).get('/api/posts/').end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(1) res.body[0]._comments.length.should.equal(1) res.body[0]._comments[0].comment.should.equal('Asdf1234') done() describe 'Pagination', -> beforeEach (done) -> # set up endpoints @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) # Create a whole bunch of posts data = [ date:moment().add('days', 26).toDate() number:13 string:'a' , date:moment().add('days', 25).toDate() number:17 string:'c' , date:moment().add('days', 24).toDate() number:12 string:'f' , date:moment().add('days', 20).toDate() number:50 string:'z' ] promises = [] for post in data promises.push(createPost(post)) Q.all(promises).then => new mre('/api/posts', 'Post').paginate(2, 'string') .register(@app) done() afterEach (done) -> # clear out mongoose.connection.collections.posts.drop() done() it 'should give paginated results by default', (done) -> request(@app).get('/api/posts').end (err, res) -> res.body.length.should.equal(2) res.body[0].string.should.equal('a') res.body[1].string.should.equal('c') done() it 'should give you the total results in the header', (done) -> request(@app).get('/api/posts').end (err, res) -> res.header['record-count'].should.equal('4') done() it 'should take your custom pagination parameters', (done) -> request(@app).get('/api/posts').query page:2 perPage:1 sortField:'-number' .end (err, res) -> res.body.length.should.equal(1) res.body[0].string.should.equal('c') done() it 'should sort by date too!', (done) -> request(@app).get('/api/posts').query page:1 perPage:2 sortField:'date' .end (err, res) -> res.body.length.should.equal(2) res.body[0].string.should.equal('z') done() describe 'Deep querying', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' foo: bar:6 mod.save (err, res) => @mod = res done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should allow deep querying', (done) -> @endpoint.allowQueryParam(['foo.bar']).register(@app) request(@app).get('/api/posts/').query 'foo.bar':7 .end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(0) done() describe 'Alternator bug', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' foo: bar:6 mod.save (err, res) => @mod = res done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should allow deep querying', (done) -> @endpoint.tap 'pre_filter', 'list', (req, data, next) -> data.number = 6 console.log 'Set number to 6' next(data) .register(@app) request(@app).get('/api/posts/').end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(0) done()
true
express = require 'express' bodyParser = require 'body-parser' methodOverride = require 'method-override' request = require 'supertest' should = require 'should' Q = require 'q' mongoose = require 'mongoose' require('../lib/log').verbose(true) moment = require 'moment' mre = require '../lib/endpoint' # Custom "Post" and "Comment" documents commentSchema = new mongoose.Schema comment:String _post: type:mongoose.Schema.Types.ObjectId ref:'Post' _author: type:mongoose.Schema.Types.ObjectId ref:'Author' postSchema = new mongoose.Schema date:Date number:Number string: type:String required:true _comments:[ type:mongoose.Schema.Types.ObjectId ref:'Comment' $through:'_post' ] foo: bar:Number otherField:mongoose.Schema.Types.Mixed authorSchema = new mongoose.Schema name:'String' # Custom middleware for testing requirePassword = (password) -> return (req, res, next) -> if req.query.password and req.query.password is password next() else res.send(401) createPost = (data) -> deferred = Q.defer() postClass = mongoose.model('Post') post = new postClass(data) post.save (err, res) -> if err return deferred.reject(err) return deferred.resolve() return deferred.promise mongoUrlCreds = if process.env.MONGO_USERNAME then "#{process.env.MONGO_USERNAME}:#{process.env.MONGO_PASSWORD}@" else "" mongoose.connect("mongodb://#{mongoUrlCreds}#{process.env.MONGO_HOST}/mre_test") mongoose.model('Post', postSchema) mongoose.model('Comment', commentSchema) mongoose.model('Author', authorSchema) mongoose.set 'debug', true describe 'List', -> describe 'Basics', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' otherField: foo:'bar' mod.save (err, res) => @mod = res done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should retrieve with no hooks', (done) -> @endpoint.register(@app) request(@app).get('/api/posts/').end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(1) res.body[0].number.should.equal(5) res.body[0].string.should.equal('Test') done() it 'should allow through with middleware', (done) -> @endpoint.addMiddleware('list', requirePassword('asdf')).register(@app) request(@app).get('/api/posts').query password:'PI:PASSWORD:<PASSWORD>END_PI' .end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should prevent on bad middleware', (done) -> @endpoint.addMiddleware('list', requirePassword('asdf')).register(@app) request(@app).get('/api/posts').query password:'PI:PASSWORD:<PASSWORD>END_PI' .end (err, res) -> res.status.should.equal(401) done() it 'should fetch only specified fields', (done) -> @endpoint.limitFields(['string', 'date']).register(@app) request(@app).get('/api/posts').end (err, res) -> res.body.length.should.equal(1) res.body[0].string.should.equal('Test') should.not.exist(res.body[0].number) done() it 'should work with default query hook', (done) -> @endpoint.allowQueryParam(['$gte_number', '$lte_number', '$gte_date', '$lte_date']).register(@app) request(@app).get('/api/posts/').query '$gte_number':6 .end (err, res) => console.log res.body res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').query '$lte_number':6 .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) request(@app).get('/api/posts/').query '$gte_date':moment().add('day', 1).toDate() .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').query '$lte_date':moment().add('day', 1).toDate() .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should work with pre_response hook', (done) -> @endpoint.tap 'pre_response', 'list', (req, collection, next) -> for col in collection col.number = 10 next(collection) .register(@app) request(@app).get('/api/posts/').end (err, res) => res.body.length.should.equal(1) res.body[0].number.should.equal(10) done() it 'should do a regex search', (done) -> @endpoint.allowQueryParam('$regex_string').register(@app) request(@app).get('/api/posts/').query '$regex_string':'tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').query '$regex_string':'Tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should do a case insensitive regex search', (done) -> @endpoint.allowQueryParam('$regexi_string').register(@app) request(@app).get('/api/posts/').query '$regexi_string':'tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) request(@app).get('/api/posts/').query '$regexi_string':'Tes' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) done() it 'should work with $exists', (done) -> @endpoint.allowQueryParam(['otherField.*']).register(@app) request(@app).get('/api/posts/').query 'otherField.foo':'$exists' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(1) request(@app).get('/api/posts/').query 'otherField.bar':'$exists' .end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) done() describe 'Populate', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' comment = new (mongoose.model('Comment'))() comment._post = mod._id comment.comment = 'PI:PASSWORD:<PASSWORD>END_PI1234' comment.otherField = 5 mod._comments = [comment._id] @mod = mod Q.all([mod.save(), comment.save()]).then -> done() .fail(done).done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should return populated data', (done) -> @endpoint.populate('_comments').register(@app) request(@app).get('/api/posts/').end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(1) res.body[0]._comments.length.should.equal(1) res.body[0]._comments[0].comment.should.equal('Asdf1234') done() describe 'Pagination', -> beforeEach (done) -> # set up endpoints @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) # Create a whole bunch of posts data = [ date:moment().add('days', 26).toDate() number:13 string:'a' , date:moment().add('days', 25).toDate() number:17 string:'c' , date:moment().add('days', 24).toDate() number:12 string:'f' , date:moment().add('days', 20).toDate() number:50 string:'z' ] promises = [] for post in data promises.push(createPost(post)) Q.all(promises).then => new mre('/api/posts', 'Post').paginate(2, 'string') .register(@app) done() afterEach (done) -> # clear out mongoose.connection.collections.posts.drop() done() it 'should give paginated results by default', (done) -> request(@app).get('/api/posts').end (err, res) -> res.body.length.should.equal(2) res.body[0].string.should.equal('a') res.body[1].string.should.equal('c') done() it 'should give you the total results in the header', (done) -> request(@app).get('/api/posts').end (err, res) -> res.header['record-count'].should.equal('4') done() it 'should take your custom pagination parameters', (done) -> request(@app).get('/api/posts').query page:2 perPage:1 sortField:'-number' .end (err, res) -> res.body.length.should.equal(1) res.body[0].string.should.equal('c') done() it 'should sort by date too!', (done) -> request(@app).get('/api/posts').query page:1 perPage:2 sortField:'date' .end (err, res) -> res.body.length.should.equal(2) res.body[0].string.should.equal('z') done() describe 'Deep querying', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' foo: bar:6 mod.save (err, res) => @mod = res done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should allow deep querying', (done) -> @endpoint.allowQueryParam(['foo.bar']).register(@app) request(@app).get('/api/posts/').query 'foo.bar':7 .end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(0) done() describe 'Alternator bug', -> beforeEach (done) -> @endpoint = new mre('/api/posts', 'Post') @app = express() @app.use(bodyParser.urlencoded({extended: true})) @app.use(bodyParser.json()) @app.use(methodOverride()) modClass = mongoose.model('Post') mod = modClass date:Date.now() number:5 string:'Test' foo: bar:6 mod.save (err, res) => @mod = res done() afterEach (done) -> @mod.remove (err, res) -> done() it 'should allow deep querying', (done) -> @endpoint.tap 'pre_filter', 'list', (req, data, next) -> data.number = 6 console.log 'Set number to 6' next(data) .register(@app) request(@app).get('/api/posts/').end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').end (err, res) => res.status.should.equal(200) res.body.length.should.equal(0) request(@app).get('/api/posts/').end (err, res) -> res.status.should.equal(200) res.body.length.should.equal(0) done()
[ { "context": " /> \n <input type=\"hidden\" name=\"business\" value=\"mooneer@gmail.com\" /> \n <input type=\"hidden\" name=\"lc\" value=\"US\" /", "end": 4911, "score": 0.9999188184738159, "start": 4894, "tag": "EMAIL", "value": "mooneer@gmail.com" } ]
src/main/coffee/main.coffee
tmiw/newsrdr
9
if not @NR? NR = exports? and exports or @NR = {} else NR = @NR class NR.Application extends SimpleMVC.Controller _processFeedPosts: (data) => for i in data post = new NR.Models.NewsFeedArticleInfo for k,v of i post[k] = v if k == "article" v.titleEmpty = !v.title this.articleList.add post _apiError: (type, desc, data) => errorText = "Communications error with the server. Please try again." switch type when NR.API.AuthenticationFailed then location.reload() when NR.API.ServerError if desc == NR.API.NotAFeedError this._createFeedView = new NR.Views.CreateFeedWindow feedModel = new NR.Models.CreateFeedModel feedModel.baseHtml = data feedModel.baseUrl = $("#addFeedUrl").val() this._createFeedView.model = feedModel this._createFeedView.show() else if desc == NR.API.MultipleFeedsFoundError foundList = new SimpleMVC.Collection this._multipleFeedFoundView = new NR.Views.MultipleFeedsFoundWindow foundList this._multipleFeedFoundView.show() for i in data entry = new NR.Models.MultipleFeedEntry entry.title = i.title entry.url = i.url foundList.add entry else errorText = "The server encountered an error while processing the request. Please try again." if desc != NR.API.NotAFeedError && desc != NR.API.MultipleFeedsFoundError noty({ text: errorText, layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }); @route "saved/:uid", (uid) -> this._uid = uid this._savedPostsMode = true this._postPage = 1 this._maxId = "" this.newsArticleView.show() @route "news/:uid/feeds/add", (uid) -> this._uid = uid $("#addFeedUrl").val(this.urlParams["url"]) $("#addFeed").on("shown.bs.modal", () -> $("#addFeedUrl").focus()) $("#addFeed").on("hidden.bs.modal", () => # return to original page if this._fid this.navigate("/news/" + this._uid + "/feeds/" + this._fid) else if this._fid == 0 this.navigate("/news/" + this._uid + "/feeds") else this.navigate("/news/" + this._uid)) $("#addFeed").modal() @route "news/:uid/feeds/:fid", (uid, fid) -> index = this.feedList.any((i) -> i.id.toString() == fid.toString()) if index >= 0 this._uid = uid this._fid = fid this._maxId = "" this._postPage = 0 this._seenUnread = 0 this._enableFetch = true this.currentArticle = -1 # Specific feed listing. this.newsArticleView.show() this.articleList.reset() this.welcomeView.hide() # Get posts from server this.fetchMorePosts() # Update nav elements. feed = this.feedList.at index this.newsFeedView.feedSelected fid this.topNavView.feedSelected feed true else false @route "news/:uid/feeds", (uid) -> this._uid = uid this._fid = 0 this._postPage = 0 this._seenUnread = 0 this._maxId = "" this._enableFetch = true this.currentArticle = -1 # "All Feeds" listing. this.newsArticleView.show() this.articleList.reset() this.welcomeView.hide() # Get posts from server this.fetchMorePosts() # Update nav elements. this.newsFeedView.allFeedsSelected() this.topNavView.allFeedsSelected() @route "news/:uid", (uid) -> this._uid = uid this._fid = null this._maxId = "" this.currentArticle = -1 # Hide articles. this.newsArticleView.hide() this.articleList.reset() this.welcomeView.show() # Update nav elements. this.newsFeedView.homeSelected() this.topNavView.homeSelected() _adblocked: () -> $("#ad-body").html('<div class="sponsor_content"> <center> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"> <span>newsrdr relies on your support.</span> <input type="hidden" name="cmd" value="_donations" /> <input type="hidden" name="business" value="mooneer@gmail.com" /> <input type="hidden" name="lc" value="US" /> <input type="hidden" name="no_note" value="0" /> <input type="hidden" name="currency_code" value="USD" /> <input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHostedGuest" /> <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" valign="center" style="display: inline;" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" /> <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1" /> </form> </center> </div>') submitUpdateProfileBox: () => good = false if event? event.preventDefault() if $('#profileEmail').val().length == 0 noty({ text: "Email is required.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else if !$('#profileEmail').val().match(/^[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+@[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+/) noty({ text: "Email address is invalid.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else if $('#profilePassword').val().length > 0 if $('#profilePassword').val().length < 8 noty({ text: "Password must be at least eight characters long.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else if $('#profilePassword').val() != $('#profilePassword2').val() noty({ text: "Both passwords must match in order to reset your password.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else good = true else good = true if good == true successWrapper = (data) => noty({ text: "Profile updated.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "success" }) this.profileModel.email = $('#profileEmail').val() NR.API.UpdateProfile( $('#profileEmail').val(), $('#profilePassword').val(), $('#profilePassword2').val(), successWrapper, this._apiError) $("#updateProfile").modal('hide') submitAddFeedBox: => if event? event.preventDefault() if $('#addFeedUrl').val().length > 0 this.addFeed($('#addFeedUrl').val()) $('#addFeed').modal('hide') navigate: (uri, executeFn = false, addState = true) => ret = super uri, executeFn, addState $("#ad-body").html("<!-- newsrdr-new-site --> <div id='div-gpt-ad-1379655552510-0' style='width:728px; height:90px;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.defineSlot('/70574502/newsrdr-new-site', [728, 90], 'div-gpt-ad-1379655552510-0').addService(googletag.pubads()); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); googletag.cmd.push(function() { googletag.display('div-gpt-ad-1379655552510-0'); }); </script> </div>") # Detect adblock and perform countermeasures setTimeout(() => if ($("#ad-body div iframe").length == 0) this._adblocked(); , 1000); ret _modalVisible: -> $(".modal[aria-hidden!='true']").length > 0 _handlePostKeys: (e) => kc = e.keyCode || e.charCode # Scroll up/down one article. if this.articleList? && this.articleList.length > 0 if ((kc == 75 || kc == 107) && this.currentArticle?) # Mark as read only if we are scrolling downward. this.currentArticle = this.currentArticle - 1 else if ((kc == 74 || kc == 106) && this.currentArticle <= this.articleList.length - 1) article = this.articleList.at this.currentArticle if this.authedUser && article? && article.unread # Mark current article as read before proceeding. this.togglePostAsRead article this.currentArticle = this.currentArticle + 1 if not this.currentArticle || this.currentArticle < 0 this.currentArticle = 0 else if this.currentArticle == this.articleList.length - 1 this.fetchMorePosts() else if this.currentArticle > this.articleList.length - 1 this.currentArticle = this.articleList.length - 1 scrollToBottom = true $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle:eq(" + this.currentArticle + ") .article-panel").addClass "selected-article" newArticle = this.articleList.at this.currentArticle newArticleId = newArticle.article.id; newArticleOffset = $("a[name='article" + newArticleId + "']").offset() if scrollToBottom newArticleOffset = $("a[name='bottom']").offset() this.scrollDisabled = true objSelf = this $(window).off("scroll", this._onScrollFn) doneFn = () -> objSelf.scrollDisabled = false $(window).scroll(objSelf._onScrollFn) $('html, body').animate({ scrollTop: newArticleOffset.top - 130 }, 500, "swing", () -> doneFn()) e.preventDefault() _handleFeedKeys: (e) => kc = e.keyCode || e.charCode if this.newsFeedView.canNavigateDownList() && (kc == 115 || kc == 83) # s/S (navigate down list) initUrl = "/news/" + this._uid + "/feeds" nextFeed = this.newsFeedView.getNextFeed() if nextFeed > 0 initUrl = initUrl + "/" + nextFeed this.navigate initUrl, true else if this.newsFeedView.canNavigateUpList() && (kc == 119 || kc == 87) # w/W (navigate up list) initUrl = "/news/" + this._uid nextFeed = this.newsFeedView.getPrevFeed() if nextFeed? && nextFeed >= 0 initUrl = initUrl + "/feeds" if nextFeed > 0 initUrl = initUrl + "/" + nextFeed this.navigate initUrl, true e.preventDefault() _handleOpenArticleKeys: (e) => if this.articleList? && this.articleList.length > 0 if !this.currentArticle? || this.currentArticle < 0 || this.currentArticle >= this.articleList.length this.currentArticle = 0 article = this.articleList.at this.currentArticle articleId = article.article.id; articleOffset = $("a[name='article" + articleId + "']").offset() e.preventDefault() window.open article.article.link, "_blank" if this.authedUser && article? && article.unread this.togglePostAsRead article this.currentArticle = this.currentArticle + 1 if not this.currentArticle || this.currentArticle < 0 this.currentArticle = 0 else if this.currentArticle == this.articleList.length - 1 this.fetchMorePosts() else if this.currentArticle > this.articleList.length - 1 this.currentArticle = this.articleList.length - 1 scrollToBottom = true $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle:eq(" + this.currentArticle + ") .article-panel").addClass "selected-article" newArticle = this.articleList.at this.currentArticle newArticleId = newArticle.article.id; newArticleOffset = $("a[name='article" + newArticleId + "']").offset() if scrollToBottom newArticleOffset = $("a[name='bottom']").offset() this.scrollDisabled = true objSelf = this $(window).off("scroll", this._onScrollFn) doneFn = () -> objSelf.scrollDisabled = false $(window).scroll(objSelf._onScrollFn) $('html, body').animate({ scrollTop: newArticleOffset.top - 130 }, 500, "swing", () -> doneFn()) _initializeKeyboardNavigation: -> # Set up keyboard navigation $(window).keypress (e) => if not this._modalVisible() kc = e.keyCode || e.charCode if (kc == 74 || kc == 75 || kc == 106 || kc == 107) # j/k/J/K (post navigation) this._handlePostKeys e else if (kc == 63) # ? (help) e.preventDefault() $("#keyboardHelp").modal("show") else if (kc == 119 || kc == 87 || kc == 115 || kc == 83) # w/W/s/S (feed navigation) this._handleFeedKeys e else if (kc == 114 || kc == 82) # r/R (mark all as read) e.preventDefault() this.markAllRead() else if (kc == 100 || kc == 68) # d/D (deletes current feed) e.preventDefault() if not $("#removeFeedLink").parent().hasClass("disabled") $("#removeFeedConfirm").modal() else if (kc == 97 || kc == 65) # a/A (add new feed) e.preventDefault() this.showAddFeedWindow() else if (kc == 79 || kc == 111) # o/O (open current article in new window) this._handleOpenArticleKeys e constructor: (bootstrappedFeeds, bootstrappedPosts, optedOut, suppressLeftAndTop, email = "") -> super() NR.API.Initialize() this._initializeKeyboardNavigation() # Initialize scroll handler (to enable "where you left off" scrolling if you're # switching between keyboard navigation and mouse navigation) objSelf = this this._onScrollFn = () -> clearTimeout($.data(this, 'scrollTimer')); $.data(this, 'scrollTimer', setTimeout(() -> if not objSelf.scrollDisabled scrollTop = $(window).scrollTop() windowHeight = $(window).height() first = false index = 0 $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle .article-panel").each(() -> offset = $(this).offset() if (scrollTop + 130) <= (offset.top + $(this).height()) and first == false first = true objSelf.currentArticle = index $(this).addClass "selected-article" index = index + 1 ) )) $(window).scroll(this._onScrollFn) this.authedUser = not suppressLeftAndTop this.feedList = new SimpleMVC.Collection this.articleList = new SimpleMVC.Collection this.localSettings = new NR.Models.HtmlLocalStorage this.localSettings.optedOut = optedOut if not suppressLeftAndTop this.profileModel = new NR.Models.ProfileModel this.profileModel.email = email this.topNavView = new NR.Views.TopNavBar this.topNavView.model = this.localSettings this.welcomeView = new NR.Views.WelcomeBlock this.newsFeedView = new NR.Views.NewsFeedListing this.feedList if email != "" $("#updateProfileLink").parent().removeClass "disabled" for i in bootstrappedFeeds feed = new NR.Models.NewsFeedInfo for k,v of i feed[k] = v this.feedList.add feed # Set up timer for feed updates (every 5min). setInterval this.updateFeeds, 1000*60*5 # Restart feed import as needed if this.localSettings.importQueue? && this.localSettings.importQueue.length > 0 this._beginFeedImport() this.newsArticleView = new NR.Views.NewsArticleListing this.articleList for i in bootstrappedPosts post = new NR.Models.NewsFeedArticleInfo for k,v of i post[k] = v this.articleList.add post selectAllFeeds: () => this.navigate "/news/" + this._uid + "/feeds", true selectFeed: (feed) => this.navigate "/news/" + this._uid + "/feeds/" + feed.id, true deselectFeed: () => this.navigate "/news/" + this._uid, true showAddFeedWindow: () => this.navigate "/news/" + this._uid + "/feeds/add", true removeCurrentFeed: () => currentFeed = this._fid NR.API.RemoveFeed this._fid, () => index = this.feedList.any((i) -> i.id.toString() == currentFeed.toString()) this.feedList.removeAt index this.navigate "/news/" + this._uid + "/feeds", true addFeed: (url) => NR.API.AddFeed url, (data) => feed = new NR.Models.NewsFeedInfo for k,v of data feed[k] = v if this.feedList.any((i) -> i.id == feed.id) == -1 this.feedList.add feed this.selectFeed feed , this._apiError markAllRead: () => successFn = (data) => this.articleList.reset() this.updateFeeds() this._enableFetch = true this._maxId = "" this._postPage = 0 this._seenUnread = 0 this.fetchMorePosts() if this._fid > 0 NR.API.MarkAllFeedPostsAsRead this._fid, 0, Date.parse(this.articleList.at(0).article.pubDate) / 1000, successFn, this._apiError else NR.API.MarkAllPostsAsRead 0, Date.parse(this.articleList.at(0).article.pubDate) / 1000, successFn, this._apiError importSingleFeed: () => nextImport = () => this.localSettings.importQueue.shift() this.localSettings.feedsImported = this.localSettings.feedsImported + 1 if this.localSettings.importQueue.length > 0 # import next feed window.setTimeout this.importSingleFeed, 0 else # all done noty({ text: "Import complete.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "success" }); this.localSettings.importQueue = [] # Unlike addFeed above, we're ignoring errors from the server. NR.API.AddFeed this.localSettings.importQueue[0], (data) => feed = new NR.Models.NewsFeedInfo for k,v of data feed[k] = v if this.feedList.any((i) -> i.id == feed.id) == -1 this.feedList.add feed nextImport.call(this) , nextImport.bind(this) _beginFeedImport: () => noty({ text: "Feed import has begun.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "information" }); window.setTimeout this.importSingleFeed, 0 fetchMorePosts: => errorWrapper = (type, desc) => this._enableFetch = true this._apiError type, desc successWrapper = (data) => if data.list.length > 0 this._enableFetch = true this._maxId = data.id this._postPage = this._postPage + 1 this._processFeedPosts data.list if this.currentArticle < 0 this.currentArticle = 0 $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle:eq(" + this.currentArticle + ") .article-panel").addClass "selected-article" if not this._lastSeenUnread? this._lastSeenUnread = this._seenUnread if this._postPage > 0 lastArticleId = Date.parse(this.articleList.at(this.articleList.length - 1).article.pubDate) / 1000 else lastArticleId = "" if this._enableFetch this._enableFetch = false if this._fid > 0 NR.API.GetPostsForFeed( this._fid, 0, lastArticleId, this._maxId, this.localSettings.showOnlyUnread, successWrapper, errorWrapper) else if this._savedPostsMode NR.API.GetSavedPosts( this._uid, 0, lastArticleId, this._maxId, successWrapper, errorWrapper) else NR.API.GetAllPosts( 0, lastArticleId, this._maxId, this.localSettings.showOnlyUnread, successWrapper, errorWrapper) togglePostAsRead: (article) => if article.unread NR.API.MarkPostAsRead article.article.id, (data) => article.unread = false if article.feed.numUnread > 0 article.feed.numUnread = article.feed.numUnread - 1 this.newsFeedView.sort() , this._apiError else NR.API.MarkPostAsUnread article.article.id, (data) => article.unread = true article.feed.numUnread = article.feed.numUnread + 1 this.newsFeedView.sort() , this._apiError toggleSavePost: (article) => if article.saved NR.API.UnsavePost article.feed.id, article.article.id, (data) => article.saved = false , this._apiError else NR.API.SavePost article.feed.id, article.article.id, (data) => article.saved = true , this._apiError finishedUploadingFeedList: (result) => if (!result.success) errorText = "Error encountered while uploading file." if (result.error_string == "forgot_file") errorText = "Please select a file and try again." else if (result.error_string == "cant_parse") errorText = "The file provided is not a valid OPML file. Select another file and try again." else if (result.error_string == "not_authorized") # Force user to login screen. location.reload(); else if (result.error_string == "too_big") errorText = "The file provided is too big to be parsed. Select another file and try again." noty({ text: errorText, layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }); else $('#importFeeds').modal('hide') # Queue up feeds for processing. this.localSettings.importQueue = result.feeds this.localSettings.feedsImported = 0 this._beginFeedImport() toggleShowUnread: () => this.localSettings.showOnlyUnread = !this.localSettings.showOnlyUnread this.articleList.reset() if this._fid? this._postPage = 0 this._seenUnread = 0 this._maxId = "" this._enableFetch = true this.fetchMorePosts() toggleOptOut: => NR.API.OptOutSharing (not this.localSettings.optedOut), () => this.localSettings.optedOut = not this.localSettings.optedOut , this._apiError updateFeeds: => NR.API.GetFeeds (feeds) => # Disable sorting until the very end for performance. this.newsFeedView.disableSort() for i in feeds feed = new NR.Models.NewsFeedInfo for k,v of i feed[k] = v index = this.feedList.any (x) -> feed.id == x.id if index >= 0 # Don't use Collection#replace so we can maintain active state. other = this.feedList.at index other.feed = feed.feed other.id = feed.id other.numUnread = feed.numUnread other.errorsUpdating = feed.errorsUpdating else this.feedList.add feed # Remove feeds that no longer exist. toRemove = [] this.feedList.each (i) -> found = false for j in feeds if i.id == j.id found = true if not found toRemove.push i for k in toRemove this.feedList.remove k # Reenable sorting. this.newsFeedView.enableSort() , this._apiError
71989
if not @NR? NR = exports? and exports or @NR = {} else NR = @NR class NR.Application extends SimpleMVC.Controller _processFeedPosts: (data) => for i in data post = new NR.Models.NewsFeedArticleInfo for k,v of i post[k] = v if k == "article" v.titleEmpty = !v.title this.articleList.add post _apiError: (type, desc, data) => errorText = "Communications error with the server. Please try again." switch type when NR.API.AuthenticationFailed then location.reload() when NR.API.ServerError if desc == NR.API.NotAFeedError this._createFeedView = new NR.Views.CreateFeedWindow feedModel = new NR.Models.CreateFeedModel feedModel.baseHtml = data feedModel.baseUrl = $("#addFeedUrl").val() this._createFeedView.model = feedModel this._createFeedView.show() else if desc == NR.API.MultipleFeedsFoundError foundList = new SimpleMVC.Collection this._multipleFeedFoundView = new NR.Views.MultipleFeedsFoundWindow foundList this._multipleFeedFoundView.show() for i in data entry = new NR.Models.MultipleFeedEntry entry.title = i.title entry.url = i.url foundList.add entry else errorText = "The server encountered an error while processing the request. Please try again." if desc != NR.API.NotAFeedError && desc != NR.API.MultipleFeedsFoundError noty({ text: errorText, layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }); @route "saved/:uid", (uid) -> this._uid = uid this._savedPostsMode = true this._postPage = 1 this._maxId = "" this.newsArticleView.show() @route "news/:uid/feeds/add", (uid) -> this._uid = uid $("#addFeedUrl").val(this.urlParams["url"]) $("#addFeed").on("shown.bs.modal", () -> $("#addFeedUrl").focus()) $("#addFeed").on("hidden.bs.modal", () => # return to original page if this._fid this.navigate("/news/" + this._uid + "/feeds/" + this._fid) else if this._fid == 0 this.navigate("/news/" + this._uid + "/feeds") else this.navigate("/news/" + this._uid)) $("#addFeed").modal() @route "news/:uid/feeds/:fid", (uid, fid) -> index = this.feedList.any((i) -> i.id.toString() == fid.toString()) if index >= 0 this._uid = uid this._fid = fid this._maxId = "" this._postPage = 0 this._seenUnread = 0 this._enableFetch = true this.currentArticle = -1 # Specific feed listing. this.newsArticleView.show() this.articleList.reset() this.welcomeView.hide() # Get posts from server this.fetchMorePosts() # Update nav elements. feed = this.feedList.at index this.newsFeedView.feedSelected fid this.topNavView.feedSelected feed true else false @route "news/:uid/feeds", (uid) -> this._uid = uid this._fid = 0 this._postPage = 0 this._seenUnread = 0 this._maxId = "" this._enableFetch = true this.currentArticle = -1 # "All Feeds" listing. this.newsArticleView.show() this.articleList.reset() this.welcomeView.hide() # Get posts from server this.fetchMorePosts() # Update nav elements. this.newsFeedView.allFeedsSelected() this.topNavView.allFeedsSelected() @route "news/:uid", (uid) -> this._uid = uid this._fid = null this._maxId = "" this.currentArticle = -1 # Hide articles. this.newsArticleView.hide() this.articleList.reset() this.welcomeView.show() # Update nav elements. this.newsFeedView.homeSelected() this.topNavView.homeSelected() _adblocked: () -> $("#ad-body").html('<div class="sponsor_content"> <center> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"> <span>newsrdr relies on your support.</span> <input type="hidden" name="cmd" value="_donations" /> <input type="hidden" name="business" value="<EMAIL>" /> <input type="hidden" name="lc" value="US" /> <input type="hidden" name="no_note" value="0" /> <input type="hidden" name="currency_code" value="USD" /> <input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHostedGuest" /> <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" valign="center" style="display: inline;" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" /> <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1" /> </form> </center> </div>') submitUpdateProfileBox: () => good = false if event? event.preventDefault() if $('#profileEmail').val().length == 0 noty({ text: "Email is required.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else if !$('#profileEmail').val().match(/^[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+@[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+/) noty({ text: "Email address is invalid.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else if $('#profilePassword').val().length > 0 if $('#profilePassword').val().length < 8 noty({ text: "Password must be at least eight characters long.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else if $('#profilePassword').val() != $('#profilePassword2').val() noty({ text: "Both passwords must match in order to reset your password.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else good = true else good = true if good == true successWrapper = (data) => noty({ text: "Profile updated.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "success" }) this.profileModel.email = $('#profileEmail').val() NR.API.UpdateProfile( $('#profileEmail').val(), $('#profilePassword').val(), $('#profilePassword2').val(), successWrapper, this._apiError) $("#updateProfile").modal('hide') submitAddFeedBox: => if event? event.preventDefault() if $('#addFeedUrl').val().length > 0 this.addFeed($('#addFeedUrl').val()) $('#addFeed').modal('hide') navigate: (uri, executeFn = false, addState = true) => ret = super uri, executeFn, addState $("#ad-body").html("<!-- newsrdr-new-site --> <div id='div-gpt-ad-1379655552510-0' style='width:728px; height:90px;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.defineSlot('/70574502/newsrdr-new-site', [728, 90], 'div-gpt-ad-1379655552510-0').addService(googletag.pubads()); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); googletag.cmd.push(function() { googletag.display('div-gpt-ad-1379655552510-0'); }); </script> </div>") # Detect adblock and perform countermeasures setTimeout(() => if ($("#ad-body div iframe").length == 0) this._adblocked(); , 1000); ret _modalVisible: -> $(".modal[aria-hidden!='true']").length > 0 _handlePostKeys: (e) => kc = e.keyCode || e.charCode # Scroll up/down one article. if this.articleList? && this.articleList.length > 0 if ((kc == 75 || kc == 107) && this.currentArticle?) # Mark as read only if we are scrolling downward. this.currentArticle = this.currentArticle - 1 else if ((kc == 74 || kc == 106) && this.currentArticle <= this.articleList.length - 1) article = this.articleList.at this.currentArticle if this.authedUser && article? && article.unread # Mark current article as read before proceeding. this.togglePostAsRead article this.currentArticle = this.currentArticle + 1 if not this.currentArticle || this.currentArticle < 0 this.currentArticle = 0 else if this.currentArticle == this.articleList.length - 1 this.fetchMorePosts() else if this.currentArticle > this.articleList.length - 1 this.currentArticle = this.articleList.length - 1 scrollToBottom = true $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle:eq(" + this.currentArticle + ") .article-panel").addClass "selected-article" newArticle = this.articleList.at this.currentArticle newArticleId = newArticle.article.id; newArticleOffset = $("a[name='article" + newArticleId + "']").offset() if scrollToBottom newArticleOffset = $("a[name='bottom']").offset() this.scrollDisabled = true objSelf = this $(window).off("scroll", this._onScrollFn) doneFn = () -> objSelf.scrollDisabled = false $(window).scroll(objSelf._onScrollFn) $('html, body').animate({ scrollTop: newArticleOffset.top - 130 }, 500, "swing", () -> doneFn()) e.preventDefault() _handleFeedKeys: (e) => kc = e.keyCode || e.charCode if this.newsFeedView.canNavigateDownList() && (kc == 115 || kc == 83) # s/S (navigate down list) initUrl = "/news/" + this._uid + "/feeds" nextFeed = this.newsFeedView.getNextFeed() if nextFeed > 0 initUrl = initUrl + "/" + nextFeed this.navigate initUrl, true else if this.newsFeedView.canNavigateUpList() && (kc == 119 || kc == 87) # w/W (navigate up list) initUrl = "/news/" + this._uid nextFeed = this.newsFeedView.getPrevFeed() if nextFeed? && nextFeed >= 0 initUrl = initUrl + "/feeds" if nextFeed > 0 initUrl = initUrl + "/" + nextFeed this.navigate initUrl, true e.preventDefault() _handleOpenArticleKeys: (e) => if this.articleList? && this.articleList.length > 0 if !this.currentArticle? || this.currentArticle < 0 || this.currentArticle >= this.articleList.length this.currentArticle = 0 article = this.articleList.at this.currentArticle articleId = article.article.id; articleOffset = $("a[name='article" + articleId + "']").offset() e.preventDefault() window.open article.article.link, "_blank" if this.authedUser && article? && article.unread this.togglePostAsRead article this.currentArticle = this.currentArticle + 1 if not this.currentArticle || this.currentArticle < 0 this.currentArticle = 0 else if this.currentArticle == this.articleList.length - 1 this.fetchMorePosts() else if this.currentArticle > this.articleList.length - 1 this.currentArticle = this.articleList.length - 1 scrollToBottom = true $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle:eq(" + this.currentArticle + ") .article-panel").addClass "selected-article" newArticle = this.articleList.at this.currentArticle newArticleId = newArticle.article.id; newArticleOffset = $("a[name='article" + newArticleId + "']").offset() if scrollToBottom newArticleOffset = $("a[name='bottom']").offset() this.scrollDisabled = true objSelf = this $(window).off("scroll", this._onScrollFn) doneFn = () -> objSelf.scrollDisabled = false $(window).scroll(objSelf._onScrollFn) $('html, body').animate({ scrollTop: newArticleOffset.top - 130 }, 500, "swing", () -> doneFn()) _initializeKeyboardNavigation: -> # Set up keyboard navigation $(window).keypress (e) => if not this._modalVisible() kc = e.keyCode || e.charCode if (kc == 74 || kc == 75 || kc == 106 || kc == 107) # j/k/J/K (post navigation) this._handlePostKeys e else if (kc == 63) # ? (help) e.preventDefault() $("#keyboardHelp").modal("show") else if (kc == 119 || kc == 87 || kc == 115 || kc == 83) # w/W/s/S (feed navigation) this._handleFeedKeys e else if (kc == 114 || kc == 82) # r/R (mark all as read) e.preventDefault() this.markAllRead() else if (kc == 100 || kc == 68) # d/D (deletes current feed) e.preventDefault() if not $("#removeFeedLink").parent().hasClass("disabled") $("#removeFeedConfirm").modal() else if (kc == 97 || kc == 65) # a/A (add new feed) e.preventDefault() this.showAddFeedWindow() else if (kc == 79 || kc == 111) # o/O (open current article in new window) this._handleOpenArticleKeys e constructor: (bootstrappedFeeds, bootstrappedPosts, optedOut, suppressLeftAndTop, email = "") -> super() NR.API.Initialize() this._initializeKeyboardNavigation() # Initialize scroll handler (to enable "where you left off" scrolling if you're # switching between keyboard navigation and mouse navigation) objSelf = this this._onScrollFn = () -> clearTimeout($.data(this, 'scrollTimer')); $.data(this, 'scrollTimer', setTimeout(() -> if not objSelf.scrollDisabled scrollTop = $(window).scrollTop() windowHeight = $(window).height() first = false index = 0 $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle .article-panel").each(() -> offset = $(this).offset() if (scrollTop + 130) <= (offset.top + $(this).height()) and first == false first = true objSelf.currentArticle = index $(this).addClass "selected-article" index = index + 1 ) )) $(window).scroll(this._onScrollFn) this.authedUser = not suppressLeftAndTop this.feedList = new SimpleMVC.Collection this.articleList = new SimpleMVC.Collection this.localSettings = new NR.Models.HtmlLocalStorage this.localSettings.optedOut = optedOut if not suppressLeftAndTop this.profileModel = new NR.Models.ProfileModel this.profileModel.email = email this.topNavView = new NR.Views.TopNavBar this.topNavView.model = this.localSettings this.welcomeView = new NR.Views.WelcomeBlock this.newsFeedView = new NR.Views.NewsFeedListing this.feedList if email != "" $("#updateProfileLink").parent().removeClass "disabled" for i in bootstrappedFeeds feed = new NR.Models.NewsFeedInfo for k,v of i feed[k] = v this.feedList.add feed # Set up timer for feed updates (every 5min). setInterval this.updateFeeds, 1000*60*5 # Restart feed import as needed if this.localSettings.importQueue? && this.localSettings.importQueue.length > 0 this._beginFeedImport() this.newsArticleView = new NR.Views.NewsArticleListing this.articleList for i in bootstrappedPosts post = new NR.Models.NewsFeedArticleInfo for k,v of i post[k] = v this.articleList.add post selectAllFeeds: () => this.navigate "/news/" + this._uid + "/feeds", true selectFeed: (feed) => this.navigate "/news/" + this._uid + "/feeds/" + feed.id, true deselectFeed: () => this.navigate "/news/" + this._uid, true showAddFeedWindow: () => this.navigate "/news/" + this._uid + "/feeds/add", true removeCurrentFeed: () => currentFeed = this._fid NR.API.RemoveFeed this._fid, () => index = this.feedList.any((i) -> i.id.toString() == currentFeed.toString()) this.feedList.removeAt index this.navigate "/news/" + this._uid + "/feeds", true addFeed: (url) => NR.API.AddFeed url, (data) => feed = new NR.Models.NewsFeedInfo for k,v of data feed[k] = v if this.feedList.any((i) -> i.id == feed.id) == -1 this.feedList.add feed this.selectFeed feed , this._apiError markAllRead: () => successFn = (data) => this.articleList.reset() this.updateFeeds() this._enableFetch = true this._maxId = "" this._postPage = 0 this._seenUnread = 0 this.fetchMorePosts() if this._fid > 0 NR.API.MarkAllFeedPostsAsRead this._fid, 0, Date.parse(this.articleList.at(0).article.pubDate) / 1000, successFn, this._apiError else NR.API.MarkAllPostsAsRead 0, Date.parse(this.articleList.at(0).article.pubDate) / 1000, successFn, this._apiError importSingleFeed: () => nextImport = () => this.localSettings.importQueue.shift() this.localSettings.feedsImported = this.localSettings.feedsImported + 1 if this.localSettings.importQueue.length > 0 # import next feed window.setTimeout this.importSingleFeed, 0 else # all done noty({ text: "Import complete.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "success" }); this.localSettings.importQueue = [] # Unlike addFeed above, we're ignoring errors from the server. NR.API.AddFeed this.localSettings.importQueue[0], (data) => feed = new NR.Models.NewsFeedInfo for k,v of data feed[k] = v if this.feedList.any((i) -> i.id == feed.id) == -1 this.feedList.add feed nextImport.call(this) , nextImport.bind(this) _beginFeedImport: () => noty({ text: "Feed import has begun.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "information" }); window.setTimeout this.importSingleFeed, 0 fetchMorePosts: => errorWrapper = (type, desc) => this._enableFetch = true this._apiError type, desc successWrapper = (data) => if data.list.length > 0 this._enableFetch = true this._maxId = data.id this._postPage = this._postPage + 1 this._processFeedPosts data.list if this.currentArticle < 0 this.currentArticle = 0 $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle:eq(" + this.currentArticle + ") .article-panel").addClass "selected-article" if not this._lastSeenUnread? this._lastSeenUnread = this._seenUnread if this._postPage > 0 lastArticleId = Date.parse(this.articleList.at(this.articleList.length - 1).article.pubDate) / 1000 else lastArticleId = "" if this._enableFetch this._enableFetch = false if this._fid > 0 NR.API.GetPostsForFeed( this._fid, 0, lastArticleId, this._maxId, this.localSettings.showOnlyUnread, successWrapper, errorWrapper) else if this._savedPostsMode NR.API.GetSavedPosts( this._uid, 0, lastArticleId, this._maxId, successWrapper, errorWrapper) else NR.API.GetAllPosts( 0, lastArticleId, this._maxId, this.localSettings.showOnlyUnread, successWrapper, errorWrapper) togglePostAsRead: (article) => if article.unread NR.API.MarkPostAsRead article.article.id, (data) => article.unread = false if article.feed.numUnread > 0 article.feed.numUnread = article.feed.numUnread - 1 this.newsFeedView.sort() , this._apiError else NR.API.MarkPostAsUnread article.article.id, (data) => article.unread = true article.feed.numUnread = article.feed.numUnread + 1 this.newsFeedView.sort() , this._apiError toggleSavePost: (article) => if article.saved NR.API.UnsavePost article.feed.id, article.article.id, (data) => article.saved = false , this._apiError else NR.API.SavePost article.feed.id, article.article.id, (data) => article.saved = true , this._apiError finishedUploadingFeedList: (result) => if (!result.success) errorText = "Error encountered while uploading file." if (result.error_string == "forgot_file") errorText = "Please select a file and try again." else if (result.error_string == "cant_parse") errorText = "The file provided is not a valid OPML file. Select another file and try again." else if (result.error_string == "not_authorized") # Force user to login screen. location.reload(); else if (result.error_string == "too_big") errorText = "The file provided is too big to be parsed. Select another file and try again." noty({ text: errorText, layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }); else $('#importFeeds').modal('hide') # Queue up feeds for processing. this.localSettings.importQueue = result.feeds this.localSettings.feedsImported = 0 this._beginFeedImport() toggleShowUnread: () => this.localSettings.showOnlyUnread = !this.localSettings.showOnlyUnread this.articleList.reset() if this._fid? this._postPage = 0 this._seenUnread = 0 this._maxId = "" this._enableFetch = true this.fetchMorePosts() toggleOptOut: => NR.API.OptOutSharing (not this.localSettings.optedOut), () => this.localSettings.optedOut = not this.localSettings.optedOut , this._apiError updateFeeds: => NR.API.GetFeeds (feeds) => # Disable sorting until the very end for performance. this.newsFeedView.disableSort() for i in feeds feed = new NR.Models.NewsFeedInfo for k,v of i feed[k] = v index = this.feedList.any (x) -> feed.id == x.id if index >= 0 # Don't use Collection#replace so we can maintain active state. other = this.feedList.at index other.feed = feed.feed other.id = feed.id other.numUnread = feed.numUnread other.errorsUpdating = feed.errorsUpdating else this.feedList.add feed # Remove feeds that no longer exist. toRemove = [] this.feedList.each (i) -> found = false for j in feeds if i.id == j.id found = true if not found toRemove.push i for k in toRemove this.feedList.remove k # Reenable sorting. this.newsFeedView.enableSort() , this._apiError
true
if not @NR? NR = exports? and exports or @NR = {} else NR = @NR class NR.Application extends SimpleMVC.Controller _processFeedPosts: (data) => for i in data post = new NR.Models.NewsFeedArticleInfo for k,v of i post[k] = v if k == "article" v.titleEmpty = !v.title this.articleList.add post _apiError: (type, desc, data) => errorText = "Communications error with the server. Please try again." switch type when NR.API.AuthenticationFailed then location.reload() when NR.API.ServerError if desc == NR.API.NotAFeedError this._createFeedView = new NR.Views.CreateFeedWindow feedModel = new NR.Models.CreateFeedModel feedModel.baseHtml = data feedModel.baseUrl = $("#addFeedUrl").val() this._createFeedView.model = feedModel this._createFeedView.show() else if desc == NR.API.MultipleFeedsFoundError foundList = new SimpleMVC.Collection this._multipleFeedFoundView = new NR.Views.MultipleFeedsFoundWindow foundList this._multipleFeedFoundView.show() for i in data entry = new NR.Models.MultipleFeedEntry entry.title = i.title entry.url = i.url foundList.add entry else errorText = "The server encountered an error while processing the request. Please try again." if desc != NR.API.NotAFeedError && desc != NR.API.MultipleFeedsFoundError noty({ text: errorText, layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }); @route "saved/:uid", (uid) -> this._uid = uid this._savedPostsMode = true this._postPage = 1 this._maxId = "" this.newsArticleView.show() @route "news/:uid/feeds/add", (uid) -> this._uid = uid $("#addFeedUrl").val(this.urlParams["url"]) $("#addFeed").on("shown.bs.modal", () -> $("#addFeedUrl").focus()) $("#addFeed").on("hidden.bs.modal", () => # return to original page if this._fid this.navigate("/news/" + this._uid + "/feeds/" + this._fid) else if this._fid == 0 this.navigate("/news/" + this._uid + "/feeds") else this.navigate("/news/" + this._uid)) $("#addFeed").modal() @route "news/:uid/feeds/:fid", (uid, fid) -> index = this.feedList.any((i) -> i.id.toString() == fid.toString()) if index >= 0 this._uid = uid this._fid = fid this._maxId = "" this._postPage = 0 this._seenUnread = 0 this._enableFetch = true this.currentArticle = -1 # Specific feed listing. this.newsArticleView.show() this.articleList.reset() this.welcomeView.hide() # Get posts from server this.fetchMorePosts() # Update nav elements. feed = this.feedList.at index this.newsFeedView.feedSelected fid this.topNavView.feedSelected feed true else false @route "news/:uid/feeds", (uid) -> this._uid = uid this._fid = 0 this._postPage = 0 this._seenUnread = 0 this._maxId = "" this._enableFetch = true this.currentArticle = -1 # "All Feeds" listing. this.newsArticleView.show() this.articleList.reset() this.welcomeView.hide() # Get posts from server this.fetchMorePosts() # Update nav elements. this.newsFeedView.allFeedsSelected() this.topNavView.allFeedsSelected() @route "news/:uid", (uid) -> this._uid = uid this._fid = null this._maxId = "" this.currentArticle = -1 # Hide articles. this.newsArticleView.hide() this.articleList.reset() this.welcomeView.show() # Update nav elements. this.newsFeedView.homeSelected() this.topNavView.homeSelected() _adblocked: () -> $("#ad-body").html('<div class="sponsor_content"> <center> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank"> <span>newsrdr relies on your support.</span> <input type="hidden" name="cmd" value="_donations" /> <input type="hidden" name="business" value="PI:EMAIL:<EMAIL>END_PI" /> <input type="hidden" name="lc" value="US" /> <input type="hidden" name="no_note" value="0" /> <input type="hidden" name="currency_code" value="USD" /> <input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHostedGuest" /> <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" valign="center" style="display: inline;" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!" /> <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1" /> </form> </center> </div>') submitUpdateProfileBox: () => good = false if event? event.preventDefault() if $('#profileEmail').val().length == 0 noty({ text: "Email is required.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else if !$('#profileEmail').val().match(/^[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+@[-0-9A-Za-z!#$%&'*+/=?^_`{|}~.]+/) noty({ text: "Email address is invalid.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else if $('#profilePassword').val().length > 0 if $('#profilePassword').val().length < 8 noty({ text: "Password must be at least eight characters long.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else if $('#profilePassword').val() != $('#profilePassword2').val() noty({ text: "Both passwords must match in order to reset your password.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }) else good = true else good = true if good == true successWrapper = (data) => noty({ text: "Profile updated.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "success" }) this.profileModel.email = $('#profileEmail').val() NR.API.UpdateProfile( $('#profileEmail').val(), $('#profilePassword').val(), $('#profilePassword2').val(), successWrapper, this._apiError) $("#updateProfile").modal('hide') submitAddFeedBox: => if event? event.preventDefault() if $('#addFeedUrl').val().length > 0 this.addFeed($('#addFeedUrl').val()) $('#addFeed').modal('hide') navigate: (uri, executeFn = false, addState = true) => ret = super uri, executeFn, addState $("#ad-body").html("<!-- newsrdr-new-site --> <div id='div-gpt-ad-1379655552510-0' style='width:728px; height:90px;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.defineSlot('/70574502/newsrdr-new-site', [728, 90], 'div-gpt-ad-1379655552510-0').addService(googletag.pubads()); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); googletag.cmd.push(function() { googletag.display('div-gpt-ad-1379655552510-0'); }); </script> </div>") # Detect adblock and perform countermeasures setTimeout(() => if ($("#ad-body div iframe").length == 0) this._adblocked(); , 1000); ret _modalVisible: -> $(".modal[aria-hidden!='true']").length > 0 _handlePostKeys: (e) => kc = e.keyCode || e.charCode # Scroll up/down one article. if this.articleList? && this.articleList.length > 0 if ((kc == 75 || kc == 107) && this.currentArticle?) # Mark as read only if we are scrolling downward. this.currentArticle = this.currentArticle - 1 else if ((kc == 74 || kc == 106) && this.currentArticle <= this.articleList.length - 1) article = this.articleList.at this.currentArticle if this.authedUser && article? && article.unread # Mark current article as read before proceeding. this.togglePostAsRead article this.currentArticle = this.currentArticle + 1 if not this.currentArticle || this.currentArticle < 0 this.currentArticle = 0 else if this.currentArticle == this.articleList.length - 1 this.fetchMorePosts() else if this.currentArticle > this.articleList.length - 1 this.currentArticle = this.articleList.length - 1 scrollToBottom = true $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle:eq(" + this.currentArticle + ") .article-panel").addClass "selected-article" newArticle = this.articleList.at this.currentArticle newArticleId = newArticle.article.id; newArticleOffset = $("a[name='article" + newArticleId + "']").offset() if scrollToBottom newArticleOffset = $("a[name='bottom']").offset() this.scrollDisabled = true objSelf = this $(window).off("scroll", this._onScrollFn) doneFn = () -> objSelf.scrollDisabled = false $(window).scroll(objSelf._onScrollFn) $('html, body').animate({ scrollTop: newArticleOffset.top - 130 }, 500, "swing", () -> doneFn()) e.preventDefault() _handleFeedKeys: (e) => kc = e.keyCode || e.charCode if this.newsFeedView.canNavigateDownList() && (kc == 115 || kc == 83) # s/S (navigate down list) initUrl = "/news/" + this._uid + "/feeds" nextFeed = this.newsFeedView.getNextFeed() if nextFeed > 0 initUrl = initUrl + "/" + nextFeed this.navigate initUrl, true else if this.newsFeedView.canNavigateUpList() && (kc == 119 || kc == 87) # w/W (navigate up list) initUrl = "/news/" + this._uid nextFeed = this.newsFeedView.getPrevFeed() if nextFeed? && nextFeed >= 0 initUrl = initUrl + "/feeds" if nextFeed > 0 initUrl = initUrl + "/" + nextFeed this.navigate initUrl, true e.preventDefault() _handleOpenArticleKeys: (e) => if this.articleList? && this.articleList.length > 0 if !this.currentArticle? || this.currentArticle < 0 || this.currentArticle >= this.articleList.length this.currentArticle = 0 article = this.articleList.at this.currentArticle articleId = article.article.id; articleOffset = $("a[name='article" + articleId + "']").offset() e.preventDefault() window.open article.article.link, "_blank" if this.authedUser && article? && article.unread this.togglePostAsRead article this.currentArticle = this.currentArticle + 1 if not this.currentArticle || this.currentArticle < 0 this.currentArticle = 0 else if this.currentArticle == this.articleList.length - 1 this.fetchMorePosts() else if this.currentArticle > this.articleList.length - 1 this.currentArticle = this.articleList.length - 1 scrollToBottom = true $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle:eq(" + this.currentArticle + ") .article-panel").addClass "selected-article" newArticle = this.articleList.at this.currentArticle newArticleId = newArticle.article.id; newArticleOffset = $("a[name='article" + newArticleId + "']").offset() if scrollToBottom newArticleOffset = $("a[name='bottom']").offset() this.scrollDisabled = true objSelf = this $(window).off("scroll", this._onScrollFn) doneFn = () -> objSelf.scrollDisabled = false $(window).scroll(objSelf._onScrollFn) $('html, body').animate({ scrollTop: newArticleOffset.top - 130 }, 500, "swing", () -> doneFn()) _initializeKeyboardNavigation: -> # Set up keyboard navigation $(window).keypress (e) => if not this._modalVisible() kc = e.keyCode || e.charCode if (kc == 74 || kc == 75 || kc == 106 || kc == 107) # j/k/J/K (post navigation) this._handlePostKeys e else if (kc == 63) # ? (help) e.preventDefault() $("#keyboardHelp").modal("show") else if (kc == 119 || kc == 87 || kc == 115 || kc == 83) # w/W/s/S (feed navigation) this._handleFeedKeys e else if (kc == 114 || kc == 82) # r/R (mark all as read) e.preventDefault() this.markAllRead() else if (kc == 100 || kc == 68) # d/D (deletes current feed) e.preventDefault() if not $("#removeFeedLink").parent().hasClass("disabled") $("#removeFeedConfirm").modal() else if (kc == 97 || kc == 65) # a/A (add new feed) e.preventDefault() this.showAddFeedWindow() else if (kc == 79 || kc == 111) # o/O (open current article in new window) this._handleOpenArticleKeys e constructor: (bootstrappedFeeds, bootstrappedPosts, optedOut, suppressLeftAndTop, email = "") -> super() NR.API.Initialize() this._initializeKeyboardNavigation() # Initialize scroll handler (to enable "where you left off" scrolling if you're # switching between keyboard navigation and mouse navigation) objSelf = this this._onScrollFn = () -> clearTimeout($.data(this, 'scrollTimer')); $.data(this, 'scrollTimer', setTimeout(() -> if not objSelf.scrollDisabled scrollTop = $(window).scrollTop() windowHeight = $(window).height() first = false index = 0 $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle .article-panel").each(() -> offset = $(this).offset() if (scrollTop + 130) <= (offset.top + $(this).height()) and first == false first = true objSelf.currentArticle = index $(this).addClass "selected-article" index = index + 1 ) )) $(window).scroll(this._onScrollFn) this.authedUser = not suppressLeftAndTop this.feedList = new SimpleMVC.Collection this.articleList = new SimpleMVC.Collection this.localSettings = new NR.Models.HtmlLocalStorage this.localSettings.optedOut = optedOut if not suppressLeftAndTop this.profileModel = new NR.Models.ProfileModel this.profileModel.email = email this.topNavView = new NR.Views.TopNavBar this.topNavView.model = this.localSettings this.welcomeView = new NR.Views.WelcomeBlock this.newsFeedView = new NR.Views.NewsFeedListing this.feedList if email != "" $("#updateProfileLink").parent().removeClass "disabled" for i in bootstrappedFeeds feed = new NR.Models.NewsFeedInfo for k,v of i feed[k] = v this.feedList.add feed # Set up timer for feed updates (every 5min). setInterval this.updateFeeds, 1000*60*5 # Restart feed import as needed if this.localSettings.importQueue? && this.localSettings.importQueue.length > 0 this._beginFeedImport() this.newsArticleView = new NR.Views.NewsArticleListing this.articleList for i in bootstrappedPosts post = new NR.Models.NewsFeedArticleInfo for k,v of i post[k] = v this.articleList.add post selectAllFeeds: () => this.navigate "/news/" + this._uid + "/feeds", true selectFeed: (feed) => this.navigate "/news/" + this._uid + "/feeds/" + feed.id, true deselectFeed: () => this.navigate "/news/" + this._uid, true showAddFeedWindow: () => this.navigate "/news/" + this._uid + "/feeds/add", true removeCurrentFeed: () => currentFeed = this._fid NR.API.RemoveFeed this._fid, () => index = this.feedList.any((i) -> i.id.toString() == currentFeed.toString()) this.feedList.removeAt index this.navigate "/news/" + this._uid + "/feeds", true addFeed: (url) => NR.API.AddFeed url, (data) => feed = new NR.Models.NewsFeedInfo for k,v of data feed[k] = v if this.feedList.any((i) -> i.id == feed.id) == -1 this.feedList.add feed this.selectFeed feed , this._apiError markAllRead: () => successFn = (data) => this.articleList.reset() this.updateFeeds() this._enableFetch = true this._maxId = "" this._postPage = 0 this._seenUnread = 0 this.fetchMorePosts() if this._fid > 0 NR.API.MarkAllFeedPostsAsRead this._fid, 0, Date.parse(this.articleList.at(0).article.pubDate) / 1000, successFn, this._apiError else NR.API.MarkAllPostsAsRead 0, Date.parse(this.articleList.at(0).article.pubDate) / 1000, successFn, this._apiError importSingleFeed: () => nextImport = () => this.localSettings.importQueue.shift() this.localSettings.feedsImported = this.localSettings.feedsImported + 1 if this.localSettings.importQueue.length > 0 # import next feed window.setTimeout this.importSingleFeed, 0 else # all done noty({ text: "Import complete.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "success" }); this.localSettings.importQueue = [] # Unlike addFeed above, we're ignoring errors from the server. NR.API.AddFeed this.localSettings.importQueue[0], (data) => feed = new NR.Models.NewsFeedInfo for k,v of data feed[k] = v if this.feedList.any((i) -> i.id == feed.id) == -1 this.feedList.add feed nextImport.call(this) , nextImport.bind(this) _beginFeedImport: () => noty({ text: "Feed import has begun.", layout: "topRight", timeout: 2000, dismissQueue: true, type: "information" }); window.setTimeout this.importSingleFeed, 0 fetchMorePosts: => errorWrapper = (type, desc) => this._enableFetch = true this._apiError type, desc successWrapper = (data) => if data.list.length > 0 this._enableFetch = true this._maxId = data.id this._postPage = this._postPage + 1 this._processFeedPosts data.list if this.currentArticle < 0 this.currentArticle = 0 $(".newsArticle .article-panel").removeClass "selected-article" $(".newsArticle:eq(" + this.currentArticle + ") .article-panel").addClass "selected-article" if not this._lastSeenUnread? this._lastSeenUnread = this._seenUnread if this._postPage > 0 lastArticleId = Date.parse(this.articleList.at(this.articleList.length - 1).article.pubDate) / 1000 else lastArticleId = "" if this._enableFetch this._enableFetch = false if this._fid > 0 NR.API.GetPostsForFeed( this._fid, 0, lastArticleId, this._maxId, this.localSettings.showOnlyUnread, successWrapper, errorWrapper) else if this._savedPostsMode NR.API.GetSavedPosts( this._uid, 0, lastArticleId, this._maxId, successWrapper, errorWrapper) else NR.API.GetAllPosts( 0, lastArticleId, this._maxId, this.localSettings.showOnlyUnread, successWrapper, errorWrapper) togglePostAsRead: (article) => if article.unread NR.API.MarkPostAsRead article.article.id, (data) => article.unread = false if article.feed.numUnread > 0 article.feed.numUnread = article.feed.numUnread - 1 this.newsFeedView.sort() , this._apiError else NR.API.MarkPostAsUnread article.article.id, (data) => article.unread = true article.feed.numUnread = article.feed.numUnread + 1 this.newsFeedView.sort() , this._apiError toggleSavePost: (article) => if article.saved NR.API.UnsavePost article.feed.id, article.article.id, (data) => article.saved = false , this._apiError else NR.API.SavePost article.feed.id, article.article.id, (data) => article.saved = true , this._apiError finishedUploadingFeedList: (result) => if (!result.success) errorText = "Error encountered while uploading file." if (result.error_string == "forgot_file") errorText = "Please select a file and try again." else if (result.error_string == "cant_parse") errorText = "The file provided is not a valid OPML file. Select another file and try again." else if (result.error_string == "not_authorized") # Force user to login screen. location.reload(); else if (result.error_string == "too_big") errorText = "The file provided is too big to be parsed. Select another file and try again." noty({ text: errorText, layout: "topRight", timeout: 2000, dismissQueue: true, type: "error" }); else $('#importFeeds').modal('hide') # Queue up feeds for processing. this.localSettings.importQueue = result.feeds this.localSettings.feedsImported = 0 this._beginFeedImport() toggleShowUnread: () => this.localSettings.showOnlyUnread = !this.localSettings.showOnlyUnread this.articleList.reset() if this._fid? this._postPage = 0 this._seenUnread = 0 this._maxId = "" this._enableFetch = true this.fetchMorePosts() toggleOptOut: => NR.API.OptOutSharing (not this.localSettings.optedOut), () => this.localSettings.optedOut = not this.localSettings.optedOut , this._apiError updateFeeds: => NR.API.GetFeeds (feeds) => # Disable sorting until the very end for performance. this.newsFeedView.disableSort() for i in feeds feed = new NR.Models.NewsFeedInfo for k,v of i feed[k] = v index = this.feedList.any (x) -> feed.id == x.id if index >= 0 # Don't use Collection#replace so we can maintain active state. other = this.feedList.at index other.feed = feed.feed other.id = feed.id other.numUnread = feed.numUnread other.errorsUpdating = feed.errorsUpdating else this.feedList.add feed # Remove feeds that no longer exist. toRemove = [] this.feedList.each (i) -> found = false for j in feeds if i.id == j.id found = true if not found toRemove.push i for k in toRemove this.feedList.remove k # Reenable sorting. this.newsFeedView.enableSort() , this._apiError
[ { "context": " keys_set: stat('query_engine')('written_docs_per_sec')\n ), 1000, @stats.on_resu", "end": 15312, "score": 0.515143096446991, "start": 15312, "tag": "KEY", "value": "" }, { "context": " keys_set: stat('query_engine')('written_docs_per_sec')\n ...
admin/static/coffee/tables/table.coffee
zadcha/rethinkdb
21,684
# Copyright 2010-2015 RethinkDB models = require('../models.coffee') modals = require('../modals.coffee') shard_assignments = require('./shard_assignments.coffee') shard_distribution = require('./shard_distribution.coffee') vis = require('../vis.coffee') ui_modals = require('../ui_components/modals.coffee') ui_progress = require('../ui_components/progressbar.coffee') app = require('../app.coffee') driver = app.driver system_db = app.system_db r = require('rethinkdb') class TableContainer extends Backbone.View template: not_found: require('../../handlebars/element_view-not_found.hbs') error: require('../../handlebars/error-query.hbs') className: 'table-view' initialize: (id) => @id = id @table_found = true @indexes = null @distribution = new models.Distribution @guaranteed_timer = null @failable_index_timer = null @failable_misc_timer = null # This is the cache of error messages we've received from # @failable_index_query and @failable_misc_query @current_errors = {index: [], misc: []} # Initialize the model with mostly empty dummy data so we # can render it right away # # We have two types of errors that can trip us # up. info_unavailable errors happen when a you can't # fetch table.info(). index_unavailable errors happen when # you can't fetch table.indexStatus() @model = new models.Table id: id info_unavailable: false index_unavailable: false @listenTo @model, 'change:index_unavailable', (=> @maybe_refetch_data()) @table_view = new TableMainView model: @model indexes: @indexes distribution: @distribution shards_assignments: @shards_assignments @fetch_data() maybe_refetch_data: => if @model.get('info_unavailable') and not @model.get('index_unavailable') # This is triggered when we go from # table.indexStatus() failing to it succeeding. If # that's the case, we should refetch everything. What # happens is we try to fetch indexes every 1s, but # more expensive stuff like table.info() only every # 10s. To avoid having the table UI in an error state # longer than we need to, we use the secondary index # query as a canary in the coalmine to decide when to # try again with the info queries. @fetch_once() fetch_once: _.debounce((=> # fetches data once, but only does it if we flap less than # once every 2 seconds driver.run_once(@failable_misc_query, @failable_misc_handler) driver.run_once(@guaranteed_query, @guaranted_handler) ), 2000, true) add_error_message: (type, error) => # This avoids spamming the console with the same error # message. It keeps a cache of messages, prints out # anything new, and resets the cache once we stop # receiving errors if error not in @current_errors[type] console.log "#{type} error: #{error}" @current_errors[type].push(error) clear_cached_error_messages: (type) => # We clear the cache of errors once a successful query # makes it through if @current_errors[type].length > 0 @current_errors[type] = [] guaranteed_query: => # This query should succeed as long as the cluster is # available, since we get it from the system tables. Info # we don't get from the system tables includes things like # table/shard counts, or secondary index status. Those are # obtained from table.info() and table.indexStatus() below # in `failable_*_query` so if they fail we still get the # data available in the system tables. r.do( r.db(system_db).table('server_config').coerceTo('array'), r.db(system_db).table('table_status').get(@id), r.db(system_db).table('table_config').get(@id), (server_config, table_status, table_config) -> r.branch( table_status.eq(null), null, table_status.merge( max_shards: 64 num_shards: table_config("shards").count().default(0) num_servers: server_config.count() num_default_servers: server_config.filter((server) -> server('tags').contains('default')).count() max_num_shards: r.expr([64, server_config.filter(((server) -> server('tags').contains('default'))).count()]).min() num_primary_replicas: table_status("shards").count( (row) -> row('primary_replicas').isEmpty().not()) .default(0) num_replicas: table_status("shards").default([]).map((shard) -> shard('replicas').count()).sum() num_available_replicas: table_status("shards").concatMap( (shard) -> shard('replicas').filter({state: "ready"})) .count().default(0) num_replicas_per_shard: table_config("shards").default([]).map( (shard) -> shard('replicas').count()).max().default(0) status: table_status('status') id: table_status("id") # These are updated below if the table is ready ).without('shards') ) ) failable_index_query: => # This query only checks the status of secondary indexes. # It can throw an exception and failif the primary # replica is unavailable (which happens immediately after # a reconfigure). r.do( r.db(system_db).table('table_config').get(@id) (table_config) -> r.db(table_config("db")) .table(table_config("name"), read_mode: "single") .indexStatus() .pluck('index', 'ready', 'progress') .merge( (index) -> { id: index("index") db: table_config("db") table: table_config("name") }) # add an id for backbone ) failable_misc_query: => # Query to load data distribution and shard assignments. # We keep this separate from the failable_index_query because we don't want # to run it as often. # This query can throw an exception and failif the primary # replica is unavailable (which happens immediately after # a reconfigure). Since this query makes use of # table.info(), it's separated from the guaranteed query r.do( r.db(system_db).table('table_status').get(@id), r.db(system_db).table('table_config').get(@id), r.db(system_db).table('server_config') .map((x) -> [x('name'), x('id')]).coerceTo('ARRAY').coerceTo('OBJECT'), (table_status, table_config, server_name_to_id) -> table_status.merge({ distribution: r.db(table_status('db')) .table(table_status('name'), read_mode: "single") .info()('doc_count_estimates') .map(r.range(), (num_keys, position) -> num_keys: num_keys id: position) .coerceTo('array') total_keys: r.db(table_status('db')) .table(table_status('name'), read_mode: "single") .info()('doc_count_estimates') .sum() shard_assignments: table_status.merge((table_status) -> table_status('shards').default([]).map( table_config('shards').default([]), r.db(table_status('db')) .table(table_status('name'), read_mode: "single") .info()('doc_count_estimates'), (status, config, estimate) -> num_keys: estimate, replicas: status('replicas').merge((replica) -> id: server_name_to_id(replica('server')).default(null), configured_primary: config('primary_replica').eq(replica('server')) currently_primary: status('primary_replicas').contains(replica('server')) nonvoting: config('nonvoting_replicas').contains(replica('server')) ).orderBy(r.desc('currently_primary'), r.desc('configured_primary')) ) ) }) ) handle_failable_index_response: (error, result) => # Handle the result of failable_index_query if error? @add_error_message('index', error.msg) @model.set 'index_unavailable', true return @model.set 'index_unavailable', false @clear_cached_error_messages('index') if @indexes? @indexes.set _.map(result, (index) -> new models.Index index) else @indexes = new models.Indexes _.map result, (index) -> new models.Index index @table_view?.set_indexes @indexes @model.set indexes: result if !@table_view? @table_view = new TableMainView model: @model indexes: @indexes distribution: @distribution shards_assignments: @shards_assignments @render() handle_failable_misc_response: (error, result) => if error? @add_error_message('misc', error.msg) @model.set 'info_unavailable', true return @model.set 'info_unavailable', false @clear_cached_error_messages('misc') if @distribution? @distribution.set _.map result.distribution, (shard) -> new models.Shard shard @distribution.trigger 'update' else @distribution = new models.Distribution _.map( result.distribution, (shard) -> new models.Shard shard) @table_view?.set_distribution @distribution if @shards_assignments? @shards_assignments.set _.map result.shard_assignments, (shard) -> new models.ShardAssignment shard else @shards_assignments = new models.ShardAssignments( _.map result.shard_assignments, (shard) -> new models.ShardAssignment shard ) @table_view?.set_assignments @shards_assignments @model.set result if !@table_view? @table_view = new TableMainView model: @model indexes: @indexes distribution: @distribution shards_assignments: @shards_assignments @render() handle_guaranteed_response: (error, result) => if error? # TODO: We may want to render only if we failed to open a connection # TODO: Handle when the table is deleted @error = error @render() else rerender = @error? @error = null if result is null rerender = rerender or @table_found @table_found = false # Reset the data @indexes = null @render() else rerender = rerender or not @table_found @table_found = true @model.set result if rerender @render() fetch_data: => # This timer keeps track of the failable index query, so we can # cancel it when we navigate away from the table page. @failable_index_timer = driver.run( @failable_index_query(), 1000, @handle_failable_index_response ) # This timer keeps track of the failable misc query, so we can # cancel it when we navigate away from the table page. @failable_misc_timer = driver.run( @failable_misc_query(), 10000, @handle_failable_misc_response, ) # This timer keeps track of the guaranteed query, running # it every 5 seconds. We cancel it when navigating away # from the table page. @guaranteed_timer = driver.run( @guaranteed_query(), 5000, @handle_guaranteed_response, ) render: => if @error? @$el.html @template.error error: @error?.message url: '#tables/'+@id else if @table_found @$el.html @table_view.render().$el else # In this case, the query returned null, so the table was not found @$el.html @template.not_found id: @id type: 'table' type_url: 'tables' type_all_url: 'tables' @ remove: => driver.stop_timer @guaranteed_timer driver.stop_timer @failable_index_timer driver.stop_timer @failable_misc_timer @table_view?.remove() super() class TableMainView extends Backbone.View className: 'namespace-view' template: main: require('../../handlebars/table_container.hbs') alert: null # unused, delete this events: 'click .close': 'close_alert' 'click .operations .rename': 'rename_table' 'click .operations .delete': 'delete_table' initialize: (data, options) => @indexes = data.indexes @distribution = data.distribution @shards_assignments = data.shards_assignments # Panels for namespace view @title = new Title model: @model @profile = new Profile model: @model @secondary_indexes_view = new SecondaryIndexesView collection: @indexes model: @model @shard_distribution = new shard_distribution.ShardDistribution collection: @distribution model: @model @server_assignments = new shard_assignments.ShardAssignmentsView model: @model collection: @shards_assignments @reconfigure = new ReconfigurePanel model: @model @stats = new models.Stats @stats_timer = driver.run( r.db(system_db).table('stats') .get(["table", @model.get('id')]) .do((stat) -> keys_read: stat('query_engine')('read_docs_per_sec') keys_set: stat('query_engine')('written_docs_per_sec') ), 1000, @stats.on_result) @performance_graph = new vis.OpsPlot(@stats.get_stats, width: 564 # width in pixels height: 210 # height in pixels seconds: 73 # num seconds to track type: 'table' ) set_indexes: (indexes) => if not @indexes? @indexes = indexes @secondary_indexes_view.set_indexes @indexes set_distribution: (distribution) => @distribution = distribution @shard_distribution.set_distribution @distribution set_assignments: (shards_assignments) => @shards_assignments = shards_assignments @server_assignments.set_assignments @shards_assignments render: => @$el.html @template.main namespace_id: @model.get 'id' # fill the title of this page @$('.main_title').html @title.render().$el # Add the replica and shards views @$('.profile').html @profile.render().$el @$('.performance-graph').html @performance_graph.render().$el # Display the shards @$('.sharding').html @shard_distribution.render().el # Display the server assignments @$('.server-assignments').html @server_assignments.render().el # Display the secondary indexes @$('.secondary_indexes').html @secondary_indexes_view.render().el # Display server reconfiguration @$('.reconfigure-panel').html @reconfigure.render().el @ close_alert: (event) -> event.preventDefault() $(event.currentTarget).parent().slideUp('fast', -> $(this).remove()) # Rename operation rename_table: (event) => event.preventDefault() if @rename_modal? @rename_modal.remove() @rename_modal = new ui_modals.RenameItemModal model: @model @rename_modal.render() # Delete operation delete_table: (event) -> event.preventDefault() if @remove_table_dialog? @remove_table_dialog.remove() @remove_table_dialog = new modals.RemoveTableModal @remove_table_dialog.render [{ table: @model.get 'name' database: @model.get 'db' }] remove: => @title.remove() @profile.remove() @shard_distribution.remove() @server_assignments.remove() @performance_graph.remove() @secondary_indexes_view.remove() @reconfigure.remove() driver.stop_timer @stats_timer if @remove_table_dialog? @remove_table_dialog.remove() if @rename_modal? @rename_modal.remove() super() class ReconfigurePanel extends Backbone.View className: 'reconfigure-panel' templates: main: require('../../handlebars/reconfigure.hbs') status: require('../../handlebars/replica_status.hbs') events: 'click .reconfigure.btn': 'launch_modal' initialize: (obj) => @model = obj.model @listenTo @model, 'change:num_shards', @render @listenTo @model, 'change:num_replicas_per_shard', @render @listenTo @model, 'change:num_available_replicas', @render_status @progress_bar = new ui_progress.OperationProgressBar @templates.status @timer = null launch_modal: => if @reconfigure_modal? @reconfigure_modal.remove() @reconfigure_modal = new modals.ReconfigureModal model: new models.Reconfigure parent: @ id: @model.get('id') db: @model.get('db') name: @model.get('name') total_keys: @model.get('total_keys') shards: [] max_shards: @model.get('max_shards') num_shards: @model.get('num_shards') num_servers: @model.get('num_servers') num_default_servers: @model.get('num_default_servers') max_num_shards: @model.get('max_num_shards') num_replicas_per_shard: @model.get('num_replicas_per_shard') @reconfigure_modal.render() remove: => if @reconfigure_modal? @reconfigure_modal.remove() if @timer? driver.stop_timer @timer @timer = null @progress_bar.remove() super() fetch_progress: => query = r.db(system_db).table('table_status') .get(@model.get('id'))('shards').default([])('replicas') .concatMap((x) -> x) .do((replicas) -> num_available_replicas: replicas.filter(state: 'ready').count() num_replicas: replicas.count() ) if @timer? driver.stop_timer @timer @timer = null @timer = driver.run query, 1000, (error, result) => if error? # This can happen if the table is temporarily # unavailable. We log the error, and ignore it console.log "Nothing bad - Could not fetch replicas statuses" console.log error else @model.set result @render_status() # Force to refresh the progress bar # Render the status of the replicas and the progress bar if needed render_status: => #TODO Handle backfilling when available in the api directly if @model.get('num_available_replicas') < @model.get('num_replicas') if not @timer? @fetch_progress() return if @progress_bar.get_stage() is 'none' @progress_bar.skip_to_processing() else if @timer? driver.stop_timer @timer @timer = null @progress_bar.render( @model.get('num_available_replicas'), @model.get('num_replicas'), {got_response: true} ) render: => @$el.html @templates.main @model.toJSON() if @model.get('num_available_replicas') < @model.get('num_replicas') if @progress_bar.get_stage() is 'none' @progress_bar.skip_to_processing() @$('.backfill-progress').html @progress_bar.render( @model.get('num_available_replicas'), @model.get('num_replicas'), {got_response: true}, ).$el @ class ReconfigureDiffView extends Backbone.View # This is just for the diff view in the reconfigure # modal. It's so that the diff can be rerendered independently # of the modal itself (which includes the input form). If you # rerended the entire modal, you lose focus in the text boxes # since handlebars creates an entirely new dom tree. # # You can find the ReconfigureModal in coffee/modals.coffee className: 'reconfigure-diff' template: require('../../handlebars/reconfigure-diff.hbs') initialize: => @listenTo @model, 'change:shards', @render render: => @$el.html @template @model.toJSON() @ class Title extends Backbone.View className: 'namespace-info-view' template: require('../../handlebars/table_title.hbs') initialize: => @listenTo @model, 'change:name', @render render: => @$el.html @template name: @model.get 'name' db: @model.get 'db' @ remove: => @stopListening() super() # Profile view class Profile extends Backbone.View template: require('../../handlebars/table_profile.hbs') initialize: => @listenTo @model, 'change', @render @indicator = new TableStatusIndicator model: @model render: => obj = { status: @model.get 'status' total_keys: @model.get 'total_keys' num_shards: @model.get 'num_shards' num_primary_replicas: @model.get 'num_primary_replicas' num_replicas: @model.get 'num_replicas' num_available_replicas: @model.get 'num_available_replicas' } if obj.status?.ready_for_writes and not obj?.status.all_replicas_ready obj.parenthetical = true @$el.html @template obj @$('.availability').prepend(@indicator.$el) return @ remove: => @indicator.remove() super() class TableStatusIndicator extends Backbone.View # This is an svg element showing the table's status in the # appropriate color. Unlike a lot of other views, its @$el is # set to the svg element from the template, rather than being # wrapped. template: require('../../handlebars/table_status_indicator.hbs') initialize: => status_class = @status_to_class(@model.get('status')) @setElement(@template(status_class: status_class)) @render() @listenTo @model, 'change:status', @render status_to_class: (status) => if not status return "unknown" # ensure this matches "humanize_table_readiness" in util.coffee if status.all_replicas_ready return "ready" else if status.ready_for_writes return "ready-but-with-caveats" else return "not-ready" render: => # We don't re-render the template, just update the class of the svg stat_class = @status_to_class(@model.get('status')) # .addClass and .removeClass don't work on <svg> elements @$el.attr('class', "ionicon-table-status #{stat_class}") class SecondaryIndexesView extends Backbone.View template: require('../../handlebars/table-secondary_indexes.hbs') alert_message_template: require('../../handlebars/secondary_indexes-alert_msg.hbs') error_template: require('../../handlebars/secondary_indexes-error.hbs') events: 'click .create_link': 'show_add_index' 'click .create_btn': 'create_index' 'keydown .new_index_name': 'handle_keypress' 'click .cancel_btn': 'hide_add_index' 'click .reconnect_link': 'init_connection' 'click .close_hide': 'hide_alert' error_interval: 5*1000 # In case of an error, we try to retrieve the secondary index in 5 seconds normal_interval: 10*1000 # Retrieve secondary indexes every 10 seconds short_interval: 1000 # Interval when an index is being created initialize: (data) => @indexes_view = [] @interval_progress = null @collection = data.collection @model = data.model @adding_index = false @listenTo @model, 'change:index_unavailable', @set_warnings @render() @hook() if @collection? set_warnings: -> if @model.get('index_unavailable') @$('.unavailable-error').show() else @$('.unavailable-error').hide() set_fetch_progress: (index) => if not @interval_progress? @fetch_progress() @interval_progress = setInterval @fetch_progress, 1000 fetch_progress: => build_in_progress = false for index in @collection.models if index.get('ready') isnt true build_in_progress = true break if build_in_progress and @model.get('db')? query = r.db(@model.get('db')).table(@model.get('name')).indexStatus() .pluck('index', 'ready', 'progress') .merge( (index) => { id: index("index") db: @model.get("db") table: @model.get("name") }) driver.run_once query, (error, result) => if error? # This can happen if the table is temporarily # unavailable. We log the error, and ignore it console.log "Nothing bad - Could not fetch secondary indexes statuses" console.log error else all_ready = true for index in result if index.ready isnt true all_ready = false @collection.add new models.Index index, {merge: true} if all_ready is true clearInterval @interval_progress @interval_progress = null else clearInterval @interval_progress @interval_progress = null set_indexes: (indexes) => @collection = indexes @hook() hook: => @collection.each (index) => view = new SecondaryIndexView model: index container: @ # The first time, the collection is sorted @indexes_view.push view @$('.list_secondary_indexes').append view.render().$el if @collection.length is 0 @$('.no_index').show() else @$('.no_index').hide() @listenTo @collection, 'add', (index) => new_view = new SecondaryIndexView model: index container: @ if @indexes_view.length is 0 @indexes_view.push new_view @$('.list_secondary_indexes').html new_view.render().$el else added = false for view, position in @indexes_view if view.model.get('index') > index.get('index') added = true @indexes_view.splice position, 0, new_view if position is 0 @$('.list_secondary_indexes').prepend new_view.render().$el else @$('.index_container').eq(position-1).after new_view.render().$el break if added is false @indexes_view.push new_view @$('.list_secondary_indexes').append new_view.render().$el if @indexes_view.length is 1 @$('.no_index').hide() @listenTo @collection, 'remove', (index) => for view in @indexes_view if view.model is index index.destroy() ((view) => view.remove() @indexes_view.splice(@indexes_view.indexOf(view), 1) )(view) break if @collection.length is 0 @$('.no_index').show() render_error: (args) => @$('.alert_error_content').html @error_template args @$('.main_alert_error').show() @$('.main_alert').hide() render_feedback: (args) => if @$('.main_alert').css('display') is 'none' @$('.alert_content').html @alert_message_template args @$('.main_alert').show() else @$('.main_alert').fadeOut 'fast', => @$('.alert_content').html @alert_message_template args @$('.main_alert').fadeIn 'fast' @$('.main_alert_error').hide() render: => @$el.html @template adding_index: @adding_index @set_warnings() return @ # Show the form to add a secondary index show_add_index: (event) => event.preventDefault() @$('.add_index_li').show() @$('.create_container').hide() @$('.new_index_name').focus() # Hide the form to add a secondary index hide_add_index: => @$('.add_index_li').hide() @$('.create_container').show() @$('.new_index_name').val '' # We catch enter and esc when the user is writing a secondary index name handle_keypress: (event) => if event.which is 13 # Enter event.preventDefault() @create_index() else if event.which is 27 # ESC event.preventDefault() @hide_add_index() on_fail_to_connect: => @render_error connect_fail: true return @ create_index: => @$('.create_btn').prop 'disabled', 'disabled' @$('.cancel_btn').prop 'disabled', 'disabled' index_name = @$('.new_index_name').val() ((index_name) => query = r.db(@model.get('db')).table(@model.get('name')).indexCreate(index_name) driver.run_once query, (error, result) => @$('.create_btn').prop 'disabled', false @$('.cancel_btn').prop 'disabled', false that = @ if error? @render_error create_fail: true message: error.msg.replace('\n', '<br/>') else @collection.add new models.Index id: index_name index: index_name db: @model.get 'db' table: @model.get 'name' @render_feedback create_ok: true name: index_name @hide_add_index() )(index_name) # Hide alert BUT do not remove it hide_alert: (event) -> if event? and @$(event.target)?.data('name')? @deleting_secondary_index = null event.preventDefault() $(event.target).parent().hide() remove: => @stopListening() for view in @indexes_view view.remove() super() class SecondaryIndexView extends Backbone.View template: require('../../handlebars/table-secondary_index.hbs') progress_template: require('../../handlebars/simple_progressbar.hbs') events: 'click .delete_link': 'confirm_delete' 'click .delete_index_btn': 'delete_index' 'click .cancel_delete_btn': 'cancel_delete' tagName: 'li' className: 'index_container' initialize: (data) => @container = data.container @model.on 'change:progress', @update @model.on 'change:ready', @update update: (args) => if @model.get('ready') is false @render_progress_bar() else if @progress_bar? @render_progress_bar() else @render() render: => @$el.html @template is_empty: @model.get('name') is '' name: @model.get 'index' ready: @model.get 'ready' if @model.get('ready') is false @render_progress_bar() @container.set_fetch_progress() @ render_progress_bar: => progress = @model.get 'progress' if @progress_bar? if @model.get('ready') is true @progress_bar.render 100, 100, got_response: true check: true , => @render() else @progress_bar.render progress, 1, got_response: true check: true , => @render() else @progress_bar = new ui_progress.OperationProgressBar @progress_template @$('.progress_li').html @progress_bar.render(0, Infinity, {new_value: true, check: true}).$el # Show a confirmation before deleting a secondary index confirm_delete: (event) => event.preventDefault() @$('.alert_confirm_delete').show() delete_index: => @$('.btn').prop 'disabled', 'disabled' query = r.db(@model.get('db')).table(@model.get('table')).indexDrop(@model.get('index')) driver.run_once query, (error, result) => @$('.btn').prop 'disabled', false if error? @container.render_error delete_fail: true message: error.msg.replace('\n', '<br/>') else if result.dropped is 1 @container.render_feedback delete_ok: true name: @model.get('index') @model.destroy() else @container.render_error delete_fail: true message: "Result was not {dropped: 1}" # Close to hide_alert, but the way to reach the alert is slightly different than with the x link cancel_delete: -> @$('.alert_confirm_delete').hide() remove: => @progress_bar?.remove() super() exports.TableContainer = TableContainer exports.TableMainView = TableMainView exports.ReconfigurePanel = ReconfigurePanel exports.ReconfigureDiffView = ReconfigureDiffView exports.Title = Title exports.Profile = Profile exports.TableStatusIndicator = TableStatusIndicator exports.SecondaryIndexesView = SecondaryIndexesView exports.SecondaryIndexView = SecondaryIndexView
185223
# Copyright 2010-2015 RethinkDB models = require('../models.coffee') modals = require('../modals.coffee') shard_assignments = require('./shard_assignments.coffee') shard_distribution = require('./shard_distribution.coffee') vis = require('../vis.coffee') ui_modals = require('../ui_components/modals.coffee') ui_progress = require('../ui_components/progressbar.coffee') app = require('../app.coffee') driver = app.driver system_db = app.system_db r = require('rethinkdb') class TableContainer extends Backbone.View template: not_found: require('../../handlebars/element_view-not_found.hbs') error: require('../../handlebars/error-query.hbs') className: 'table-view' initialize: (id) => @id = id @table_found = true @indexes = null @distribution = new models.Distribution @guaranteed_timer = null @failable_index_timer = null @failable_misc_timer = null # This is the cache of error messages we've received from # @failable_index_query and @failable_misc_query @current_errors = {index: [], misc: []} # Initialize the model with mostly empty dummy data so we # can render it right away # # We have two types of errors that can trip us # up. info_unavailable errors happen when a you can't # fetch table.info(). index_unavailable errors happen when # you can't fetch table.indexStatus() @model = new models.Table id: id info_unavailable: false index_unavailable: false @listenTo @model, 'change:index_unavailable', (=> @maybe_refetch_data()) @table_view = new TableMainView model: @model indexes: @indexes distribution: @distribution shards_assignments: @shards_assignments @fetch_data() maybe_refetch_data: => if @model.get('info_unavailable') and not @model.get('index_unavailable') # This is triggered when we go from # table.indexStatus() failing to it succeeding. If # that's the case, we should refetch everything. What # happens is we try to fetch indexes every 1s, but # more expensive stuff like table.info() only every # 10s. To avoid having the table UI in an error state # longer than we need to, we use the secondary index # query as a canary in the coalmine to decide when to # try again with the info queries. @fetch_once() fetch_once: _.debounce((=> # fetches data once, but only does it if we flap less than # once every 2 seconds driver.run_once(@failable_misc_query, @failable_misc_handler) driver.run_once(@guaranteed_query, @guaranted_handler) ), 2000, true) add_error_message: (type, error) => # This avoids spamming the console with the same error # message. It keeps a cache of messages, prints out # anything new, and resets the cache once we stop # receiving errors if error not in @current_errors[type] console.log "#{type} error: #{error}" @current_errors[type].push(error) clear_cached_error_messages: (type) => # We clear the cache of errors once a successful query # makes it through if @current_errors[type].length > 0 @current_errors[type] = [] guaranteed_query: => # This query should succeed as long as the cluster is # available, since we get it from the system tables. Info # we don't get from the system tables includes things like # table/shard counts, or secondary index status. Those are # obtained from table.info() and table.indexStatus() below # in `failable_*_query` so if they fail we still get the # data available in the system tables. r.do( r.db(system_db).table('server_config').coerceTo('array'), r.db(system_db).table('table_status').get(@id), r.db(system_db).table('table_config').get(@id), (server_config, table_status, table_config) -> r.branch( table_status.eq(null), null, table_status.merge( max_shards: 64 num_shards: table_config("shards").count().default(0) num_servers: server_config.count() num_default_servers: server_config.filter((server) -> server('tags').contains('default')).count() max_num_shards: r.expr([64, server_config.filter(((server) -> server('tags').contains('default'))).count()]).min() num_primary_replicas: table_status("shards").count( (row) -> row('primary_replicas').isEmpty().not()) .default(0) num_replicas: table_status("shards").default([]).map((shard) -> shard('replicas').count()).sum() num_available_replicas: table_status("shards").concatMap( (shard) -> shard('replicas').filter({state: "ready"})) .count().default(0) num_replicas_per_shard: table_config("shards").default([]).map( (shard) -> shard('replicas').count()).max().default(0) status: table_status('status') id: table_status("id") # These are updated below if the table is ready ).without('shards') ) ) failable_index_query: => # This query only checks the status of secondary indexes. # It can throw an exception and failif the primary # replica is unavailable (which happens immediately after # a reconfigure). r.do( r.db(system_db).table('table_config').get(@id) (table_config) -> r.db(table_config("db")) .table(table_config("name"), read_mode: "single") .indexStatus() .pluck('index', 'ready', 'progress') .merge( (index) -> { id: index("index") db: table_config("db") table: table_config("name") }) # add an id for backbone ) failable_misc_query: => # Query to load data distribution and shard assignments. # We keep this separate from the failable_index_query because we don't want # to run it as often. # This query can throw an exception and failif the primary # replica is unavailable (which happens immediately after # a reconfigure). Since this query makes use of # table.info(), it's separated from the guaranteed query r.do( r.db(system_db).table('table_status').get(@id), r.db(system_db).table('table_config').get(@id), r.db(system_db).table('server_config') .map((x) -> [x('name'), x('id')]).coerceTo('ARRAY').coerceTo('OBJECT'), (table_status, table_config, server_name_to_id) -> table_status.merge({ distribution: r.db(table_status('db')) .table(table_status('name'), read_mode: "single") .info()('doc_count_estimates') .map(r.range(), (num_keys, position) -> num_keys: num_keys id: position) .coerceTo('array') total_keys: r.db(table_status('db')) .table(table_status('name'), read_mode: "single") .info()('doc_count_estimates') .sum() shard_assignments: table_status.merge((table_status) -> table_status('shards').default([]).map( table_config('shards').default([]), r.db(table_status('db')) .table(table_status('name'), read_mode: "single") .info()('doc_count_estimates'), (status, config, estimate) -> num_keys: estimate, replicas: status('replicas').merge((replica) -> id: server_name_to_id(replica('server')).default(null), configured_primary: config('primary_replica').eq(replica('server')) currently_primary: status('primary_replicas').contains(replica('server')) nonvoting: config('nonvoting_replicas').contains(replica('server')) ).orderBy(r.desc('currently_primary'), r.desc('configured_primary')) ) ) }) ) handle_failable_index_response: (error, result) => # Handle the result of failable_index_query if error? @add_error_message('index', error.msg) @model.set 'index_unavailable', true return @model.set 'index_unavailable', false @clear_cached_error_messages('index') if @indexes? @indexes.set _.map(result, (index) -> new models.Index index) else @indexes = new models.Indexes _.map result, (index) -> new models.Index index @table_view?.set_indexes @indexes @model.set indexes: result if !@table_view? @table_view = new TableMainView model: @model indexes: @indexes distribution: @distribution shards_assignments: @shards_assignments @render() handle_failable_misc_response: (error, result) => if error? @add_error_message('misc', error.msg) @model.set 'info_unavailable', true return @model.set 'info_unavailable', false @clear_cached_error_messages('misc') if @distribution? @distribution.set _.map result.distribution, (shard) -> new models.Shard shard @distribution.trigger 'update' else @distribution = new models.Distribution _.map( result.distribution, (shard) -> new models.Shard shard) @table_view?.set_distribution @distribution if @shards_assignments? @shards_assignments.set _.map result.shard_assignments, (shard) -> new models.ShardAssignment shard else @shards_assignments = new models.ShardAssignments( _.map result.shard_assignments, (shard) -> new models.ShardAssignment shard ) @table_view?.set_assignments @shards_assignments @model.set result if !@table_view? @table_view = new TableMainView model: @model indexes: @indexes distribution: @distribution shards_assignments: @shards_assignments @render() handle_guaranteed_response: (error, result) => if error? # TODO: We may want to render only if we failed to open a connection # TODO: Handle when the table is deleted @error = error @render() else rerender = @error? @error = null if result is null rerender = rerender or @table_found @table_found = false # Reset the data @indexes = null @render() else rerender = rerender or not @table_found @table_found = true @model.set result if rerender @render() fetch_data: => # This timer keeps track of the failable index query, so we can # cancel it when we navigate away from the table page. @failable_index_timer = driver.run( @failable_index_query(), 1000, @handle_failable_index_response ) # This timer keeps track of the failable misc query, so we can # cancel it when we navigate away from the table page. @failable_misc_timer = driver.run( @failable_misc_query(), 10000, @handle_failable_misc_response, ) # This timer keeps track of the guaranteed query, running # it every 5 seconds. We cancel it when navigating away # from the table page. @guaranteed_timer = driver.run( @guaranteed_query(), 5000, @handle_guaranteed_response, ) render: => if @error? @$el.html @template.error error: @error?.message url: '#tables/'+@id else if @table_found @$el.html @table_view.render().$el else # In this case, the query returned null, so the table was not found @$el.html @template.not_found id: @id type: 'table' type_url: 'tables' type_all_url: 'tables' @ remove: => driver.stop_timer @guaranteed_timer driver.stop_timer @failable_index_timer driver.stop_timer @failable_misc_timer @table_view?.remove() super() class TableMainView extends Backbone.View className: 'namespace-view' template: main: require('../../handlebars/table_container.hbs') alert: null # unused, delete this events: 'click .close': 'close_alert' 'click .operations .rename': 'rename_table' 'click .operations .delete': 'delete_table' initialize: (data, options) => @indexes = data.indexes @distribution = data.distribution @shards_assignments = data.shards_assignments # Panels for namespace view @title = new Title model: @model @profile = new Profile model: @model @secondary_indexes_view = new SecondaryIndexesView collection: @indexes model: @model @shard_distribution = new shard_distribution.ShardDistribution collection: @distribution model: @model @server_assignments = new shard_assignments.ShardAssignmentsView model: @model collection: @shards_assignments @reconfigure = new ReconfigurePanel model: @model @stats = new models.Stats @stats_timer = driver.run( r.db(system_db).table('stats') .get(["table", @model.get('id')]) .do((stat) -> keys_read: stat('query_engine')('read_docs_per_sec') keys_set: stat('query_engine')('written<KEY>_docs<KEY>_per_sec') ), 1000, @stats.on_result) @performance_graph = new vis.OpsPlot(@stats.get_stats, width: 564 # width in pixels height: 210 # height in pixels seconds: 73 # num seconds to track type: 'table' ) set_indexes: (indexes) => if not @indexes? @indexes = indexes @secondary_indexes_view.set_indexes @indexes set_distribution: (distribution) => @distribution = distribution @shard_distribution.set_distribution @distribution set_assignments: (shards_assignments) => @shards_assignments = shards_assignments @server_assignments.set_assignments @shards_assignments render: => @$el.html @template.main namespace_id: @model.get 'id' # fill the title of this page @$('.main_title').html @title.render().$el # Add the replica and shards views @$('.profile').html @profile.render().$el @$('.performance-graph').html @performance_graph.render().$el # Display the shards @$('.sharding').html @shard_distribution.render().el # Display the server assignments @$('.server-assignments').html @server_assignments.render().el # Display the secondary indexes @$('.secondary_indexes').html @secondary_indexes_view.render().el # Display server reconfiguration @$('.reconfigure-panel').html @reconfigure.render().el @ close_alert: (event) -> event.preventDefault() $(event.currentTarget).parent().slideUp('fast', -> $(this).remove()) # Rename operation rename_table: (event) => event.preventDefault() if @rename_modal? @rename_modal.remove() @rename_modal = new ui_modals.RenameItemModal model: @model @rename_modal.render() # Delete operation delete_table: (event) -> event.preventDefault() if @remove_table_dialog? @remove_table_dialog.remove() @remove_table_dialog = new modals.RemoveTableModal @remove_table_dialog.render [{ table: @model.get 'name' database: @model.get 'db' }] remove: => @title.remove() @profile.remove() @shard_distribution.remove() @server_assignments.remove() @performance_graph.remove() @secondary_indexes_view.remove() @reconfigure.remove() driver.stop_timer @stats_timer if @remove_table_dialog? @remove_table_dialog.remove() if @rename_modal? @rename_modal.remove() super() class ReconfigurePanel extends Backbone.View className: 'reconfigure-panel' templates: main: require('../../handlebars/reconfigure.hbs') status: require('../../handlebars/replica_status.hbs') events: 'click .reconfigure.btn': 'launch_modal' initialize: (obj) => @model = obj.model @listenTo @model, 'change:num_shards', @render @listenTo @model, 'change:num_replicas_per_shard', @render @listenTo @model, 'change:num_available_replicas', @render_status @progress_bar = new ui_progress.OperationProgressBar @templates.status @timer = null launch_modal: => if @reconfigure_modal? @reconfigure_modal.remove() @reconfigure_modal = new modals.ReconfigureModal model: new models.Reconfigure parent: @ id: @model.get('id') db: @model.get('db') name: @model.get('name') total_keys: @model.get('total_keys') shards: [] max_shards: @model.get('max_shards') num_shards: @model.get('num_shards') num_servers: @model.get('num_servers') num_default_servers: @model.get('num_default_servers') max_num_shards: @model.get('max_num_shards') num_replicas_per_shard: @model.get('num_replicas_per_shard') @reconfigure_modal.render() remove: => if @reconfigure_modal? @reconfigure_modal.remove() if @timer? driver.stop_timer @timer @timer = null @progress_bar.remove() super() fetch_progress: => query = r.db(system_db).table('table_status') .get(@model.get('id'))('shards').default([])('replicas') .concatMap((x) -> x) .do((replicas) -> num_available_replicas: replicas.filter(state: 'ready').count() num_replicas: replicas.count() ) if @timer? driver.stop_timer @timer @timer = null @timer = driver.run query, 1000, (error, result) => if error? # This can happen if the table is temporarily # unavailable. We log the error, and ignore it console.log "Nothing bad - Could not fetch replicas statuses" console.log error else @model.set result @render_status() # Force to refresh the progress bar # Render the status of the replicas and the progress bar if needed render_status: => #TODO Handle backfilling when available in the api directly if @model.get('num_available_replicas') < @model.get('num_replicas') if not @timer? @fetch_progress() return if @progress_bar.get_stage() is 'none' @progress_bar.skip_to_processing() else if @timer? driver.stop_timer @timer @timer = null @progress_bar.render( @model.get('num_available_replicas'), @model.get('num_replicas'), {got_response: true} ) render: => @$el.html @templates.main @model.toJSON() if @model.get('num_available_replicas') < @model.get('num_replicas') if @progress_bar.get_stage() is 'none' @progress_bar.skip_to_processing() @$('.backfill-progress').html @progress_bar.render( @model.get('num_available_replicas'), @model.get('num_replicas'), {got_response: true}, ).$el @ class ReconfigureDiffView extends Backbone.View # This is just for the diff view in the reconfigure # modal. It's so that the diff can be rerendered independently # of the modal itself (which includes the input form). If you # rerended the entire modal, you lose focus in the text boxes # since handlebars creates an entirely new dom tree. # # You can find the ReconfigureModal in coffee/modals.coffee className: 'reconfigure-diff' template: require('../../handlebars/reconfigure-diff.hbs') initialize: => @listenTo @model, 'change:shards', @render render: => @$el.html @template @model.toJSON() @ class Title extends Backbone.View className: 'namespace-info-view' template: require('../../handlebars/table_title.hbs') initialize: => @listenTo @model, 'change:name', @render render: => @$el.html @template name: @model.get 'name' db: @model.get 'db' @ remove: => @stopListening() super() # Profile view class Profile extends Backbone.View template: require('../../handlebars/table_profile.hbs') initialize: => @listenTo @model, 'change', @render @indicator = new TableStatusIndicator model: @model render: => obj = { status: @model.get 'status' total_keys: @model.get 'total_keys' num_shards: @model.get 'num_shards' num_primary_replicas: @model.get 'num_primary_replicas' num_replicas: @model.get 'num_replicas' num_available_replicas: @model.get 'num_available_replicas' } if obj.status?.ready_for_writes and not obj?.status.all_replicas_ready obj.parenthetical = true @$el.html @template obj @$('.availability').prepend(@indicator.$el) return @ remove: => @indicator.remove() super() class TableStatusIndicator extends Backbone.View # This is an svg element showing the table's status in the # appropriate color. Unlike a lot of other views, its @$el is # set to the svg element from the template, rather than being # wrapped. template: require('../../handlebars/table_status_indicator.hbs') initialize: => status_class = @status_to_class(@model.get('status')) @setElement(@template(status_class: status_class)) @render() @listenTo @model, 'change:status', @render status_to_class: (status) => if not status return "unknown" # ensure this matches "humanize_table_readiness" in util.coffee if status.all_replicas_ready return "ready" else if status.ready_for_writes return "ready-but-with-caveats" else return "not-ready" render: => # We don't re-render the template, just update the class of the svg stat_class = @status_to_class(@model.get('status')) # .addClass and .removeClass don't work on <svg> elements @$el.attr('class', "ionicon-table-status #{stat_class}") class SecondaryIndexesView extends Backbone.View template: require('../../handlebars/table-secondary_indexes.hbs') alert_message_template: require('../../handlebars/secondary_indexes-alert_msg.hbs') error_template: require('../../handlebars/secondary_indexes-error.hbs') events: 'click .create_link': 'show_add_index' 'click .create_btn': 'create_index' 'keydown .new_index_name': 'handle_keypress' 'click .cancel_btn': 'hide_add_index' 'click .reconnect_link': 'init_connection' 'click .close_hide': 'hide_alert' error_interval: 5*1000 # In case of an error, we try to retrieve the secondary index in 5 seconds normal_interval: 10*1000 # Retrieve secondary indexes every 10 seconds short_interval: 1000 # Interval when an index is being created initialize: (data) => @indexes_view = [] @interval_progress = null @collection = data.collection @model = data.model @adding_index = false @listenTo @model, 'change:index_unavailable', @set_warnings @render() @hook() if @collection? set_warnings: -> if @model.get('index_unavailable') @$('.unavailable-error').show() else @$('.unavailable-error').hide() set_fetch_progress: (index) => if not @interval_progress? @fetch_progress() @interval_progress = setInterval @fetch_progress, 1000 fetch_progress: => build_in_progress = false for index in @collection.models if index.get('ready') isnt true build_in_progress = true break if build_in_progress and @model.get('db')? query = r.db(@model.get('db')).table(@model.get('name')).indexStatus() .pluck('index', 'ready', 'progress') .merge( (index) => { id: index("index") db: @model.get("db") table: @model.get("name") }) driver.run_once query, (error, result) => if error? # This can happen if the table is temporarily # unavailable. We log the error, and ignore it console.log "Nothing bad - Could not fetch secondary indexes statuses" console.log error else all_ready = true for index in result if index.ready isnt true all_ready = false @collection.add new models.Index index, {merge: true} if all_ready is true clearInterval @interval_progress @interval_progress = null else clearInterval @interval_progress @interval_progress = null set_indexes: (indexes) => @collection = indexes @hook() hook: => @collection.each (index) => view = new SecondaryIndexView model: index container: @ # The first time, the collection is sorted @indexes_view.push view @$('.list_secondary_indexes').append view.render().$el if @collection.length is 0 @$('.no_index').show() else @$('.no_index').hide() @listenTo @collection, 'add', (index) => new_view = new SecondaryIndexView model: index container: @ if @indexes_view.length is 0 @indexes_view.push new_view @$('.list_secondary_indexes').html new_view.render().$el else added = false for view, position in @indexes_view if view.model.get('index') > index.get('index') added = true @indexes_view.splice position, 0, new_view if position is 0 @$('.list_secondary_indexes').prepend new_view.render().$el else @$('.index_container').eq(position-1).after new_view.render().$el break if added is false @indexes_view.push new_view @$('.list_secondary_indexes').append new_view.render().$el if @indexes_view.length is 1 @$('.no_index').hide() @listenTo @collection, 'remove', (index) => for view in @indexes_view if view.model is index index.destroy() ((view) => view.remove() @indexes_view.splice(@indexes_view.indexOf(view), 1) )(view) break if @collection.length is 0 @$('.no_index').show() render_error: (args) => @$('.alert_error_content').html @error_template args @$('.main_alert_error').show() @$('.main_alert').hide() render_feedback: (args) => if @$('.main_alert').css('display') is 'none' @$('.alert_content').html @alert_message_template args @$('.main_alert').show() else @$('.main_alert').fadeOut 'fast', => @$('.alert_content').html @alert_message_template args @$('.main_alert').fadeIn 'fast' @$('.main_alert_error').hide() render: => @$el.html @template adding_index: @adding_index @set_warnings() return @ # Show the form to add a secondary index show_add_index: (event) => event.preventDefault() @$('.add_index_li').show() @$('.create_container').hide() @$('.new_index_name').focus() # Hide the form to add a secondary index hide_add_index: => @$('.add_index_li').hide() @$('.create_container').show() @$('.new_index_name').val '' # We catch enter and esc when the user is writing a secondary index name handle_keypress: (event) => if event.which is 13 # Enter event.preventDefault() @create_index() else if event.which is 27 # ESC event.preventDefault() @hide_add_index() on_fail_to_connect: => @render_error connect_fail: true return @ create_index: => @$('.create_btn').prop 'disabled', 'disabled' @$('.cancel_btn').prop 'disabled', 'disabled' index_name = @$('.new_index_name').val() ((index_name) => query = r.db(@model.get('db')).table(@model.get('name')).indexCreate(index_name) driver.run_once query, (error, result) => @$('.create_btn').prop 'disabled', false @$('.cancel_btn').prop 'disabled', false that = @ if error? @render_error create_fail: true message: error.msg.replace('\n', '<br/>') else @collection.add new models.Index id: index_name index: index_name db: @model.get 'db' table: @model.get 'name' @render_feedback create_ok: true name: index_name @hide_add_index() )(index_name) # Hide alert BUT do not remove it hide_alert: (event) -> if event? and @$(event.target)?.data('name')? @deleting_secondary_index = null event.preventDefault() $(event.target).parent().hide() remove: => @stopListening() for view in @indexes_view view.remove() super() class SecondaryIndexView extends Backbone.View template: require('../../handlebars/table-secondary_index.hbs') progress_template: require('../../handlebars/simple_progressbar.hbs') events: 'click .delete_link': 'confirm_delete' 'click .delete_index_btn': 'delete_index' 'click .cancel_delete_btn': 'cancel_delete' tagName: 'li' className: 'index_container' initialize: (data) => @container = data.container @model.on 'change:progress', @update @model.on 'change:ready', @update update: (args) => if @model.get('ready') is false @render_progress_bar() else if @progress_bar? @render_progress_bar() else @render() render: => @$el.html @template is_empty: @model.get('name') is '' name: @model.get 'index' ready: @model.get 'ready' if @model.get('ready') is false @render_progress_bar() @container.set_fetch_progress() @ render_progress_bar: => progress = @model.get 'progress' if @progress_bar? if @model.get('ready') is true @progress_bar.render 100, 100, got_response: true check: true , => @render() else @progress_bar.render progress, 1, got_response: true check: true , => @render() else @progress_bar = new ui_progress.OperationProgressBar @progress_template @$('.progress_li').html @progress_bar.render(0, Infinity, {new_value: true, check: true}).$el # Show a confirmation before deleting a secondary index confirm_delete: (event) => event.preventDefault() @$('.alert_confirm_delete').show() delete_index: => @$('.btn').prop 'disabled', 'disabled' query = r.db(@model.get('db')).table(@model.get('table')).indexDrop(@model.get('index')) driver.run_once query, (error, result) => @$('.btn').prop 'disabled', false if error? @container.render_error delete_fail: true message: error.msg.replace('\n', '<br/>') else if result.dropped is 1 @container.render_feedback delete_ok: true name: @model.get('index') @model.destroy() else @container.render_error delete_fail: true message: "Result was not {dropped: 1}" # Close to hide_alert, but the way to reach the alert is slightly different than with the x link cancel_delete: -> @$('.alert_confirm_delete').hide() remove: => @progress_bar?.remove() super() exports.TableContainer = TableContainer exports.TableMainView = TableMainView exports.ReconfigurePanel = ReconfigurePanel exports.ReconfigureDiffView = ReconfigureDiffView exports.Title = Title exports.Profile = Profile exports.TableStatusIndicator = TableStatusIndicator exports.SecondaryIndexesView = SecondaryIndexesView exports.SecondaryIndexView = SecondaryIndexView
true
# Copyright 2010-2015 RethinkDB models = require('../models.coffee') modals = require('../modals.coffee') shard_assignments = require('./shard_assignments.coffee') shard_distribution = require('./shard_distribution.coffee') vis = require('../vis.coffee') ui_modals = require('../ui_components/modals.coffee') ui_progress = require('../ui_components/progressbar.coffee') app = require('../app.coffee') driver = app.driver system_db = app.system_db r = require('rethinkdb') class TableContainer extends Backbone.View template: not_found: require('../../handlebars/element_view-not_found.hbs') error: require('../../handlebars/error-query.hbs') className: 'table-view' initialize: (id) => @id = id @table_found = true @indexes = null @distribution = new models.Distribution @guaranteed_timer = null @failable_index_timer = null @failable_misc_timer = null # This is the cache of error messages we've received from # @failable_index_query and @failable_misc_query @current_errors = {index: [], misc: []} # Initialize the model with mostly empty dummy data so we # can render it right away # # We have two types of errors that can trip us # up. info_unavailable errors happen when a you can't # fetch table.info(). index_unavailable errors happen when # you can't fetch table.indexStatus() @model = new models.Table id: id info_unavailable: false index_unavailable: false @listenTo @model, 'change:index_unavailable', (=> @maybe_refetch_data()) @table_view = new TableMainView model: @model indexes: @indexes distribution: @distribution shards_assignments: @shards_assignments @fetch_data() maybe_refetch_data: => if @model.get('info_unavailable') and not @model.get('index_unavailable') # This is triggered when we go from # table.indexStatus() failing to it succeeding. If # that's the case, we should refetch everything. What # happens is we try to fetch indexes every 1s, but # more expensive stuff like table.info() only every # 10s. To avoid having the table UI in an error state # longer than we need to, we use the secondary index # query as a canary in the coalmine to decide when to # try again with the info queries. @fetch_once() fetch_once: _.debounce((=> # fetches data once, but only does it if we flap less than # once every 2 seconds driver.run_once(@failable_misc_query, @failable_misc_handler) driver.run_once(@guaranteed_query, @guaranted_handler) ), 2000, true) add_error_message: (type, error) => # This avoids spamming the console with the same error # message. It keeps a cache of messages, prints out # anything new, and resets the cache once we stop # receiving errors if error not in @current_errors[type] console.log "#{type} error: #{error}" @current_errors[type].push(error) clear_cached_error_messages: (type) => # We clear the cache of errors once a successful query # makes it through if @current_errors[type].length > 0 @current_errors[type] = [] guaranteed_query: => # This query should succeed as long as the cluster is # available, since we get it from the system tables. Info # we don't get from the system tables includes things like # table/shard counts, or secondary index status. Those are # obtained from table.info() and table.indexStatus() below # in `failable_*_query` so if they fail we still get the # data available in the system tables. r.do( r.db(system_db).table('server_config').coerceTo('array'), r.db(system_db).table('table_status').get(@id), r.db(system_db).table('table_config').get(@id), (server_config, table_status, table_config) -> r.branch( table_status.eq(null), null, table_status.merge( max_shards: 64 num_shards: table_config("shards").count().default(0) num_servers: server_config.count() num_default_servers: server_config.filter((server) -> server('tags').contains('default')).count() max_num_shards: r.expr([64, server_config.filter(((server) -> server('tags').contains('default'))).count()]).min() num_primary_replicas: table_status("shards").count( (row) -> row('primary_replicas').isEmpty().not()) .default(0) num_replicas: table_status("shards").default([]).map((shard) -> shard('replicas').count()).sum() num_available_replicas: table_status("shards").concatMap( (shard) -> shard('replicas').filter({state: "ready"})) .count().default(0) num_replicas_per_shard: table_config("shards").default([]).map( (shard) -> shard('replicas').count()).max().default(0) status: table_status('status') id: table_status("id") # These are updated below if the table is ready ).without('shards') ) ) failable_index_query: => # This query only checks the status of secondary indexes. # It can throw an exception and failif the primary # replica is unavailable (which happens immediately after # a reconfigure). r.do( r.db(system_db).table('table_config').get(@id) (table_config) -> r.db(table_config("db")) .table(table_config("name"), read_mode: "single") .indexStatus() .pluck('index', 'ready', 'progress') .merge( (index) -> { id: index("index") db: table_config("db") table: table_config("name") }) # add an id for backbone ) failable_misc_query: => # Query to load data distribution and shard assignments. # We keep this separate from the failable_index_query because we don't want # to run it as often. # This query can throw an exception and failif the primary # replica is unavailable (which happens immediately after # a reconfigure). Since this query makes use of # table.info(), it's separated from the guaranteed query r.do( r.db(system_db).table('table_status').get(@id), r.db(system_db).table('table_config').get(@id), r.db(system_db).table('server_config') .map((x) -> [x('name'), x('id')]).coerceTo('ARRAY').coerceTo('OBJECT'), (table_status, table_config, server_name_to_id) -> table_status.merge({ distribution: r.db(table_status('db')) .table(table_status('name'), read_mode: "single") .info()('doc_count_estimates') .map(r.range(), (num_keys, position) -> num_keys: num_keys id: position) .coerceTo('array') total_keys: r.db(table_status('db')) .table(table_status('name'), read_mode: "single") .info()('doc_count_estimates') .sum() shard_assignments: table_status.merge((table_status) -> table_status('shards').default([]).map( table_config('shards').default([]), r.db(table_status('db')) .table(table_status('name'), read_mode: "single") .info()('doc_count_estimates'), (status, config, estimate) -> num_keys: estimate, replicas: status('replicas').merge((replica) -> id: server_name_to_id(replica('server')).default(null), configured_primary: config('primary_replica').eq(replica('server')) currently_primary: status('primary_replicas').contains(replica('server')) nonvoting: config('nonvoting_replicas').contains(replica('server')) ).orderBy(r.desc('currently_primary'), r.desc('configured_primary')) ) ) }) ) handle_failable_index_response: (error, result) => # Handle the result of failable_index_query if error? @add_error_message('index', error.msg) @model.set 'index_unavailable', true return @model.set 'index_unavailable', false @clear_cached_error_messages('index') if @indexes? @indexes.set _.map(result, (index) -> new models.Index index) else @indexes = new models.Indexes _.map result, (index) -> new models.Index index @table_view?.set_indexes @indexes @model.set indexes: result if !@table_view? @table_view = new TableMainView model: @model indexes: @indexes distribution: @distribution shards_assignments: @shards_assignments @render() handle_failable_misc_response: (error, result) => if error? @add_error_message('misc', error.msg) @model.set 'info_unavailable', true return @model.set 'info_unavailable', false @clear_cached_error_messages('misc') if @distribution? @distribution.set _.map result.distribution, (shard) -> new models.Shard shard @distribution.trigger 'update' else @distribution = new models.Distribution _.map( result.distribution, (shard) -> new models.Shard shard) @table_view?.set_distribution @distribution if @shards_assignments? @shards_assignments.set _.map result.shard_assignments, (shard) -> new models.ShardAssignment shard else @shards_assignments = new models.ShardAssignments( _.map result.shard_assignments, (shard) -> new models.ShardAssignment shard ) @table_view?.set_assignments @shards_assignments @model.set result if !@table_view? @table_view = new TableMainView model: @model indexes: @indexes distribution: @distribution shards_assignments: @shards_assignments @render() handle_guaranteed_response: (error, result) => if error? # TODO: We may want to render only if we failed to open a connection # TODO: Handle when the table is deleted @error = error @render() else rerender = @error? @error = null if result is null rerender = rerender or @table_found @table_found = false # Reset the data @indexes = null @render() else rerender = rerender or not @table_found @table_found = true @model.set result if rerender @render() fetch_data: => # This timer keeps track of the failable index query, so we can # cancel it when we navigate away from the table page. @failable_index_timer = driver.run( @failable_index_query(), 1000, @handle_failable_index_response ) # This timer keeps track of the failable misc query, so we can # cancel it when we navigate away from the table page. @failable_misc_timer = driver.run( @failable_misc_query(), 10000, @handle_failable_misc_response, ) # This timer keeps track of the guaranteed query, running # it every 5 seconds. We cancel it when navigating away # from the table page. @guaranteed_timer = driver.run( @guaranteed_query(), 5000, @handle_guaranteed_response, ) render: => if @error? @$el.html @template.error error: @error?.message url: '#tables/'+@id else if @table_found @$el.html @table_view.render().$el else # In this case, the query returned null, so the table was not found @$el.html @template.not_found id: @id type: 'table' type_url: 'tables' type_all_url: 'tables' @ remove: => driver.stop_timer @guaranteed_timer driver.stop_timer @failable_index_timer driver.stop_timer @failable_misc_timer @table_view?.remove() super() class TableMainView extends Backbone.View className: 'namespace-view' template: main: require('../../handlebars/table_container.hbs') alert: null # unused, delete this events: 'click .close': 'close_alert' 'click .operations .rename': 'rename_table' 'click .operations .delete': 'delete_table' initialize: (data, options) => @indexes = data.indexes @distribution = data.distribution @shards_assignments = data.shards_assignments # Panels for namespace view @title = new Title model: @model @profile = new Profile model: @model @secondary_indexes_view = new SecondaryIndexesView collection: @indexes model: @model @shard_distribution = new shard_distribution.ShardDistribution collection: @distribution model: @model @server_assignments = new shard_assignments.ShardAssignmentsView model: @model collection: @shards_assignments @reconfigure = new ReconfigurePanel model: @model @stats = new models.Stats @stats_timer = driver.run( r.db(system_db).table('stats') .get(["table", @model.get('id')]) .do((stat) -> keys_read: stat('query_engine')('read_docs_per_sec') keys_set: stat('query_engine')('writtenPI:KEY:<KEY>END_PI_docsPI:KEY:<KEY>END_PI_per_sec') ), 1000, @stats.on_result) @performance_graph = new vis.OpsPlot(@stats.get_stats, width: 564 # width in pixels height: 210 # height in pixels seconds: 73 # num seconds to track type: 'table' ) set_indexes: (indexes) => if not @indexes? @indexes = indexes @secondary_indexes_view.set_indexes @indexes set_distribution: (distribution) => @distribution = distribution @shard_distribution.set_distribution @distribution set_assignments: (shards_assignments) => @shards_assignments = shards_assignments @server_assignments.set_assignments @shards_assignments render: => @$el.html @template.main namespace_id: @model.get 'id' # fill the title of this page @$('.main_title').html @title.render().$el # Add the replica and shards views @$('.profile').html @profile.render().$el @$('.performance-graph').html @performance_graph.render().$el # Display the shards @$('.sharding').html @shard_distribution.render().el # Display the server assignments @$('.server-assignments').html @server_assignments.render().el # Display the secondary indexes @$('.secondary_indexes').html @secondary_indexes_view.render().el # Display server reconfiguration @$('.reconfigure-panel').html @reconfigure.render().el @ close_alert: (event) -> event.preventDefault() $(event.currentTarget).parent().slideUp('fast', -> $(this).remove()) # Rename operation rename_table: (event) => event.preventDefault() if @rename_modal? @rename_modal.remove() @rename_modal = new ui_modals.RenameItemModal model: @model @rename_modal.render() # Delete operation delete_table: (event) -> event.preventDefault() if @remove_table_dialog? @remove_table_dialog.remove() @remove_table_dialog = new modals.RemoveTableModal @remove_table_dialog.render [{ table: @model.get 'name' database: @model.get 'db' }] remove: => @title.remove() @profile.remove() @shard_distribution.remove() @server_assignments.remove() @performance_graph.remove() @secondary_indexes_view.remove() @reconfigure.remove() driver.stop_timer @stats_timer if @remove_table_dialog? @remove_table_dialog.remove() if @rename_modal? @rename_modal.remove() super() class ReconfigurePanel extends Backbone.View className: 'reconfigure-panel' templates: main: require('../../handlebars/reconfigure.hbs') status: require('../../handlebars/replica_status.hbs') events: 'click .reconfigure.btn': 'launch_modal' initialize: (obj) => @model = obj.model @listenTo @model, 'change:num_shards', @render @listenTo @model, 'change:num_replicas_per_shard', @render @listenTo @model, 'change:num_available_replicas', @render_status @progress_bar = new ui_progress.OperationProgressBar @templates.status @timer = null launch_modal: => if @reconfigure_modal? @reconfigure_modal.remove() @reconfigure_modal = new modals.ReconfigureModal model: new models.Reconfigure parent: @ id: @model.get('id') db: @model.get('db') name: @model.get('name') total_keys: @model.get('total_keys') shards: [] max_shards: @model.get('max_shards') num_shards: @model.get('num_shards') num_servers: @model.get('num_servers') num_default_servers: @model.get('num_default_servers') max_num_shards: @model.get('max_num_shards') num_replicas_per_shard: @model.get('num_replicas_per_shard') @reconfigure_modal.render() remove: => if @reconfigure_modal? @reconfigure_modal.remove() if @timer? driver.stop_timer @timer @timer = null @progress_bar.remove() super() fetch_progress: => query = r.db(system_db).table('table_status') .get(@model.get('id'))('shards').default([])('replicas') .concatMap((x) -> x) .do((replicas) -> num_available_replicas: replicas.filter(state: 'ready').count() num_replicas: replicas.count() ) if @timer? driver.stop_timer @timer @timer = null @timer = driver.run query, 1000, (error, result) => if error? # This can happen if the table is temporarily # unavailable. We log the error, and ignore it console.log "Nothing bad - Could not fetch replicas statuses" console.log error else @model.set result @render_status() # Force to refresh the progress bar # Render the status of the replicas and the progress bar if needed render_status: => #TODO Handle backfilling when available in the api directly if @model.get('num_available_replicas') < @model.get('num_replicas') if not @timer? @fetch_progress() return if @progress_bar.get_stage() is 'none' @progress_bar.skip_to_processing() else if @timer? driver.stop_timer @timer @timer = null @progress_bar.render( @model.get('num_available_replicas'), @model.get('num_replicas'), {got_response: true} ) render: => @$el.html @templates.main @model.toJSON() if @model.get('num_available_replicas') < @model.get('num_replicas') if @progress_bar.get_stage() is 'none' @progress_bar.skip_to_processing() @$('.backfill-progress').html @progress_bar.render( @model.get('num_available_replicas'), @model.get('num_replicas'), {got_response: true}, ).$el @ class ReconfigureDiffView extends Backbone.View # This is just for the diff view in the reconfigure # modal. It's so that the diff can be rerendered independently # of the modal itself (which includes the input form). If you # rerended the entire modal, you lose focus in the text boxes # since handlebars creates an entirely new dom tree. # # You can find the ReconfigureModal in coffee/modals.coffee className: 'reconfigure-diff' template: require('../../handlebars/reconfigure-diff.hbs') initialize: => @listenTo @model, 'change:shards', @render render: => @$el.html @template @model.toJSON() @ class Title extends Backbone.View className: 'namespace-info-view' template: require('../../handlebars/table_title.hbs') initialize: => @listenTo @model, 'change:name', @render render: => @$el.html @template name: @model.get 'name' db: @model.get 'db' @ remove: => @stopListening() super() # Profile view class Profile extends Backbone.View template: require('../../handlebars/table_profile.hbs') initialize: => @listenTo @model, 'change', @render @indicator = new TableStatusIndicator model: @model render: => obj = { status: @model.get 'status' total_keys: @model.get 'total_keys' num_shards: @model.get 'num_shards' num_primary_replicas: @model.get 'num_primary_replicas' num_replicas: @model.get 'num_replicas' num_available_replicas: @model.get 'num_available_replicas' } if obj.status?.ready_for_writes and not obj?.status.all_replicas_ready obj.parenthetical = true @$el.html @template obj @$('.availability').prepend(@indicator.$el) return @ remove: => @indicator.remove() super() class TableStatusIndicator extends Backbone.View # This is an svg element showing the table's status in the # appropriate color. Unlike a lot of other views, its @$el is # set to the svg element from the template, rather than being # wrapped. template: require('../../handlebars/table_status_indicator.hbs') initialize: => status_class = @status_to_class(@model.get('status')) @setElement(@template(status_class: status_class)) @render() @listenTo @model, 'change:status', @render status_to_class: (status) => if not status return "unknown" # ensure this matches "humanize_table_readiness" in util.coffee if status.all_replicas_ready return "ready" else if status.ready_for_writes return "ready-but-with-caveats" else return "not-ready" render: => # We don't re-render the template, just update the class of the svg stat_class = @status_to_class(@model.get('status')) # .addClass and .removeClass don't work on <svg> elements @$el.attr('class', "ionicon-table-status #{stat_class}") class SecondaryIndexesView extends Backbone.View template: require('../../handlebars/table-secondary_indexes.hbs') alert_message_template: require('../../handlebars/secondary_indexes-alert_msg.hbs') error_template: require('../../handlebars/secondary_indexes-error.hbs') events: 'click .create_link': 'show_add_index' 'click .create_btn': 'create_index' 'keydown .new_index_name': 'handle_keypress' 'click .cancel_btn': 'hide_add_index' 'click .reconnect_link': 'init_connection' 'click .close_hide': 'hide_alert' error_interval: 5*1000 # In case of an error, we try to retrieve the secondary index in 5 seconds normal_interval: 10*1000 # Retrieve secondary indexes every 10 seconds short_interval: 1000 # Interval when an index is being created initialize: (data) => @indexes_view = [] @interval_progress = null @collection = data.collection @model = data.model @adding_index = false @listenTo @model, 'change:index_unavailable', @set_warnings @render() @hook() if @collection? set_warnings: -> if @model.get('index_unavailable') @$('.unavailable-error').show() else @$('.unavailable-error').hide() set_fetch_progress: (index) => if not @interval_progress? @fetch_progress() @interval_progress = setInterval @fetch_progress, 1000 fetch_progress: => build_in_progress = false for index in @collection.models if index.get('ready') isnt true build_in_progress = true break if build_in_progress and @model.get('db')? query = r.db(@model.get('db')).table(@model.get('name')).indexStatus() .pluck('index', 'ready', 'progress') .merge( (index) => { id: index("index") db: @model.get("db") table: @model.get("name") }) driver.run_once query, (error, result) => if error? # This can happen if the table is temporarily # unavailable. We log the error, and ignore it console.log "Nothing bad - Could not fetch secondary indexes statuses" console.log error else all_ready = true for index in result if index.ready isnt true all_ready = false @collection.add new models.Index index, {merge: true} if all_ready is true clearInterval @interval_progress @interval_progress = null else clearInterval @interval_progress @interval_progress = null set_indexes: (indexes) => @collection = indexes @hook() hook: => @collection.each (index) => view = new SecondaryIndexView model: index container: @ # The first time, the collection is sorted @indexes_view.push view @$('.list_secondary_indexes').append view.render().$el if @collection.length is 0 @$('.no_index').show() else @$('.no_index').hide() @listenTo @collection, 'add', (index) => new_view = new SecondaryIndexView model: index container: @ if @indexes_view.length is 0 @indexes_view.push new_view @$('.list_secondary_indexes').html new_view.render().$el else added = false for view, position in @indexes_view if view.model.get('index') > index.get('index') added = true @indexes_view.splice position, 0, new_view if position is 0 @$('.list_secondary_indexes').prepend new_view.render().$el else @$('.index_container').eq(position-1).after new_view.render().$el break if added is false @indexes_view.push new_view @$('.list_secondary_indexes').append new_view.render().$el if @indexes_view.length is 1 @$('.no_index').hide() @listenTo @collection, 'remove', (index) => for view in @indexes_view if view.model is index index.destroy() ((view) => view.remove() @indexes_view.splice(@indexes_view.indexOf(view), 1) )(view) break if @collection.length is 0 @$('.no_index').show() render_error: (args) => @$('.alert_error_content').html @error_template args @$('.main_alert_error').show() @$('.main_alert').hide() render_feedback: (args) => if @$('.main_alert').css('display') is 'none' @$('.alert_content').html @alert_message_template args @$('.main_alert').show() else @$('.main_alert').fadeOut 'fast', => @$('.alert_content').html @alert_message_template args @$('.main_alert').fadeIn 'fast' @$('.main_alert_error').hide() render: => @$el.html @template adding_index: @adding_index @set_warnings() return @ # Show the form to add a secondary index show_add_index: (event) => event.preventDefault() @$('.add_index_li').show() @$('.create_container').hide() @$('.new_index_name').focus() # Hide the form to add a secondary index hide_add_index: => @$('.add_index_li').hide() @$('.create_container').show() @$('.new_index_name').val '' # We catch enter and esc when the user is writing a secondary index name handle_keypress: (event) => if event.which is 13 # Enter event.preventDefault() @create_index() else if event.which is 27 # ESC event.preventDefault() @hide_add_index() on_fail_to_connect: => @render_error connect_fail: true return @ create_index: => @$('.create_btn').prop 'disabled', 'disabled' @$('.cancel_btn').prop 'disabled', 'disabled' index_name = @$('.new_index_name').val() ((index_name) => query = r.db(@model.get('db')).table(@model.get('name')).indexCreate(index_name) driver.run_once query, (error, result) => @$('.create_btn').prop 'disabled', false @$('.cancel_btn').prop 'disabled', false that = @ if error? @render_error create_fail: true message: error.msg.replace('\n', '<br/>') else @collection.add new models.Index id: index_name index: index_name db: @model.get 'db' table: @model.get 'name' @render_feedback create_ok: true name: index_name @hide_add_index() )(index_name) # Hide alert BUT do not remove it hide_alert: (event) -> if event? and @$(event.target)?.data('name')? @deleting_secondary_index = null event.preventDefault() $(event.target).parent().hide() remove: => @stopListening() for view in @indexes_view view.remove() super() class SecondaryIndexView extends Backbone.View template: require('../../handlebars/table-secondary_index.hbs') progress_template: require('../../handlebars/simple_progressbar.hbs') events: 'click .delete_link': 'confirm_delete' 'click .delete_index_btn': 'delete_index' 'click .cancel_delete_btn': 'cancel_delete' tagName: 'li' className: 'index_container' initialize: (data) => @container = data.container @model.on 'change:progress', @update @model.on 'change:ready', @update update: (args) => if @model.get('ready') is false @render_progress_bar() else if @progress_bar? @render_progress_bar() else @render() render: => @$el.html @template is_empty: @model.get('name') is '' name: @model.get 'index' ready: @model.get 'ready' if @model.get('ready') is false @render_progress_bar() @container.set_fetch_progress() @ render_progress_bar: => progress = @model.get 'progress' if @progress_bar? if @model.get('ready') is true @progress_bar.render 100, 100, got_response: true check: true , => @render() else @progress_bar.render progress, 1, got_response: true check: true , => @render() else @progress_bar = new ui_progress.OperationProgressBar @progress_template @$('.progress_li').html @progress_bar.render(0, Infinity, {new_value: true, check: true}).$el # Show a confirmation before deleting a secondary index confirm_delete: (event) => event.preventDefault() @$('.alert_confirm_delete').show() delete_index: => @$('.btn').prop 'disabled', 'disabled' query = r.db(@model.get('db')).table(@model.get('table')).indexDrop(@model.get('index')) driver.run_once query, (error, result) => @$('.btn').prop 'disabled', false if error? @container.render_error delete_fail: true message: error.msg.replace('\n', '<br/>') else if result.dropped is 1 @container.render_feedback delete_ok: true name: @model.get('index') @model.destroy() else @container.render_error delete_fail: true message: "Result was not {dropped: 1}" # Close to hide_alert, but the way to reach the alert is slightly different than with the x link cancel_delete: -> @$('.alert_confirm_delete').hide() remove: => @progress_bar?.remove() super() exports.TableContainer = TableContainer exports.TableMainView = TableMainView exports.ReconfigurePanel = ReconfigurePanel exports.ReconfigureDiffView = ReconfigureDiffView exports.Title = Title exports.Profile = Profile exports.TableStatusIndicator = TableStatusIndicator exports.SecondaryIndexesView = SecondaryIndexesView exports.SecondaryIndexView = SecondaryIndexView
[ { "context": "er to use as timer.\n\n @class bkcore.Timer\n @author Thibaut 'BKcore' Despoulain <http://bkcore.com>\n###\nclass", "end": 89, "score": 0.999880313873291, "start": 82, "tag": "NAME", "value": "Thibaut" }, { "context": "r.\n\n @class bkcore.Timer\n @author Thibaut 'BKcor...
webInterface/game/bkcore.coffee/Timer.coffee
ploh007/design-project
1,017
### new Date().getTime() wrapper to use as timer. @class bkcore.Timer @author Thibaut 'BKcore' Despoulain <http://bkcore.com> ### class Timer ### Creates a new timer, inactive by default. Call Timer.start() to activate. ### constructor: ()-> @time = start: 0 current: 0 previous: 0 elapsed: 0 delta: 0 @active = false ### Starts/restarts the timer. ### start: ()-> now = (new Date).getTime() @time.start = now @time.current = now @time.previous = now @time.elapsed = 0 @time.delta = 0 @active = true ### Pauses(true)/Unpauses(false) the timer. @param bool Do pause ### pause: (doPause)-> @active = not doPause ### Update method to be called inside a RAF loop ### update: ()-> if not @active then return now = (new Date).getTime() @time.current = now @time.elapsed = @time.current - @time.start @time.delta = now - @time.previous @time.previous = now ### Returns a formatted version of the current elapsed time using msToTime(). ### getElapsedTime: ()-> return @constructor.msToTime(@time.elapsed) ### Formats a millisecond integer into a h/m/s/ms object @param x int In milliseconds @return Object{h,m,s,ms} ### @msToTime: (t)-> ms = t%1000 s = Math.floor((t/1000)%60) m = Math.floor((t/60000)%60) h = Math.floor(t/3600000) return {h:h, m:m, s:s, ms,ms} ### Formats a millisecond integer into a h/m/s/ms object with prefix zeros @param x int In milliseconds @return Object<string>{h,m,s,ms} ### @msToTimeString: (t)-> time = @msToTime(t) time.h = @zfill(time.h, 2) time.m = @zfill(time.m, 2) time.s = @zfill(time.s, 2) time.ms = @zfill(time.ms, 4) return time ### Convert given integer to string and fill with heading zeros @param num int Number to convert/fill @param size int Desired string size ### @zfill: (num, size)-> len = size - num.toString().length return if len > 0 then new Array(len+1).join('0') + num else num.toString() ### Exports @package bkcore ### exports = exports ? @ exports.bkcore ||= {} exports.bkcore.Timer = Timer
41228
### new Date().getTime() wrapper to use as timer. @class bkcore.Timer @author <NAME> 'BKcore' <NAME> <http://bkcore.com> ### class Timer ### Creates a new timer, inactive by default. Call Timer.start() to activate. ### constructor: ()-> @time = start: 0 current: 0 previous: 0 elapsed: 0 delta: 0 @active = false ### Starts/restarts the timer. ### start: ()-> now = (new Date).getTime() @time.start = now @time.current = now @time.previous = now @time.elapsed = 0 @time.delta = 0 @active = true ### Pauses(true)/Unpauses(false) the timer. @param bool Do pause ### pause: (doPause)-> @active = not doPause ### Update method to be called inside a RAF loop ### update: ()-> if not @active then return now = (new Date).getTime() @time.current = now @time.elapsed = @time.current - @time.start @time.delta = now - @time.previous @time.previous = now ### Returns a formatted version of the current elapsed time using msToTime(). ### getElapsedTime: ()-> return @constructor.msToTime(@time.elapsed) ### Formats a millisecond integer into a h/m/s/ms object @param x int In milliseconds @return Object{h,m,s,ms} ### @msToTime: (t)-> ms = t%1000 s = Math.floor((t/1000)%60) m = Math.floor((t/60000)%60) h = Math.floor(t/3600000) return {h:h, m:m, s:s, ms,ms} ### Formats a millisecond integer into a h/m/s/ms object with prefix zeros @param x int In milliseconds @return Object<string>{h,m,s,ms} ### @msToTimeString: (t)-> time = @msToTime(t) time.h = @zfill(time.h, 2) time.m = @zfill(time.m, 2) time.s = @zfill(time.s, 2) time.ms = @zfill(time.ms, 4) return time ### Convert given integer to string and fill with heading zeros @param num int Number to convert/fill @param size int Desired string size ### @zfill: (num, size)-> len = size - num.toString().length return if len > 0 then new Array(len+1).join('0') + num else num.toString() ### Exports @package bkcore ### exports = exports ? @ exports.bkcore ||= {} exports.bkcore.Timer = Timer
true
### new Date().getTime() wrapper to use as timer. @class bkcore.Timer @author PI:NAME:<NAME>END_PI 'BKcore' PI:NAME:<NAME>END_PI <http://bkcore.com> ### class Timer ### Creates a new timer, inactive by default. Call Timer.start() to activate. ### constructor: ()-> @time = start: 0 current: 0 previous: 0 elapsed: 0 delta: 0 @active = false ### Starts/restarts the timer. ### start: ()-> now = (new Date).getTime() @time.start = now @time.current = now @time.previous = now @time.elapsed = 0 @time.delta = 0 @active = true ### Pauses(true)/Unpauses(false) the timer. @param bool Do pause ### pause: (doPause)-> @active = not doPause ### Update method to be called inside a RAF loop ### update: ()-> if not @active then return now = (new Date).getTime() @time.current = now @time.elapsed = @time.current - @time.start @time.delta = now - @time.previous @time.previous = now ### Returns a formatted version of the current elapsed time using msToTime(). ### getElapsedTime: ()-> return @constructor.msToTime(@time.elapsed) ### Formats a millisecond integer into a h/m/s/ms object @param x int In milliseconds @return Object{h,m,s,ms} ### @msToTime: (t)-> ms = t%1000 s = Math.floor((t/1000)%60) m = Math.floor((t/60000)%60) h = Math.floor(t/3600000) return {h:h, m:m, s:s, ms,ms} ### Formats a millisecond integer into a h/m/s/ms object with prefix zeros @param x int In milliseconds @return Object<string>{h,m,s,ms} ### @msToTimeString: (t)-> time = @msToTime(t) time.h = @zfill(time.h, 2) time.m = @zfill(time.m, 2) time.s = @zfill(time.s, 2) time.ms = @zfill(time.ms, 4) return time ### Convert given integer to string and fill with heading zeros @param num int Number to convert/fill @param size int Desired string size ### @zfill: (num, size)-> len = size - num.toString().length return if len > 0 then new Array(len+1).join('0') + num else num.toString() ### Exports @package bkcore ### exports = exports ? @ exports.bkcore ||= {} exports.bkcore.Timer = Timer
[ { "context": "WithWindowProps::onDraftReady\n windowKey: \"composer-#{draftClientId}\"\n windowType: \"composer-pr", "end": 10817, "score": 0.6834719181060791, "start": 10808, "tag": "KEY", "value": "composer-" }, { "context": ":onDraftReady\n windowKey: \"compos...
app/src/flux/stores/draft-store.coffee
immershy/nodemail
0
_ = require 'underscore' {ipcRenderer} = require 'electron' NylasAPI = require '../nylas-api' DraftEditingSession = require './draft-editing-session' DraftFactory = require './draft-factory' DatabaseStore = require './database-store' AccountStore = require './account-store' TaskQueueStatusStore = require './task-queue-status-store' FocusedContentStore = require './focused-content-store' BaseDraftTask = require '../tasks/base-draft-task' SendDraftTask = require '../tasks/send-draft-task' SyncbackDraftFilesTask = require '../tasks/syncback-draft-files-task' SyncbackDraftTask = require '../tasks/syncback-draft-task' DestroyDraftTask = require '../tasks/destroy-draft-task' Thread = require '../models/thread' Contact = require '../models/contact' Message = require '../models/message' Actions = require '../actions' TaskQueue = require './task-queue' SoundRegistry = require '../../sound-registry' {Listener, Publisher} = require '../modules/reflux-coffee' CoffeeHelpers = require '../coffee-helpers' ExtensionRegistry = require '../../extension-registry' {deprecate} = require '../../deprecate-utils' ### Public: DraftStore responds to Actions that interact with Drafts and exposes public getter methods to return Draft objects and sessions. It also creates and queues {Task} objects to persist changes to the Nylas API. Remember that a "Draft" is actually just a "Message" with `draft: true`. Section: Drafts ### class DraftStore @include: CoffeeHelpers.includeModule @include Publisher @include Listener constructor: -> @listenTo DatabaseStore, @_onDataChanged @listenTo Actions.composeReply, @_onComposeReply @listenTo Actions.composeForward, @_onComposeForward @listenTo Actions.sendDraftSuccess, => @trigger() @listenTo Actions.composePopoutDraft, @_onPopoutDraftClientId @listenTo Actions.composeNewBlankDraft, @_onPopoutBlankDraft @listenTo Actions.draftSendingFailed, @_onDraftSendingFailed @listenTo Actions.sendQuickReply, @_onSendQuickReply if NylasEnv.isMainWindow() ipcRenderer.on 'new-message', => @_onPopoutBlankDraft() # Remember that these two actions only fire in the current window and # are picked up by the instance of the DraftStore in the current # window. @listenTo Actions.ensureDraftSynced, @_onEnsureDraftSynced @listenTo Actions.sendDraft, @_onSendDraft @listenTo Actions.sendDrafts, @_onSendDrafts @listenTo Actions.destroyDraft, @_onDestroyDraft @listenTo Actions.removeFile, @_onRemoveFile NylasEnv.onBeforeUnload @_onBeforeUnload @_draftSessions = {} # We would ideally like to be able to calculate the sending state # declaratively from the existence of the SendDraftTask on the # TaskQueue. # # Unfortunately it takes a while for the Task to end up on the Queue. # Before it's there, the Draft session is fetched, changes are # applied, it's saved to the DB, and performLocal is run. In the # meantime, several triggers from the DraftStore may fire (like when # it's saved to the DB). At the time of those triggers, the task is # not yet on the Queue and the DraftStore incorrectly says # `isSendingDraft` is false. # # As a result, we keep track of the intermediate time between when we # request to queue something, and when it appears on the queue. @_draftsSending = {} ipcRenderer.on 'mailto', @_onHandleMailtoLink ipcRenderer.on 'mailfiles', @_onHandleMailFiles ######### PUBLIC ####################################################### # Public: Fetch a {DraftEditingSession} for displaying and/or editing the # draft with `clientId`. # # Example: # # ```coffee # session = DraftStore.sessionForClientId(clientId) # session.prepare().then -> # # session.draft() is now ready # ``` # # - `clientId` The {String} clientId of the draft. # # Returns a {Promise} that resolves to an {DraftEditingSession} for the # draft once it has been prepared: sessionForClientId: (clientId) => if not clientId throw new Error("DraftStore::sessionForClientId requires a clientId") @_draftSessions[clientId] ?= @_createSession(clientId) @_draftSessions[clientId].prepare() # Public: Look up the sending state of the given draftClientId. # In popout windows the existance of the window is the sending state. isSendingDraft: (draftClientId) -> return @_draftsSending[draftClientId] ? false ### Composer Extensions ### # Public: Returns the extensions registered with the DraftStore. extensions: => ExtensionRegistry.Composer.extensions() # Public: Deprecated, use {ExtensionRegistry.Composer.register} instead. # Registers a new extension with the DraftStore. DraftStore extensions # make it possible to extend the editor experience, modify draft contents, # display warnings before draft are sent, and more. # # - `ext` A {ComposerExtension} instance. # registerExtension: (ext) => ExtensionRegistry.Composer.register(ext) # Public: Deprecated, use {ExtensionRegistry.Composer.unregister} instead. # Unregisters the extension provided from the DraftStore. # # - `ext` A {ComposerExtension} instance. # unregisterExtension: (ext) => ExtensionRegistry.Composer.unregister(ext) ########### PRIVATE #################################################### _doneWithSession: (session) -> session.teardown() delete @_draftSessions[session.draftClientId] _cleanupAllSessions: -> for draftClientId, session of @_draftSessions @_doneWithSession(session) _onBeforeUnload: (readyToUnload) => promises = [] # Normally we'd just append all promises, even the ones already # fulfilled (nothing to save), but in this case we only want to # block window closing if we have to do real work. Calling # window.close() within on onbeforeunload could do weird things. for key, session of @_draftSessions if session.draft()?.pristine Actions.queueTask(new DestroyDraftTask(session.draftClientId)) else promises.push(session.changes.commit()) if promises.length > 0 # Important: There are some scenarios where all the promises resolve instantly. # Firing NylasEnv.close() does nothing if called within an existing beforeUnload # handler, so we need to always defer by one tick before re-firing close. Promise.settle(promises).then => @_draftSessions = {} readyToUnload() # Stop and wait before closing return false else # Continue closing return true _onDataChanged: (change) => return unless change.objectClass is Message.name containsDraft = _.some(change.objects, (msg) -> msg.draft) return unless containsDraft @trigger(change) _onSendQuickReply: ({thread, threadId, message, messageId}, body) => Promise.props(@_modelifyContext({thread, threadId, message, messageId})) .then ({message, thread}) => DraftFactory.createDraftForReply({message, thread, type: 'reply'}) .then (draft) => draft.body = body + "\n\n" + draft.body draft.pristine = false DatabaseStore.inTransaction (t) => t.persistModel(draft) .then => Actions.sendDraft(draft.clientId) _onComposeReply: ({thread, threadId, message, messageId, popout, type, behavior}) => Promise.props(@_modelifyContext({thread, threadId, message, messageId})) .then ({message, thread}) => DraftFactory.createOrUpdateDraftForReply({message, thread, type, behavior}) .then (draft) => @_finalizeAndPersistNewMessage(draft, {popout}) _onComposeForward: ({thread, threadId, message, messageId, popout}) => Promise.props(@_modelifyContext({thread, threadId, message, messageId})) .then(DraftFactory.createDraftForForward) .then (draft) => @_finalizeAndPersistNewMessage(draft, {popout}) _modelifyContext: ({thread, threadId, message, messageId}) -> queries = {} if thread throw new Error("newMessageWithContext: `thread` present, expected a Model. Maybe you wanted to pass `threadId`?") unless thread instanceof Thread queries.thread = thread else queries.thread = DatabaseStore.find(Thread, threadId) if message throw new Error("newMessageWithContext: `message` present, expected a Model. Maybe you wanted to pass `messageId`?") unless message instanceof Message queries.message = message else if messageId? queries.message = DatabaseStore .find(Message, messageId) .include(Message.attributes.body) else queries.message = DatabaseStore .findBy(Message, {threadId: threadId ? thread.id}) .order(Message.attributes.date.descending()) .limit(1) .include(Message.attributes.body) queries _finalizeAndPersistNewMessage: (draft, {popout} = {}) => # Give extensions an opportunity to perform additional setup to the draft for extension in @extensions() continue unless extension.prepareNewDraft extension.prepareNewDraft({draft}) # Optimistically create a draft session and hand it the draft so that it # doesn't need to do a query for it a second from now when the composer wants it. @_createSession(draft.clientId, draft) DatabaseStore.inTransaction (t) => t.persistModel(draft) .then => if popout @_onPopoutDraftClientId(draft.clientId) else Actions.focusDraft({draftClientId: draft.clientId}) .thenReturn({draftClientId: draft.clientId, draft: draft}) _createSession: (clientId, draft) => @_draftSessions[clientId] = new DraftEditingSession(clientId, draft) _onPopoutBlankDraft: => DraftFactory.createDraft().then (draft) => @_finalizeAndPersistNewMessage(draft).then ({draftClientId}) => @_onPopoutDraftClientId(draftClientId, {newDraft: true}) _onPopoutDraftClientId: (draftClientId, options = {}) => if not draftClientId? throw new Error("DraftStore::onPopoutDraftId - You must provide a draftClientId") draftJSON = null save = Promise.resolve() if @_draftSessions[draftClientId] save = @_draftSessions[draftClientId].changes.commit() draftJSON = @_draftSessions[draftClientId].draft().toJSON() else save = @sessionForClientId(draftClientId).then (session) => draftJSON = session.draft().toJSON() title = if options.newDraft then "New Message" else "Message" save.then => # Since we pass a windowKey, if the popout composer draft already # exists we'll simply show that one instead of spawning a whole new # window. NylasEnv.newWindow title: title hidden: true # We manually show in ComposerWithWindowProps::onDraftReady windowKey: "composer-#{draftClientId}" windowType: "composer-preload" windowProps: _.extend(options, {draftClientId, draftJSON}) _onHandleMailtoLink: (event, urlString) => DraftFactory.createDraftForMailto(urlString).then (draft) => @_finalizeAndPersistNewMessage(draft, popout: true) _onHandleMailFiles: (event, paths) => DraftFactory.createDraft().then (draft) => @_finalizeAndPersistNewMessage(draft, popout: true) .then ({draftClientId}) => for path in paths Actions.addAttachment({filePath: path, messageClientId: draftClientId}) _onDestroyDraft: (draftClientId) => session = @_draftSessions[draftClientId] # Immediately reset any pending changes so no saves occur if session @_doneWithSession(session) # Stop any pending tasks related ot the draft for task in TaskQueueStatusStore.queue() if task instanceof BaseDraftTask and task.draftClientId is draftClientId Actions.dequeueTask(task.id) # Queue the task to destroy the draft Actions.queueTask(new DestroyDraftTask(draftClientId)) NylasEnv.close() if @_isPopout() _onEnsureDraftSynced: (draftClientId) => @sessionForClientId(draftClientId).then (session) => @_prepareForSyncback(session).then => @_queueDraftAssetTasks(session.draft()) Actions.queueTask(new SyncbackDraftTask(draftClientId)) _onSendDraft: (draftClientId) => @_sendDraft(draftClientId) .then => if @_isPopout() NylasEnv.close() _onSendDrafts: (draftClientIds) => Promise.each(draftClientIds, (draftClientId) => @_sendDraft(draftClientId) ).then => if @_isPopout() NylasEnv.close() _sendDraft: (draftClientId) => @_draftsSending[draftClientId] = true @sessionForClientId(draftClientId).then (session) => @_prepareForSyncback(session).then => if NylasEnv.config.get("core.sending.sounds") SoundRegistry.playSound('hit-send') @_queueDraftAssetTasks(session.draft()) Actions.queueTask(new SendDraftTask(draftClientId)) @_doneWithSession(session) Promise.resolve() _queueDraftAssetTasks: (draft) => if draft.files.length > 0 or draft.uploads.length > 0 Actions.queueTask(new SyncbackDraftFilesTask(draft.clientId)) _isPopout: -> NylasEnv.getWindowType() is "composer" _prepareForSyncback: (session) => draft = session.draft() # Make sure the draft is attached to a valid account, and change it's # accountId if the from address does not match the current account. account = AccountStore.accountForEmail(draft.from[0].email) unless account return Promise.reject(new Error("DraftStore::_prepareForSyncback - you can only send drafts from a configured account.")) if account.id isnt draft.accountId NylasAPI.makeDraftDeletionRequest(draft) session.changes.add({ accountId: account.id version: null serverId: null threadId: null replyToMessageId: null }) # Run draft transformations registered by third-party plugins allowedFields = ['to', 'from', 'cc', 'bcc', 'subject', 'body'] session.changes.commit(noSyncback: true).then => draft = session.draft().clone() Promise.each @extensions(), (ext) -> extApply = ext.applyTransformsToDraft extUnapply = ext.unapplyTransformsToDraft unless extApply and extUnapply return Promise.resolve() Promise.resolve(extUnapply({draft})).then (cleaned) => cleaned = draft if cleaned is 'unnecessary' Promise.resolve(extApply({draft: cleaned})).then (transformed) => Promise.resolve(extUnapply({draft: transformed.clone()})).then (untransformed) => untransformed = cleaned if untransformed is 'unnecessary' if not _.isEqual(_.pick(untransformed, allowedFields), _.pick(cleaned, allowedFields)) console.log("-- BEFORE --") console.log(draft.body) console.log("-- TRANSFORMED --") console.log(transformed.body) console.log("-- UNTRANSFORMED (should match BEFORE) --") console.log(untransformed.body) NylasEnv.reportError(new Error("An extension applied a tranform to the draft that it could not reverse.")) draft = transformed .then => DatabaseStore.inTransaction (t) => t.persistModel(draft) _onRemoveFile: ({file, messageClientId}) => @sessionForClientId(messageClientId).then (session) -> files = _.clone(session.draft().files) ? [] files = _.reject files, (f) -> f.id is file.id session.changes.add({files}) session.changes.commit() _onDraftSendingFailed: ({draftClientId, threadId, errorMessage}) -> @_draftsSending[draftClientId] = false @trigger(draftClientId) if NylasEnv.isMainWindow() # We delay so the view has time to update the restored draft. If we # don't delay the modal may come up in a state where the draft looks # like it hasn't been restored or has been lost. _.delay => @_notifyUserOfError({draftClientId, threadId, errorMessage}) , 100 _notifyUserOfError: ({draftClientId, threadId, errorMessage}) -> focusedThread = FocusedContentStore.focused('thread') if threadId and focusedThread?.id is threadId NylasEnv.showErrorDialog(errorMessage) else Actions.composePopoutDraft(draftClientId, {errorMessage}) # Deprecations store = new DraftStore() store.registerExtension = deprecate( 'DraftStore.registerExtension', 'ExtensionRegistry.Composer.register', store, store.registerExtension ) store.unregisterExtension = deprecate( 'DraftStore.unregisterExtension', 'ExtensionRegistry.Composer.unregister', store, store.unregisterExtension ) module.exports = store
156637
_ = require 'underscore' {ipcRenderer} = require 'electron' NylasAPI = require '../nylas-api' DraftEditingSession = require './draft-editing-session' DraftFactory = require './draft-factory' DatabaseStore = require './database-store' AccountStore = require './account-store' TaskQueueStatusStore = require './task-queue-status-store' FocusedContentStore = require './focused-content-store' BaseDraftTask = require '../tasks/base-draft-task' SendDraftTask = require '../tasks/send-draft-task' SyncbackDraftFilesTask = require '../tasks/syncback-draft-files-task' SyncbackDraftTask = require '../tasks/syncback-draft-task' DestroyDraftTask = require '../tasks/destroy-draft-task' Thread = require '../models/thread' Contact = require '../models/contact' Message = require '../models/message' Actions = require '../actions' TaskQueue = require './task-queue' SoundRegistry = require '../../sound-registry' {Listener, Publisher} = require '../modules/reflux-coffee' CoffeeHelpers = require '../coffee-helpers' ExtensionRegistry = require '../../extension-registry' {deprecate} = require '../../deprecate-utils' ### Public: DraftStore responds to Actions that interact with Drafts and exposes public getter methods to return Draft objects and sessions. It also creates and queues {Task} objects to persist changes to the Nylas API. Remember that a "Draft" is actually just a "Message" with `draft: true`. Section: Drafts ### class DraftStore @include: CoffeeHelpers.includeModule @include Publisher @include Listener constructor: -> @listenTo DatabaseStore, @_onDataChanged @listenTo Actions.composeReply, @_onComposeReply @listenTo Actions.composeForward, @_onComposeForward @listenTo Actions.sendDraftSuccess, => @trigger() @listenTo Actions.composePopoutDraft, @_onPopoutDraftClientId @listenTo Actions.composeNewBlankDraft, @_onPopoutBlankDraft @listenTo Actions.draftSendingFailed, @_onDraftSendingFailed @listenTo Actions.sendQuickReply, @_onSendQuickReply if NylasEnv.isMainWindow() ipcRenderer.on 'new-message', => @_onPopoutBlankDraft() # Remember that these two actions only fire in the current window and # are picked up by the instance of the DraftStore in the current # window. @listenTo Actions.ensureDraftSynced, @_onEnsureDraftSynced @listenTo Actions.sendDraft, @_onSendDraft @listenTo Actions.sendDrafts, @_onSendDrafts @listenTo Actions.destroyDraft, @_onDestroyDraft @listenTo Actions.removeFile, @_onRemoveFile NylasEnv.onBeforeUnload @_onBeforeUnload @_draftSessions = {} # We would ideally like to be able to calculate the sending state # declaratively from the existence of the SendDraftTask on the # TaskQueue. # # Unfortunately it takes a while for the Task to end up on the Queue. # Before it's there, the Draft session is fetched, changes are # applied, it's saved to the DB, and performLocal is run. In the # meantime, several triggers from the DraftStore may fire (like when # it's saved to the DB). At the time of those triggers, the task is # not yet on the Queue and the DraftStore incorrectly says # `isSendingDraft` is false. # # As a result, we keep track of the intermediate time between when we # request to queue something, and when it appears on the queue. @_draftsSending = {} ipcRenderer.on 'mailto', @_onHandleMailtoLink ipcRenderer.on 'mailfiles', @_onHandleMailFiles ######### PUBLIC ####################################################### # Public: Fetch a {DraftEditingSession} for displaying and/or editing the # draft with `clientId`. # # Example: # # ```coffee # session = DraftStore.sessionForClientId(clientId) # session.prepare().then -> # # session.draft() is now ready # ``` # # - `clientId` The {String} clientId of the draft. # # Returns a {Promise} that resolves to an {DraftEditingSession} for the # draft once it has been prepared: sessionForClientId: (clientId) => if not clientId throw new Error("DraftStore::sessionForClientId requires a clientId") @_draftSessions[clientId] ?= @_createSession(clientId) @_draftSessions[clientId].prepare() # Public: Look up the sending state of the given draftClientId. # In popout windows the existance of the window is the sending state. isSendingDraft: (draftClientId) -> return @_draftsSending[draftClientId] ? false ### Composer Extensions ### # Public: Returns the extensions registered with the DraftStore. extensions: => ExtensionRegistry.Composer.extensions() # Public: Deprecated, use {ExtensionRegistry.Composer.register} instead. # Registers a new extension with the DraftStore. DraftStore extensions # make it possible to extend the editor experience, modify draft contents, # display warnings before draft are sent, and more. # # - `ext` A {ComposerExtension} instance. # registerExtension: (ext) => ExtensionRegistry.Composer.register(ext) # Public: Deprecated, use {ExtensionRegistry.Composer.unregister} instead. # Unregisters the extension provided from the DraftStore. # # - `ext` A {ComposerExtension} instance. # unregisterExtension: (ext) => ExtensionRegistry.Composer.unregister(ext) ########### PRIVATE #################################################### _doneWithSession: (session) -> session.teardown() delete @_draftSessions[session.draftClientId] _cleanupAllSessions: -> for draftClientId, session of @_draftSessions @_doneWithSession(session) _onBeforeUnload: (readyToUnload) => promises = [] # Normally we'd just append all promises, even the ones already # fulfilled (nothing to save), but in this case we only want to # block window closing if we have to do real work. Calling # window.close() within on onbeforeunload could do weird things. for key, session of @_draftSessions if session.draft()?.pristine Actions.queueTask(new DestroyDraftTask(session.draftClientId)) else promises.push(session.changes.commit()) if promises.length > 0 # Important: There are some scenarios where all the promises resolve instantly. # Firing NylasEnv.close() does nothing if called within an existing beforeUnload # handler, so we need to always defer by one tick before re-firing close. Promise.settle(promises).then => @_draftSessions = {} readyToUnload() # Stop and wait before closing return false else # Continue closing return true _onDataChanged: (change) => return unless change.objectClass is Message.name containsDraft = _.some(change.objects, (msg) -> msg.draft) return unless containsDraft @trigger(change) _onSendQuickReply: ({thread, threadId, message, messageId}, body) => Promise.props(@_modelifyContext({thread, threadId, message, messageId})) .then ({message, thread}) => DraftFactory.createDraftForReply({message, thread, type: 'reply'}) .then (draft) => draft.body = body + "\n\n" + draft.body draft.pristine = false DatabaseStore.inTransaction (t) => t.persistModel(draft) .then => Actions.sendDraft(draft.clientId) _onComposeReply: ({thread, threadId, message, messageId, popout, type, behavior}) => Promise.props(@_modelifyContext({thread, threadId, message, messageId})) .then ({message, thread}) => DraftFactory.createOrUpdateDraftForReply({message, thread, type, behavior}) .then (draft) => @_finalizeAndPersistNewMessage(draft, {popout}) _onComposeForward: ({thread, threadId, message, messageId, popout}) => Promise.props(@_modelifyContext({thread, threadId, message, messageId})) .then(DraftFactory.createDraftForForward) .then (draft) => @_finalizeAndPersistNewMessage(draft, {popout}) _modelifyContext: ({thread, threadId, message, messageId}) -> queries = {} if thread throw new Error("newMessageWithContext: `thread` present, expected a Model. Maybe you wanted to pass `threadId`?") unless thread instanceof Thread queries.thread = thread else queries.thread = DatabaseStore.find(Thread, threadId) if message throw new Error("newMessageWithContext: `message` present, expected a Model. Maybe you wanted to pass `messageId`?") unless message instanceof Message queries.message = message else if messageId? queries.message = DatabaseStore .find(Message, messageId) .include(Message.attributes.body) else queries.message = DatabaseStore .findBy(Message, {threadId: threadId ? thread.id}) .order(Message.attributes.date.descending()) .limit(1) .include(Message.attributes.body) queries _finalizeAndPersistNewMessage: (draft, {popout} = {}) => # Give extensions an opportunity to perform additional setup to the draft for extension in @extensions() continue unless extension.prepareNewDraft extension.prepareNewDraft({draft}) # Optimistically create a draft session and hand it the draft so that it # doesn't need to do a query for it a second from now when the composer wants it. @_createSession(draft.clientId, draft) DatabaseStore.inTransaction (t) => t.persistModel(draft) .then => if popout @_onPopoutDraftClientId(draft.clientId) else Actions.focusDraft({draftClientId: draft.clientId}) .thenReturn({draftClientId: draft.clientId, draft: draft}) _createSession: (clientId, draft) => @_draftSessions[clientId] = new DraftEditingSession(clientId, draft) _onPopoutBlankDraft: => DraftFactory.createDraft().then (draft) => @_finalizeAndPersistNewMessage(draft).then ({draftClientId}) => @_onPopoutDraftClientId(draftClientId, {newDraft: true}) _onPopoutDraftClientId: (draftClientId, options = {}) => if not draftClientId? throw new Error("DraftStore::onPopoutDraftId - You must provide a draftClientId") draftJSON = null save = Promise.resolve() if @_draftSessions[draftClientId] save = @_draftSessions[draftClientId].changes.commit() draftJSON = @_draftSessions[draftClientId].draft().toJSON() else save = @sessionForClientId(draftClientId).then (session) => draftJSON = session.draft().toJSON() title = if options.newDraft then "New Message" else "Message" save.then => # Since we pass a windowKey, if the popout composer draft already # exists we'll simply show that one instead of spawning a whole new # window. NylasEnv.newWindow title: title hidden: true # We manually show in ComposerWithWindowProps::onDraftReady windowKey: "<KEY>#{draft<KEY>}" windowType: "composer-preload" windowProps: _.extend(options, {draftClientId, draftJSON}) _onHandleMailtoLink: (event, urlString) => DraftFactory.createDraftForMailto(urlString).then (draft) => @_finalizeAndPersistNewMessage(draft, popout: true) _onHandleMailFiles: (event, paths) => DraftFactory.createDraft().then (draft) => @_finalizeAndPersistNewMessage(draft, popout: true) .then ({draftClientId}) => for path in paths Actions.addAttachment({filePath: path, messageClientId: draftClientId}) _onDestroyDraft: (draftClientId) => session = @_draftSessions[draftClientId] # Immediately reset any pending changes so no saves occur if session @_doneWithSession(session) # Stop any pending tasks related ot the draft for task in TaskQueueStatusStore.queue() if task instanceof BaseDraftTask and task.draftClientId is draftClientId Actions.dequeueTask(task.id) # Queue the task to destroy the draft Actions.queueTask(new DestroyDraftTask(draftClientId)) NylasEnv.close() if @_isPopout() _onEnsureDraftSynced: (draftClientId) => @sessionForClientId(draftClientId).then (session) => @_prepareForSyncback(session).then => @_queueDraftAssetTasks(session.draft()) Actions.queueTask(new SyncbackDraftTask(draftClientId)) _onSendDraft: (draftClientId) => @_sendDraft(draftClientId) .then => if @_isPopout() NylasEnv.close() _onSendDrafts: (draftClientIds) => Promise.each(draftClientIds, (draftClientId) => @_sendDraft(draftClientId) ).then => if @_isPopout() NylasEnv.close() _sendDraft: (draftClientId) => @_draftsSending[draftClientId] = true @sessionForClientId(draftClientId).then (session) => @_prepareForSyncback(session).then => if NylasEnv.config.get("core.sending.sounds") SoundRegistry.playSound('hit-send') @_queueDraftAssetTasks(session.draft()) Actions.queueTask(new SendDraftTask(draftClientId)) @_doneWithSession(session) Promise.resolve() _queueDraftAssetTasks: (draft) => if draft.files.length > 0 or draft.uploads.length > 0 Actions.queueTask(new SyncbackDraftFilesTask(draft.clientId)) _isPopout: -> NylasEnv.getWindowType() is "composer" _prepareForSyncback: (session) => draft = session.draft() # Make sure the draft is attached to a valid account, and change it's # accountId if the from address does not match the current account. account = AccountStore.accountForEmail(draft.from[0].email) unless account return Promise.reject(new Error("DraftStore::_prepareForSyncback - you can only send drafts from a configured account.")) if account.id isnt draft.accountId NylasAPI.makeDraftDeletionRequest(draft) session.changes.add({ accountId: account.id version: null serverId: null threadId: null replyToMessageId: null }) # Run draft transformations registered by third-party plugins allowedFields = ['to', 'from', 'cc', 'bcc', 'subject', 'body'] session.changes.commit(noSyncback: true).then => draft = session.draft().clone() Promise.each @extensions(), (ext) -> extApply = ext.applyTransformsToDraft extUnapply = ext.unapplyTransformsToDraft unless extApply and extUnapply return Promise.resolve() Promise.resolve(extUnapply({draft})).then (cleaned) => cleaned = draft if cleaned is 'unnecessary' Promise.resolve(extApply({draft: cleaned})).then (transformed) => Promise.resolve(extUnapply({draft: transformed.clone()})).then (untransformed) => untransformed = cleaned if untransformed is 'unnecessary' if not _.isEqual(_.pick(untransformed, allowedFields), _.pick(cleaned, allowedFields)) console.log("-- BEFORE --") console.log(draft.body) console.log("-- TRANSFORMED --") console.log(transformed.body) console.log("-- UNTRANSFORMED (should match BEFORE) --") console.log(untransformed.body) NylasEnv.reportError(new Error("An extension applied a tranform to the draft that it could not reverse.")) draft = transformed .then => DatabaseStore.inTransaction (t) => t.persistModel(draft) _onRemoveFile: ({file, messageClientId}) => @sessionForClientId(messageClientId).then (session) -> files = _.clone(session.draft().files) ? [] files = _.reject files, (f) -> f.id is file.id session.changes.add({files}) session.changes.commit() _onDraftSendingFailed: ({draftClientId, threadId, errorMessage}) -> @_draftsSending[draftClientId] = false @trigger(draftClientId) if NylasEnv.isMainWindow() # We delay so the view has time to update the restored draft. If we # don't delay the modal may come up in a state where the draft looks # like it hasn't been restored or has been lost. _.delay => @_notifyUserOfError({draftClientId, threadId, errorMessage}) , 100 _notifyUserOfError: ({draftClientId, threadId, errorMessage}) -> focusedThread = FocusedContentStore.focused('thread') if threadId and focusedThread?.id is threadId NylasEnv.showErrorDialog(errorMessage) else Actions.composePopoutDraft(draftClientId, {errorMessage}) # Deprecations store = new DraftStore() store.registerExtension = deprecate( 'DraftStore.registerExtension', 'ExtensionRegistry.Composer.register', store, store.registerExtension ) store.unregisterExtension = deprecate( 'DraftStore.unregisterExtension', 'ExtensionRegistry.Composer.unregister', store, store.unregisterExtension ) module.exports = store
true
_ = require 'underscore' {ipcRenderer} = require 'electron' NylasAPI = require '../nylas-api' DraftEditingSession = require './draft-editing-session' DraftFactory = require './draft-factory' DatabaseStore = require './database-store' AccountStore = require './account-store' TaskQueueStatusStore = require './task-queue-status-store' FocusedContentStore = require './focused-content-store' BaseDraftTask = require '../tasks/base-draft-task' SendDraftTask = require '../tasks/send-draft-task' SyncbackDraftFilesTask = require '../tasks/syncback-draft-files-task' SyncbackDraftTask = require '../tasks/syncback-draft-task' DestroyDraftTask = require '../tasks/destroy-draft-task' Thread = require '../models/thread' Contact = require '../models/contact' Message = require '../models/message' Actions = require '../actions' TaskQueue = require './task-queue' SoundRegistry = require '../../sound-registry' {Listener, Publisher} = require '../modules/reflux-coffee' CoffeeHelpers = require '../coffee-helpers' ExtensionRegistry = require '../../extension-registry' {deprecate} = require '../../deprecate-utils' ### Public: DraftStore responds to Actions that interact with Drafts and exposes public getter methods to return Draft objects and sessions. It also creates and queues {Task} objects to persist changes to the Nylas API. Remember that a "Draft" is actually just a "Message" with `draft: true`. Section: Drafts ### class DraftStore @include: CoffeeHelpers.includeModule @include Publisher @include Listener constructor: -> @listenTo DatabaseStore, @_onDataChanged @listenTo Actions.composeReply, @_onComposeReply @listenTo Actions.composeForward, @_onComposeForward @listenTo Actions.sendDraftSuccess, => @trigger() @listenTo Actions.composePopoutDraft, @_onPopoutDraftClientId @listenTo Actions.composeNewBlankDraft, @_onPopoutBlankDraft @listenTo Actions.draftSendingFailed, @_onDraftSendingFailed @listenTo Actions.sendQuickReply, @_onSendQuickReply if NylasEnv.isMainWindow() ipcRenderer.on 'new-message', => @_onPopoutBlankDraft() # Remember that these two actions only fire in the current window and # are picked up by the instance of the DraftStore in the current # window. @listenTo Actions.ensureDraftSynced, @_onEnsureDraftSynced @listenTo Actions.sendDraft, @_onSendDraft @listenTo Actions.sendDrafts, @_onSendDrafts @listenTo Actions.destroyDraft, @_onDestroyDraft @listenTo Actions.removeFile, @_onRemoveFile NylasEnv.onBeforeUnload @_onBeforeUnload @_draftSessions = {} # We would ideally like to be able to calculate the sending state # declaratively from the existence of the SendDraftTask on the # TaskQueue. # # Unfortunately it takes a while for the Task to end up on the Queue. # Before it's there, the Draft session is fetched, changes are # applied, it's saved to the DB, and performLocal is run. In the # meantime, several triggers from the DraftStore may fire (like when # it's saved to the DB). At the time of those triggers, the task is # not yet on the Queue and the DraftStore incorrectly says # `isSendingDraft` is false. # # As a result, we keep track of the intermediate time between when we # request to queue something, and when it appears on the queue. @_draftsSending = {} ipcRenderer.on 'mailto', @_onHandleMailtoLink ipcRenderer.on 'mailfiles', @_onHandleMailFiles ######### PUBLIC ####################################################### # Public: Fetch a {DraftEditingSession} for displaying and/or editing the # draft with `clientId`. # # Example: # # ```coffee # session = DraftStore.sessionForClientId(clientId) # session.prepare().then -> # # session.draft() is now ready # ``` # # - `clientId` The {String} clientId of the draft. # # Returns a {Promise} that resolves to an {DraftEditingSession} for the # draft once it has been prepared: sessionForClientId: (clientId) => if not clientId throw new Error("DraftStore::sessionForClientId requires a clientId") @_draftSessions[clientId] ?= @_createSession(clientId) @_draftSessions[clientId].prepare() # Public: Look up the sending state of the given draftClientId. # In popout windows the existance of the window is the sending state. isSendingDraft: (draftClientId) -> return @_draftsSending[draftClientId] ? false ### Composer Extensions ### # Public: Returns the extensions registered with the DraftStore. extensions: => ExtensionRegistry.Composer.extensions() # Public: Deprecated, use {ExtensionRegistry.Composer.register} instead. # Registers a new extension with the DraftStore. DraftStore extensions # make it possible to extend the editor experience, modify draft contents, # display warnings before draft are sent, and more. # # - `ext` A {ComposerExtension} instance. # registerExtension: (ext) => ExtensionRegistry.Composer.register(ext) # Public: Deprecated, use {ExtensionRegistry.Composer.unregister} instead. # Unregisters the extension provided from the DraftStore. # # - `ext` A {ComposerExtension} instance. # unregisterExtension: (ext) => ExtensionRegistry.Composer.unregister(ext) ########### PRIVATE #################################################### _doneWithSession: (session) -> session.teardown() delete @_draftSessions[session.draftClientId] _cleanupAllSessions: -> for draftClientId, session of @_draftSessions @_doneWithSession(session) _onBeforeUnload: (readyToUnload) => promises = [] # Normally we'd just append all promises, even the ones already # fulfilled (nothing to save), but in this case we only want to # block window closing if we have to do real work. Calling # window.close() within on onbeforeunload could do weird things. for key, session of @_draftSessions if session.draft()?.pristine Actions.queueTask(new DestroyDraftTask(session.draftClientId)) else promises.push(session.changes.commit()) if promises.length > 0 # Important: There are some scenarios where all the promises resolve instantly. # Firing NylasEnv.close() does nothing if called within an existing beforeUnload # handler, so we need to always defer by one tick before re-firing close. Promise.settle(promises).then => @_draftSessions = {} readyToUnload() # Stop and wait before closing return false else # Continue closing return true _onDataChanged: (change) => return unless change.objectClass is Message.name containsDraft = _.some(change.objects, (msg) -> msg.draft) return unless containsDraft @trigger(change) _onSendQuickReply: ({thread, threadId, message, messageId}, body) => Promise.props(@_modelifyContext({thread, threadId, message, messageId})) .then ({message, thread}) => DraftFactory.createDraftForReply({message, thread, type: 'reply'}) .then (draft) => draft.body = body + "\n\n" + draft.body draft.pristine = false DatabaseStore.inTransaction (t) => t.persistModel(draft) .then => Actions.sendDraft(draft.clientId) _onComposeReply: ({thread, threadId, message, messageId, popout, type, behavior}) => Promise.props(@_modelifyContext({thread, threadId, message, messageId})) .then ({message, thread}) => DraftFactory.createOrUpdateDraftForReply({message, thread, type, behavior}) .then (draft) => @_finalizeAndPersistNewMessage(draft, {popout}) _onComposeForward: ({thread, threadId, message, messageId, popout}) => Promise.props(@_modelifyContext({thread, threadId, message, messageId})) .then(DraftFactory.createDraftForForward) .then (draft) => @_finalizeAndPersistNewMessage(draft, {popout}) _modelifyContext: ({thread, threadId, message, messageId}) -> queries = {} if thread throw new Error("newMessageWithContext: `thread` present, expected a Model. Maybe you wanted to pass `threadId`?") unless thread instanceof Thread queries.thread = thread else queries.thread = DatabaseStore.find(Thread, threadId) if message throw new Error("newMessageWithContext: `message` present, expected a Model. Maybe you wanted to pass `messageId`?") unless message instanceof Message queries.message = message else if messageId? queries.message = DatabaseStore .find(Message, messageId) .include(Message.attributes.body) else queries.message = DatabaseStore .findBy(Message, {threadId: threadId ? thread.id}) .order(Message.attributes.date.descending()) .limit(1) .include(Message.attributes.body) queries _finalizeAndPersistNewMessage: (draft, {popout} = {}) => # Give extensions an opportunity to perform additional setup to the draft for extension in @extensions() continue unless extension.prepareNewDraft extension.prepareNewDraft({draft}) # Optimistically create a draft session and hand it the draft so that it # doesn't need to do a query for it a second from now when the composer wants it. @_createSession(draft.clientId, draft) DatabaseStore.inTransaction (t) => t.persistModel(draft) .then => if popout @_onPopoutDraftClientId(draft.clientId) else Actions.focusDraft({draftClientId: draft.clientId}) .thenReturn({draftClientId: draft.clientId, draft: draft}) _createSession: (clientId, draft) => @_draftSessions[clientId] = new DraftEditingSession(clientId, draft) _onPopoutBlankDraft: => DraftFactory.createDraft().then (draft) => @_finalizeAndPersistNewMessage(draft).then ({draftClientId}) => @_onPopoutDraftClientId(draftClientId, {newDraft: true}) _onPopoutDraftClientId: (draftClientId, options = {}) => if not draftClientId? throw new Error("DraftStore::onPopoutDraftId - You must provide a draftClientId") draftJSON = null save = Promise.resolve() if @_draftSessions[draftClientId] save = @_draftSessions[draftClientId].changes.commit() draftJSON = @_draftSessions[draftClientId].draft().toJSON() else save = @sessionForClientId(draftClientId).then (session) => draftJSON = session.draft().toJSON() title = if options.newDraft then "New Message" else "Message" save.then => # Since we pass a windowKey, if the popout composer draft already # exists we'll simply show that one instead of spawning a whole new # window. NylasEnv.newWindow title: title hidden: true # We manually show in ComposerWithWindowProps::onDraftReady windowKey: "PI:KEY:<KEY>END_PI#{draftPI:KEY:<KEY>END_PI}" windowType: "composer-preload" windowProps: _.extend(options, {draftClientId, draftJSON}) _onHandleMailtoLink: (event, urlString) => DraftFactory.createDraftForMailto(urlString).then (draft) => @_finalizeAndPersistNewMessage(draft, popout: true) _onHandleMailFiles: (event, paths) => DraftFactory.createDraft().then (draft) => @_finalizeAndPersistNewMessage(draft, popout: true) .then ({draftClientId}) => for path in paths Actions.addAttachment({filePath: path, messageClientId: draftClientId}) _onDestroyDraft: (draftClientId) => session = @_draftSessions[draftClientId] # Immediately reset any pending changes so no saves occur if session @_doneWithSession(session) # Stop any pending tasks related ot the draft for task in TaskQueueStatusStore.queue() if task instanceof BaseDraftTask and task.draftClientId is draftClientId Actions.dequeueTask(task.id) # Queue the task to destroy the draft Actions.queueTask(new DestroyDraftTask(draftClientId)) NylasEnv.close() if @_isPopout() _onEnsureDraftSynced: (draftClientId) => @sessionForClientId(draftClientId).then (session) => @_prepareForSyncback(session).then => @_queueDraftAssetTasks(session.draft()) Actions.queueTask(new SyncbackDraftTask(draftClientId)) _onSendDraft: (draftClientId) => @_sendDraft(draftClientId) .then => if @_isPopout() NylasEnv.close() _onSendDrafts: (draftClientIds) => Promise.each(draftClientIds, (draftClientId) => @_sendDraft(draftClientId) ).then => if @_isPopout() NylasEnv.close() _sendDraft: (draftClientId) => @_draftsSending[draftClientId] = true @sessionForClientId(draftClientId).then (session) => @_prepareForSyncback(session).then => if NylasEnv.config.get("core.sending.sounds") SoundRegistry.playSound('hit-send') @_queueDraftAssetTasks(session.draft()) Actions.queueTask(new SendDraftTask(draftClientId)) @_doneWithSession(session) Promise.resolve() _queueDraftAssetTasks: (draft) => if draft.files.length > 0 or draft.uploads.length > 0 Actions.queueTask(new SyncbackDraftFilesTask(draft.clientId)) _isPopout: -> NylasEnv.getWindowType() is "composer" _prepareForSyncback: (session) => draft = session.draft() # Make sure the draft is attached to a valid account, and change it's # accountId if the from address does not match the current account. account = AccountStore.accountForEmail(draft.from[0].email) unless account return Promise.reject(new Error("DraftStore::_prepareForSyncback - you can only send drafts from a configured account.")) if account.id isnt draft.accountId NylasAPI.makeDraftDeletionRequest(draft) session.changes.add({ accountId: account.id version: null serverId: null threadId: null replyToMessageId: null }) # Run draft transformations registered by third-party plugins allowedFields = ['to', 'from', 'cc', 'bcc', 'subject', 'body'] session.changes.commit(noSyncback: true).then => draft = session.draft().clone() Promise.each @extensions(), (ext) -> extApply = ext.applyTransformsToDraft extUnapply = ext.unapplyTransformsToDraft unless extApply and extUnapply return Promise.resolve() Promise.resolve(extUnapply({draft})).then (cleaned) => cleaned = draft if cleaned is 'unnecessary' Promise.resolve(extApply({draft: cleaned})).then (transformed) => Promise.resolve(extUnapply({draft: transformed.clone()})).then (untransformed) => untransformed = cleaned if untransformed is 'unnecessary' if not _.isEqual(_.pick(untransformed, allowedFields), _.pick(cleaned, allowedFields)) console.log("-- BEFORE --") console.log(draft.body) console.log("-- TRANSFORMED --") console.log(transformed.body) console.log("-- UNTRANSFORMED (should match BEFORE) --") console.log(untransformed.body) NylasEnv.reportError(new Error("An extension applied a tranform to the draft that it could not reverse.")) draft = transformed .then => DatabaseStore.inTransaction (t) => t.persistModel(draft) _onRemoveFile: ({file, messageClientId}) => @sessionForClientId(messageClientId).then (session) -> files = _.clone(session.draft().files) ? [] files = _.reject files, (f) -> f.id is file.id session.changes.add({files}) session.changes.commit() _onDraftSendingFailed: ({draftClientId, threadId, errorMessage}) -> @_draftsSending[draftClientId] = false @trigger(draftClientId) if NylasEnv.isMainWindow() # We delay so the view has time to update the restored draft. If we # don't delay the modal may come up in a state where the draft looks # like it hasn't been restored or has been lost. _.delay => @_notifyUserOfError({draftClientId, threadId, errorMessage}) , 100 _notifyUserOfError: ({draftClientId, threadId, errorMessage}) -> focusedThread = FocusedContentStore.focused('thread') if threadId and focusedThread?.id is threadId NylasEnv.showErrorDialog(errorMessage) else Actions.composePopoutDraft(draftClientId, {errorMessage}) # Deprecations store = new DraftStore() store.registerExtension = deprecate( 'DraftStore.registerExtension', 'ExtensionRegistry.Composer.register', store, store.registerExtension ) store.unregisterExtension = deprecate( 'DraftStore.unregisterExtension', 'ExtensionRegistry.Composer.unregister', store, store.unregisterExtension ) module.exports = store
[ { "context": "ike memory layout for javascript\r\n# Copyright 2014 Robert Nix\r\nC = {}\r\n\r\n# Returns objects for struct member de", "end": 77, "score": 0.9998037219047546, "start": 67, "tag": "NAME", "value": "Robert Nix" } ]
src/cheap.coffee
Mischanix/cheap
3
# cheap.js - C-like memory layout for javascript # Copyright 2014 Robert Nix C = {} # Returns objects for struct member definitions makeStructMember = (typeName, pointerDepth, memberName, arrayLength, offset) -> { typeName, pointerDepth, memberName, offset, arrayLength, isArray: arrayLength? } C._typedefs = {} C.typedef = (typeName, structDef) -> throw new Error 'name collides' if typeName of C C._typedefs[typeName] = structDef C[typeName] = (memberName, arrayLength) -> if typeof memberName is 'string' makeStructMember typeName, 0, memberName, arrayLength else makeStructMember typeName, 0, undefined, arrayLength, memberName C.ptr = (typeName, memberName, pointerDepth = 1) -> makeStructMember typeName, pointerDepth, memberName C.typedef 'uint' # 0 C.typedef 'int' # 1 C.typedef 'ushort' # 2 C.typedef 'short' # 3 C.typedef 'uchar' # 4 C.typedef 'char' # 5 C.typedef 'float' # 6 C.typedef 'double' # 7 C.typedef 'void' pointerSize = 4 pointerShift = 2 C.set64Bit = (is64Bit) -> if is64Bit pointerSize = 8 pointerShift = 3 else pointerSize = 4 pointerShift = 2 C._typeNameToId = (n) -> switch n when 'uint' then 0 when 'int' then 1 when 'ushort' then 2 when 'short' then 3 when 'uchar' then 4 when 'char' then 5 when 'float' then 6 when 'double' then 7 else -1 C._arrayName = (t) -> switch t when 0, 'uint' then 'ui32' when 1, 'int' then 'i32' when 2, 'ushort' then 'ui16' when 3, 'short' then 'i16' when 4, 'uchar' then 'ui8' when 5, 'char' then 'i8' when 6, 'float' then 'f32' when 7, 'double' then 'f64' else 'ui32' C._arrayElSize = (t) -> switch t when 0, 'uint', 1, 'int' then 4 when 2, 'ushort', 3, 'short' then 2 when 4, 'uchar', 5, 'char' then 1 when 6, 'float' then 4 when 7, 'double' then 8 else pointerSize C._arrayElShift = (t) -> switch t when 0, 'uint', 1, 'int', 6, 'float' then 2 when 2, 'ushort', 3, 'short' then 1 when 4, 'uchar', 5, 'char' then 0 when 7, 'double' then 3 else pointerShift C.sizeof = (type) -> if typeof type is 'string' switch type when 'char', 'uchar' then 1 when 'short', 'ushort' then 2 when 'int', 'uint', 'float' then 4 when 'double' then 8 when 'void*' then pointerSize else 1 # void else type.__size C.strideof = (type) -> if typeof type is 'string' C.sizeof type else (type.__size + type.__align - 1) & -type.__align C.alignof = (type) -> if typeof type is 'string' C.sizeof type else type.__align C.offsetof = (type, member) -> type[member].offset makeAccessors = (def) -> { offset, member, type, stride, align, size } = def basic = typeof type is 'string' typeId = C._typeNameToId type arr = C._arrayName type elShift = C._arrayElShift type if member.pointerDepth is 0 and not member.isArray if basic # basic value type: { get: -> @__b[arr][(@__a+offset) >> elShift] set: (x) -> @__b[arr][(@__a+offset) >> elShift] = x } else # complex value type: cName = '__c_' + member.memberName # for caching { get: -> if @[cName]? @[cName] else res = new type.__ctor(@__b, @__a+offset) @[cName] = res res set: (x) -> C.memcpy @__b, @__a+offset, x.__b, x.__a, size } else if member.pointerDepth is 0 if basic # basic array type { get: -> bIdx = (@__a+offset) >> elShift {__b} = @ (idx, val) -> if not val? __b[arr][bIdx+idx] else __b[arr][bIdx+idx] = val } else # complex array type { get: -> bOff = @__a+offset {__b} = @ (idx, val) -> if not val? new type.__ctor(__b, bOff+idx*stride) else C.memcpy __b, bOff+idx*stride, val.__b, val.__a, size } else # pointer type: T = typeId if T < 0 T = type pd = member.pointerDepth { get: -> addr = @__b.ui32[(@__a+offset)/4] new ptr addr, T, pd set: (x) -> @__b.ui32[(@__a+offset)/4] = x.a } C.struct = (def) -> struct = -> struct.__ctor.apply this, arguments struct.__size = 0 struct.__align = 1 if Array.isArray def for member in def type = C._typedefs[member.typeName] or member.typeName _type = type _type = 'void*' if member.pointerDepth > 0 size = C.sizeof _type align = C.alignof _type stride = (size + align - 1) &-align if member.isArray size += stride * (member.arrayLength - 1) struct.__size = (struct.__size + align - 1) & -align offset = struct.__size struct.__size += size if align > struct.__align struct.__align = align struct[member.memberName] = { offset, member, type, stride, align, size } else for name, member of def type = C._typedefs[member.typeName] or member.typeName _type = type _type = 'void*' if member.pointerDepth > 0 member.memberName = name size = C.sizeof _type align = C.alignof _type stride = (size + align - 1) &-align if member.isArray size += stride * (member.arrayLength - 1) offset = member.offset end = offset + size if end > struct.__size struct.__size = end if align > struct.__align struct.__align = align struct[member.memberName] = { offset, member, type, stride, align, size } struct.__ctor = (buffer, address) -> @__b = buffer @__a = address @ struct.__ctor.prototype = do-> result = { __t: struct } for k, v of struct when k.substr(0,2) isnt '__' Object.defineProperty result, k, makeAccessors v result struct.prototype = struct.__ctor.prototype struct C._heapLast = null block = (addr, size, prev, next) -> @a = addr @l = size @e = addr + size @prev = prev if prev? prev.next = @ @next = next if next? next.prev = @ # create all views up front: @buf = buf = new ArrayBuffer(size) @ui32 = new Uint32Array(buf) @i32 = new Int32Array(buf) @ui16 = new Uint16Array(buf) @i16 = new Int16Array(buf) @ui8 = new Uint8Array(buf) @i8 = new Int8Array(buf) @f32 = new Float32Array(buf) @f64 = new Float64Array(buf) @ block.prototype.free = -> if @ is C._heapLast C._heapLast = @prev if @prev? @prev.next = @next if @next? @next.prev = @prev return # pad to help mitigate null pointer+math derefs addressMin = 0x00010000 addressMax = 0x7fff0000 C.malloc = (size) -> if size < 0 throw new Error 'invalid allocation size' # round up so that the underlying TypedArrays are accessible; 16 because I # like round numbers size = (size + 0xf) & -0x10 if C._heapLast == null if size+addressMin > addressMax throw new Error 'invalid allocation size' C._heapLast = new block(addressMin, size, null, null) else curr = C._heapLast if size+curr.e <= addressMax addr = curr.e C._heapLast = new block(addr, size, curr, null) else b = null loop min = curr.prev?.e or addressMin room = curr.a - min if room >= size addr = curr.a - size b = new block(addr, size, curr.prev, curr) break curr = curr.prev if not curr? # yeah, fragmentation can get us here easily, but 2gigs of VA space # seems bountiful for this purpose, and I'd rather not overengineer it throw new Error 'heap space not available' return b C.free = (addr) -> if typeof addr is 'object' return addr.free() return if addr < addressMin return if addr >= addressMax curr = C._heapLast loop break if not curr? if curr.a is addr return curr.free() curr = curr.prev C.getBufferAddress = (addr) -> if typeof addr is 'object' # grab address from ptr objects addr = addr.a curr = C._heapLast loop break if not curr? if curr.e > addr and curr.a <= addr return [curr, addr - curr.a] curr = curr.prev # i feel bad about not throwing here where the errant stack is, but C. return [null, 0] C._getHeapValue = (addr, t) -> [buf, rva] = C.getBufferAddress addr switch t when 0 then buf.ui32[0|rva/4] when 1 then buf.i32[0|rva/4] when 2 then buf.ui16[0|rva/2] when 3 then buf.i16[0|rva/2] when 4 then buf.ui8[0|rva] when 5 then buf.i8[0|rva] when 6 then buf.f32[0|rva/4] when 7 then buf.f64[0|rva/8] else buf.ui32[0|rva/4] C._setHeapValue = (addr, t, v) -> [buf, rva] = C.getBufferAddress addr switch t when 0 then buf.ui32[0|rva/4] = v when 1 then buf.i32[0|rva/4] = v when 2 then buf.ui16[0|rva/2] = v when 3 then buf.i16[0|rva/2] = v when 4 then buf.ui8[0|rva] = v when 5 then buf.i8[0|rva] = v when 6 then buf.f32[0|rva/4] = v when 7 then buf.f64[0|rva/8] = v else buf.ui32[0|rva/4] = v C.memcpy = (dstBuf, dstRva, srcBuf, srcRva, size) -> if not size? dstAddr = dstBuf srcAddr = dstRva size = srcBuf [dstBuf, dstRva] = C.getBufferAddress dstAddr [srcBuf, srcRva] = C.getBufferAddress srcAddr dstBuf.ui8.set srcBuf.ui8.subarray(srcRva, srcRva + size), dstRva C.copyBuffer = (buf) -> res = C.malloc buf.byteLength res.ui8.set new Uint8Array(buf), 0 res ptr = (a, t, p) -> @a = a @t = t @p = p @ ptr.prototype.deref = (head, tail...) -> nextDepth = @p - 1 currAddr = @a head or= 0 if nextDepth is 0 if typeof @t is 'number' C._getHeapValue currAddr + head * C._arrayElSize(@t), @t else [buf, rva] = C.getBufferAddress currAddr + head * C.sizeof(@t) new @t buf, rva else nextPtr = C._getHeapValue currAddr + head * pointerSize, 0 nextObj = new ptr nextPtr, @t, nextDepth # Object.create Object.getPrototypeOf @ # nextObj.t = @t # nextObj.p = nextDepth # nextObj.a = nextPtr if tail.length > 0 @deref.apply nextObj, tail else nextObj ptr.prototype.set = (idx, val) -> nextDepth = @p - 1 currAddr = @a throw new Error 'bad pointer' if nextDepth < 0 if nextDepth is 0 if typeof @t is 'number' C._setHeapValue currAddr + idx * C._arrayElSize(@t), @t, val else [dstBuf, dstRva] = C.getBufferAddress currAddr + idx * C.sizeof(@t) C.memcpy dstBuf, dstRva, val.__b, val.__a, C.sizeof(@t) else C._setHeapValue currAddr + idx * pointerSize, 0, val.a ptr.prototype.cast = (type) -> if typeof type is 'string' type = type.split '*' p = type.length - 1 p = @p if p is 0 tId = C._typeNameToId type[0] tId = C._typedefs[type[0]] if tId < 0 new ptr @a, tId, p else new ptr @a, type, @p C.ref = (locatable, memberName) -> if locatable.__t? t = locatable.__t a = locatable.__a + locatable.__b.a p = 1 if memberName? a += t[memberName].offset p += t[memberName].pointerDepth t = t[memberName].type new ptr a, t, p else new ptr locatable.a, 'void*', 1 ptr.prototype.add = (offset) -> new ptr @a + offset, @t, @p if typeof module is 'object' and typeof module.exports is 'object' # node/browserify module.exports = C else if typeof define == 'function' && define.amd # amd define ['cheap'], -> @cheap = C else # window/etc. @cheap = C
199353
# cheap.js - C-like memory layout for javascript # Copyright 2014 <NAME> C = {} # Returns objects for struct member definitions makeStructMember = (typeName, pointerDepth, memberName, arrayLength, offset) -> { typeName, pointerDepth, memberName, offset, arrayLength, isArray: arrayLength? } C._typedefs = {} C.typedef = (typeName, structDef) -> throw new Error 'name collides' if typeName of C C._typedefs[typeName] = structDef C[typeName] = (memberName, arrayLength) -> if typeof memberName is 'string' makeStructMember typeName, 0, memberName, arrayLength else makeStructMember typeName, 0, undefined, arrayLength, memberName C.ptr = (typeName, memberName, pointerDepth = 1) -> makeStructMember typeName, pointerDepth, memberName C.typedef 'uint' # 0 C.typedef 'int' # 1 C.typedef 'ushort' # 2 C.typedef 'short' # 3 C.typedef 'uchar' # 4 C.typedef 'char' # 5 C.typedef 'float' # 6 C.typedef 'double' # 7 C.typedef 'void' pointerSize = 4 pointerShift = 2 C.set64Bit = (is64Bit) -> if is64Bit pointerSize = 8 pointerShift = 3 else pointerSize = 4 pointerShift = 2 C._typeNameToId = (n) -> switch n when 'uint' then 0 when 'int' then 1 when 'ushort' then 2 when 'short' then 3 when 'uchar' then 4 when 'char' then 5 when 'float' then 6 when 'double' then 7 else -1 C._arrayName = (t) -> switch t when 0, 'uint' then 'ui32' when 1, 'int' then 'i32' when 2, 'ushort' then 'ui16' when 3, 'short' then 'i16' when 4, 'uchar' then 'ui8' when 5, 'char' then 'i8' when 6, 'float' then 'f32' when 7, 'double' then 'f64' else 'ui32' C._arrayElSize = (t) -> switch t when 0, 'uint', 1, 'int' then 4 when 2, 'ushort', 3, 'short' then 2 when 4, 'uchar', 5, 'char' then 1 when 6, 'float' then 4 when 7, 'double' then 8 else pointerSize C._arrayElShift = (t) -> switch t when 0, 'uint', 1, 'int', 6, 'float' then 2 when 2, 'ushort', 3, 'short' then 1 when 4, 'uchar', 5, 'char' then 0 when 7, 'double' then 3 else pointerShift C.sizeof = (type) -> if typeof type is 'string' switch type when 'char', 'uchar' then 1 when 'short', 'ushort' then 2 when 'int', 'uint', 'float' then 4 when 'double' then 8 when 'void*' then pointerSize else 1 # void else type.__size C.strideof = (type) -> if typeof type is 'string' C.sizeof type else (type.__size + type.__align - 1) & -type.__align C.alignof = (type) -> if typeof type is 'string' C.sizeof type else type.__align C.offsetof = (type, member) -> type[member].offset makeAccessors = (def) -> { offset, member, type, stride, align, size } = def basic = typeof type is 'string' typeId = C._typeNameToId type arr = C._arrayName type elShift = C._arrayElShift type if member.pointerDepth is 0 and not member.isArray if basic # basic value type: { get: -> @__b[arr][(@__a+offset) >> elShift] set: (x) -> @__b[arr][(@__a+offset) >> elShift] = x } else # complex value type: cName = '__c_' + member.memberName # for caching { get: -> if @[cName]? @[cName] else res = new type.__ctor(@__b, @__a+offset) @[cName] = res res set: (x) -> C.memcpy @__b, @__a+offset, x.__b, x.__a, size } else if member.pointerDepth is 0 if basic # basic array type { get: -> bIdx = (@__a+offset) >> elShift {__b} = @ (idx, val) -> if not val? __b[arr][bIdx+idx] else __b[arr][bIdx+idx] = val } else # complex array type { get: -> bOff = @__a+offset {__b} = @ (idx, val) -> if not val? new type.__ctor(__b, bOff+idx*stride) else C.memcpy __b, bOff+idx*stride, val.__b, val.__a, size } else # pointer type: T = typeId if T < 0 T = type pd = member.pointerDepth { get: -> addr = @__b.ui32[(@__a+offset)/4] new ptr addr, T, pd set: (x) -> @__b.ui32[(@__a+offset)/4] = x.a } C.struct = (def) -> struct = -> struct.__ctor.apply this, arguments struct.__size = 0 struct.__align = 1 if Array.isArray def for member in def type = C._typedefs[member.typeName] or member.typeName _type = type _type = 'void*' if member.pointerDepth > 0 size = C.sizeof _type align = C.alignof _type stride = (size + align - 1) &-align if member.isArray size += stride * (member.arrayLength - 1) struct.__size = (struct.__size + align - 1) & -align offset = struct.__size struct.__size += size if align > struct.__align struct.__align = align struct[member.memberName] = { offset, member, type, stride, align, size } else for name, member of def type = C._typedefs[member.typeName] or member.typeName _type = type _type = 'void*' if member.pointerDepth > 0 member.memberName = name size = C.sizeof _type align = C.alignof _type stride = (size + align - 1) &-align if member.isArray size += stride * (member.arrayLength - 1) offset = member.offset end = offset + size if end > struct.__size struct.__size = end if align > struct.__align struct.__align = align struct[member.memberName] = { offset, member, type, stride, align, size } struct.__ctor = (buffer, address) -> @__b = buffer @__a = address @ struct.__ctor.prototype = do-> result = { __t: struct } for k, v of struct when k.substr(0,2) isnt '__' Object.defineProperty result, k, makeAccessors v result struct.prototype = struct.__ctor.prototype struct C._heapLast = null block = (addr, size, prev, next) -> @a = addr @l = size @e = addr + size @prev = prev if prev? prev.next = @ @next = next if next? next.prev = @ # create all views up front: @buf = buf = new ArrayBuffer(size) @ui32 = new Uint32Array(buf) @i32 = new Int32Array(buf) @ui16 = new Uint16Array(buf) @i16 = new Int16Array(buf) @ui8 = new Uint8Array(buf) @i8 = new Int8Array(buf) @f32 = new Float32Array(buf) @f64 = new Float64Array(buf) @ block.prototype.free = -> if @ is C._heapLast C._heapLast = @prev if @prev? @prev.next = @next if @next? @next.prev = @prev return # pad to help mitigate null pointer+math derefs addressMin = 0x00010000 addressMax = 0x7fff0000 C.malloc = (size) -> if size < 0 throw new Error 'invalid allocation size' # round up so that the underlying TypedArrays are accessible; 16 because I # like round numbers size = (size + 0xf) & -0x10 if C._heapLast == null if size+addressMin > addressMax throw new Error 'invalid allocation size' C._heapLast = new block(addressMin, size, null, null) else curr = C._heapLast if size+curr.e <= addressMax addr = curr.e C._heapLast = new block(addr, size, curr, null) else b = null loop min = curr.prev?.e or addressMin room = curr.a - min if room >= size addr = curr.a - size b = new block(addr, size, curr.prev, curr) break curr = curr.prev if not curr? # yeah, fragmentation can get us here easily, but 2gigs of VA space # seems bountiful for this purpose, and I'd rather not overengineer it throw new Error 'heap space not available' return b C.free = (addr) -> if typeof addr is 'object' return addr.free() return if addr < addressMin return if addr >= addressMax curr = C._heapLast loop break if not curr? if curr.a is addr return curr.free() curr = curr.prev C.getBufferAddress = (addr) -> if typeof addr is 'object' # grab address from ptr objects addr = addr.a curr = C._heapLast loop break if not curr? if curr.e > addr and curr.a <= addr return [curr, addr - curr.a] curr = curr.prev # i feel bad about not throwing here where the errant stack is, but C. return [null, 0] C._getHeapValue = (addr, t) -> [buf, rva] = C.getBufferAddress addr switch t when 0 then buf.ui32[0|rva/4] when 1 then buf.i32[0|rva/4] when 2 then buf.ui16[0|rva/2] when 3 then buf.i16[0|rva/2] when 4 then buf.ui8[0|rva] when 5 then buf.i8[0|rva] when 6 then buf.f32[0|rva/4] when 7 then buf.f64[0|rva/8] else buf.ui32[0|rva/4] C._setHeapValue = (addr, t, v) -> [buf, rva] = C.getBufferAddress addr switch t when 0 then buf.ui32[0|rva/4] = v when 1 then buf.i32[0|rva/4] = v when 2 then buf.ui16[0|rva/2] = v when 3 then buf.i16[0|rva/2] = v when 4 then buf.ui8[0|rva] = v when 5 then buf.i8[0|rva] = v when 6 then buf.f32[0|rva/4] = v when 7 then buf.f64[0|rva/8] = v else buf.ui32[0|rva/4] = v C.memcpy = (dstBuf, dstRva, srcBuf, srcRva, size) -> if not size? dstAddr = dstBuf srcAddr = dstRva size = srcBuf [dstBuf, dstRva] = C.getBufferAddress dstAddr [srcBuf, srcRva] = C.getBufferAddress srcAddr dstBuf.ui8.set srcBuf.ui8.subarray(srcRva, srcRva + size), dstRva C.copyBuffer = (buf) -> res = C.malloc buf.byteLength res.ui8.set new Uint8Array(buf), 0 res ptr = (a, t, p) -> @a = a @t = t @p = p @ ptr.prototype.deref = (head, tail...) -> nextDepth = @p - 1 currAddr = @a head or= 0 if nextDepth is 0 if typeof @t is 'number' C._getHeapValue currAddr + head * C._arrayElSize(@t), @t else [buf, rva] = C.getBufferAddress currAddr + head * C.sizeof(@t) new @t buf, rva else nextPtr = C._getHeapValue currAddr + head * pointerSize, 0 nextObj = new ptr nextPtr, @t, nextDepth # Object.create Object.getPrototypeOf @ # nextObj.t = @t # nextObj.p = nextDepth # nextObj.a = nextPtr if tail.length > 0 @deref.apply nextObj, tail else nextObj ptr.prototype.set = (idx, val) -> nextDepth = @p - 1 currAddr = @a throw new Error 'bad pointer' if nextDepth < 0 if nextDepth is 0 if typeof @t is 'number' C._setHeapValue currAddr + idx * C._arrayElSize(@t), @t, val else [dstBuf, dstRva] = C.getBufferAddress currAddr + idx * C.sizeof(@t) C.memcpy dstBuf, dstRva, val.__b, val.__a, C.sizeof(@t) else C._setHeapValue currAddr + idx * pointerSize, 0, val.a ptr.prototype.cast = (type) -> if typeof type is 'string' type = type.split '*' p = type.length - 1 p = @p if p is 0 tId = C._typeNameToId type[0] tId = C._typedefs[type[0]] if tId < 0 new ptr @a, tId, p else new ptr @a, type, @p C.ref = (locatable, memberName) -> if locatable.__t? t = locatable.__t a = locatable.__a + locatable.__b.a p = 1 if memberName? a += t[memberName].offset p += t[memberName].pointerDepth t = t[memberName].type new ptr a, t, p else new ptr locatable.a, 'void*', 1 ptr.prototype.add = (offset) -> new ptr @a + offset, @t, @p if typeof module is 'object' and typeof module.exports is 'object' # node/browserify module.exports = C else if typeof define == 'function' && define.amd # amd define ['cheap'], -> @cheap = C else # window/etc. @cheap = C
true
# cheap.js - C-like memory layout for javascript # Copyright 2014 PI:NAME:<NAME>END_PI C = {} # Returns objects for struct member definitions makeStructMember = (typeName, pointerDepth, memberName, arrayLength, offset) -> { typeName, pointerDepth, memberName, offset, arrayLength, isArray: arrayLength? } C._typedefs = {} C.typedef = (typeName, structDef) -> throw new Error 'name collides' if typeName of C C._typedefs[typeName] = structDef C[typeName] = (memberName, arrayLength) -> if typeof memberName is 'string' makeStructMember typeName, 0, memberName, arrayLength else makeStructMember typeName, 0, undefined, arrayLength, memberName C.ptr = (typeName, memberName, pointerDepth = 1) -> makeStructMember typeName, pointerDepth, memberName C.typedef 'uint' # 0 C.typedef 'int' # 1 C.typedef 'ushort' # 2 C.typedef 'short' # 3 C.typedef 'uchar' # 4 C.typedef 'char' # 5 C.typedef 'float' # 6 C.typedef 'double' # 7 C.typedef 'void' pointerSize = 4 pointerShift = 2 C.set64Bit = (is64Bit) -> if is64Bit pointerSize = 8 pointerShift = 3 else pointerSize = 4 pointerShift = 2 C._typeNameToId = (n) -> switch n when 'uint' then 0 when 'int' then 1 when 'ushort' then 2 when 'short' then 3 when 'uchar' then 4 when 'char' then 5 when 'float' then 6 when 'double' then 7 else -1 C._arrayName = (t) -> switch t when 0, 'uint' then 'ui32' when 1, 'int' then 'i32' when 2, 'ushort' then 'ui16' when 3, 'short' then 'i16' when 4, 'uchar' then 'ui8' when 5, 'char' then 'i8' when 6, 'float' then 'f32' when 7, 'double' then 'f64' else 'ui32' C._arrayElSize = (t) -> switch t when 0, 'uint', 1, 'int' then 4 when 2, 'ushort', 3, 'short' then 2 when 4, 'uchar', 5, 'char' then 1 when 6, 'float' then 4 when 7, 'double' then 8 else pointerSize C._arrayElShift = (t) -> switch t when 0, 'uint', 1, 'int', 6, 'float' then 2 when 2, 'ushort', 3, 'short' then 1 when 4, 'uchar', 5, 'char' then 0 when 7, 'double' then 3 else pointerShift C.sizeof = (type) -> if typeof type is 'string' switch type when 'char', 'uchar' then 1 when 'short', 'ushort' then 2 when 'int', 'uint', 'float' then 4 when 'double' then 8 when 'void*' then pointerSize else 1 # void else type.__size C.strideof = (type) -> if typeof type is 'string' C.sizeof type else (type.__size + type.__align - 1) & -type.__align C.alignof = (type) -> if typeof type is 'string' C.sizeof type else type.__align C.offsetof = (type, member) -> type[member].offset makeAccessors = (def) -> { offset, member, type, stride, align, size } = def basic = typeof type is 'string' typeId = C._typeNameToId type arr = C._arrayName type elShift = C._arrayElShift type if member.pointerDepth is 0 and not member.isArray if basic # basic value type: { get: -> @__b[arr][(@__a+offset) >> elShift] set: (x) -> @__b[arr][(@__a+offset) >> elShift] = x } else # complex value type: cName = '__c_' + member.memberName # for caching { get: -> if @[cName]? @[cName] else res = new type.__ctor(@__b, @__a+offset) @[cName] = res res set: (x) -> C.memcpy @__b, @__a+offset, x.__b, x.__a, size } else if member.pointerDepth is 0 if basic # basic array type { get: -> bIdx = (@__a+offset) >> elShift {__b} = @ (idx, val) -> if not val? __b[arr][bIdx+idx] else __b[arr][bIdx+idx] = val } else # complex array type { get: -> bOff = @__a+offset {__b} = @ (idx, val) -> if not val? new type.__ctor(__b, bOff+idx*stride) else C.memcpy __b, bOff+idx*stride, val.__b, val.__a, size } else # pointer type: T = typeId if T < 0 T = type pd = member.pointerDepth { get: -> addr = @__b.ui32[(@__a+offset)/4] new ptr addr, T, pd set: (x) -> @__b.ui32[(@__a+offset)/4] = x.a } C.struct = (def) -> struct = -> struct.__ctor.apply this, arguments struct.__size = 0 struct.__align = 1 if Array.isArray def for member in def type = C._typedefs[member.typeName] or member.typeName _type = type _type = 'void*' if member.pointerDepth > 0 size = C.sizeof _type align = C.alignof _type stride = (size + align - 1) &-align if member.isArray size += stride * (member.arrayLength - 1) struct.__size = (struct.__size + align - 1) & -align offset = struct.__size struct.__size += size if align > struct.__align struct.__align = align struct[member.memberName] = { offset, member, type, stride, align, size } else for name, member of def type = C._typedefs[member.typeName] or member.typeName _type = type _type = 'void*' if member.pointerDepth > 0 member.memberName = name size = C.sizeof _type align = C.alignof _type stride = (size + align - 1) &-align if member.isArray size += stride * (member.arrayLength - 1) offset = member.offset end = offset + size if end > struct.__size struct.__size = end if align > struct.__align struct.__align = align struct[member.memberName] = { offset, member, type, stride, align, size } struct.__ctor = (buffer, address) -> @__b = buffer @__a = address @ struct.__ctor.prototype = do-> result = { __t: struct } for k, v of struct when k.substr(0,2) isnt '__' Object.defineProperty result, k, makeAccessors v result struct.prototype = struct.__ctor.prototype struct C._heapLast = null block = (addr, size, prev, next) -> @a = addr @l = size @e = addr + size @prev = prev if prev? prev.next = @ @next = next if next? next.prev = @ # create all views up front: @buf = buf = new ArrayBuffer(size) @ui32 = new Uint32Array(buf) @i32 = new Int32Array(buf) @ui16 = new Uint16Array(buf) @i16 = new Int16Array(buf) @ui8 = new Uint8Array(buf) @i8 = new Int8Array(buf) @f32 = new Float32Array(buf) @f64 = new Float64Array(buf) @ block.prototype.free = -> if @ is C._heapLast C._heapLast = @prev if @prev? @prev.next = @next if @next? @next.prev = @prev return # pad to help mitigate null pointer+math derefs addressMin = 0x00010000 addressMax = 0x7fff0000 C.malloc = (size) -> if size < 0 throw new Error 'invalid allocation size' # round up so that the underlying TypedArrays are accessible; 16 because I # like round numbers size = (size + 0xf) & -0x10 if C._heapLast == null if size+addressMin > addressMax throw new Error 'invalid allocation size' C._heapLast = new block(addressMin, size, null, null) else curr = C._heapLast if size+curr.e <= addressMax addr = curr.e C._heapLast = new block(addr, size, curr, null) else b = null loop min = curr.prev?.e or addressMin room = curr.a - min if room >= size addr = curr.a - size b = new block(addr, size, curr.prev, curr) break curr = curr.prev if not curr? # yeah, fragmentation can get us here easily, but 2gigs of VA space # seems bountiful for this purpose, and I'd rather not overengineer it throw new Error 'heap space not available' return b C.free = (addr) -> if typeof addr is 'object' return addr.free() return if addr < addressMin return if addr >= addressMax curr = C._heapLast loop break if not curr? if curr.a is addr return curr.free() curr = curr.prev C.getBufferAddress = (addr) -> if typeof addr is 'object' # grab address from ptr objects addr = addr.a curr = C._heapLast loop break if not curr? if curr.e > addr and curr.a <= addr return [curr, addr - curr.a] curr = curr.prev # i feel bad about not throwing here where the errant stack is, but C. return [null, 0] C._getHeapValue = (addr, t) -> [buf, rva] = C.getBufferAddress addr switch t when 0 then buf.ui32[0|rva/4] when 1 then buf.i32[0|rva/4] when 2 then buf.ui16[0|rva/2] when 3 then buf.i16[0|rva/2] when 4 then buf.ui8[0|rva] when 5 then buf.i8[0|rva] when 6 then buf.f32[0|rva/4] when 7 then buf.f64[0|rva/8] else buf.ui32[0|rva/4] C._setHeapValue = (addr, t, v) -> [buf, rva] = C.getBufferAddress addr switch t when 0 then buf.ui32[0|rva/4] = v when 1 then buf.i32[0|rva/4] = v when 2 then buf.ui16[0|rva/2] = v when 3 then buf.i16[0|rva/2] = v when 4 then buf.ui8[0|rva] = v when 5 then buf.i8[0|rva] = v when 6 then buf.f32[0|rva/4] = v when 7 then buf.f64[0|rva/8] = v else buf.ui32[0|rva/4] = v C.memcpy = (dstBuf, dstRva, srcBuf, srcRva, size) -> if not size? dstAddr = dstBuf srcAddr = dstRva size = srcBuf [dstBuf, dstRva] = C.getBufferAddress dstAddr [srcBuf, srcRva] = C.getBufferAddress srcAddr dstBuf.ui8.set srcBuf.ui8.subarray(srcRva, srcRva + size), dstRva C.copyBuffer = (buf) -> res = C.malloc buf.byteLength res.ui8.set new Uint8Array(buf), 0 res ptr = (a, t, p) -> @a = a @t = t @p = p @ ptr.prototype.deref = (head, tail...) -> nextDepth = @p - 1 currAddr = @a head or= 0 if nextDepth is 0 if typeof @t is 'number' C._getHeapValue currAddr + head * C._arrayElSize(@t), @t else [buf, rva] = C.getBufferAddress currAddr + head * C.sizeof(@t) new @t buf, rva else nextPtr = C._getHeapValue currAddr + head * pointerSize, 0 nextObj = new ptr nextPtr, @t, nextDepth # Object.create Object.getPrototypeOf @ # nextObj.t = @t # nextObj.p = nextDepth # nextObj.a = nextPtr if tail.length > 0 @deref.apply nextObj, tail else nextObj ptr.prototype.set = (idx, val) -> nextDepth = @p - 1 currAddr = @a throw new Error 'bad pointer' if nextDepth < 0 if nextDepth is 0 if typeof @t is 'number' C._setHeapValue currAddr + idx * C._arrayElSize(@t), @t, val else [dstBuf, dstRva] = C.getBufferAddress currAddr + idx * C.sizeof(@t) C.memcpy dstBuf, dstRva, val.__b, val.__a, C.sizeof(@t) else C._setHeapValue currAddr + idx * pointerSize, 0, val.a ptr.prototype.cast = (type) -> if typeof type is 'string' type = type.split '*' p = type.length - 1 p = @p if p is 0 tId = C._typeNameToId type[0] tId = C._typedefs[type[0]] if tId < 0 new ptr @a, tId, p else new ptr @a, type, @p C.ref = (locatable, memberName) -> if locatable.__t? t = locatable.__t a = locatable.__a + locatable.__b.a p = 1 if memberName? a += t[memberName].offset p += t[memberName].pointerDepth t = t[memberName].type new ptr a, t, p else new ptr locatable.a, 'void*', 1 ptr.prototype.add = (offset) -> new ptr @a + offset, @t, @p if typeof module is 'object' and typeof module.exports is 'object' # node/browserify module.exports = C else if typeof define == 'function' && define.amd # amd define ['cheap'], -> @cheap = C else # window/etc. @cheap = C
[ { "context": " created on 25/12/2016 All rights reserved by @NeZha\n# Today is chrismas :) but Dan Shen Gou st", "end": 439, "score": 0.9996720552444458, "start": 433, "tag": "USERNAME", "value": "@NeZha" }, { "context": "served by @NeZha\n# Today is chrismas :) bu...
src/examples/kinect-one-point-cloud.coffee
CallmeNezha/Crystal
0
# ______ _____ _________ _____ _____ # / /_ / / \___ / / /__/ / # / \/ / ___ / / / / ___ # / / \ / /\__\ / /___ / ___ / / \ # _/____ / \___ / _\___ _/_______ / _/___ / _/___ / _\___/\_ # created on 25/12/2016 All rights reserved by @NeZha # Today is chrismas :) but Dan Shen Gou still keep finding source code of the world instead of meeting # a girl to make little human(in biology aspect of source code), so the saying: Ge Si Qi Zhi fs = require 'fs' env = require '../../env' THREE = require "#{env.PATH.THREE}build/three" Kinect = require "./Crystal_Geo.node" console.log(Kinect) do -> file = fs.readFileSync("#{env.PATH.THREE}examples/js/loaders/STLLoader.js", 'utf-8'); eval file file = fs.readFileSync("#{env.PATH.THREE}examples/js/loaders/3MFLoader.js", 'utf-8'); eval file file = fs.readFileSync("#{env.PATH.THREE}examples/js/loaders/OBJLoader.js", 'utf-8'); eval file file = fs.readFileSync("#{env.PATH.THREE}examples/js/controls/OrbitControls.js", 'utf-8'); eval file vertexShader = """ uniform float width; uniform float height; varying vec2 vUv; uniform sampler2D map; uniform float time; void main() { vUv = vec2(position.x / width, position.y / height); vec2 vUvsround[8]; vUvsround[0] = vec2(position.x - 1.0, position.y + 1.0); vUvsround[1] = vec2(position.x - 1.0, position.y); vUvsround[2] = vec2(position.x - 1.0, position.y - 1.0); vUvsround[3] = vec2(position.x, position.y - 1.0); vUvsround[4] = vec2(position.x + 1.01, position.y - 1.0); vUvsround[5] = vec2(position.x + 1.0, position.y); vUvsround[6] = vec2(position.x + 1.0, position.y + 1.0); vUvsround[7] = vec2(position.x, position.y + 1.0); vec4 center = texture2D(map, vUv); float error = 0.0; for(int i=0; i < 8; ++i) { vUvsround[i] = vec2(vUvsround[i].x / width, vUvsround[i].y / height); vec4 color = texture2D(map, vUvsround[i]); error += abs(center.z - color.z); } if (error > 0.1) { center.z = 0.0; } vec3 offset = vec3(0.0, 0.0, center.z * 600.0); if (abs(offset.z) < 0.01) offset.z = 600.0; vec4 mvPosition = modelViewMatrix * vec4( position + offset, 1.0 ); gl_PointSize = 5.0; gl_Position = projectionMatrix * mvPosition; } """ fragmentShader = """ uniform sampler2D map; varying vec2 vUv; uniform float time; void main() { vec4 color = texture2D(map, vUv); gl_FragColor = vec4(color.rgb, 1.0); } """ class View constructor: -> @scene = new THREE.Scene() @camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.01, 10000) @clock = new THREE.Clock() @objects = {} @_control = null init: (renderer) -> renderer.setClearColor(0xDBDBDB) renderer.gammaInput = on renderer.gammaOutput = on # renderer.shadowMap.enabled = true @_control = new THREE.OrbitControls(@camera, renderer.domElement) @_control.enableZoom = yes @camera.position.set(20, 20, 0) @camera.lookAt(new THREE.Vector3()) # Lights @scene.add(new THREE.HemisphereLight(0xffffbb, 0x080820, 1)) @_addShadowedLight(1, 1, 1) Kinect.CreateKinect() width = 512 height = 424 @_depthframe = new Float32Array(width * height) # geometry = new THREE.PlaneGeometry(1, 1) geometry = new THREE.BufferGeometry() vertices = new Float32Array( width * height * 3) ``` for ( var i = 0, j = 0, l = vertices.length; i < l; i += 3, j ++ ) { vertices[ i ] = j % width; vertices[ i + 1 ] = Math.floor( j / width ); } ``` geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ) @_texture = new THREE.Texture(@_generateTexture()) @_texture.needsUpdate = true @_uniforms = map: { value: @_texture } width: {value: width} height: {value: height} time: {value: 0.0} blending: THREE.AdditiveBlending depthTest: false depthWrite: false, transparent: true material = new THREE.ShaderMaterial(uniforms: @_uniforms , vertexShader: vertexShader , fragmentShader: fragmentShader) #material = new THREE.MeshBasicMaterial( {color: 0x102000, side: THREE.DoubleSide} ) mesh = new THREE.Points(geometry, material) mesh.scale.set(0.01, 0.01, 0.01) @scene.add(mesh) return onRender: -> dt = this.clock.getDelta() @_control.update() success = Kinect.GetDepthBuffer(@_depthframe) # console.log("#{success} GetDepthBuffer returns") @_putImageData() @_texture.needsUpdate = true @_uniforms.time.value += 0.05 return onExit: -> Kinect.DestroyKinect() return ## # Add some direct light from sky # _addShadowedLight: (x, y, z, d = 10000, color = 0xffffbb, intensity = 0.2) -> directLight = new THREE.DirectionalLight(color, intensity) directLight.position.set(x, y, z) @scene.add(directLight) return _generateTexture: -> canvas = document.createElement('canvas') canvas.width = 512 canvas.height = 424 @_context = canvas.getContext('2d') image = @_context.getImageData(0, 0, 512, 424) for i in [0...512 * 424] image.data[i] = Math.random() * 255 @_context.putImageData(image, 0, 0) return canvas _putImageData: -> image = @_context.getImageData(0, 0, 512, 424) for ipxl in [0...512 * 424 * 4] by 4 intensity = @_depthframe[ipxl / 4] intensity = if intensity < 1800 then (intensity / 1800) * 255 else 0 image.data[ipxl ] = intensity image.data[ipxl + 1] = intensity image.data[ipxl + 2] = intensity image.data[ipxl + 3] = 255 @_context.putImageData(image, 0, 0) return module.exports = View if module?
97879
# ______ _____ _________ _____ _____ # / /_ / / \___ / / /__/ / # / \/ / ___ / / / / ___ # / / \ / /\__\ / /___ / ___ / / \ # _/____ / \___ / _\___ _/_______ / _/___ / _/___ / _\___/\_ # created on 25/12/2016 All rights reserved by @NeZha # Today is chrismas :) but <NAME> still keep finding source code of the world instead of meeting # a girl to make little human(in biology aspect of source code), so the saying: Ge Si <NAME> Zhi fs = require 'fs' env = require '../../env' THREE = require "#{env.PATH.THREE}build/three" Kinect = require "./Crystal_Geo.node" console.log(Kinect) do -> file = fs.readFileSync("#{env.PATH.THREE}examples/js/loaders/STLLoader.js", 'utf-8'); eval file file = fs.readFileSync("#{env.PATH.THREE}examples/js/loaders/3MFLoader.js", 'utf-8'); eval file file = fs.readFileSync("#{env.PATH.THREE}examples/js/loaders/OBJLoader.js", 'utf-8'); eval file file = fs.readFileSync("#{env.PATH.THREE}examples/js/controls/OrbitControls.js", 'utf-8'); eval file vertexShader = """ uniform float width; uniform float height; varying vec2 vUv; uniform sampler2D map; uniform float time; void main() { vUv = vec2(position.x / width, position.y / height); vec2 vUvsround[8]; vUvsround[0] = vec2(position.x - 1.0, position.y + 1.0); vUvsround[1] = vec2(position.x - 1.0, position.y); vUvsround[2] = vec2(position.x - 1.0, position.y - 1.0); vUvsround[3] = vec2(position.x, position.y - 1.0); vUvsround[4] = vec2(position.x + 1.01, position.y - 1.0); vUvsround[5] = vec2(position.x + 1.0, position.y); vUvsround[6] = vec2(position.x + 1.0, position.y + 1.0); vUvsround[7] = vec2(position.x, position.y + 1.0); vec4 center = texture2D(map, vUv); float error = 0.0; for(int i=0; i < 8; ++i) { vUvsround[i] = vec2(vUvsround[i].x / width, vUvsround[i].y / height); vec4 color = texture2D(map, vUvsround[i]); error += abs(center.z - color.z); } if (error > 0.1) { center.z = 0.0; } vec3 offset = vec3(0.0, 0.0, center.z * 600.0); if (abs(offset.z) < 0.01) offset.z = 600.0; vec4 mvPosition = modelViewMatrix * vec4( position + offset, 1.0 ); gl_PointSize = 5.0; gl_Position = projectionMatrix * mvPosition; } """ fragmentShader = """ uniform sampler2D map; varying vec2 vUv; uniform float time; void main() { vec4 color = texture2D(map, vUv); gl_FragColor = vec4(color.rgb, 1.0); } """ class View constructor: -> @scene = new THREE.Scene() @camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.01, 10000) @clock = new THREE.Clock() @objects = {} @_control = null init: (renderer) -> renderer.setClearColor(0xDBDBDB) renderer.gammaInput = on renderer.gammaOutput = on # renderer.shadowMap.enabled = true @_control = new THREE.OrbitControls(@camera, renderer.domElement) @_control.enableZoom = yes @camera.position.set(20, 20, 0) @camera.lookAt(new THREE.Vector3()) # Lights @scene.add(new THREE.HemisphereLight(0xffffbb, 0x080820, 1)) @_addShadowedLight(1, 1, 1) Kinect.CreateKinect() width = 512 height = 424 @_depthframe = new Float32Array(width * height) # geometry = new THREE.PlaneGeometry(1, 1) geometry = new THREE.BufferGeometry() vertices = new Float32Array( width * height * 3) ``` for ( var i = 0, j = 0, l = vertices.length; i < l; i += 3, j ++ ) { vertices[ i ] = j % width; vertices[ i + 1 ] = Math.floor( j / width ); } ``` geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ) @_texture = new THREE.Texture(@_generateTexture()) @_texture.needsUpdate = true @_uniforms = map: { value: @_texture } width: {value: width} height: {value: height} time: {value: 0.0} blending: THREE.AdditiveBlending depthTest: false depthWrite: false, transparent: true material = new THREE.ShaderMaterial(uniforms: @_uniforms , vertexShader: vertexShader , fragmentShader: fragmentShader) #material = new THREE.MeshBasicMaterial( {color: 0x102000, side: THREE.DoubleSide} ) mesh = new THREE.Points(geometry, material) mesh.scale.set(0.01, 0.01, 0.01) @scene.add(mesh) return onRender: -> dt = this.clock.getDelta() @_control.update() success = Kinect.GetDepthBuffer(@_depthframe) # console.log("#{success} GetDepthBuffer returns") @_putImageData() @_texture.needsUpdate = true @_uniforms.time.value += 0.05 return onExit: -> Kinect.DestroyKinect() return ## # Add some direct light from sky # _addShadowedLight: (x, y, z, d = 10000, color = 0xffffbb, intensity = 0.2) -> directLight = new THREE.DirectionalLight(color, intensity) directLight.position.set(x, y, z) @scene.add(directLight) return _generateTexture: -> canvas = document.createElement('canvas') canvas.width = 512 canvas.height = 424 @_context = canvas.getContext('2d') image = @_context.getImageData(0, 0, 512, 424) for i in [0...512 * 424] image.data[i] = Math.random() * 255 @_context.putImageData(image, 0, 0) return canvas _putImageData: -> image = @_context.getImageData(0, 0, 512, 424) for ipxl in [0...512 * 424 * 4] by 4 intensity = @_depthframe[ipxl / 4] intensity = if intensity < 1800 then (intensity / 1800) * 255 else 0 image.data[ipxl ] = intensity image.data[ipxl + 1] = intensity image.data[ipxl + 2] = intensity image.data[ipxl + 3] = 255 @_context.putImageData(image, 0, 0) return module.exports = View if module?
true
# ______ _____ _________ _____ _____ # / /_ / / \___ / / /__/ / # / \/ / ___ / / / / ___ # / / \ / /\__\ / /___ / ___ / / \ # _/____ / \___ / _\___ _/_______ / _/___ / _/___ / _\___/\_ # created on 25/12/2016 All rights reserved by @NeZha # Today is chrismas :) but PI:NAME:<NAME>END_PI still keep finding source code of the world instead of meeting # a girl to make little human(in biology aspect of source code), so the saying: Ge Si PI:NAME:<NAME>END_PI Zhi fs = require 'fs' env = require '../../env' THREE = require "#{env.PATH.THREE}build/three" Kinect = require "./Crystal_Geo.node" console.log(Kinect) do -> file = fs.readFileSync("#{env.PATH.THREE}examples/js/loaders/STLLoader.js", 'utf-8'); eval file file = fs.readFileSync("#{env.PATH.THREE}examples/js/loaders/3MFLoader.js", 'utf-8'); eval file file = fs.readFileSync("#{env.PATH.THREE}examples/js/loaders/OBJLoader.js", 'utf-8'); eval file file = fs.readFileSync("#{env.PATH.THREE}examples/js/controls/OrbitControls.js", 'utf-8'); eval file vertexShader = """ uniform float width; uniform float height; varying vec2 vUv; uniform sampler2D map; uniform float time; void main() { vUv = vec2(position.x / width, position.y / height); vec2 vUvsround[8]; vUvsround[0] = vec2(position.x - 1.0, position.y + 1.0); vUvsround[1] = vec2(position.x - 1.0, position.y); vUvsround[2] = vec2(position.x - 1.0, position.y - 1.0); vUvsround[3] = vec2(position.x, position.y - 1.0); vUvsround[4] = vec2(position.x + 1.01, position.y - 1.0); vUvsround[5] = vec2(position.x + 1.0, position.y); vUvsround[6] = vec2(position.x + 1.0, position.y + 1.0); vUvsround[7] = vec2(position.x, position.y + 1.0); vec4 center = texture2D(map, vUv); float error = 0.0; for(int i=0; i < 8; ++i) { vUvsround[i] = vec2(vUvsround[i].x / width, vUvsround[i].y / height); vec4 color = texture2D(map, vUvsround[i]); error += abs(center.z - color.z); } if (error > 0.1) { center.z = 0.0; } vec3 offset = vec3(0.0, 0.0, center.z * 600.0); if (abs(offset.z) < 0.01) offset.z = 600.0; vec4 mvPosition = modelViewMatrix * vec4( position + offset, 1.0 ); gl_PointSize = 5.0; gl_Position = projectionMatrix * mvPosition; } """ fragmentShader = """ uniform sampler2D map; varying vec2 vUv; uniform float time; void main() { vec4 color = texture2D(map, vUv); gl_FragColor = vec4(color.rgb, 1.0); } """ class View constructor: -> @scene = new THREE.Scene() @camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.01, 10000) @clock = new THREE.Clock() @objects = {} @_control = null init: (renderer) -> renderer.setClearColor(0xDBDBDB) renderer.gammaInput = on renderer.gammaOutput = on # renderer.shadowMap.enabled = true @_control = new THREE.OrbitControls(@camera, renderer.domElement) @_control.enableZoom = yes @camera.position.set(20, 20, 0) @camera.lookAt(new THREE.Vector3()) # Lights @scene.add(new THREE.HemisphereLight(0xffffbb, 0x080820, 1)) @_addShadowedLight(1, 1, 1) Kinect.CreateKinect() width = 512 height = 424 @_depthframe = new Float32Array(width * height) # geometry = new THREE.PlaneGeometry(1, 1) geometry = new THREE.BufferGeometry() vertices = new Float32Array( width * height * 3) ``` for ( var i = 0, j = 0, l = vertices.length; i < l; i += 3, j ++ ) { vertices[ i ] = j % width; vertices[ i + 1 ] = Math.floor( j / width ); } ``` geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) ) @_texture = new THREE.Texture(@_generateTexture()) @_texture.needsUpdate = true @_uniforms = map: { value: @_texture } width: {value: width} height: {value: height} time: {value: 0.0} blending: THREE.AdditiveBlending depthTest: false depthWrite: false, transparent: true material = new THREE.ShaderMaterial(uniforms: @_uniforms , vertexShader: vertexShader , fragmentShader: fragmentShader) #material = new THREE.MeshBasicMaterial( {color: 0x102000, side: THREE.DoubleSide} ) mesh = new THREE.Points(geometry, material) mesh.scale.set(0.01, 0.01, 0.01) @scene.add(mesh) return onRender: -> dt = this.clock.getDelta() @_control.update() success = Kinect.GetDepthBuffer(@_depthframe) # console.log("#{success} GetDepthBuffer returns") @_putImageData() @_texture.needsUpdate = true @_uniforms.time.value += 0.05 return onExit: -> Kinect.DestroyKinect() return ## # Add some direct light from sky # _addShadowedLight: (x, y, z, d = 10000, color = 0xffffbb, intensity = 0.2) -> directLight = new THREE.DirectionalLight(color, intensity) directLight.position.set(x, y, z) @scene.add(directLight) return _generateTexture: -> canvas = document.createElement('canvas') canvas.width = 512 canvas.height = 424 @_context = canvas.getContext('2d') image = @_context.getImageData(0, 0, 512, 424) for i in [0...512 * 424] image.data[i] = Math.random() * 255 @_context.putImageData(image, 0, 0) return canvas _putImageData: -> image = @_context.getImageData(0, 0, 512, 424) for ipxl in [0...512 * 424 * 4] by 4 intensity = @_depthframe[ipxl / 4] intensity = if intensity < 1800 then (intensity / 1800) * 255 else 0 image.data[ipxl ] = intensity image.data[ipxl + 1] = intensity image.data[ipxl + 2] = intensity image.data[ipxl + 3] = 255 @_context.putImageData(image, 0, 0) return module.exports = View if module?
[ { "context": "ite\n# hubot stacko me - As above\n#\n# Author:\n# Ryan Tomlinson\n\nspuds = [\n \"http://webspace.webring.com/people/", "end": 227, "score": 0.9998279809951782, "start": 213, "tag": "NAME", "value": "Ryan Tomlinson" } ]
src/scripts/spudme.coffee
ryantomlinson/hubot-scripts
0
# Description: # Spud Me - Definitely not a racist script to display hilarious potato images # # Commands: # hubot spud me - Sends an image of an Irish favourite # hubot stacko me - As above # # Author: # Ryan Tomlinson spuds = [ "http://webspace.webring.com/people/mc/christina2320/stpats/irishpotato.gif", "http://grocery-genie.com/wp-content/uploads/2013/03/mr-potato-head.jpg", "http://shakebakeandparty.files.wordpress.com/2013/03/drunken-irish-potato-1.jpg", "http://www.mtnking.com/images/promotions/irish/irish_tommytater.gif" ] module.exports = (robot) -> robot.respond /(spud|stacko) me/i, (msg) -> msg.send msg.random spuds
18660
# Description: # Spud Me - Definitely not a racist script to display hilarious potato images # # Commands: # hubot spud me - Sends an image of an Irish favourite # hubot stacko me - As above # # Author: # <NAME> spuds = [ "http://webspace.webring.com/people/mc/christina2320/stpats/irishpotato.gif", "http://grocery-genie.com/wp-content/uploads/2013/03/mr-potato-head.jpg", "http://shakebakeandparty.files.wordpress.com/2013/03/drunken-irish-potato-1.jpg", "http://www.mtnking.com/images/promotions/irish/irish_tommytater.gif" ] module.exports = (robot) -> robot.respond /(spud|stacko) me/i, (msg) -> msg.send msg.random spuds
true
# Description: # Spud Me - Definitely not a racist script to display hilarious potato images # # Commands: # hubot spud me - Sends an image of an Irish favourite # hubot stacko me - As above # # Author: # PI:NAME:<NAME>END_PI spuds = [ "http://webspace.webring.com/people/mc/christina2320/stpats/irishpotato.gif", "http://grocery-genie.com/wp-content/uploads/2013/03/mr-potato-head.jpg", "http://shakebakeandparty.files.wordpress.com/2013/03/drunken-irish-potato-1.jpg", "http://www.mtnking.com/images/promotions/irish/irish_tommytater.gif" ] module.exports = (robot) -> robot.respond /(spud|stacko) me/i, (msg) -> msg.send msg.random spuds
[ { "context": "an-grunt-travis-github-pages/\n\thttps://github.com/sindresorhus/grunt-shell\n\n\t[REQUIRED] “pipenv run”, that scrip", "end": 349, "score": 0.9994913339614868, "start": 337, "tag": "USERNAME", "value": "sindresorhus" }, { "context": "nv --update”, users have bug:\n\tht...
grunt/shell.coffee
Kristinita/---
0
################# ## grunt-shell ## ################# ### [PURPOSE] Grunt plugin to run non-Grunt CLI commands. https://www.npmjs.com/package/grunt-shell ### module.exports = ############# ## Pelican ## ############# ### Build Pelican site: http://manos.im/blog/static-site-pelican-grunt-travis-github-pages/ https://github.com/sindresorhus/grunt-shell [REQUIRED] “pipenv run”, that scripts from pipenv virtual environment successful run; for example, “pipenv run pelican --help”, not “pelican --help”. https://robots.thoughtbot.com/how-to-manage-your-python-projects-with-pipenv “--fatal” — exit(1), if any warning or error [INFO] Disable “--debug” flag due to too detailed output: https://app.travis-ci.com/github/Kristinita/KristinitaPelican/jobs/560440148#L624-L2274 ### generate: command: 'pipenv run pelican content -s pelicanconf.py --fatal warnings' deploy: command: 'pipenv run pelican content -s publishconf.py --fatal warnings' ### [DEPRECATED] If “pipenv --update”, users have bug: https://github.com/pypa/pipenv/issues/1761 # Update Pip and Pipenv pipenvupdate: command: 'pipenv --update' ### ############ ## pipenv ## ############ ### [INFO] Update all Python Pipenv packages: https://stackoverflow.com/a/16269635/5951529 https://github.com/jgonggrijp/pip-review#pip-review ### pipenvupdateall: command: 'pipenv run pip-review --auto' ### [INFO] Clean unused packages: https://pipenv.pypa.io/en/latest/cli/#pipenv-clean [NOTE] So that “pipenv clean” doesn’t remove Python Markdown git extensions, you need install them in format: “pipenv install -e git+https://github.com/user/package_name.git#egg=package_name --dev”: https://pipenv.pypa.io/en/latest/basics/#a-note-about-vcs-dependencies https://github.com/pypa/pipenv/issues/1524 This is “editable” format: http://pipenv.readthedocs.io/en/latest/basics/#editable-dependencies-e-g-e [NOTE] Use correct “package_name” for “editable” packages, so that “pipenv clean” doesn’t delete them: https://github.com/pypa/pipenv/issues/1524#issuecomment-695213982 ### pipenvcleanunused: command: 'pipenv clean --verbose' ### Update packages versions to the newest in “Pipfile.lock”, that: 1. Another users have newest packages versions in their environment: 2. Fix CI errors as https://travis-ci.org/Kristinita/KristinitaPelican/jobs/368968779#L658-L677 https://docs.pipenv.org/basics/#example-pipenv-upgrade-workflow [INFO] Remove “--verbose” flag due to highly long details: https://app.travis-ci.com/github/Kristinita/KristinitaPelican/jobs/560271334#L736-L1277 ### pipenvupdatepipfilelock: command: 'pipenv update' ######### ## git ## ######### ### Shrink .git folder https://stackoverflow.com/a/2116892/5951529 Before: 568 MB — <https://i.imgur.com/aMvcfY1.png> After: 341 MB — <https://i.imgur.com/52cQ1AL.png> Remove reflog entries older, than 90 days: https://stackoverflow.com/a/3824970/5951529 ### gitreflog: command: 'git reflog expire --all' ### git gc https://stackoverflow.com/a/55738/5951529 Prune loose objects older than 2 weeks ago: https://www.kernel.org/pub/software/scm/git/docgit-gc.html ### gitgarbagecollector: command: 'git gc --aggressive' ############### ## HTML Tidy ## ############### ### Validate and fix HTML files: http://www.html-tidy.org/ Description: http://api.html-tidy.org/tidy/tidylib_api_next/index.html Options: http://api.html-tidy.org/tidy/quickref_next.html ### tidymodify: # [LEARN][GRUNT] Platform-specific tasks: # https://stackoverflow.com/a/23848087/5951529 # [REQUIRED] Single-line comments after a colon; otherwise the error “unexpected_newline”: # https://travis-ci.com/github/Kristinita/KristinitaPelican/jobs/488737915#L1945 if process.platform is "win32" # Need quotes, that command run: command: '"batch/tidy-modify.bat"' else ### [NOTE] Fix permission denied: https://stackoverflow.com/a/46818913/5951529 ### command: 'bash bash/tidy-modify.sh' tidyvalidate: if process.platform is "win32" command: '"batch/tidy-validate.bat"' else command: 'bash bash/tidy-validate.sh' ############ ## covgen ## ############ ### Generate Code of conduct for project: https://contributor-covenant.org/ https://www.npmjs.com/package/covgen [WARNING] Generate “CODE_OF_CONDUCT.md” for root folder: https://github.com/simonv3/covenant-generator/issues/15 [WARNING] Unobfuscated plain text e-mail: https://github.com/ContributorCovenant/contributor_covenant/issues/523 ### ######### ## npx ## ######### ### Tool for running npm CLI commands: https://www.npmjs.com/package/npx https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b https://stackoverflow.com/a/45164863/5951529 ### covgen: command: 'npx covgen kristinita$cock.li' ################## ## pip-licenses ## ################## ### Output licenses of all PyPI packages: https://pypi.org/project/pip-licenses/ Options: https://pypi.org/project/pip-licenses/#command-line-options ### piplicenses: command: 'pipenv run pip-licenses --with-authors --with-urls --with-description --format=markdown > python.md' ########################## ## commitlint Travis CI ## ########################## ### Commit linting for Travis CI: http://marionebl.github.io/commitlint/#/guides-ci-setup ### commitlint: command: 'commitlint-travis' ################### ## Travis Client ## ################### ### [ACTION] Lint “.travis.yml” file locally: https://stackoverflow.com/a/35607499/5951529 https://rubygems.org/gems/travis [INFO] “-x” argument — exit code 1, if any warning: https://github.com/travis-ci/travis.rb#lint ### travislint: command: 'travis lint -x' ########## # EClint # ########## ### Lint and fix files for EditorConfig rules: https://www.npmjs.com/package/eclint eclint doesn't search files and folders, that ignored in “.gitignore”: https://github.com/jedmao/eclint/issues/80#issuecomment-314936365 “eclint infer” — show current statistic: https://www.npmjs.com/package/eclint#infer [WARNING] Another eclint check and fix methods doesn't work: https://github.com/jedmao/eclint/issues/130 [WARNING] User can get different results for Windows and *NIX: https://github.com/jedmao/eclint/issues/129#event-1574600632 [BUG] 2 blank lines in end of file “CODE_OF_CONDUCT.md”, needs fix it: https://github.com/ContributorCovenant/contributor_covenant/issues/528 ### eclintfix: command: "npx eclint fix CODE_OF_CONDUCT.md && cd <%= templates.yamlconfig.OUTPUT_PATH %> \ && npx eclint fix && cd <%= templates.paths.cwd %>" eclintcheck: command: "cd <%= templates.yamlconfig.OUTPUT_PATH %> && npx eclint check && cd <%= templates.paths.cwd %>" ##################### # license-generator # ##################### ### Generate license: https://www.npmjs.com/package/license-generator ### licensegenerator: command: "npx license-generator install mit -n \"Sasha Chernykh\"" ############## # ShellCheck # ############## ### Check “.sh” files: https://www.shellcheck.net/ ### shellcheck: if process.platform is "win32" command: '"batch/shellcheck.bat"' else command: 'bash bash/shellcheck.sh' ########### # bashate # ########### ### Check “.sh” files: https://docs.openstack.org/bashate/latest/readme ### bashate: if process.platform is "win32" command: '"batch/bashate.bat"' else command: 'bash bash/bashate.sh' ################# # LocalAppVeyor # ################# ### Validate “appveyor.yml” file: https://github.com/joaope/LocalAppVeyor [INFO] Get system environment variables: https://stackoverflow.com/a/14089064/5951529 https://gruntjs.com/creating-tasks#cli-options-environment ### localappveyor: command: "LocalAppVeyor lint --token <%= templates.tokens.api_key_appveyor %>"
5066
################# ## grunt-shell ## ################# ### [PURPOSE] Grunt plugin to run non-Grunt CLI commands. https://www.npmjs.com/package/grunt-shell ### module.exports = ############# ## Pelican ## ############# ### Build Pelican site: http://manos.im/blog/static-site-pelican-grunt-travis-github-pages/ https://github.com/sindresorhus/grunt-shell [REQUIRED] “pipenv run”, that scripts from pipenv virtual environment successful run; for example, “pipenv run pelican --help”, not “pelican --help”. https://robots.thoughtbot.com/how-to-manage-your-python-projects-with-pipenv “--fatal” — exit(1), if any warning or error [INFO] Disable “--debug” flag due to too detailed output: https://app.travis-ci.com/github/Kristinita/KristinitaPelican/jobs/560440148#L624-L2274 ### generate: command: 'pipenv run pelican content -s pelicanconf.py --fatal warnings' deploy: command: 'pipenv run pelican content -s publishconf.py --fatal warnings' ### [DEPRECATED] If “pipenv --update”, users have bug: https://github.com/pypa/pipenv/issues/1761 # Update Pip and Pipenv pipenvupdate: command: 'pipenv --update' ### ############ ## pipenv ## ############ ### [INFO] Update all Python Pipenv packages: https://stackoverflow.com/a/16269635/5951529 https://github.com/jgonggrijp/pip-review#pip-review ### pipenvupdateall: command: 'pipenv run pip-review --auto' ### [INFO] Clean unused packages: https://pipenv.pypa.io/en/latest/cli/#pipenv-clean [NOTE] So that “pipenv clean” doesn’t remove Python Markdown git extensions, you need install them in format: “pipenv install -e git+https://github.com/user/package_name.git#egg=package_name --dev”: https://pipenv.pypa.io/en/latest/basics/#a-note-about-vcs-dependencies https://github.com/pypa/pipenv/issues/1524 This is “editable” format: http://pipenv.readthedocs.io/en/latest/basics/#editable-dependencies-e-g-e [NOTE] Use correct “package_name” for “editable” packages, so that “pipenv clean” doesn’t delete them: https://github.com/pypa/pipenv/issues/1524#issuecomment-695213982 ### pipenvcleanunused: command: 'pipenv clean --verbose' ### Update packages versions to the newest in “Pipfile.lock”, that: 1. Another users have newest packages versions in their environment: 2. Fix CI errors as https://travis-ci.org/Kristinita/KristinitaPelican/jobs/368968779#L658-L677 https://docs.pipenv.org/basics/#example-pipenv-upgrade-workflow [INFO] Remove “--verbose” flag due to highly long details: https://app.travis-ci.com/github/Kristinita/KristinitaPelican/jobs/560271334#L736-L1277 ### pipenvupdatepipfilelock: command: 'pipenv update' ######### ## git ## ######### ### Shrink .git folder https://stackoverflow.com/a/2116892/5951529 Before: 568 MB — <https://i.imgur.com/aMvcfY1.png> After: 341 MB — <https://i.imgur.com/52cQ1AL.png> Remove reflog entries older, than 90 days: https://stackoverflow.com/a/3824970/5951529 ### gitreflog: command: 'git reflog expire --all' ### git gc https://stackoverflow.com/a/55738/5951529 Prune loose objects older than 2 weeks ago: https://www.kernel.org/pub/software/scm/git/docgit-gc.html ### gitgarbagecollector: command: 'git gc --aggressive' ############### ## HTML Tidy ## ############### ### Validate and fix HTML files: http://www.html-tidy.org/ Description: http://api.html-tidy.org/tidy/tidylib_api_next/index.html Options: http://api.html-tidy.org/tidy/quickref_next.html ### tidymodify: # [LEARN][GRUNT] Platform-specific tasks: # https://stackoverflow.com/a/23848087/5951529 # [REQUIRED] Single-line comments after a colon; otherwise the error “unexpected_newline”: # https://travis-ci.com/github/Kristinita/KristinitaPelican/jobs/488737915#L1945 if process.platform is "win32" # Need quotes, that command run: command: '"batch/tidy-modify.bat"' else ### [NOTE] Fix permission denied: https://stackoverflow.com/a/46818913/5951529 ### command: 'bash bash/tidy-modify.sh' tidyvalidate: if process.platform is "win32" command: '"batch/tidy-validate.bat"' else command: 'bash bash/tidy-validate.sh' ############ ## covgen ## ############ ### Generate Code of conduct for project: https://contributor-covenant.org/ https://www.npmjs.com/package/covgen [WARNING] Generate “CODE_OF_CONDUCT.md” for root folder: https://github.com/simonv3/covenant-generator/issues/15 [WARNING] Unobfuscated plain text e-mail: https://github.com/ContributorCovenant/contributor_covenant/issues/523 ### ######### ## npx ## ######### ### Tool for running npm CLI commands: https://www.npmjs.com/package/npx https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b https://stackoverflow.com/a/45164863/5951529 ### covgen: command: 'npx covgen kristinita$cock.li' ################## ## pip-licenses ## ################## ### Output licenses of all PyPI packages: https://pypi.org/project/pip-licenses/ Options: https://pypi.org/project/pip-licenses/#command-line-options ### piplicenses: command: 'pipenv run pip-licenses --with-authors --with-urls --with-description --format=markdown > python.md' ########################## ## commitlint Travis CI ## ########################## ### Commit linting for Travis CI: http://marionebl.github.io/commitlint/#/guides-ci-setup ### commitlint: command: 'commitlint-travis' ################### ## Travis Client ## ################### ### [ACTION] Lint “.travis.yml” file locally: https://stackoverflow.com/a/35607499/5951529 https://rubygems.org/gems/travis [INFO] “-x” argument — exit code 1, if any warning: https://github.com/travis-ci/travis.rb#lint ### travislint: command: 'travis lint -x' ########## # EClint # ########## ### Lint and fix files for EditorConfig rules: https://www.npmjs.com/package/eclint eclint doesn't search files and folders, that ignored in “.gitignore”: https://github.com/jedmao/eclint/issues/80#issuecomment-314936365 “eclint infer” — show current statistic: https://www.npmjs.com/package/eclint#infer [WARNING] Another eclint check and fix methods doesn't work: https://github.com/jedmao/eclint/issues/130 [WARNING] User can get different results for Windows and *NIX: https://github.com/jedmao/eclint/issues/129#event-1574600632 [BUG] 2 blank lines in end of file “CODE_OF_CONDUCT.md”, needs fix it: https://github.com/ContributorCovenant/contributor_covenant/issues/528 ### eclintfix: command: "npx eclint fix CODE_OF_CONDUCT.md && cd <%= templates.yamlconfig.OUTPUT_PATH %> \ && npx eclint fix && cd <%= templates.paths.cwd %>" eclintcheck: command: "cd <%= templates.yamlconfig.OUTPUT_PATH %> && npx eclint check && cd <%= templates.paths.cwd %>" ##################### # license-generator # ##################### ### Generate license: https://www.npmjs.com/package/license-generator ### licensegenerator: command: "npx license-generator install mit -n \"<NAME>\"" ############## # ShellCheck # ############## ### Check “.sh” files: https://www.shellcheck.net/ ### shellcheck: if process.platform is "win32" command: '"batch/shellcheck.bat"' else command: 'bash bash/shellcheck.sh' ########### # bashate # ########### ### Check “.sh” files: https://docs.openstack.org/bashate/latest/readme ### bashate: if process.platform is "win32" command: '"batch/bashate.bat"' else command: 'bash bash/bashate.sh' ################# # LocalAppVeyor # ################# ### Validate “appveyor.yml” file: https://github.com/joaope/LocalAppVeyor [INFO] Get system environment variables: https://stackoverflow.com/a/14089064/5951529 https://gruntjs.com/creating-tasks#cli-options-environment ### localappveyor: command: "LocalAppVeyor lint --token <%= templates.tokens.api_key_appveyor %>"
true
################# ## grunt-shell ## ################# ### [PURPOSE] Grunt plugin to run non-Grunt CLI commands. https://www.npmjs.com/package/grunt-shell ### module.exports = ############# ## Pelican ## ############# ### Build Pelican site: http://manos.im/blog/static-site-pelican-grunt-travis-github-pages/ https://github.com/sindresorhus/grunt-shell [REQUIRED] “pipenv run”, that scripts from pipenv virtual environment successful run; for example, “pipenv run pelican --help”, not “pelican --help”. https://robots.thoughtbot.com/how-to-manage-your-python-projects-with-pipenv “--fatal” — exit(1), if any warning or error [INFO] Disable “--debug” flag due to too detailed output: https://app.travis-ci.com/github/Kristinita/KristinitaPelican/jobs/560440148#L624-L2274 ### generate: command: 'pipenv run pelican content -s pelicanconf.py --fatal warnings' deploy: command: 'pipenv run pelican content -s publishconf.py --fatal warnings' ### [DEPRECATED] If “pipenv --update”, users have bug: https://github.com/pypa/pipenv/issues/1761 # Update Pip and Pipenv pipenvupdate: command: 'pipenv --update' ### ############ ## pipenv ## ############ ### [INFO] Update all Python Pipenv packages: https://stackoverflow.com/a/16269635/5951529 https://github.com/jgonggrijp/pip-review#pip-review ### pipenvupdateall: command: 'pipenv run pip-review --auto' ### [INFO] Clean unused packages: https://pipenv.pypa.io/en/latest/cli/#pipenv-clean [NOTE] So that “pipenv clean” doesn’t remove Python Markdown git extensions, you need install them in format: “pipenv install -e git+https://github.com/user/package_name.git#egg=package_name --dev”: https://pipenv.pypa.io/en/latest/basics/#a-note-about-vcs-dependencies https://github.com/pypa/pipenv/issues/1524 This is “editable” format: http://pipenv.readthedocs.io/en/latest/basics/#editable-dependencies-e-g-e [NOTE] Use correct “package_name” for “editable” packages, so that “pipenv clean” doesn’t delete them: https://github.com/pypa/pipenv/issues/1524#issuecomment-695213982 ### pipenvcleanunused: command: 'pipenv clean --verbose' ### Update packages versions to the newest in “Pipfile.lock”, that: 1. Another users have newest packages versions in their environment: 2. Fix CI errors as https://travis-ci.org/Kristinita/KristinitaPelican/jobs/368968779#L658-L677 https://docs.pipenv.org/basics/#example-pipenv-upgrade-workflow [INFO] Remove “--verbose” flag due to highly long details: https://app.travis-ci.com/github/Kristinita/KristinitaPelican/jobs/560271334#L736-L1277 ### pipenvupdatepipfilelock: command: 'pipenv update' ######### ## git ## ######### ### Shrink .git folder https://stackoverflow.com/a/2116892/5951529 Before: 568 MB — <https://i.imgur.com/aMvcfY1.png> After: 341 MB — <https://i.imgur.com/52cQ1AL.png> Remove reflog entries older, than 90 days: https://stackoverflow.com/a/3824970/5951529 ### gitreflog: command: 'git reflog expire --all' ### git gc https://stackoverflow.com/a/55738/5951529 Prune loose objects older than 2 weeks ago: https://www.kernel.org/pub/software/scm/git/docgit-gc.html ### gitgarbagecollector: command: 'git gc --aggressive' ############### ## HTML Tidy ## ############### ### Validate and fix HTML files: http://www.html-tidy.org/ Description: http://api.html-tidy.org/tidy/tidylib_api_next/index.html Options: http://api.html-tidy.org/tidy/quickref_next.html ### tidymodify: # [LEARN][GRUNT] Platform-specific tasks: # https://stackoverflow.com/a/23848087/5951529 # [REQUIRED] Single-line comments after a colon; otherwise the error “unexpected_newline”: # https://travis-ci.com/github/Kristinita/KristinitaPelican/jobs/488737915#L1945 if process.platform is "win32" # Need quotes, that command run: command: '"batch/tidy-modify.bat"' else ### [NOTE] Fix permission denied: https://stackoverflow.com/a/46818913/5951529 ### command: 'bash bash/tidy-modify.sh' tidyvalidate: if process.platform is "win32" command: '"batch/tidy-validate.bat"' else command: 'bash bash/tidy-validate.sh' ############ ## covgen ## ############ ### Generate Code of conduct for project: https://contributor-covenant.org/ https://www.npmjs.com/package/covgen [WARNING] Generate “CODE_OF_CONDUCT.md” for root folder: https://github.com/simonv3/covenant-generator/issues/15 [WARNING] Unobfuscated plain text e-mail: https://github.com/ContributorCovenant/contributor_covenant/issues/523 ### ######### ## npx ## ######### ### Tool for running npm CLI commands: https://www.npmjs.com/package/npx https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b https://stackoverflow.com/a/45164863/5951529 ### covgen: command: 'npx covgen kristinita$cock.li' ################## ## pip-licenses ## ################## ### Output licenses of all PyPI packages: https://pypi.org/project/pip-licenses/ Options: https://pypi.org/project/pip-licenses/#command-line-options ### piplicenses: command: 'pipenv run pip-licenses --with-authors --with-urls --with-description --format=markdown > python.md' ########################## ## commitlint Travis CI ## ########################## ### Commit linting for Travis CI: http://marionebl.github.io/commitlint/#/guides-ci-setup ### commitlint: command: 'commitlint-travis' ################### ## Travis Client ## ################### ### [ACTION] Lint “.travis.yml” file locally: https://stackoverflow.com/a/35607499/5951529 https://rubygems.org/gems/travis [INFO] “-x” argument — exit code 1, if any warning: https://github.com/travis-ci/travis.rb#lint ### travislint: command: 'travis lint -x' ########## # EClint # ########## ### Lint and fix files for EditorConfig rules: https://www.npmjs.com/package/eclint eclint doesn't search files and folders, that ignored in “.gitignore”: https://github.com/jedmao/eclint/issues/80#issuecomment-314936365 “eclint infer” — show current statistic: https://www.npmjs.com/package/eclint#infer [WARNING] Another eclint check and fix methods doesn't work: https://github.com/jedmao/eclint/issues/130 [WARNING] User can get different results for Windows and *NIX: https://github.com/jedmao/eclint/issues/129#event-1574600632 [BUG] 2 blank lines in end of file “CODE_OF_CONDUCT.md”, needs fix it: https://github.com/ContributorCovenant/contributor_covenant/issues/528 ### eclintfix: command: "npx eclint fix CODE_OF_CONDUCT.md && cd <%= templates.yamlconfig.OUTPUT_PATH %> \ && npx eclint fix && cd <%= templates.paths.cwd %>" eclintcheck: command: "cd <%= templates.yamlconfig.OUTPUT_PATH %> && npx eclint check && cd <%= templates.paths.cwd %>" ##################### # license-generator # ##################### ### Generate license: https://www.npmjs.com/package/license-generator ### licensegenerator: command: "npx license-generator install mit -n \"PI:NAME:<NAME>END_PI\"" ############## # ShellCheck # ############## ### Check “.sh” files: https://www.shellcheck.net/ ### shellcheck: if process.platform is "win32" command: '"batch/shellcheck.bat"' else command: 'bash bash/shellcheck.sh' ########### # bashate # ########### ### Check “.sh” files: https://docs.openstack.org/bashate/latest/readme ### bashate: if process.platform is "win32" command: '"batch/bashate.bat"' else command: 'bash bash/bashate.sh' ################# # LocalAppVeyor # ################# ### Validate “appveyor.yml” file: https://github.com/joaope/LocalAppVeyor [INFO] Get system environment variables: https://stackoverflow.com/a/14089064/5951529 https://gruntjs.com/creating-tasks#cli-options-environment ### localappveyor: command: "LocalAppVeyor lint --token <%= templates.tokens.api_key_appveyor %>"
[ { "context": " every prop that is not a required prop.\n# @author Vitor Balocco\n###\n'use strict'\n\n# -----------------------------", "end": 122, "score": 0.9997835159301758, "start": 109, "tag": "NAME", "value": "Vitor Balocco" }, { "context": "\n # ' return {'\n # ...
src/tests/rules/require-default-props.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Enforce a defaultProps definition for every prop that is not a required prop. # @author Vitor Balocco ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/require-default-props' {RuleTester} = require 'eslint' path = require 'path' ruleTester = new RuleTester parser: path.join __dirname, '../../..' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester.run 'require-default-props', rule, valid: [ # # stateless components code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string.isRequired,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' <div>{foo}{bar}</div>' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes.foo = PropTypes.string' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes.foo = PropTypes.string' 'MyStatelessComponent.defaultProps = {}' 'MyStatelessComponent.defaultProps.foo = "foo"' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo }) ->' ' return <div>{foo}</div>' 'MyStatelessComponent.propTypes = {}' 'MyStatelessComponent.propTypes.foo = PropTypes.string' 'MyStatelessComponent.defaultProps = {}' 'MyStatelessComponent.defaultProps.foo = "foo"' ].join '\n' , code: [ 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'defaults = {' ' foo: "foo"' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , code: [ 'defaults = {' ' foo: "foo"' '}' 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , # # createReactClass components code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string.isRequired,' ' bar: PropTypes.string.isRequired' ' }' '})' ].join '\n' , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' ' },' ' getDefaultProps: ->' ' return {' ' foo: "foo"' ' }' '})' ].join '\n' , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' foo: "foo",' ' bar: "bar"' ' }' '})' ].join '\n' , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' '})' ].join '\n' , # # ES6 class component code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string.isRequired,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.foo = "foo"' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.foo = "foo"' ].join '\n' , # # edge cases # not a react component code: [ 'NotAComponent = ({ foo, bar }) ->' 'NotAComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , code: [ 'class Greeting' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , # external references code: [ 'defaults = require("./defaults")' 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , code: [ 'defaults = {' ' foo: "foo"' '}' 'types = require("./propTypes")' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = require("./defaults").foo' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = require("./defaults").foo' 'MyStatelessComponent.defaultProps.bar = "bar"' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'import defaults from "./defaults"' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = defaults' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'import { foo } from "./defaults"' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = foo' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , # using spread operator code: [ 'component = rowsOfType(GuestlistEntry, (rowData, ownProps) => ({' ' ...rowData,' ' onPress: () => ownProps.onPress(rowData.id),' '}))' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' ...stuff,' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = {' ' ...defaults,' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' ...someProps,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' ...defaults,' ' bar: "bar"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' ...defaults,' ' bar: "bar"' '}' ].join '\n' , # , # # # # with Flow annotations # code: [ # 'type Props = {' # ' foo: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' bar: "bar"' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' bar: "bar"' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello(props: { foo: string }) ->' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = (props: { foo?: string }) => {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = (props: { foo: string }) => {' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = function(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = function(props: { foo: string }) ->' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'type Props2 = {' # ' foo: string,' # ' baz?: string' # '}' # 'Hello(props: Props | Props2) {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = {' # ' bar: "bar",' # ' baz: "baz"' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'import type Props from "fake"' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.name.firstname}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'type Props = any' # 'Hello = function({ foo }: Props) {' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'import type ImportedProps from "fake"' # 'type Props = ImportedProps' # 'Hello(props: Props) {' # ' return <div>Hello {props.name.firstname}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # # don't error when variable is not in scope # code: [ # 'import type { ImportedType } from "fake"' # 'type Props = ImportedType' # 'Hello(props: Props) {' # ' return <div>Hello {props.name.firstname}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # # make sure error is not thrown with multiple assignments # code: [ # 'import type ImportedProps from "fake"' # 'type NestedProps = ImportedProps' # 'type Props = NestedProps' # 'Hello(props: Props) {' # ' return <div>Hello {props.name.firstname}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # make sure defaultProps are correctly detected with quoted properties code: [ 'Hello = (props) ->' ' return <div>Hello {props.bar}</div>' 'Hello.propTypes = {' ' bar: PropTypes.string' '}' 'Hello.defaultProps = {' ' "bar": "bar"' '}' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends React.Component' ' @propTypes = {' ' foo: PropTypes.string.isRequired' ' }' ' render: ->' ' return <div>Hello {this.props.foo}</div>' ].join '\n' # parser: 'babel-eslint' options: [forbidDefaultForRequired: yes] # , # # test support for React PropTypes as Component's class generic # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component<HelloProps> {' # ' @defaultProps = {' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' @defaultProps = {' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'type HelloState = {' # ' dummyState: string' # '}' # 'class Hello extends Component<HelloProps, HelloState> {' # ' @defaultProps = {' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] # , # code: [ # 'type HelloProps = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' @defaultProps = {' # ' foo: "foo",' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] ] invalid: [ # # stateless components code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = forbidExtraProps({' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '})' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] settings: propWrapperFunctions: ['forbidExtraProps'] , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes = forbidExtraProps(propTypes)' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] settings: propWrapperFunctions: ['forbidExtraProps'] , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes.baz = React.propTypes.string' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 , message: 'propType "baz" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 1 ] , code: [ 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 2 column: 3 ] , code: [ 'defaults = {' ' foo: "foo"' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 3 ] , code: [ 'defaults = {' ' foo: "foo"' '}' 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 3 ] , # # createReactClass components code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' ' }' '})' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 5 column: 5 ] , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' foo: "foo"' ' }' '})' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 5 ] , # # ES6 class component code: [ 'class Greeting extends React.Component' ' render: ->' ' (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes.foo = PropTypes.string' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 9 column: 1 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string' '}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.foo = "foo"' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.bar = "bar"' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 1 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes = props' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'defaults = {' ' foo: "foo"' '}' 'Greeting.propTypes = props' 'Greeting.defaultProps = defaults' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 3 ] , # , # # # # ES6 classes with @getter methods # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' name: PropTypes.string' # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "name" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 7 # ] # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' foo: PropTypes.string,' # ' bar: PropTypes.string' # ' }' # ' }' # ' @get defaultProps: ->' # ' return {' # ' bar: "world"' # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 7 # ] # , # code: [ # 'props = {' # ' foo: PropTypes.string' # '}' # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return props' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'defaults = {' # ' bar: "world"' # '}' # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' foo: PropTypes.string,' # ' bar: PropTypes.string' # ' }' # ' }' # ' @get defaultProps: ->' # ' return defaults' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 7 # column: 7 # ] # # ES6 classes with property initializers code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' ' }' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 5 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' ' }' ' @defaultProps = {' ' foo: "foo"' ' }' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 5 ] , code: [ 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = props' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 2 column: 3 ] , code: [ 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'defaults = {' ' foo: "foo"' '}' 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = props' ' @defaultProps = defaults' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 3 column: 3 ] , # # edge cases code: [ 'Greetings = {}' 'Greetings.Hello = class extends React.Component' ' render : ->' ' return <div>Hello {this.props.foo}</div>' 'Greetings.Hello.propTypes = {' ' foo: PropTypes.string' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 3 ] , code: [ 'Greetings = ({ foo = "foo" }) =>' ' return <div>Hello {this.props.foo}</div>' 'Greetings.propTypes = {' ' foo: PropTypes.string' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] , # component with no declared props followed by a failing component code: [ 'ComponentWithNoProps = ({ bar = "bar" }) =>' ' return <div>Hello {this.props.foo}</div>' 'Greetings = ({ foo = "foo" }) =>' ' return <div>Hello {this.props.foo}</div>' 'Greetings.propTypes = {' ' foo: PropTypes.string' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 3 ] , # , # # # # with Flow annotations # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' @defaultProps: { foo: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 5 # , # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string' # ' }' # ' @defaultProps: { foo: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 5 # ] # , # code: [ # 'type Props = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' @defaultProps: { foo: string, bar: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string,' # ' bar?: string' # ' }' # ' @defaultProps: { foo: string, bar: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'Hello(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # ] # , # code: [ # 'Hello({ foo = "foo" }: { foo?: string }) ->' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 35 # ] # , # code: [ # 'Hello(props: { foo?: string, bar?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 39 # ] # , # code: [ # 'Hello(props: { foo?: string, bar?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # , # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 39 # ] # , # code: [ # 'type Props = {' # ' foo?: string' # '}' # 'Hello(props: Props) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'Hello = (props: { foo?: string }) => {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # ] # , # code: [ # 'Hello = (props: { foo?: string, bar?: string }) => {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 39 # ] # , # code: [ # 'Hello = function(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 33 # ] # , # code: [ # 'Hello = function(props: { foo?: string, bar?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 47 # ] # , # code: [ # 'type Props = {' # ' foo?: string' # '}' # 'Hello(props: Props) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo?: string,' # ' bar?: string' # '}' # 'Hello(props: Props) {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # # UnionType # code: [ # 'Hello(props: { one?: string } | { two?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "one" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # , # message: # 'propType "two" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 44 # ] # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'type Props2 = {' # ' foo: string,' # ' baz?: string' # '}' # 'Hello(props: Props | Props2) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # , # message: # 'propType "baz" is not required, but has no corresponding defaultProp declaration.' # line: 7 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'type Props2 = {' # ' foo: string,' # ' baz?: string' # '}' # 'Hello(props: Props | Props2) {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = {' # ' bar: "bar"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "baz" is not required, but has no corresponding defaultProp declaration.' # line: 7 # column: 3 # ] # , # code: [ # 'type HelloProps = {' # ' two?: string,' # ' three: string' # '}' # 'Hello(props: { one?: string } | HelloProps) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "two" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # , # message: # 'propType "one" is not required, but has no corresponding defaultProp declaration.' # line: 5 # column: 25 # ] # , # code: [ # 'type HelloProps = {' # ' two?: string,' # ' three: string' # '}' # 'Hello(props: ExternalProps | HelloProps) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "two" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] code: [ 'class Hello extends React.Component' ' @propTypes = {' ' foo: PropTypes.string' ' }' ' render: ->' ' return <div>Hello {this.props.foo}</div>' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 3 column: 5 ] , # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' name: PropTypes.string' # ' }' # ' }' # ' @defaultProps: ->' # ' return {' # " name: 'John'" # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "name" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # " 'first-name': PropTypes.string" # ' }' # ' }' # ' render: ->' # " return <div>Hello {this.props['first-name']}</div>" # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "first-name" is not required, but has no corresponding defaultProp declaration.' # ] code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello {this.props.foo}</div>' 'Hello.propTypes = {' ' foo: PropTypes.string.isRequired' '}' 'Hello.defaultProps = {' " foo: 'bar'" '}' ].join '\n' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] , code: [ 'Hello = (props) ->' ' return <div>Hello {props.foo}</div>' 'Hello.propTypes = {' ' foo: PropTypes.string.isRequired' '}' 'Hello.defaultProps = {' " foo: 'bar'" '}' ].join '\n' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] , code: [ 'Hello = (props) =>' ' return <div>Hello {props.foo}</div>' 'Hello.propTypes = {' ' foo: PropTypes.string.isRequired' '}' 'Hello.defaultProps = {' " foo: 'bar'" '}' ].join '\n' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] , code: [ 'class Hello extends React.Component' ' @propTypes = {' ' foo: PropTypes.string.isRequired' ' }' ' @defaultProps = {' " foo: 'bar'" ' }' ' render: ->' ' return <div>Hello {this.props.foo}</div>' ].join '\n' # parser: 'babel-eslint' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes : ->' # ' return {' # ' foo: PropTypes.string.isRequired' # ' }' # ' }' # ' @get defaultProps: ->' # ' return {' # " foo: 'bar'" # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # options: [forbidDefaultForRequired: yes] # errors: [ # message: # 'propType "foo" is required and should not have a defaultProp declaration.' # ] # , # # test support for React PropTypes as Component's class generic # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component<HelloProps> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'type HelloState = {' # ' dummyState: string' # '}' # 'class Hello extends Component<HelloProps, HelloState> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'type HelloProps = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # , # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] ]
71137
###* # @fileoverview Enforce a defaultProps definition for every prop that is not a required prop. # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/require-default-props' {RuleTester} = require 'eslint' path = require 'path' ruleTester = new RuleTester parser: path.join __dirname, '../../..' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester.run 'require-default-props', rule, valid: [ # # stateless components code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string.isRequired,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' <div>{foo}{bar}</div>' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes.foo = PropTypes.string' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes.foo = PropTypes.string' 'MyStatelessComponent.defaultProps = {}' 'MyStatelessComponent.defaultProps.foo = "foo"' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo }) ->' ' return <div>{foo}</div>' 'MyStatelessComponent.propTypes = {}' 'MyStatelessComponent.propTypes.foo = PropTypes.string' 'MyStatelessComponent.defaultProps = {}' 'MyStatelessComponent.defaultProps.foo = "foo"' ].join '\n' , code: [ 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'defaults = {' ' foo: "foo"' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , code: [ 'defaults = {' ' foo: "foo"' '}' 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , # # createReactClass components code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string.isRequired,' ' bar: PropTypes.string.isRequired' ' }' '})' ].join '\n' , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' ' },' ' getDefaultProps: ->' ' return {' ' foo: "foo"' ' }' '})' ].join '\n' , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' foo: "foo",' ' bar: "bar"' ' }' '})' ].join '\n' , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' '})' ].join '\n' , # # ES6 class component code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string.isRequired,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.foo = "foo"' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.foo = "foo"' ].join '\n' , # # edge cases # not a react component code: [ 'NotAComponent = ({ foo, bar }) ->' 'NotAComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , code: [ 'class Greeting' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , # external references code: [ 'defaults = require("./defaults")' 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , code: [ 'defaults = {' ' foo: "foo"' '}' 'types = require("./propTypes")' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = require("./defaults").foo' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = require("./defaults").foo' 'MyStatelessComponent.defaultProps.bar = "bar"' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'import defaults from "./defaults"' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = defaults' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'import { foo } from "./defaults"' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = foo' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , # using spread operator code: [ 'component = rowsOfType(GuestlistEntry, (rowData, ownProps) => ({' ' ...rowData,' ' onPress: () => ownProps.onPress(rowData.id),' '}))' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' ...stuff,' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = {' ' ...defaults,' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' ...someProps,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' ...defaults,' ' bar: "bar"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' ...defaults,' ' bar: "bar"' '}' ].join '\n' , # , # # # # with Flow annotations # code: [ # 'type Props = {' # ' foo: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' bar: "bar"' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' bar: "bar"' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello(props: { foo: string }) ->' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = (props: { foo?: string }) => {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = (props: { foo: string }) => {' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = function(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = function(props: { foo: string }) ->' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'type Props2 = {' # ' foo: string,' # ' baz?: string' # '}' # 'Hello(props: Props | Props2) {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = {' # ' bar: "bar",' # ' baz: "baz"' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'import type Props from "fake"' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.name.firstname}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'type Props = any' # 'Hello = function({ foo }: Props) {' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'import type ImportedProps from "fake"' # 'type Props = ImportedProps' # 'Hello(props: Props) {' # ' return <div>Hello {props.name.firstname}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # # don't error when variable is not in scope # code: [ # 'import type { ImportedType } from "fake"' # 'type Props = ImportedType' # 'Hello(props: Props) {' # ' return <div>Hello {props.name.firstname}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # # make sure error is not thrown with multiple assignments # code: [ # 'import type ImportedProps from "fake"' # 'type NestedProps = ImportedProps' # 'type Props = NestedProps' # 'Hello(props: Props) {' # ' return <div>Hello {props.name.firstname}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # make sure defaultProps are correctly detected with quoted properties code: [ 'Hello = (props) ->' ' return <div>Hello {props.bar}</div>' 'Hello.propTypes = {' ' bar: PropTypes.string' '}' 'Hello.defaultProps = {' ' "bar": "bar"' '}' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends React.Component' ' @propTypes = {' ' foo: PropTypes.string.isRequired' ' }' ' render: ->' ' return <div>Hello {this.props.foo}</div>' ].join '\n' # parser: 'babel-eslint' options: [forbidDefaultForRequired: yes] # , # # test support for React PropTypes as Component's class generic # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component<HelloProps> {' # ' @defaultProps = {' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' @defaultProps = {' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'type HelloState = {' # ' dummyState: string' # '}' # 'class Hello extends Component<HelloProps, HelloState> {' # ' @defaultProps = {' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] # , # code: [ # 'type HelloProps = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' @defaultProps = {' # ' foo: "foo",' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] ] invalid: [ # # stateless components code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = forbidExtraProps({' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '})' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] settings: propWrapperFunctions: ['forbidExtraProps'] , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes = forbidExtraProps(propTypes)' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] settings: propWrapperFunctions: ['forbidExtraProps'] , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes.baz = React.propTypes.string' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 , message: 'propType "baz" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 1 ] , code: [ 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 2 column: 3 ] , code: [ 'defaults = {' ' foo: "foo"' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 3 ] , code: [ 'defaults = {' ' foo: "foo"' '}' 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 3 ] , # # createReactClass components code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' ' }' '})' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 5 column: 5 ] , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' foo: "foo"' ' }' '})' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 5 ] , # # ES6 class component code: [ 'class Greeting extends React.Component' ' render: ->' ' (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes.foo = PropTypes.string' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 9 column: 1 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string' '}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.foo = "foo"' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.bar = "bar"' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 1 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes = props' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'defaults = {' ' foo: "foo"' '}' 'Greeting.propTypes = props' 'Greeting.defaultProps = defaults' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 3 ] , # , # # # # ES6 classes with @getter methods # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' name: PropTypes.string' # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "name" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 7 # ] # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' foo: PropTypes.string,' # ' bar: PropTypes.string' # ' }' # ' }' # ' @get defaultProps: ->' # ' return {' # ' bar: "world"' # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 7 # ] # , # code: [ # 'props = {' # ' foo: PropTypes.string' # '}' # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return props' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'defaults = {' # ' bar: "world"' # '}' # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' foo: PropTypes.string,' # ' bar: PropTypes.string' # ' }' # ' }' # ' @get defaultProps: ->' # ' return defaults' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 7 # column: 7 # ] # # ES6 classes with property initializers code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' ' }' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 5 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' ' }' ' @defaultProps = {' ' foo: "foo"' ' }' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 5 ] , code: [ 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = props' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 2 column: 3 ] , code: [ 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'defaults = {' ' foo: "foo"' '}' 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = props' ' @defaultProps = defaults' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 3 column: 3 ] , # # edge cases code: [ 'Greetings = {}' 'Greetings.Hello = class extends React.Component' ' render : ->' ' return <div>Hello {this.props.foo}</div>' 'Greetings.Hello.propTypes = {' ' foo: PropTypes.string' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 3 ] , code: [ 'Greetings = ({ foo = "foo" }) =>' ' return <div>Hello {this.props.foo}</div>' 'Greetings.propTypes = {' ' foo: PropTypes.string' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] , # component with no declared props followed by a failing component code: [ 'ComponentWithNoProps = ({ bar = "bar" }) =>' ' return <div>Hello {this.props.foo}</div>' 'Greetings = ({ foo = "foo" }) =>' ' return <div>Hello {this.props.foo}</div>' 'Greetings.propTypes = {' ' foo: PropTypes.string' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 3 ] , # , # # # # with Flow annotations # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' @defaultProps: { foo: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 5 # , # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string' # ' }' # ' @defaultProps: { foo: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 5 # ] # , # code: [ # 'type Props = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' @defaultProps: { foo: string, bar: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string,' # ' bar?: string' # ' }' # ' @defaultProps: { foo: string, bar: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'Hello(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # ] # , # code: [ # 'Hello({ foo = "foo" }: { foo?: string }) ->' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 35 # ] # , # code: [ # 'Hello(props: { foo?: string, bar?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 39 # ] # , # code: [ # 'Hello(props: { foo?: string, bar?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # , # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 39 # ] # , # code: [ # 'type Props = {' # ' foo?: string' # '}' # 'Hello(props: Props) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'Hello = (props: { foo?: string }) => {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # ] # , # code: [ # 'Hello = (props: { foo?: string, bar?: string }) => {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 39 # ] # , # code: [ # 'Hello = function(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 33 # ] # , # code: [ # 'Hello = function(props: { foo?: string, bar?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 47 # ] # , # code: [ # 'type Props = {' # ' foo?: string' # '}' # 'Hello(props: Props) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo?: string,' # ' bar?: string' # '}' # 'Hello(props: Props) {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # # UnionType # code: [ # 'Hello(props: { one?: string } | { two?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "one" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # , # message: # 'propType "two" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 44 # ] # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'type Props2 = {' # ' foo: string,' # ' baz?: string' # '}' # 'Hello(props: Props | Props2) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # , # message: # 'propType "baz" is not required, but has no corresponding defaultProp declaration.' # line: 7 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'type Props2 = {' # ' foo: string,' # ' baz?: string' # '}' # 'Hello(props: Props | Props2) {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = {' # ' bar: "bar"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "baz" is not required, but has no corresponding defaultProp declaration.' # line: 7 # column: 3 # ] # , # code: [ # 'type HelloProps = {' # ' two?: string,' # ' three: string' # '}' # 'Hello(props: { one?: string } | HelloProps) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "two" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # , # message: # 'propType "one" is not required, but has no corresponding defaultProp declaration.' # line: 5 # column: 25 # ] # , # code: [ # 'type HelloProps = {' # ' two?: string,' # ' three: string' # '}' # 'Hello(props: ExternalProps | HelloProps) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "two" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] code: [ 'class Hello extends React.Component' ' @propTypes = {' ' foo: PropTypes.string' ' }' ' render: ->' ' return <div>Hello {this.props.foo}</div>' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 3 column: 5 ] , # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' name: PropTypes.string' # ' }' # ' }' # ' @defaultProps: ->' # ' return {' # " name: '<NAME>'" # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "name" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # " 'first-name': PropTypes.string" # ' }' # ' }' # ' render: ->' # " return <div>Hello {this.props['first-name']}</div>" # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "first-name" is not required, but has no corresponding defaultProp declaration.' # ] code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello {this.props.foo}</div>' 'Hello.propTypes = {' ' foo: PropTypes.string.isRequired' '}' 'Hello.defaultProps = {' " foo: 'bar'" '}' ].join '\n' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] , code: [ 'Hello = (props) ->' ' return <div>Hello {props.foo}</div>' 'Hello.propTypes = {' ' foo: PropTypes.string.isRequired' '}' 'Hello.defaultProps = {' " foo: 'bar'" '}' ].join '\n' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] , code: [ 'Hello = (props) =>' ' return <div>Hello {props.foo}</div>' 'Hello.propTypes = {' ' foo: PropTypes.string.isRequired' '}' 'Hello.defaultProps = {' " foo: 'bar'" '}' ].join '\n' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] , code: [ 'class Hello extends React.Component' ' @propTypes = {' ' foo: PropTypes.string.isRequired' ' }' ' @defaultProps = {' " foo: 'bar'" ' }' ' render: ->' ' return <div>Hello {this.props.foo}</div>' ].join '\n' # parser: 'babel-eslint' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes : ->' # ' return {' # ' foo: PropTypes.string.isRequired' # ' }' # ' }' # ' @get defaultProps: ->' # ' return {' # " foo: 'bar'" # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # options: [forbidDefaultForRequired: yes] # errors: [ # message: # 'propType "foo" is required and should not have a defaultProp declaration.' # ] # , # # test support for React PropTypes as Component's class generic # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component<HelloProps> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'type HelloState = {' # ' dummyState: string' # '}' # 'class Hello extends Component<HelloProps, HelloState> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'type HelloProps = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # , # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] ]
true
###* # @fileoverview Enforce a defaultProps definition for every prop that is not a required prop. # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/require-default-props' {RuleTester} = require 'eslint' path = require 'path' ruleTester = new RuleTester parser: path.join __dirname, '../../..' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester.run 'require-default-props', rule, valid: [ # # stateless components code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string.isRequired,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' <div>{foo}{bar}</div>' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes.foo = PropTypes.string' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes.foo = PropTypes.string' 'MyStatelessComponent.defaultProps = {}' 'MyStatelessComponent.defaultProps.foo = "foo"' ].join '\n' , code: [ 'MyStatelessComponent = ({ foo }) ->' ' return <div>{foo}</div>' 'MyStatelessComponent.propTypes = {}' 'MyStatelessComponent.propTypes.foo = PropTypes.string' 'MyStatelessComponent.defaultProps = {}' 'MyStatelessComponent.defaultProps.foo = "foo"' ].join '\n' , code: [ 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'defaults = {' ' foo: "foo"' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , code: [ 'defaults = {' ' foo: "foo"' '}' 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , # # createReactClass components code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string.isRequired,' ' bar: PropTypes.string.isRequired' ' }' '})' ].join '\n' , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' ' },' ' getDefaultProps: ->' ' return {' ' foo: "foo"' ' }' '})' ].join '\n' , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' foo: "foo",' ' bar: "bar"' ' }' '})' ].join '\n' , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' '})' ].join '\n' , # # ES6 class component code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string.isRequired,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.foo = "foo"' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.foo = "foo"' ].join '\n' , # # edge cases # not a react component code: [ 'NotAComponent = ({ foo, bar }) ->' 'NotAComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , code: [ 'class Greeting' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , # external references code: [ 'defaults = require("./defaults")' 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , code: [ 'defaults = {' ' foo: "foo"' '}' 'types = require("./propTypes")' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = require("./defaults").foo' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = require("./defaults").foo' 'MyStatelessComponent.defaultProps.bar = "bar"' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'import defaults from "./defaults"' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = defaults' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'import { foo } from "./defaults"' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = foo' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , # using spread operator code: [ 'component = rowsOfType(GuestlistEntry, (rowData, ownProps) => ({' ' ...rowData,' ' onPress: () => ownProps.onPress(rowData.id),' '}))' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' ...stuff,' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = {' ' foo: "foo"' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = {' ' ...defaults,' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' ...someProps,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' ...defaults,' ' bar: "bar"' '}' ].join '\n' , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.defaultProps = {' ' ...defaults,' ' bar: "bar"' '}' ].join '\n' , # , # # # # with Flow annotations # code: [ # 'type Props = {' # ' foo: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' bar: "bar"' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' bar: "bar"' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello(props: { foo: string }) ->' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = (props: { foo?: string }) => {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = (props: { foo: string }) => {' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = function(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'Hello = function(props: { foo: string }) ->' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'type Props2 = {' # ' foo: string,' # ' baz?: string' # '}' # 'Hello(props: Props | Props2) {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = {' # ' bar: "bar",' # ' baz: "baz"' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'import type Props from "fake"' # 'class Hello extends React.Component' # ' props: Props' # ' render : ->' # ' return <div>Hello {this.props.name.firstname}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'type Props = any' # 'Hello = function({ foo }: Props) {' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # code: [ # 'import type ImportedProps from "fake"' # 'type Props = ImportedProps' # 'Hello(props: Props) {' # ' return <div>Hello {props.name.firstname}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # # don't error when variable is not in scope # code: [ # 'import type { ImportedType } from "fake"' # 'type Props = ImportedType' # 'Hello(props: Props) {' # ' return <div>Hello {props.name.firstname}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # , # # make sure error is not thrown with multiple assignments # code: [ # 'import type ImportedProps from "fake"' # 'type NestedProps = ImportedProps' # 'type Props = NestedProps' # 'Hello(props: Props) {' # ' return <div>Hello {props.name.firstname}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # make sure defaultProps are correctly detected with quoted properties code: [ 'Hello = (props) ->' ' return <div>Hello {props.bar}</div>' 'Hello.propTypes = {' ' bar: PropTypes.string' '}' 'Hello.defaultProps = {' ' "bar": "bar"' '}' ].join '\n' , # parser: 'babel-eslint' code: [ 'class Hello extends React.Component' ' @propTypes = {' ' foo: PropTypes.string.isRequired' ' }' ' render: ->' ' return <div>Hello {this.props.foo}</div>' ].join '\n' # parser: 'babel-eslint' options: [forbidDefaultForRequired: yes] # , # # test support for React PropTypes as Component's class generic # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component<HelloProps> {' # ' @defaultProps = {' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' @defaultProps = {' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'type HelloState = {' # ' dummyState: string' # '}' # 'class Hello extends Component<HelloProps, HelloState> {' # ' @defaultProps = {' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] # , # code: [ # 'type HelloProps = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' @defaultProps = {' # ' foo: "foo",' # ' bar: "bar"' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # options: [forbidDefaultForRequired: yes] ] invalid: [ # # stateless components code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = forbidExtraProps({' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '})' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] settings: propWrapperFunctions: ['forbidExtraProps'] , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes = forbidExtraProps(propTypes)' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] settings: propWrapperFunctions: ['forbidExtraProps'] , code: [ 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent.propTypes.baz = React.propTypes.string' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 , message: 'propType "baz" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 1 ] , code: [ 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 2 column: 3 ] , code: [ 'defaults = {' ' foo: "foo"' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 3 ] , code: [ 'defaults = {' ' foo: "foo"' '}' 'types = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'MyStatelessComponent = ({ foo, bar }) ->' ' return <div>{foo}{bar}</div>' 'MyStatelessComponent.propTypes = types' 'MyStatelessComponent.defaultProps = defaults' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 3 ] , # # createReactClass components code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' ' }' '})' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 5 column: 5 ] , code: [ 'Greeting = createReactClass({' ' render: ->' ' return <div>Hello {this.props.foo} {this.props.bar}</div>' ' propTypes: {' ' foo: PropTypes.string,' ' bar: PropTypes.string' ' },' ' getDefaultProps: ->' ' return {' ' foo: "foo"' ' }' '})' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 5 ] , # # ES6 class component code: [ 'class Greeting extends React.Component' ' render: ->' ' (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'Greeting.defaultProps = {' ' foo: "foo"' '}' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes.foo = PropTypes.string' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 9 column: 1 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {' ' bar: PropTypes.string' '}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.foo = "foo"' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'Greeting.propTypes = {}' 'Greeting.propTypes.foo = PropTypes.string' 'Greeting.defaultProps = {}' 'Greeting.defaultProps.bar = "bar"' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 1 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'Greeting.propTypes = props' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 3 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'defaults = {' ' foo: "foo"' '}' 'Greeting.propTypes = props' 'Greeting.defaultProps = defaults' ].join '\n' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 3 ] , # , # # # # ES6 classes with @getter methods # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' name: PropTypes.string' # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "name" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 7 # ] # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' foo: PropTypes.string,' # ' bar: PropTypes.string' # ' }' # ' }' # ' @get defaultProps: ->' # ' return {' # ' bar: "world"' # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 7 # ] # , # code: [ # 'props = {' # ' foo: PropTypes.string' # '}' # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return props' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'defaults = {' # ' bar: "world"' # '}' # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' foo: PropTypes.string,' # ' bar: PropTypes.string' # ' }' # ' }' # ' @get defaultProps: ->' # ' return defaults' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 7 # column: 7 # ] # # ES6 classes with property initializers code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' ' }' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 7 column: 5 ] , code: [ 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' ' }' ' @defaultProps = {' ' foo: "foo"' ' }' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 8 column: 5 ] , code: [ 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string.isRequired' '}' 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = props' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 2 column: 3 ] , code: [ 'props = {' ' foo: PropTypes.string,' ' bar: PropTypes.string' '}' 'defaults = {' ' foo: "foo"' '}' 'class Greeting extends React.Component' ' render: ->' ' return (' ' <h1>Hello, {this.props.foo} {this.props.bar}</h1>' ' )' ' @propTypes = props' ' @defaultProps = defaults' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "bar" is not required, but has no corresponding defaultProp declaration.' line: 3 column: 3 ] , # # edge cases code: [ 'Greetings = {}' 'Greetings.Hello = class extends React.Component' ' render : ->' ' return <div>Hello {this.props.foo}</div>' 'Greetings.Hello.propTypes = {' ' foo: PropTypes.string' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 3 ] , code: [ 'Greetings = ({ foo = "foo" }) =>' ' return <div>Hello {this.props.foo}</div>' 'Greetings.propTypes = {' ' foo: PropTypes.string' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 4 column: 3 ] , # component with no declared props followed by a failing component code: [ 'ComponentWithNoProps = ({ bar = "bar" }) =>' ' return <div>Hello {this.props.foo}</div>' 'Greetings = ({ foo = "foo" }) =>' ' return <div>Hello {this.props.foo}</div>' 'Greetings.propTypes = {' ' foo: PropTypes.string' '}' ].join '\n' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 6 column: 3 ] , # , # # # # with Flow annotations # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' @defaultProps: { foo: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string,' # ' bar?: string' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 5 # , # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string' # ' }' # ' @defaultProps: { foo: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 5 # ] # , # code: [ # 'type Props = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component' # ' props: Props' # ' @defaultProps: { foo: string, bar: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # code: [ # 'class Hello extends React.Component' # ' props: {' # ' foo?: string,' # ' bar?: string' # ' }' # ' @defaultProps: { foo: string, bar: string }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # 'Hello.defaultProps = {' # ' foo: "foo"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 4 # column: 5 # ] # , # code: [ # 'Hello(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # ] # , # code: [ # 'Hello({ foo = "foo" }: { foo?: string }) ->' # ' return <div>Hello {foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 35 # ] # , # code: [ # 'Hello(props: { foo?: string, bar?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 39 # ] # , # code: [ # 'Hello(props: { foo?: string, bar?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # , # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 39 # ] # , # code: [ # 'type Props = {' # ' foo?: string' # '}' # 'Hello(props: Props) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'Hello = (props: { foo?: string }) => {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # ] # , # code: [ # 'Hello = (props: { foo?: string, bar?: string }) => {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 39 # ] # , # code: [ # 'Hello = function(props: { foo?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 33 # ] # , # code: [ # 'Hello = function(props: { foo?: string, bar?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 47 # ] # , # code: [ # 'type Props = {' # ' foo?: string' # '}' # 'Hello(props: Props) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo?: string,' # ' bar?: string' # '}' # 'Hello(props: Props) {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = { foo: "foo" }' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # ] # , # # UnionType # code: [ # 'Hello(props: { one?: string } | { two?: string }) ->' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "one" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 25 # , # message: # 'propType "two" is not required, but has no corresponding defaultProp declaration.' # line: 1 # column: 44 # ] # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'type Props2 = {' # ' foo: string,' # ' baz?: string' # '}' # 'Hello(props: Props | Props2) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # line: 3 # column: 3 # , # message: # 'propType "baz" is not required, but has no corresponding defaultProp declaration.' # line: 7 # column: 3 # ] # , # code: [ # 'type Props = {' # ' foo: string,' # ' bar?: string' # '}' # 'type Props2 = {' # ' foo: string,' # ' baz?: string' # '}' # 'Hello(props: Props | Props2) {' # ' return <div>Hello {props.foo}</div>' # '}' # 'Hello.defaultProps = {' # ' bar: "bar"' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "baz" is not required, but has no corresponding defaultProp declaration.' # line: 7 # column: 3 # ] # , # code: [ # 'type HelloProps = {' # ' two?: string,' # ' three: string' # '}' # 'Hello(props: { one?: string } | HelloProps) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "two" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # , # message: # 'propType "one" is not required, but has no corresponding defaultProp declaration.' # line: 5 # column: 25 # ] # , # code: [ # 'type HelloProps = {' # ' two?: string,' # ' three: string' # '}' # 'Hello(props: ExternalProps | HelloProps) {' # ' return <div>Hello {props.foo}</div>' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "two" is not required, but has no corresponding defaultProp declaration.' # line: 2 # column: 3 # ] code: [ 'class Hello extends React.Component' ' @propTypes = {' ' foo: PropTypes.string' ' }' ' render: ->' ' return <div>Hello {this.props.foo}</div>' ].join '\n' # parser: 'babel-eslint' errors: [ message: 'propType "foo" is not required, but has no corresponding defaultProp declaration.' line: 3 column: 5 ] , # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # ' name: PropTypes.string' # ' }' # ' }' # ' @defaultProps: ->' # ' return {' # " name: 'PI:NAME:<NAME>END_PI'" # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.name}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "name" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes: ->' # ' return {' # " 'first-name': PropTypes.string" # ' }' # ' }' # ' render: ->' # " return <div>Hello {this.props['first-name']}</div>" # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "first-name" is not required, but has no corresponding defaultProp declaration.' # ] code: [ 'class Hello extends React.Component' ' render: ->' ' return <div>Hello {this.props.foo}</div>' 'Hello.propTypes = {' ' foo: PropTypes.string.isRequired' '}' 'Hello.defaultProps = {' " foo: 'bar'" '}' ].join '\n' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] , code: [ 'Hello = (props) ->' ' return <div>Hello {props.foo}</div>' 'Hello.propTypes = {' ' foo: PropTypes.string.isRequired' '}' 'Hello.defaultProps = {' " foo: 'bar'" '}' ].join '\n' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] , code: [ 'Hello = (props) =>' ' return <div>Hello {props.foo}</div>' 'Hello.propTypes = {' ' foo: PropTypes.string.isRequired' '}' 'Hello.defaultProps = {' " foo: 'bar'" '}' ].join '\n' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] , code: [ 'class Hello extends React.Component' ' @propTypes = {' ' foo: PropTypes.string.isRequired' ' }' ' @defaultProps = {' " foo: 'bar'" ' }' ' render: ->' ' return <div>Hello {this.props.foo}</div>' ].join '\n' # parser: 'babel-eslint' options: [forbidDefaultForRequired: yes] errors: [ message: 'propType "foo" is required and should not have a defaultProp declaration.' ] # , # code: [ # 'class Hello extends React.Component' # ' @get propTypes : ->' # ' return {' # ' foo: PropTypes.string.isRequired' # ' }' # ' }' # ' @get defaultProps: ->' # ' return {' # " foo: 'bar'" # ' }' # ' }' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # options: [forbidDefaultForRequired: yes] # errors: [ # message: # 'propType "foo" is required and should not have a defaultProp declaration.' # ] # , # # test support for React PropTypes as Component's class generic # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends React.Component<HelloProps> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'type HelloProps = {' # ' foo: string,' # ' bar?: string' # '}' # 'type HelloState = {' # ' dummyState: string' # '}' # 'class Hello extends Component<HelloProps, HelloState> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] # , # code: [ # 'type HelloProps = {' # ' foo?: string,' # ' bar?: string' # '}' # 'class Hello extends Component<HelloProps> {' # ' render: ->' # ' return <div>Hello {this.props.foo}</div>' # ' }' # '}' # ].join '\n' # parser: 'babel-eslint' # errors: [ # message: # 'propType "foo" is not required, but has no corresponding defaultProp declaration.' # , # message: # 'propType "bar" is not required, but has no corresponding defaultProp declaration.' # ] ]
[ { "context": "ccess.show\n\t\t\temail:\t\t\t\t\t\temail\n\t\t\tpassword: \t\t\t\t\tpassword\n\n\n\terror: (notice = '') ->\n\n\t\tmark = moment().uni", "end": 1762, "score": 0.9991740584373474, "start": 1754, "tag": "PASSWORD", "value": "password" } ]
app/views/modal/registrationView.coffee
standart-n/sn-oz-client
0
require('moment') Modal = require('Modal') Registration = require('Registration') RegistrationTextSuccess = require('RegistrationTextSuccess') module.exports = Modal.extend el: '#registration' url: 'view/registration/registration.html' initialize: () -> this.model = new Registration() this.render() this.$firstname = this.$el.find('.registration-firstname') this.$lastname = this.$el.find('.registration-lastname') this.$email = this.$el.find('.registration-email') this.$company = this.$el.find('.registration-company') this.$modal = this.$el.find('.modal') this.$close = this.$el.find('.modal-header').find('.close') this.$form = this.$el.find('.registration-form') this.$button = this.$el.find('button') this.textSuccess = new RegistrationTextSuccess() this.$alertSuccess = this.$el.find('.alert-success') this.$alertError = this.$el.find('.alert-error') if window.user? window.user.on 'change:signin', () => if window.user.get('signin') is false this.model.reset() afterShow: () -> this.$alertSuccess.hide() this.$alertError.hide() this.textSuccess.hide() this.$form.show() this.$firstname.focus() data: () -> this.model.toJSON() checking: () -> setTimeout () => this.$button.button 'reset' , 400 if this.model.get('success') is true this.success this.model.get('email'), this.model.get('password') else this.error '<b>Ошибка!</b> ' + this.model.get('notice') + '.' this.model.reset() success: (email, password) -> this.$form.hide() this.$alertSuccess.show() this.$alertError.hide() this.textSuccess.show email: email password: password error: (notice = '') -> mark = moment().unix() this.$alertError.show().html notice this.$alertError.data 'mark', mark this.$alertSuccess.hide() this.textSuccess.hide() this.$form.show() setTimeout () => if this.$alertError.data('mark') is mark this.$alertError.hide() , 3000 submit: (e) -> e.preventDefault() this.model.save firstname: this.$firstname.val() lastname: this.$lastname.val() email: this.$email.val() company: this.$company.val() region: window.sn.get('region') , url: window.sn.get('server').host + '/registration' timeout: 10000 dataType: 'jsonp' beforeSend: () => this.$button.button 'loading' success: (s) => this.checking() error: () => this.$button.button 'reset' this.error '<b>Ошибка!</b> Сервер не отвечает!'
173875
require('moment') Modal = require('Modal') Registration = require('Registration') RegistrationTextSuccess = require('RegistrationTextSuccess') module.exports = Modal.extend el: '#registration' url: 'view/registration/registration.html' initialize: () -> this.model = new Registration() this.render() this.$firstname = this.$el.find('.registration-firstname') this.$lastname = this.$el.find('.registration-lastname') this.$email = this.$el.find('.registration-email') this.$company = this.$el.find('.registration-company') this.$modal = this.$el.find('.modal') this.$close = this.$el.find('.modal-header').find('.close') this.$form = this.$el.find('.registration-form') this.$button = this.$el.find('button') this.textSuccess = new RegistrationTextSuccess() this.$alertSuccess = this.$el.find('.alert-success') this.$alertError = this.$el.find('.alert-error') if window.user? window.user.on 'change:signin', () => if window.user.get('signin') is false this.model.reset() afterShow: () -> this.$alertSuccess.hide() this.$alertError.hide() this.textSuccess.hide() this.$form.show() this.$firstname.focus() data: () -> this.model.toJSON() checking: () -> setTimeout () => this.$button.button 'reset' , 400 if this.model.get('success') is true this.success this.model.get('email'), this.model.get('password') else this.error '<b>Ошибка!</b> ' + this.model.get('notice') + '.' this.model.reset() success: (email, password) -> this.$form.hide() this.$alertSuccess.show() this.$alertError.hide() this.textSuccess.show email: email password: <PASSWORD> error: (notice = '') -> mark = moment().unix() this.$alertError.show().html notice this.$alertError.data 'mark', mark this.$alertSuccess.hide() this.textSuccess.hide() this.$form.show() setTimeout () => if this.$alertError.data('mark') is mark this.$alertError.hide() , 3000 submit: (e) -> e.preventDefault() this.model.save firstname: this.$firstname.val() lastname: this.$lastname.val() email: this.$email.val() company: this.$company.val() region: window.sn.get('region') , url: window.sn.get('server').host + '/registration' timeout: 10000 dataType: 'jsonp' beforeSend: () => this.$button.button 'loading' success: (s) => this.checking() error: () => this.$button.button 'reset' this.error '<b>Ошибка!</b> Сервер не отвечает!'
true
require('moment') Modal = require('Modal') Registration = require('Registration') RegistrationTextSuccess = require('RegistrationTextSuccess') module.exports = Modal.extend el: '#registration' url: 'view/registration/registration.html' initialize: () -> this.model = new Registration() this.render() this.$firstname = this.$el.find('.registration-firstname') this.$lastname = this.$el.find('.registration-lastname') this.$email = this.$el.find('.registration-email') this.$company = this.$el.find('.registration-company') this.$modal = this.$el.find('.modal') this.$close = this.$el.find('.modal-header').find('.close') this.$form = this.$el.find('.registration-form') this.$button = this.$el.find('button') this.textSuccess = new RegistrationTextSuccess() this.$alertSuccess = this.$el.find('.alert-success') this.$alertError = this.$el.find('.alert-error') if window.user? window.user.on 'change:signin', () => if window.user.get('signin') is false this.model.reset() afterShow: () -> this.$alertSuccess.hide() this.$alertError.hide() this.textSuccess.hide() this.$form.show() this.$firstname.focus() data: () -> this.model.toJSON() checking: () -> setTimeout () => this.$button.button 'reset' , 400 if this.model.get('success') is true this.success this.model.get('email'), this.model.get('password') else this.error '<b>Ошибка!</b> ' + this.model.get('notice') + '.' this.model.reset() success: (email, password) -> this.$form.hide() this.$alertSuccess.show() this.$alertError.hide() this.textSuccess.show email: email password: PI:PASSWORD:<PASSWORD>END_PI error: (notice = '') -> mark = moment().unix() this.$alertError.show().html notice this.$alertError.data 'mark', mark this.$alertSuccess.hide() this.textSuccess.hide() this.$form.show() setTimeout () => if this.$alertError.data('mark') is mark this.$alertError.hide() , 3000 submit: (e) -> e.preventDefault() this.model.save firstname: this.$firstname.val() lastname: this.$lastname.val() email: this.$email.val() company: this.$company.val() region: window.sn.get('region') , url: window.sn.get('server').host + '/registration' timeout: 10000 dataType: 'jsonp' beforeSend: () => this.$button.button 'loading' success: (s) => this.checking() error: () => this.$button.button 'reset' this.error '<b>Ошибка!</b> Сервер не отвечает!'
[ { "context": "a})\n treema.build()\n treema.set('key', 'testValue')\n expect(treema.data.key).toBe('testValue')\n ", "end": 851, "score": 0.9341169595718384, "start": 846, "tag": "KEY", "value": "Value" } ]
test/default.spec.coffee
lgr7/codecombattreema
66
describe 'defaults', -> it 'shows properties for object nodes which are specified in a default object that are not included in the data', -> data = { } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() expect(treema.childrenTreemas.key).toBeDefined() it 'does not put default data into the containing data object', -> data = { } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() expect(treema.data.key).toBeUndefined() it 'puts data into the containing data object when its value is changed', -> data = { } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() treema.set('key', 'testValue') expect(treema.data.key).toBe('testValue') expect(treema.childrenTreemas.key.integrated).toBe(true) expect(treema.$el.find('.treema-node').length).toBe(1) it 'keeps a default node around when you delete one with backup default data', -> data = { key: 'setValue' } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() treema.delete('key') expect(treema.data.key).toBeUndefined() expect(treema.childrenTreemas.key).toBeDefined() expect(treema.childrenTreemas.key.integrated).toBe(false) expect(Object.keys(treema.data).length).toBe(0) it 'integrates up the chain when setting an inner default value', -> data = { } schema = { default: { innerObject: { key1: 'value1', key2: 'value2' } } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() treema.childrenTreemas.innerObject.open() treema.childrenTreemas.innerObject.childrenTreemas.key1.set('', 'newValue') expect(JSON.stringify(treema.data)).toBe(JSON.stringify({innerObject: {key1: 'newValue'}})) it 'takes defaultData from the make options', -> data = { } schema = { } treema = TreemaNode.make(null, {data: data, schema: schema, defaultData: { key: 'value' }}) treema.build() expect(treema.childrenTreemas.key).toBeDefined() it 'does not set defaults just by opening a collection', -> data = { } schema = { default: { inventory: { prop1: 'test', prop2: 'test' } } } treema = TreemaNode.make(null, {data: data, schema: schema, defaultData: { key: 'value' }}) treema.build() treema.open(2) expect($.isEmptyObject(treema.data)).toBe(true)
83151
describe 'defaults', -> it 'shows properties for object nodes which are specified in a default object that are not included in the data', -> data = { } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() expect(treema.childrenTreemas.key).toBeDefined() it 'does not put default data into the containing data object', -> data = { } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() expect(treema.data.key).toBeUndefined() it 'puts data into the containing data object when its value is changed', -> data = { } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() treema.set('key', 'test<KEY>') expect(treema.data.key).toBe('testValue') expect(treema.childrenTreemas.key.integrated).toBe(true) expect(treema.$el.find('.treema-node').length).toBe(1) it 'keeps a default node around when you delete one with backup default data', -> data = { key: 'setValue' } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() treema.delete('key') expect(treema.data.key).toBeUndefined() expect(treema.childrenTreemas.key).toBeDefined() expect(treema.childrenTreemas.key.integrated).toBe(false) expect(Object.keys(treema.data).length).toBe(0) it 'integrates up the chain when setting an inner default value', -> data = { } schema = { default: { innerObject: { key1: 'value1', key2: 'value2' } } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() treema.childrenTreemas.innerObject.open() treema.childrenTreemas.innerObject.childrenTreemas.key1.set('', 'newValue') expect(JSON.stringify(treema.data)).toBe(JSON.stringify({innerObject: {key1: 'newValue'}})) it 'takes defaultData from the make options', -> data = { } schema = { } treema = TreemaNode.make(null, {data: data, schema: schema, defaultData: { key: 'value' }}) treema.build() expect(treema.childrenTreemas.key).toBeDefined() it 'does not set defaults just by opening a collection', -> data = { } schema = { default: { inventory: { prop1: 'test', prop2: 'test' } } } treema = TreemaNode.make(null, {data: data, schema: schema, defaultData: { key: 'value' }}) treema.build() treema.open(2) expect($.isEmptyObject(treema.data)).toBe(true)
true
describe 'defaults', -> it 'shows properties for object nodes which are specified in a default object that are not included in the data', -> data = { } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() expect(treema.childrenTreemas.key).toBeDefined() it 'does not put default data into the containing data object', -> data = { } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() expect(treema.data.key).toBeUndefined() it 'puts data into the containing data object when its value is changed', -> data = { } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() treema.set('key', 'testPI:KEY:<KEY>END_PI') expect(treema.data.key).toBe('testValue') expect(treema.childrenTreemas.key.integrated).toBe(true) expect(treema.$el.find('.treema-node').length).toBe(1) it 'keeps a default node around when you delete one with backup default data', -> data = { key: 'setValue' } schema = { default: { key: 'value' } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() treema.delete('key') expect(treema.data.key).toBeUndefined() expect(treema.childrenTreemas.key).toBeDefined() expect(treema.childrenTreemas.key.integrated).toBe(false) expect(Object.keys(treema.data).length).toBe(0) it 'integrates up the chain when setting an inner default value', -> data = { } schema = { default: { innerObject: { key1: 'value1', key2: 'value2' } } } treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() treema.childrenTreemas.innerObject.open() treema.childrenTreemas.innerObject.childrenTreemas.key1.set('', 'newValue') expect(JSON.stringify(treema.data)).toBe(JSON.stringify({innerObject: {key1: 'newValue'}})) it 'takes defaultData from the make options', -> data = { } schema = { } treema = TreemaNode.make(null, {data: data, schema: schema, defaultData: { key: 'value' }}) treema.build() expect(treema.childrenTreemas.key).toBeDefined() it 'does not set defaults just by opening a collection', -> data = { } schema = { default: { inventory: { prop1: 'test', prop2: 'test' } } } treema = TreemaNode.make(null, {data: data, schema: schema, defaultData: { key: 'value' }}) treema.build() treema.open(2) expect($.isEmptyObject(treema.data)).toBe(true)
[ { "context": "s/helpers/and-afterward'`\n\nuserParams =\n email: \"test-email-no-#{Math.random()}@testmail.co\"\n password: \"password123\"\n username: \"test-user", "end": 299, "score": 0.9313803911209106, "start": 257, "tag": "EMAIL", "value": "test-email-no-#{Math.random()}@testmail.co...
tests/acceptance/current-account-test.coffee
simwms/simwms-shared
0
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import {validateAccount} from 'simwms-shared'` `import startApp from '../../tests/helpers/start-app'` `import andAfterward from '../../tests/helpers/and-afterward'` userParams = email: "test-email-no-#{Math.random()}@testmail.co" password: "password123" username: "test-user-no-#{Math.random()}" accountParams = companyName: "Test Co #{Math.random()}" timezone: "America/Los_Angeles" module 'Acceptance: CurrentAccount', beforeEach: -> @application = startApp() ### Don't return anything, because QUnit looks for a .then that is present on Ember.Application, but is deprecated. ### @index = @application.__container__.lookup("route:index") @currentUser = @index.currentUser @store = @index.store return afterEach: -> Ember.run @application, 'destroy' test 'account creation and session', (assert) -> visit '/' accountToken = null andThen => @store.createRecord "user", userParams .save() andThen => @currentUser.login userParams andThen => @store.createRecord "account", accountParams .save() .then (account) => accountToken = account.get("permalink") assert.ok account.id, "the account should be made" assert.ok accountToken, "the account should have its permalink" @currentUser.accountLogin(account) .catch (errors) -> assert.deepEqual errors, {}, "we should be able to make accounts" andThen => plan = @currentUser.get("servicePlan") assert.ok plan, "we should have the service plan" assert.equal plan.get("docks"), 1, "plan docks amounts should match" assert.equal plan.get("warehouses"), 4, "plan warehouses amounts should match" assert.equal plan.get("employees"), 5, "plan employees amounts should match" assert.equal plan.get("scales"), 1, "plan scales amounts should match" andThen => meta = @currentUser.get("meta") assert.ok meta, "the meta detail should be there" assert.equal meta.get("docks"), 1, "docks" assert.equal meta.get("warehouses"), 1, "warehouses" assert.equal meta.get("employees"), 1, "employees" assert.equal meta.get("scales"), 1, "scales" validateAccount meta .then (meta) -> assert.ok meta, "we should get here" .catch (errors) -> assert.deepEqual errors.core, {}, "we should pass account validation" andThen => assert.ok @currentUser.get("accountLoggedIn"), "the account should be logged in" assert.ok @currentUser.get("account"), "the account should be there" assert.ok @currentUser.get("employee"), "the employee should be there" assert.ok @currentUser.get("servicePlan"), "the account service plan should be there" @currentUser.accountLogout() assert.notOk @currentUser.get("accountLoggedIn"), "account logout should work" andThen => @currentUser.logout() andThen => @currentUser.smartLogin email: userParams.email password: userParams.password accountToken: accountToken andThen => assert.ok @currentUser.get("isLoggedIn"), "smart login should log in user" assert.ok @currentUser.get("accountLoggedIn"), "smart login should log in the account" assert.equal @currentUser.get("account.permalink"), accountToken, "we should have the right account" assert.equal @currentUser.get("session.email"), userParams.email, "the right employee should be logged in" andThen => @currentUser.accountLogout() @currentUser.logout()
66928
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import {validateAccount} from 'simwms-shared'` `import startApp from '../../tests/helpers/start-app'` `import andAfterward from '../../tests/helpers/and-afterward'` userParams = email: "<EMAIL>" password: "<PASSWORD>" username: "test-user-no-#{Math.random()}" accountParams = companyName: "Test Co #{Math.random()}" timezone: "America/Los_Angeles" module 'Acceptance: CurrentAccount', beforeEach: -> @application = startApp() ### Don't return anything, because QUnit looks for a .then that is present on Ember.Application, but is deprecated. ### @index = @application.__container__.lookup("route:index") @currentUser = @index.currentUser @store = @index.store return afterEach: -> Ember.run @application, 'destroy' test 'account creation and session', (assert) -> visit '/' accountToken = null andThen => @store.createRecord "user", userParams .save() andThen => @currentUser.login userParams andThen => @store.createRecord "account", accountParams .save() .then (account) => accountToken = account.get("permalink") assert.ok account.id, "the account should be made" assert.ok accountToken, "the account should have its permalink" @currentUser.accountLogin(account) .catch (errors) -> assert.deepEqual errors, {}, "we should be able to make accounts" andThen => plan = @currentUser.get("servicePlan") assert.ok plan, "we should have the service plan" assert.equal plan.get("docks"), 1, "plan docks amounts should match" assert.equal plan.get("warehouses"), 4, "plan warehouses amounts should match" assert.equal plan.get("employees"), 5, "plan employees amounts should match" assert.equal plan.get("scales"), 1, "plan scales amounts should match" andThen => meta = @currentUser.get("meta") assert.ok meta, "the meta detail should be there" assert.equal meta.get("docks"), 1, "docks" assert.equal meta.get("warehouses"), 1, "warehouses" assert.equal meta.get("employees"), 1, "employees" assert.equal meta.get("scales"), 1, "scales" validateAccount meta .then (meta) -> assert.ok meta, "we should get here" .catch (errors) -> assert.deepEqual errors.core, {}, "we should pass account validation" andThen => assert.ok @currentUser.get("accountLoggedIn"), "the account should be logged in" assert.ok @currentUser.get("account"), "the account should be there" assert.ok @currentUser.get("employee"), "the employee should be there" assert.ok @currentUser.get("servicePlan"), "the account service plan should be there" @currentUser.accountLogout() assert.notOk @currentUser.get("accountLoggedIn"), "account logout should work" andThen => @currentUser.logout() andThen => @currentUser.smartLogin email: userParams.email password: <PASSWORD> accountToken: accountToken andThen => assert.ok @currentUser.get("isLoggedIn"), "smart login should log in user" assert.ok @currentUser.get("accountLoggedIn"), "smart login should log in the account" assert.equal @currentUser.get("account.permalink"), accountToken, "we should have the right account" assert.equal @currentUser.get("session.email"), userParams.email, "the right employee should be logged in" andThen => @currentUser.accountLogout() @currentUser.logout()
true
`import Ember from 'ember'` `import { module, test } from 'qunit'` `import {validateAccount} from 'simwms-shared'` `import startApp from '../../tests/helpers/start-app'` `import andAfterward from '../../tests/helpers/and-afterward'` userParams = email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" username: "test-user-no-#{Math.random()}" accountParams = companyName: "Test Co #{Math.random()}" timezone: "America/Los_Angeles" module 'Acceptance: CurrentAccount', beforeEach: -> @application = startApp() ### Don't return anything, because QUnit looks for a .then that is present on Ember.Application, but is deprecated. ### @index = @application.__container__.lookup("route:index") @currentUser = @index.currentUser @store = @index.store return afterEach: -> Ember.run @application, 'destroy' test 'account creation and session', (assert) -> visit '/' accountToken = null andThen => @store.createRecord "user", userParams .save() andThen => @currentUser.login userParams andThen => @store.createRecord "account", accountParams .save() .then (account) => accountToken = account.get("permalink") assert.ok account.id, "the account should be made" assert.ok accountToken, "the account should have its permalink" @currentUser.accountLogin(account) .catch (errors) -> assert.deepEqual errors, {}, "we should be able to make accounts" andThen => plan = @currentUser.get("servicePlan") assert.ok plan, "we should have the service plan" assert.equal plan.get("docks"), 1, "plan docks amounts should match" assert.equal plan.get("warehouses"), 4, "plan warehouses amounts should match" assert.equal plan.get("employees"), 5, "plan employees amounts should match" assert.equal plan.get("scales"), 1, "plan scales amounts should match" andThen => meta = @currentUser.get("meta") assert.ok meta, "the meta detail should be there" assert.equal meta.get("docks"), 1, "docks" assert.equal meta.get("warehouses"), 1, "warehouses" assert.equal meta.get("employees"), 1, "employees" assert.equal meta.get("scales"), 1, "scales" validateAccount meta .then (meta) -> assert.ok meta, "we should get here" .catch (errors) -> assert.deepEqual errors.core, {}, "we should pass account validation" andThen => assert.ok @currentUser.get("accountLoggedIn"), "the account should be logged in" assert.ok @currentUser.get("account"), "the account should be there" assert.ok @currentUser.get("employee"), "the employee should be there" assert.ok @currentUser.get("servicePlan"), "the account service plan should be there" @currentUser.accountLogout() assert.notOk @currentUser.get("accountLoggedIn"), "account logout should work" andThen => @currentUser.logout() andThen => @currentUser.smartLogin email: userParams.email password: PI:PASSWORD:<PASSWORD>END_PI accountToken: accountToken andThen => assert.ok @currentUser.get("isLoggedIn"), "smart login should log in user" assert.ok @currentUser.get("accountLoggedIn"), "smart login should log in the account" assert.equal @currentUser.get("account.permalink"), accountToken, "we should have the right account" assert.equal @currentUser.get("session.email"), userParams.email, "the right employee should be logged in" andThen => @currentUser.accountLogout() @currentUser.logout()
[ { "context": "\nmakeNodeFromUser = (user) ->\n return {\n name: user.name\n id: user.id\n link: user.link\n group: 1\n", "end": 539, "score": 0.8073234558105469, "start": 530, "tag": "USERNAME", "value": "user.name" }, { "context": "ends = response.data\n\n me = {\n...
src/public/coffee/main.coffee
AndersDJohnson/fbviz
1
window.app = app = {} cachedFBapi = do -> cache = window.localStorage.getItem('friendsgraph') unless cache? cache = {} else cache = JSON.parse(cache) return (url, callback) -> if cache[url]? callback(cache[url].data) else FB.api url, (response) -> cache[url] = { data: response, time: Date.now() } window.localStorage.setItem('friendsgraph', JSON.stringify(cache)) callback(response) makeNodeFromUser = (user) -> return { name: user.name id: user.id link: user.link group: 1 strength: 1 } makeLink = (node1, node2) -> return { id: "#{node1.id}_#{node2.id}" source: node1 target: node2 strength: 1 } binder = ($el, getter, setter, throttle = 200) -> throttled = _.throttle(((value)-> setter(value) ), throttle) $el.on 'change', (e) -> $this = $(this) value = parseFloat($this.val()) throttled(value) app.update() $el.val(getter()) bindControls = do -> bound = false return -> return if bound bound = true force = app.force binder($('#gravity'), (-> force.gravity()), (val) -> force.gravity(val)) binder($('#charge'), (-> force.charge()), ((val) -> force.charge(val))) #binder($('#distance'), (-> force.linkDistance()), ((val) -> force.linkDistance(val))) #color = d3.scale.category20(); width = 500 height = 500 padding = 100 app.force = force = d3.layout.force() .linkDistance(((d) -> if d.strength? and not isNaN(d.strength) t = (width - padding) * 0.5 s = d.strength w = t * (1 - s) else w = 1 return w )) #.linkStrength((d) -> Math.pow(d.strength, 2) || 1 ) .size([width, height]) app.zoom = zoom = d3.behavior.zoom() zoom.on 'zoom', -> hidePopovers() scale = d3.event.scale [x, y] = d3.event.translate xs = x / scale ys = y / scale $svg = $(svg[0]) value = 'scale(' + scale + ') translate(' + xs + 'px, ' + ys + 'px)' $svg.css('transform', value) graph = d3.select("#graph") graph .call(zoom) svg = graph.append("svg") .attr("width", width) .attr("height", height) app.dataMaps = dataMaps = links: d3.map() nodes: d3.map() app.elements = elements = $nodes: [] $links: [] getLinks = -> svg.selectAll(".link") getNodes = -> svg.selectAll(".node") getPopovers = -> $('.popover') hidePopovers = ($except = []) -> # hide all popovers $popovers = $('.node') $popovers .not($except) .hoverPopover('hide') forceOnTick = -> getLinks().attr("x1", (d) -> d.source.x; ) .attr("y1", (d) -> d.source.y; ) .attr("x2", (d) -> d.target.x; ) .attr("y2", (d) -> d.target.y; ); getNodes().attr("cx", (d) -> d.x; ) .attr("cy", (d) -> d.y; ) force.on "tick", forceOnTick getMutualFriends = (friend, callback) -> uri = '/me/mutualfriends/' + friend.id cachedFBapi uri, (response) -> console.log 'mutual friends response', response callback(response) app.templates = templates = me: _.template($('script#tooltip-me').html()) friend: _.template($('script#tooltip-friend').html()) addPopover = (d, index, fixed) -> $this = $(this) friend = d if friend.isMe return else template = templates.friend data = {friend: friend} content = template(data) $this.hoverPopover({ #showTime: 100 #hideTime: 10000 popover: { trigger: 'manual' container: 'body' html: true content: content } onInitTip: ($tip, popoverData) -> cachedFBapi '/' + friend.id + '?fields=id,name,link,picture', (response) -> $this.data('facebookData', response) link = response.link src = response.picture?.data?.url $content = $('<div>' + popoverData.options.content + '</div>') $content.find('.picture img') .attr('src', src) $content.find('.name a, .picture a') .attr('href', link) content = $content.html() popoverData.options.content = content $tip.find('.popover-content').html(content) }) $this.on 'mouseenter', (e) -> if $this.hoverPopover('showing') hidePopovers($this) $this.hoverPopover('tryshow') $this.on 'mouseleave', (e) -> $this.hoverPopover('tryhide') onClick = (d) -> $this = $(this) data = $this.data('facebookData') console.log data if data.link? window.open(data.link, '_blank') app.update = update = -> force.stop() links = dataMaps.links.values() nodes = dataMaps.nodes.values() elements.$links = $links = getLinks().data(links, (d) -> d.id) $links.enter() .append('line') .attr('class', 'link') #.style('stroke-width', 1 ) elements.$nodes = $nodes = getNodes().data(nodes, (d) -> d.id) $nodes.enter() .append('circle') .classed('node', true) .classed('me', (d) -> d.isMe) .attr("r", (d) -> (d.strength * 4) + 4) #.style("fill", (d) -> color(d.group)) .each(addPopover) .on("click", onClick) #.on("mouseover", onMouseOver) #.on("mouseout", onMouseOut) #.call(force.drag); $nodes.append("title") .text((d) -> d.name ); $links.exit().remove() $nodes.exit().remove() force .links(links) .nodes(nodes) .start() bindControls() getOrSet = (map, key, value) -> if map.has(key) value = dataMaps.nodes.get(key) else map.set(key, value) return value window.fbPostInit = -> #FB.api '/me', (response) -> # alert('Your name is ' + response.name); options = cluster: false FB.login((response) -> console.log 'login response', response cachedFBapi '/me/friends', (response) -> console.log 'friends response', response friends = response.data me = { name: 'Me' id: '-1000' } meNode = makeNodeFromUser(me) meNode.group = 0 meNode.index = 0 meNode.isMe = true meNode.mutualFriendCount = friends.length dataMaps.nodes.set(meNode.id, meNode) maxMutualFriendCount = 1 async.each(friends, ((item, callback) -> friend = item fNode = makeNodeFromUser(friend) fNode = getOrSet(dataMaps.nodes, fNode.id, fNode) fLink = makeLink(meNode, fNode) getMutualFriends friend, (response) -> mutualFriends = response.data mutualFriendCount = mutualFriends.length fNode.mutualFriendCount = mutualFriendCount fLink.mutualFriendCount = mutualFriendCount if mutualFriendCount > maxMutualFriendCount maxMutualFriendCount = mutualFriendCount dataMaps.nodes.set(fNode.id, fNode) dataMaps.links.set(fLink.id, fLink) if options.cluster mutualFriends.forEach (mItem) -> mNode = makeNodeFromUser(mItem) return if fNode.id is mNode.id mNode = getOrSet(dataMaps.nodes, mNode.id, mNode) mLink = makeLink(fNode, mNode) mLink.strength = 0.5 dataMaps.links.set(mLink.id, mLink) callback() ), (err) -> dataMaps.links.forEach (key, link) -> if link.mutualFriendCount? link.strength = link.mutualFriendCount / maxMutualFriendCount link.target.strength = link.strength update() ) , {})
193353
window.app = app = {} cachedFBapi = do -> cache = window.localStorage.getItem('friendsgraph') unless cache? cache = {} else cache = JSON.parse(cache) return (url, callback) -> if cache[url]? callback(cache[url].data) else FB.api url, (response) -> cache[url] = { data: response, time: Date.now() } window.localStorage.setItem('friendsgraph', JSON.stringify(cache)) callback(response) makeNodeFromUser = (user) -> return { name: user.name id: user.id link: user.link group: 1 strength: 1 } makeLink = (node1, node2) -> return { id: "#{node1.id}_#{node2.id}" source: node1 target: node2 strength: 1 } binder = ($el, getter, setter, throttle = 200) -> throttled = _.throttle(((value)-> setter(value) ), throttle) $el.on 'change', (e) -> $this = $(this) value = parseFloat($this.val()) throttled(value) app.update() $el.val(getter()) bindControls = do -> bound = false return -> return if bound bound = true force = app.force binder($('#gravity'), (-> force.gravity()), (val) -> force.gravity(val)) binder($('#charge'), (-> force.charge()), ((val) -> force.charge(val))) #binder($('#distance'), (-> force.linkDistance()), ((val) -> force.linkDistance(val))) #color = d3.scale.category20(); width = 500 height = 500 padding = 100 app.force = force = d3.layout.force() .linkDistance(((d) -> if d.strength? and not isNaN(d.strength) t = (width - padding) * 0.5 s = d.strength w = t * (1 - s) else w = 1 return w )) #.linkStrength((d) -> Math.pow(d.strength, 2) || 1 ) .size([width, height]) app.zoom = zoom = d3.behavior.zoom() zoom.on 'zoom', -> hidePopovers() scale = d3.event.scale [x, y] = d3.event.translate xs = x / scale ys = y / scale $svg = $(svg[0]) value = 'scale(' + scale + ') translate(' + xs + 'px, ' + ys + 'px)' $svg.css('transform', value) graph = d3.select("#graph") graph .call(zoom) svg = graph.append("svg") .attr("width", width) .attr("height", height) app.dataMaps = dataMaps = links: d3.map() nodes: d3.map() app.elements = elements = $nodes: [] $links: [] getLinks = -> svg.selectAll(".link") getNodes = -> svg.selectAll(".node") getPopovers = -> $('.popover') hidePopovers = ($except = []) -> # hide all popovers $popovers = $('.node') $popovers .not($except) .hoverPopover('hide') forceOnTick = -> getLinks().attr("x1", (d) -> d.source.x; ) .attr("y1", (d) -> d.source.y; ) .attr("x2", (d) -> d.target.x; ) .attr("y2", (d) -> d.target.y; ); getNodes().attr("cx", (d) -> d.x; ) .attr("cy", (d) -> d.y; ) force.on "tick", forceOnTick getMutualFriends = (friend, callback) -> uri = '/me/mutualfriends/' + friend.id cachedFBapi uri, (response) -> console.log 'mutual friends response', response callback(response) app.templates = templates = me: _.template($('script#tooltip-me').html()) friend: _.template($('script#tooltip-friend').html()) addPopover = (d, index, fixed) -> $this = $(this) friend = d if friend.isMe return else template = templates.friend data = {friend: friend} content = template(data) $this.hoverPopover({ #showTime: 100 #hideTime: 10000 popover: { trigger: 'manual' container: 'body' html: true content: content } onInitTip: ($tip, popoverData) -> cachedFBapi '/' + friend.id + '?fields=id,name,link,picture', (response) -> $this.data('facebookData', response) link = response.link src = response.picture?.data?.url $content = $('<div>' + popoverData.options.content + '</div>') $content.find('.picture img') .attr('src', src) $content.find('.name a, .picture a') .attr('href', link) content = $content.html() popoverData.options.content = content $tip.find('.popover-content').html(content) }) $this.on 'mouseenter', (e) -> if $this.hoverPopover('showing') hidePopovers($this) $this.hoverPopover('tryshow') $this.on 'mouseleave', (e) -> $this.hoverPopover('tryhide') onClick = (d) -> $this = $(this) data = $this.data('facebookData') console.log data if data.link? window.open(data.link, '_blank') app.update = update = -> force.stop() links = dataMaps.links.values() nodes = dataMaps.nodes.values() elements.$links = $links = getLinks().data(links, (d) -> d.id) $links.enter() .append('line') .attr('class', 'link') #.style('stroke-width', 1 ) elements.$nodes = $nodes = getNodes().data(nodes, (d) -> d.id) $nodes.enter() .append('circle') .classed('node', true) .classed('me', (d) -> d.isMe) .attr("r", (d) -> (d.strength * 4) + 4) #.style("fill", (d) -> color(d.group)) .each(addPopover) .on("click", onClick) #.on("mouseover", onMouseOver) #.on("mouseout", onMouseOut) #.call(force.drag); $nodes.append("title") .text((d) -> d.name ); $links.exit().remove() $nodes.exit().remove() force .links(links) .nodes(nodes) .start() bindControls() getOrSet = (map, key, value) -> if map.has(key) value = dataMaps.nodes.get(key) else map.set(key, value) return value window.fbPostInit = -> #FB.api '/me', (response) -> # alert('Your name is ' + response.name); options = cluster: false FB.login((response) -> console.log 'login response', response cachedFBapi '/me/friends', (response) -> console.log 'friends response', response friends = response.data me = { name: '<NAME>' id: '-1000' } meNode = makeNodeFromUser(me) meNode.group = 0 meNode.index = 0 meNode.isMe = true meNode.mutualFriendCount = friends.length dataMaps.nodes.set(meNode.id, meNode) maxMutualFriendCount = 1 async.each(friends, ((item, callback) -> friend = item fNode = makeNodeFromUser(friend) fNode = getOrSet(dataMaps.nodes, fNode.id, fNode) fLink = makeLink(meNode, fNode) getMutualFriends friend, (response) -> mutualFriends = response.data mutualFriendCount = mutualFriends.length fNode.mutualFriendCount = mutualFriendCount fLink.mutualFriendCount = mutualFriendCount if mutualFriendCount > maxMutualFriendCount maxMutualFriendCount = mutualFriendCount dataMaps.nodes.set(fNode.id, fNode) dataMaps.links.set(fLink.id, fLink) if options.cluster mutualFriends.forEach (mItem) -> mNode = makeNodeFromUser(mItem) return if fNode.id is mNode.id mNode = getOrSet(dataMaps.nodes, mNode.id, mNode) mLink = makeLink(fNode, mNode) mLink.strength = 0.5 dataMaps.links.set(mLink.id, mLink) callback() ), (err) -> dataMaps.links.forEach (key, link) -> if link.mutualFriendCount? link.strength = link.mutualFriendCount / maxMutualFriendCount link.target.strength = link.strength update() ) , {})
true
window.app = app = {} cachedFBapi = do -> cache = window.localStorage.getItem('friendsgraph') unless cache? cache = {} else cache = JSON.parse(cache) return (url, callback) -> if cache[url]? callback(cache[url].data) else FB.api url, (response) -> cache[url] = { data: response, time: Date.now() } window.localStorage.setItem('friendsgraph', JSON.stringify(cache)) callback(response) makeNodeFromUser = (user) -> return { name: user.name id: user.id link: user.link group: 1 strength: 1 } makeLink = (node1, node2) -> return { id: "#{node1.id}_#{node2.id}" source: node1 target: node2 strength: 1 } binder = ($el, getter, setter, throttle = 200) -> throttled = _.throttle(((value)-> setter(value) ), throttle) $el.on 'change', (e) -> $this = $(this) value = parseFloat($this.val()) throttled(value) app.update() $el.val(getter()) bindControls = do -> bound = false return -> return if bound bound = true force = app.force binder($('#gravity'), (-> force.gravity()), (val) -> force.gravity(val)) binder($('#charge'), (-> force.charge()), ((val) -> force.charge(val))) #binder($('#distance'), (-> force.linkDistance()), ((val) -> force.linkDistance(val))) #color = d3.scale.category20(); width = 500 height = 500 padding = 100 app.force = force = d3.layout.force() .linkDistance(((d) -> if d.strength? and not isNaN(d.strength) t = (width - padding) * 0.5 s = d.strength w = t * (1 - s) else w = 1 return w )) #.linkStrength((d) -> Math.pow(d.strength, 2) || 1 ) .size([width, height]) app.zoom = zoom = d3.behavior.zoom() zoom.on 'zoom', -> hidePopovers() scale = d3.event.scale [x, y] = d3.event.translate xs = x / scale ys = y / scale $svg = $(svg[0]) value = 'scale(' + scale + ') translate(' + xs + 'px, ' + ys + 'px)' $svg.css('transform', value) graph = d3.select("#graph") graph .call(zoom) svg = graph.append("svg") .attr("width", width) .attr("height", height) app.dataMaps = dataMaps = links: d3.map() nodes: d3.map() app.elements = elements = $nodes: [] $links: [] getLinks = -> svg.selectAll(".link") getNodes = -> svg.selectAll(".node") getPopovers = -> $('.popover') hidePopovers = ($except = []) -> # hide all popovers $popovers = $('.node') $popovers .not($except) .hoverPopover('hide') forceOnTick = -> getLinks().attr("x1", (d) -> d.source.x; ) .attr("y1", (d) -> d.source.y; ) .attr("x2", (d) -> d.target.x; ) .attr("y2", (d) -> d.target.y; ); getNodes().attr("cx", (d) -> d.x; ) .attr("cy", (d) -> d.y; ) force.on "tick", forceOnTick getMutualFriends = (friend, callback) -> uri = '/me/mutualfriends/' + friend.id cachedFBapi uri, (response) -> console.log 'mutual friends response', response callback(response) app.templates = templates = me: _.template($('script#tooltip-me').html()) friend: _.template($('script#tooltip-friend').html()) addPopover = (d, index, fixed) -> $this = $(this) friend = d if friend.isMe return else template = templates.friend data = {friend: friend} content = template(data) $this.hoverPopover({ #showTime: 100 #hideTime: 10000 popover: { trigger: 'manual' container: 'body' html: true content: content } onInitTip: ($tip, popoverData) -> cachedFBapi '/' + friend.id + '?fields=id,name,link,picture', (response) -> $this.data('facebookData', response) link = response.link src = response.picture?.data?.url $content = $('<div>' + popoverData.options.content + '</div>') $content.find('.picture img') .attr('src', src) $content.find('.name a, .picture a') .attr('href', link) content = $content.html() popoverData.options.content = content $tip.find('.popover-content').html(content) }) $this.on 'mouseenter', (e) -> if $this.hoverPopover('showing') hidePopovers($this) $this.hoverPopover('tryshow') $this.on 'mouseleave', (e) -> $this.hoverPopover('tryhide') onClick = (d) -> $this = $(this) data = $this.data('facebookData') console.log data if data.link? window.open(data.link, '_blank') app.update = update = -> force.stop() links = dataMaps.links.values() nodes = dataMaps.nodes.values() elements.$links = $links = getLinks().data(links, (d) -> d.id) $links.enter() .append('line') .attr('class', 'link') #.style('stroke-width', 1 ) elements.$nodes = $nodes = getNodes().data(nodes, (d) -> d.id) $nodes.enter() .append('circle') .classed('node', true) .classed('me', (d) -> d.isMe) .attr("r", (d) -> (d.strength * 4) + 4) #.style("fill", (d) -> color(d.group)) .each(addPopover) .on("click", onClick) #.on("mouseover", onMouseOver) #.on("mouseout", onMouseOut) #.call(force.drag); $nodes.append("title") .text((d) -> d.name ); $links.exit().remove() $nodes.exit().remove() force .links(links) .nodes(nodes) .start() bindControls() getOrSet = (map, key, value) -> if map.has(key) value = dataMaps.nodes.get(key) else map.set(key, value) return value window.fbPostInit = -> #FB.api '/me', (response) -> # alert('Your name is ' + response.name); options = cluster: false FB.login((response) -> console.log 'login response', response cachedFBapi '/me/friends', (response) -> console.log 'friends response', response friends = response.data me = { name: 'PI:NAME:<NAME>END_PI' id: '-1000' } meNode = makeNodeFromUser(me) meNode.group = 0 meNode.index = 0 meNode.isMe = true meNode.mutualFriendCount = friends.length dataMaps.nodes.set(meNode.id, meNode) maxMutualFriendCount = 1 async.each(friends, ((item, callback) -> friend = item fNode = makeNodeFromUser(friend) fNode = getOrSet(dataMaps.nodes, fNode.id, fNode) fLink = makeLink(meNode, fNode) getMutualFriends friend, (response) -> mutualFriends = response.data mutualFriendCount = mutualFriends.length fNode.mutualFriendCount = mutualFriendCount fLink.mutualFriendCount = mutualFriendCount if mutualFriendCount > maxMutualFriendCount maxMutualFriendCount = mutualFriendCount dataMaps.nodes.set(fNode.id, fNode) dataMaps.links.set(fLink.id, fLink) if options.cluster mutualFriends.forEach (mItem) -> mNode = makeNodeFromUser(mItem) return if fNode.id is mNode.id mNode = getOrSet(dataMaps.nodes, mNode.id, mNode) mLink = makeLink(fNode, mNode) mLink.strength = 0.5 dataMaps.links.set(mLink.id, mLink) callback() ), (err) -> dataMaps.links.forEach (key, link) -> if link.mutualFriendCount? link.strength = link.mutualFriendCount / maxMutualFriendCount link.target.strength = link.strength update() ) , {})
[ { "context": "config.port\n\t\t\tuser\t\t\t: config.user\n\t\t\tpassword\t\t: config.pass\n\t\t\tsecure\t\t\t: config.secure\n\t\t\tsecureOptions\t: co", "end": 646, "score": 0.9991824626922607, "start": 635, "tag": "PASSWORD", "value": "config.pass" } ]
src/scheme/ftp.coffee
smartmediaas/dploy
290
ftp = require "ftp" Signal = require "signals" module.exports = class FTP connection : null connected : null failed : null closed : null constructor: -> @connected = new Signal() @failed = new Signal() @closed = new Signal() # Create a new instance of the FTP @connection = new ftp() @connection.on "error", => @failed.dispatch() @connection.on "ready", => @connected.dispatch() ### Connect to the FTP @param config <object> Configuration file for your connection ### connect: (config) -> @connection.connect host : config.host port : config.port user : config.user password : config.pass secure : config.secure secureOptions : config.secureOptions ### Close the connection ### close: (callback) -> @connection.on "end", => @closed.dispatch() @connection.end() ### Dispose ### dispose: -> if @connected @connected.dispose() @connected = null if @failed @failed.dispose() @failed = null if @closed @closed.dispose() @closed = null ### Retrieve a file on the server @param path: <string> The path of your file @param callback: <function> Callback method ### get: (path, callback) -> @connection.get path, callback ### Upload a file to the server @param local_path: <string> The local path of your file @param remote_path: <string> The remote path where you want your file to be uploaded at @param callback: <function> Callback method ### upload: (local_path, remote_path, callback) -> @connection.put local_path, remote_path, callback ### Delete a file from the server @param remote_path: <string> The remote path you want to delete @param callback: <function> Callback method ### delete: (remote_path, callback) -> @connection.delete remote_path, callback ### Create a directory @param path: <string> The path of the directory you want to create @param callback: <function> Callback method ### mkdir: (path, callback) -> @connection.mkdir path, true, callback
205021
ftp = require "ftp" Signal = require "signals" module.exports = class FTP connection : null connected : null failed : null closed : null constructor: -> @connected = new Signal() @failed = new Signal() @closed = new Signal() # Create a new instance of the FTP @connection = new ftp() @connection.on "error", => @failed.dispatch() @connection.on "ready", => @connected.dispatch() ### Connect to the FTP @param config <object> Configuration file for your connection ### connect: (config) -> @connection.connect host : config.host port : config.port user : config.user password : <PASSWORD> secure : config.secure secureOptions : config.secureOptions ### Close the connection ### close: (callback) -> @connection.on "end", => @closed.dispatch() @connection.end() ### Dispose ### dispose: -> if @connected @connected.dispose() @connected = null if @failed @failed.dispose() @failed = null if @closed @closed.dispose() @closed = null ### Retrieve a file on the server @param path: <string> The path of your file @param callback: <function> Callback method ### get: (path, callback) -> @connection.get path, callback ### Upload a file to the server @param local_path: <string> The local path of your file @param remote_path: <string> The remote path where you want your file to be uploaded at @param callback: <function> Callback method ### upload: (local_path, remote_path, callback) -> @connection.put local_path, remote_path, callback ### Delete a file from the server @param remote_path: <string> The remote path you want to delete @param callback: <function> Callback method ### delete: (remote_path, callback) -> @connection.delete remote_path, callback ### Create a directory @param path: <string> The path of the directory you want to create @param callback: <function> Callback method ### mkdir: (path, callback) -> @connection.mkdir path, true, callback
true
ftp = require "ftp" Signal = require "signals" module.exports = class FTP connection : null connected : null failed : null closed : null constructor: -> @connected = new Signal() @failed = new Signal() @closed = new Signal() # Create a new instance of the FTP @connection = new ftp() @connection.on "error", => @failed.dispatch() @connection.on "ready", => @connected.dispatch() ### Connect to the FTP @param config <object> Configuration file for your connection ### connect: (config) -> @connection.connect host : config.host port : config.port user : config.user password : PI:PASSWORD:<PASSWORD>END_PI secure : config.secure secureOptions : config.secureOptions ### Close the connection ### close: (callback) -> @connection.on "end", => @closed.dispatch() @connection.end() ### Dispose ### dispose: -> if @connected @connected.dispose() @connected = null if @failed @failed.dispose() @failed = null if @closed @closed.dispose() @closed = null ### Retrieve a file on the server @param path: <string> The path of your file @param callback: <function> Callback method ### get: (path, callback) -> @connection.get path, callback ### Upload a file to the server @param local_path: <string> The local path of your file @param remote_path: <string> The remote path where you want your file to be uploaded at @param callback: <function> Callback method ### upload: (local_path, remote_path, callback) -> @connection.put local_path, remote_path, callback ### Delete a file from the server @param remote_path: <string> The remote path you want to delete @param callback: <function> Callback method ### delete: (remote_path, callback) -> @connection.delete remote_path, callback ### Create a directory @param path: <string> The path of the directory you want to create @param callback: <function> Callback method ### mkdir: (path, callback) -> @connection.mkdir path, true, callback
[ { "context": "(Darwin)\nComment: GPGTools - https://gpgtools.org\n\nmI0EU1UoTgEEAOMP1er7XCaXhVLeHGQK7KFanTTeSLvI39kBvlxQfIjOBjsFH2/J\n3PtHazl2RGSzGqIPyqD+79TAwa15ESEDwwvwldJnlP9MwfwMk0HUeygqWbar9bj9\nLTiPLlf/4z0a9GLjuBnI6Yuy7nutd0mKatR/2v2q0pI9WJaXOurhwATTABEBAAG0\nIFdpbGxpYW0gV29yZHN3b3J0aCA8d3dAb3guYWMudWs+iL...
test/files/secret_subkeys_incomplete.iced
thinq4yourself/kbpgp
1
{KeyManager} = require '../../lib/keymanager' {bufferify,ASP} = require '../../lib/util' {make_esc} = require 'iced-error' util = require 'util' {box} = require '../../lib/keybase/encode' {Encryptor} = require 'triplesec' {base91} = require '../../lib/basex' {burn} = require '../../lib/openpgp/burner' {do_message} = require '../../lib/openpgp/processor' #--------------------------------------------- pub = """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org mI0EU1UoTgEEAOMP1er7XCaXhVLeHGQK7KFanTTeSLvI39kBvlxQfIjOBjsFH2/J 3PtHazl2RGSzGqIPyqD+79TAwa15ESEDwwvwldJnlP9MwfwMk0HUeygqWbar9bj9 LTiPLlf/4z0a9GLjuBnI6Yuy7nutd0mKatR/2v2q0pI9WJaXOurhwATTABEBAAG0 IFdpbGxpYW0gV29yZHN3b3J0aCA8d3dAb3guYWMudWs+iL4EEwEKACgFAlNVKE4C GwMFCRLMAwAGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEJLYKARjvfT1roEE AJ140DFf7DV0d51KMmwz8iwuU7OWOOMoOObdLOHox3soScrHvGqM0dg7ZZUhQSIE TQUDk2Fkcjpqizhs7sJinbWYcpiaEKv7PWYHLyIIH+RcYKv18hlaEFHaOoUdRfzZ sNSwNznnlCSCJOwkVMa1eJGJrEElzoktqPeDsforPFKhuI0EU1UoTgEEALCxOW1Y 5BQSOMoNdbby7uyS4hPaO0YVz9tvNdx+DZvNOmgmUw04Ex1EM8NNVxwmEBiPyRf1 YkNKP6CW4y+3fX2UusBeNquhke8cWolAPGWrJHeYKQhOMvT1QX/BXLewXvB6TwqU m2FhKIFlPj3qjUw6yPmT4Txj+84dBu+D24rTABEBAAGIpQQYAQoADwUCU1UoTgIb DAUJEswDAAAKCRCS2CgEY7309RooBACIrXNBBAg5WSoFr8T0nHlSkJUX9+LRexN9 TZjRKWAVXuP0Gp7ShvJwnYsVE0Od1VF4lBCPm+nBn8Hl0ChSpoxeYAPcMP7tljvn q76DStTbVng1/7B709/IDn6XHD7o9c2lhzG9T3Bd/63m+9Mut2dUB1HSFLEpZ04K AhLVWVC7Gw== =jrB1 -----END PGP PUBLIC KEY BLOCK----- """ #------------ # In this case, we have only 1 subkey for encryption, and no # subkeys for signing. Plus, we don't have an encrypted primary # key. So we shouldn't be able to sign. priv = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org lQCVBFNVKE4BBADjD9Xq+1wml4VS3hxkCuyhWp003ki7yN/ZAb5cUHyIzgY7BR9v ydz7R2s5dkRksxqiD8qg/u/UwMGteREhA8ML8JXSZ5T/TMH8DJNB1HsoKlm2q/W4 /S04jy5X/+M9GvRi47gZyOmLsu57rXdJimrUf9r9qtKSPViWlzrq4cAE0wARAQAB /gNlAkdOVQG0IFdpbGxpYW0gV29yZHN3b3J0aCA8d3dAb3guYWMudWs+iL4EEwEK ACgFAlNVKE4CGwMFCRLMAwAGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEJLY KARjvfT1roEEAJ140DFf7DV0d51KMmwz8iwuU7OWOOMoOObdLOHox3soScrHvGqM 0dg7ZZUhQSIETQUDk2Fkcjpqizhs7sJinbWYcpiaEKv7PWYHLyIIH+RcYKv18hla EFHaOoUdRfzZsNSwNznnlCSCJOwkVMa1eJGJrEElzoktqPeDsforPFKhnQH+BFNV KE4BBACwsTltWOQUEjjKDXW28u7skuIT2jtGFc/bbzXcfg2bzTpoJlMNOBMdRDPD TVccJhAYj8kX9WJDSj+gluMvt319lLrAXjaroZHvHFqJQDxlqyR3mCkITjL09UF/ wVy3sF7wek8KlJthYSiBZT496o1MOsj5k+E8Y/vOHQbvg9uK0wARAQAB/gMDAmEI mZFRPn111gNki6npnVhXyDhv7FWJw/aLHkEISwmK4fDKOnx+Ueef64K5kZdUmnBC r9HEAUZA8mKuhWnpDTCLYZwaucqMjD0KyVJiApyGl9QHU41LDyfobDWn/LabKb6t 8uz6qkGzg87fYz8XLDgLvolImbTbeqQa9wuBRK9XfRLVgWv7qemNeDCSdLFEDA6W ENR+YjDJTZzZDlaH0yLMvudJO4lKnsS+5lhX69qeBJpfp+eMsPh/K8dCOi6mYuSP SF2JI7hVpk9PurDO1ne20mLuqZvmuDHcddWM88FjXotytDtuHScaX94+vVLXQAKz mROs4Z7GkNs2om03kWCqsGmAV1B0+bbmcxTH14/vwAFrYSJwcvHsaDhshcCoxJa8 pKxttlHlUYQ6YQZflIMnxvbZAIryDDK9kwut3GGStfoJXoi5jA8uh+WG+avn+iNI k8lR0SSgo6n5/vyWS6l/ZBbF1JwX6oQ4ep7piKUEGAEKAA8FAlNVKE4CGwwFCRLM AwAACgkQktgoBGO99PUaKAQAiK1zQQQIOVkqBa/E9Jx5UpCVF/fi0XsTfU2Y0Slg FV7j9Bqe0obycJ2LFRNDndVReJQQj5vpwZ/B5dAoUqaMXmAD3DD+7ZY756u+g0rU 21Z4Nf+we9PfyA5+lxw+6PXNpYcxvU9wXf+t5vvTLrdnVAdR0hSxKWdOCgIS1VlQ uxs= =NolW -----END PGP PRIVATE KEY BLOCK----- """ #------------ book_first = """ O there is blessing in this gentle breeze, A visitant that while it fans my cheek Doth seem half-conscious of the joy it brings From the green fields, and from yon azure sky. Whate'er its mission, the soft breeze can come To none more grateful than to me; escaped From the vast city, where I long had pined A discontented sojourner: now free, Free as a bird to settle where I will. """ #------------ passphrase = "lucy" km = null km_priv = null #------------ exports.load_pub = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : pub }, defer err, tmp, warnings km = tmp T.no_error err T.assert km?, "got a key manager back" cb() #------------ exports.load_priv = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : priv }, defer err, tmp, warnings km_priv = tmp T.no_error err throw err if err? T.assert km_priv, "got a private key manager back" cb() #------------ exports.unlock_priv = (T,cb) -> await km_priv.unlock_pgp { passphrase }, defer err T.no_error err cb() #------------ exports.merge = (T,cb) -> await km.merge_pgp_private { raw : priv }, defer err T.no_error err cb() #------------ exports.unlock_merged = (T,cb) -> await km.unlock_pgp { passphrase }, defer err T.no_error err cb() #------------ armored_sig = null armored_ctext = null exports.sign = (T,cb) -> sk = km.find_signing_pgp_key() T.assert not(sk?), "can't sign, don't have the right key!" cb() #------------ exports.encrypt = (T,cb) -> ek = km.find_crypt_pgp_key() await burn { msg : book_first, encryption_key : ek }, defer err, tmp armored_ctext = tmp T.no_error err cb() #------------ exports.decrypt = (T,cb) -> await do_message { armored : armored_ctext, keyfetch : km }, defer err, literals T.no_error err T.equal literals[0].toString(), book_first, "Book 1 of the prelude came back" T.assert not(literals[0].get_data_signer()?), "wasn't signed" cb() #------------
125434
{KeyManager} = require '../../lib/keymanager' {bufferify,ASP} = require '../../lib/util' {make_esc} = require 'iced-error' util = require 'util' {box} = require '../../lib/keybase/encode' {Encryptor} = require 'triplesec' {base91} = require '../../lib/basex' {burn} = require '../../lib/openpgp/burner' {do_message} = require '../../lib/openpgp/processor' #--------------------------------------------- pub = """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> -----END PGP PUBLIC KEY BLOCK----- """ #------------ # In this case, we have only 1 subkey for encryption, and no # subkeys for signing. Plus, we don't have an encrypted primary # key. So we shouldn't be able to sign. priv = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org <KEY> <KEY> -----END PGP PRIVATE KEY BLOCK----- """ #------------ book_first = """ O there is blessing in this gentle breeze, A visitant that while it fans my cheek Doth seem half-conscious of the joy it brings From the green fields, and from yon azure sky. Whate'er its mission, the soft breeze can come To none more grateful than to me; escaped From the vast city, where I long had pined A discontented sojourner: now free, Free as a bird to settle where I will. """ #------------ passphrase = "<PASSWORD>" km = null km_priv = null #------------ exports.load_pub = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : pub }, defer err, tmp, warnings km = tmp T.no_error err T.assert km?, "got a key manager back" cb() #------------ exports.load_priv = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : priv }, defer err, tmp, warnings km_priv = tmp T.no_error err throw err if err? T.assert km_priv, "got a private key manager back" cb() #------------ exports.unlock_priv = (T,cb) -> await km_priv.unlock_pgp { passphrase }, defer err T.no_error err cb() #------------ exports.merge = (T,cb) -> await km.merge_pgp_private { raw : priv }, defer err T.no_error err cb() #------------ exports.unlock_merged = (T,cb) -> await km.unlock_pgp { passphrase }, defer err T.no_error err cb() #------------ armored_sig = null armored_ctext = null exports.sign = (T,cb) -> sk = km.find_signing_pgp_key() T.assert not(sk?), "can't sign, don't have the right key!" cb() #------------ exports.encrypt = (T,cb) -> ek = km.find_crypt_pgp_key() await burn { msg : book_first, encryption_key : ek }, defer err, tmp armored_ctext = tmp T.no_error err cb() #------------ exports.decrypt = (T,cb) -> await do_message { armored : armored_ctext, keyfetch : km }, defer err, literals T.no_error err T.equal literals[0].toString(), book_first, "Book 1 of the prelude came back" T.assert not(literals[0].get_data_signer()?), "wasn't signed" cb() #------------
true
{KeyManager} = require '../../lib/keymanager' {bufferify,ASP} = require '../../lib/util' {make_esc} = require 'iced-error' util = require 'util' {box} = require '../../lib/keybase/encode' {Encryptor} = require 'triplesec' {base91} = require '../../lib/basex' {burn} = require '../../lib/openpgp/burner' {do_message} = require '../../lib/openpgp/processor' #--------------------------------------------- pub = """ -----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----- """ #------------ # In this case, we have only 1 subkey for encryption, and no # subkeys for signing. Plus, we don't have an encrypted primary # key. So we shouldn't be able to sign. priv = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2.0.22 (Darwin) Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI -----END PGP PRIVATE KEY BLOCK----- """ #------------ book_first = """ O there is blessing in this gentle breeze, A visitant that while it fans my cheek Doth seem half-conscious of the joy it brings From the green fields, and from yon azure sky. Whate'er its mission, the soft breeze can come To none more grateful than to me; escaped From the vast city, where I long had pined A discontented sojourner: now free, Free as a bird to settle where I will. """ #------------ passphrase = "PI:PASSWORD:<PASSWORD>END_PI" km = null km_priv = null #------------ exports.load_pub = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : pub }, defer err, tmp, warnings km = tmp T.no_error err T.assert km?, "got a key manager back" cb() #------------ exports.load_priv = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : priv }, defer err, tmp, warnings km_priv = tmp T.no_error err throw err if err? T.assert km_priv, "got a private key manager back" cb() #------------ exports.unlock_priv = (T,cb) -> await km_priv.unlock_pgp { passphrase }, defer err T.no_error err cb() #------------ exports.merge = (T,cb) -> await km.merge_pgp_private { raw : priv }, defer err T.no_error err cb() #------------ exports.unlock_merged = (T,cb) -> await km.unlock_pgp { passphrase }, defer err T.no_error err cb() #------------ armored_sig = null armored_ctext = null exports.sign = (T,cb) -> sk = km.find_signing_pgp_key() T.assert not(sk?), "can't sign, don't have the right key!" cb() #------------ exports.encrypt = (T,cb) -> ek = km.find_crypt_pgp_key() await burn { msg : book_first, encryption_key : ek }, defer err, tmp armored_ctext = tmp T.no_error err cb() #------------ exports.decrypt = (T,cb) -> await do_message { armored : armored_ctext, keyfetch : km }, defer err, literals T.no_error err T.equal literals[0].toString(), book_first, "Book 1 of the prelude came back" T.assert not(literals[0].get_data_signer()?), "wasn't signed" cb() #------------
[ { "context": "cription\n\nconfiguration = iceServers: [url: 'stun:23.21.150.121']\nconstraints = optional: [DtlsSrtpKeyAgreement: ", "end": 409, "score": 0.9984222650527954, "start": 396, "tag": "IP_ADDRESS", "value": "23.21.150.121" }, { "context": "->\n @isHost = yes\n host =...
app/src/web-rtc.coffee
jordao76/ultimate-tic-tac-toe
5
# coffeelint: disable=max_line_length RTCPeerConnection = window.RTCPeerConnection or window.mozRTCPeerConnection or window.webkitRTCPeerConnection or window.msRTCPeerConnection RTCSessionDescription = window.RTCSessionDescription or window.mozRTCSessionDescription or window.webkitRTCSessionDescription or window.msRTCSessionDescription configuration = iceServers: [url: 'stun:23.21.150.121'] constraints = optional: [DtlsSrtpKeyAgreement: true] class Host constructor: -> @peerConnection = new RTCPeerConnection configuration, constraints @dataChannel = null @peerConnection.onicecandidate = (e) => if e.candidate is null @onoffercreated JSON.stringify @peerConnection.localDescription setupDataChannel: -> @dataChannel = @peerConnection.createDataChannel 'data', reliable: true @dataChannel.onopen = => @peerConnection.oniceconnectionstatechange = => if @peerConnection.iceConnectionState is 'disconnected' @ondisconnected?() @onchannelopen() @dataChannel.onmessage = (e) => @onmessage JSON.parse e.data createOffer: -> @setupDataChannel() # note: it's important to create the data channel before creating the offer @peerConnection.createOffer ((offerDesc) => @peerConnection.setLocalDescription offerDesc), -> console.warn "Couldn't create offer" acceptAnswer: (answerJSON) -> @peerConnection.setRemoteDescription new RTCSessionDescription JSON.parse answerJSON send: (data) -> @dataChannel.send JSON.stringify data class Guest constructor: -> @peerConnection = new RTCPeerConnection configuration, constraints @dataChannel = null @peerConnection.onicecandidate = (e) => if e.candidate is null @onanswercreated JSON.stringify @peerConnection.localDescription @peerConnection.ondatachannel = (e) => @dataChannel = e.channel or e @dataChannel.onopen = => @peerConnection.oniceconnectionstatechange = => if @peerConnection.iceConnectionState is 'disconnected' @ondisconnected?() @onchannelopen() @dataChannel.onmessage = (e) => @onmessage JSON.parse e.data offer: (offerJSON) -> @peerConnection.setRemoteDescription new RTCSessionDescription JSON.parse offerJSON @peerConnection.createAnswer ((answerDesc) => @peerConnection.setLocalDescription answerDesc), -> console.warn "Couldn't create answer" send: (data) -> @dataChannel.send JSON.stringify data module.exports = {Host, Guest} # WebRTC with Firebase as a signaling service RTC = greet: -> window.RTC = RTC console.log 'To play with a remote peer, start a match with %cRTC.host()', 'background: #222; color: #bada55' host: -> @isHost = yes host = new Host key = Math.random()*99999+10000|0 gameRef = new Firebase 'https://ut3.firebaseio.com/' + key host.onoffercreated = (offerJSON) -> gameRef.onDisconnect().remove() gameRef.set offer: JSON.parse offerJSON window.location.hash = key console.log 'Give this URL to the other player:' console.log window.location.href gameRef.on 'value', (snap) -> data = snap.val() return unless data?.answer? host.acceptAnswer JSON.stringify data.answer host.ondisconnected = -> console.log 'peer disconnected!' window.location.hash = '' RTC.ondisconnected?() host.onchannelopen = -> console.log 'channel open' RTC.send = (m) -> host.send m gameRef.off 'value' RTC.ondatachannelopen?() host.onmessage = (data) -> console.log 'HOST: got data', data RTC.onmessage? data host.createOffer() guest: -> hash = window.location.hash return unless hash @isGuest = yes gameRef = new Firebase 'https://ut3.firebaseio.com/' + hash.substring 1 guest = new Guest guest.onanswercreated = (answerJSON) -> gameRef.update answer: JSON.parse answerJSON guest.ondisconnected = -> console.log 'peer disconnected!' window.location.hash = '' RTC.ondisconnected?() guest.onchannelopen = -> console.log 'channel open' RTC.send = (m) -> guest.send m RTC.ondatachannelopen?() guest.onmessage = (data) -> console.log 'GUEST: got data', data RTC.onmessage? data gameRef.once 'value', (snap) -> data = snap.val() if data?.offer? guest.offer JSON.stringify data.offer else console.log 'HOST offer not found for game ' + hash window.location.hash = '' jQuery -> RTC.guest() module.exports.RTC = RTC
22994
# coffeelint: disable=max_line_length RTCPeerConnection = window.RTCPeerConnection or window.mozRTCPeerConnection or window.webkitRTCPeerConnection or window.msRTCPeerConnection RTCSessionDescription = window.RTCSessionDescription or window.mozRTCSessionDescription or window.webkitRTCSessionDescription or window.msRTCSessionDescription configuration = iceServers: [url: 'stun:172.16.31.10'] constraints = optional: [DtlsSrtpKeyAgreement: true] class Host constructor: -> @peerConnection = new RTCPeerConnection configuration, constraints @dataChannel = null @peerConnection.onicecandidate = (e) => if e.candidate is null @onoffercreated JSON.stringify @peerConnection.localDescription setupDataChannel: -> @dataChannel = @peerConnection.createDataChannel 'data', reliable: true @dataChannel.onopen = => @peerConnection.oniceconnectionstatechange = => if @peerConnection.iceConnectionState is 'disconnected' @ondisconnected?() @onchannelopen() @dataChannel.onmessage = (e) => @onmessage JSON.parse e.data createOffer: -> @setupDataChannel() # note: it's important to create the data channel before creating the offer @peerConnection.createOffer ((offerDesc) => @peerConnection.setLocalDescription offerDesc), -> console.warn "Couldn't create offer" acceptAnswer: (answerJSON) -> @peerConnection.setRemoteDescription new RTCSessionDescription JSON.parse answerJSON send: (data) -> @dataChannel.send JSON.stringify data class Guest constructor: -> @peerConnection = new RTCPeerConnection configuration, constraints @dataChannel = null @peerConnection.onicecandidate = (e) => if e.candidate is null @onanswercreated JSON.stringify @peerConnection.localDescription @peerConnection.ondatachannel = (e) => @dataChannel = e.channel or e @dataChannel.onopen = => @peerConnection.oniceconnectionstatechange = => if @peerConnection.iceConnectionState is 'disconnected' @ondisconnected?() @onchannelopen() @dataChannel.onmessage = (e) => @onmessage JSON.parse e.data offer: (offerJSON) -> @peerConnection.setRemoteDescription new RTCSessionDescription JSON.parse offerJSON @peerConnection.createAnswer ((answerDesc) => @peerConnection.setLocalDescription answerDesc), -> console.warn "Couldn't create answer" send: (data) -> @dataChannel.send JSON.stringify data module.exports = {Host, Guest} # WebRTC with Firebase as a signaling service RTC = greet: -> window.RTC = RTC console.log 'To play with a remote peer, start a match with %cRTC.host()', 'background: #222; color: #bada55' host: -> @isHost = yes host = new Host key = <KEY> gameRef = new Firebase 'https://ut3.firebaseio.com/' + key host.onoffercreated = (offerJSON) -> gameRef.onDisconnect().remove() gameRef.set offer: JSON.parse offerJSON window.location.hash = key console.log 'Give this URL to the other player:' console.log window.location.href gameRef.on 'value', (snap) -> data = snap.val() return unless data?.answer? host.acceptAnswer JSON.stringify data.answer host.ondisconnected = -> console.log 'peer disconnected!' window.location.hash = '' RTC.ondisconnected?() host.onchannelopen = -> console.log 'channel open' RTC.send = (m) -> host.send m gameRef.off 'value' RTC.ondatachannelopen?() host.onmessage = (data) -> console.log 'HOST: got data', data RTC.onmessage? data host.createOffer() guest: -> hash = window.location.hash return unless hash @isGuest = yes gameRef = new Firebase 'https://ut3.firebaseio.com/' + hash.substring 1 guest = new Guest guest.onanswercreated = (answerJSON) -> gameRef.update answer: JSON.parse answerJSON guest.ondisconnected = -> console.log 'peer disconnected!' window.location.hash = '' RTC.ondisconnected?() guest.onchannelopen = -> console.log 'channel open' RTC.send = (m) -> guest.send m RTC.ondatachannelopen?() guest.onmessage = (data) -> console.log 'GUEST: got data', data RTC.onmessage? data gameRef.once 'value', (snap) -> data = snap.val() if data?.offer? guest.offer JSON.stringify data.offer else console.log 'HOST offer not found for game ' + hash window.location.hash = '' jQuery -> RTC.guest() module.exports.RTC = RTC
true
# coffeelint: disable=max_line_length RTCPeerConnection = window.RTCPeerConnection or window.mozRTCPeerConnection or window.webkitRTCPeerConnection or window.msRTCPeerConnection RTCSessionDescription = window.RTCSessionDescription or window.mozRTCSessionDescription or window.webkitRTCSessionDescription or window.msRTCSessionDescription configuration = iceServers: [url: 'stun:PI:IP_ADDRESS:172.16.31.10END_PI'] constraints = optional: [DtlsSrtpKeyAgreement: true] class Host constructor: -> @peerConnection = new RTCPeerConnection configuration, constraints @dataChannel = null @peerConnection.onicecandidate = (e) => if e.candidate is null @onoffercreated JSON.stringify @peerConnection.localDescription setupDataChannel: -> @dataChannel = @peerConnection.createDataChannel 'data', reliable: true @dataChannel.onopen = => @peerConnection.oniceconnectionstatechange = => if @peerConnection.iceConnectionState is 'disconnected' @ondisconnected?() @onchannelopen() @dataChannel.onmessage = (e) => @onmessage JSON.parse e.data createOffer: -> @setupDataChannel() # note: it's important to create the data channel before creating the offer @peerConnection.createOffer ((offerDesc) => @peerConnection.setLocalDescription offerDesc), -> console.warn "Couldn't create offer" acceptAnswer: (answerJSON) -> @peerConnection.setRemoteDescription new RTCSessionDescription JSON.parse answerJSON send: (data) -> @dataChannel.send JSON.stringify data class Guest constructor: -> @peerConnection = new RTCPeerConnection configuration, constraints @dataChannel = null @peerConnection.onicecandidate = (e) => if e.candidate is null @onanswercreated JSON.stringify @peerConnection.localDescription @peerConnection.ondatachannel = (e) => @dataChannel = e.channel or e @dataChannel.onopen = => @peerConnection.oniceconnectionstatechange = => if @peerConnection.iceConnectionState is 'disconnected' @ondisconnected?() @onchannelopen() @dataChannel.onmessage = (e) => @onmessage JSON.parse e.data offer: (offerJSON) -> @peerConnection.setRemoteDescription new RTCSessionDescription JSON.parse offerJSON @peerConnection.createAnswer ((answerDesc) => @peerConnection.setLocalDescription answerDesc), -> console.warn "Couldn't create answer" send: (data) -> @dataChannel.send JSON.stringify data module.exports = {Host, Guest} # WebRTC with Firebase as a signaling service RTC = greet: -> window.RTC = RTC console.log 'To play with a remote peer, start a match with %cRTC.host()', 'background: #222; color: #bada55' host: -> @isHost = yes host = new Host key = PI:KEY:<KEY>END_PI gameRef = new Firebase 'https://ut3.firebaseio.com/' + key host.onoffercreated = (offerJSON) -> gameRef.onDisconnect().remove() gameRef.set offer: JSON.parse offerJSON window.location.hash = key console.log 'Give this URL to the other player:' console.log window.location.href gameRef.on 'value', (snap) -> data = snap.val() return unless data?.answer? host.acceptAnswer JSON.stringify data.answer host.ondisconnected = -> console.log 'peer disconnected!' window.location.hash = '' RTC.ondisconnected?() host.onchannelopen = -> console.log 'channel open' RTC.send = (m) -> host.send m gameRef.off 'value' RTC.ondatachannelopen?() host.onmessage = (data) -> console.log 'HOST: got data', data RTC.onmessage? data host.createOffer() guest: -> hash = window.location.hash return unless hash @isGuest = yes gameRef = new Firebase 'https://ut3.firebaseio.com/' + hash.substring 1 guest = new Guest guest.onanswercreated = (answerJSON) -> gameRef.update answer: JSON.parse answerJSON guest.ondisconnected = -> console.log 'peer disconnected!' window.location.hash = '' RTC.ondisconnected?() guest.onchannelopen = -> console.log 'channel open' RTC.send = (m) -> guest.send m RTC.ondatachannelopen?() guest.onmessage = (data) -> console.log 'GUEST: got data', data RTC.onmessage? data gameRef.once 'value', (snap) -> data = snap.val() if data?.offer? guest.offer JSON.stringify data.offer else console.log 'HOST offer not found for game ' + hash window.location.hash = '' jQuery -> RTC.guest() module.exports.RTC = RTC
[ { "context": "key: 'test'\n\npatterns: [\n 'foo'\n 'bar'\n]\n", "end": 10, "score": 0.5823095440864563, "start": 6, "tag": "KEY", "value": "test" } ]
spec/fixtures/grammars/sample01.cson
andrewcarver/atom-language-asciidoc
45
key: 'test' patterns: [ 'foo' 'bar' ]
45016
key: '<KEY>' patterns: [ 'foo' 'bar' ]
true
key: 'PI:KEY:<KEY>END_PI' patterns: [ 'foo' 'bar' ]
[ { "context": "rate(-1, false)\n\n # adef = {\n # 'key1': 'value1',\n # 'key2': 'value2'\n # }\n # aover ={\n # ", "end": 16986, "score": 0.5134392380714417, "start": 16985, "tag": "KEY", "value": "1" }, { "context": "f = {\n # 'key1': 'value1',\n # 'key2': 'value2'\n...
src/main.coffee
jitta/Natural-Language-Generation
58
###* * Natural Language base class * ------------------------------------------------------------ * @name NaturalLanguage * * @constructor * @param {Array} data - a list of inputs ### exports.NaturalLanguage = class NaturalLanguage ###* * ------------------------------------------------------------ * Prepare resource * ------------------------------------------------------------ ### global = null _ = require "underscore" config = require "./../resources/config.json" sentences = require "./../resources/sentences.json" constructor: (data) -> @data = data @dataConfig = {} @sentenceConfig = {} @random = true global = @ ###* * ------------------------------------------------------------ * HELPER FUNCTION * ------------------------------------------------------------ ### ###* * Change the first character of the string to capital * ------------------------------------------------------------ * @name capitalize * @param {string} data * @return {string} capitalized string ### capitalize = (data) -> data.charAt(0).toUpperCase() + data.slice 1 ###* * Replace sentence pattern with string in data object * (single sentence, no capitalization or full stop) * ------------------------------------------------------------ * @name replaceStr * @param {array} patterns - array of sentences * @param {object} data - displayInfo object * @return {string} final sentence ### replaceStr = (patterns, data) -> if global.random pattern = _.sample patterns else pattern = patterns[0] _.each data, (item, key) -> pattern = pattern.replace "{#{key}}", item pattern ###* * Replace sentence pattern with string in data object * (combined sentence, with capitalization and full stop) * ------------------------------------------------------------ * @name replaceCombinedStr * @param {array} patterns - array of sentences * @param {array} data - array of displayInfo object * @return {string} final sentence ### replaceCombinedStr = (patterns, data) -> if global.random pattern = _.sample patterns else pattern = patterns[0] _.each data, (items, i) -> _.each items, (item, key) -> pattern = pattern.replace "{#{key}.#{i}}", items[key] pattern ###* * ------------------------------------------------------------ * METHOD LIST * ------------------------------------------------------------ ### ###* * Add more required attributes * ------------------------------------------------------------ * @name setAttrs * @param {array} data - array of inputs * @return {Object} new data with more attributes * @private ### setAttrs = (data) -> _.each data, (item, i) -> if item.options isnt undefined # item.options = _.extend _.clone(config.default), item.options item.options = _.defaults(item.options, config.default); else item.options = { "priority": { "init": 1, "negativeFactor": 20, "positiveFactor": 100 }, "level": { "threshold": 0.09, "sensitiveness": 1 } } item.dataType = "default" unless item.dataType # Custom for more attributes if global.dataConfig[item.dataType] and global.dataConfig[item.dataType].setAttrs item = global.dataConfig[item.dataType].setAttrs item # Default attributes item.alwaysShow = false if typeof item.alwaysShow is "undefined" item.contentGroup = "default" unless item.contentGroup item.sentenceType = "default" unless item.sentenceType item.precision = 0 unless item.precision != "undefined" item.difference = getDifference item item.displayInfo = getDisplayInfo item item.priority = calculatePriority item item.level = calculateLevel item item.levelType = calculateType item.level data ###* * Get the difference between old value and current value * ------------------------------------------------------------ * @name getDifference * @param {object} data * @return {number/string} difference value or 'na' if there is no oldData * @private ### getDifference = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].getDifference return global.dataConfig[data.dataType].getDifference data # Default if typeof data.oldData isnt "undefined" and typeof data.oldData == "number" data.newData - data.oldData else "na" ###* * Prepare strings required to show in the sentence * ------------------------------------------------------------ * @name getDisplayInfo * @param {object} data * @return {object} information required to display in the sentence * @private ### getDisplayInfo = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].getDisplayInfo return global.dataConfig[data.dataType].getDisplayInfo data # Default result = {} result.title = data.title.toLowerCase() if typeof data.oldData isnt "undefined" if typeof data.oldData == "number" result.oldData = data.oldData.toFixed data.precision else result.oldData = data.oldData.toLowerCase() if typeof data.difference == "number" result.difference = Math.abs(data.difference).toFixed data.precision if typeof data.newData == "number" result.newData = data.newData.toFixed(data.precision) else result.newData = data.newData.toLowerCase() result ###* * Calculate the priority of change * ------------------------------------------------------------ * @name calculatePriority * @param {object} data * @return {number} new priority * @private ### calculatePriority = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].calculatePriority return global.dataConfig[data.dataType].calculatePriority data # Default priorityConfig = data.options.priority if data.difference is "na" return priorityConfig.init else if data.difference > 0 newPriority = priorityConfig.init + (priorityConfig.positiveFactor * data.difference) else newPriority = priorityConfig.init + (priorityConfig.negativeFactor * Math.abs(data.difference)) parseInt newPriority.toFixed(0), 10 ###* * Calculate the intesity of change * ------------------------------------------------------------ * @name calculateLevel * @param {object} data * @return {number} intensity of the change * @private ### calculateLevel = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].calculateLevel return global.dataConfig[data.dataType] .calculateLevel data.difference, data.options.level # Default levelConfig = data.options.level if data.difference is "na" level = "na" else absoluteDifference = Math.abs data.difference if absoluteDifference < levelConfig.threshold level = 0 else level = Math.ceil data.difference / levelConfig.sensitiveness level = 3 if level > 3 level = -3 if level < -3 level ###* * Calculate the type of intesity * ------------------------------------------------------------ * @name calculateType * @param {number} level * @return {string} levelType * @private ### calculateType = (level) -> if level > 0 "positive" else if level < 0 "negative" else if level is "na" "na" else "neutral" ###* * Select number of data to display and sort by priority * ------------------------------------------------------------ * @name selectData * @param {array} data - array of data split into two groups: alwaysShow and sortedData * @param {number} nData - number of data to show * @return {array} selected, sorted data by priority * @private ### selectData = (data, nData) -> groupedData = groupData data result = groupedData.alwaysShow if(nData == -1) return result.concat groupedData.sortedData if result.length < nData nRemaining = nData - result.length result = result.concat groupedData.sortedData.slice( 0, nRemaining ) result.sort (a, b) -> b.priority - a.priority result ###* * Group data by alwaysShow attr and sort the group by priority * ------------------------------------------------------------ * @name groupData * @param {array} data - array of data * @return {array} data split into two groups, alwaysShow and sortedData * @private ### groupData = (data) -> # Remove hidden items data = _.filter data, (item) -> ! item.hidden data = _.groupBy data, "alwaysShow" data.sortedData = [] data.alwaysShow = [] if data[false] data[false].sort (a, b) -> b.priority - a.priority data.sortedData = data[false] data.alwaysShow = data[true] if data[true] data ###* * Get a valid list of sentences for random selecting * ------------------------------------------------------------ * @name getSimpleSentenceList * @param {object} data - data object * @param {array} simpleSentences - sentences from all types * @return {array} array of valid sentences * @private ### getSimpleSentenceList = (data, simpleSentencese) -> # Override if global.sentenceConfig[data.sentenceType] \ and global.sentenceConfig[data.sentenceType].getSimpleSentenceList return global.sentenceConfig[data.sentenceType] .getSimpleSentenceList data, simpleSentencese # Default if typeof data.oldData is "undefined" # No oldData if typeof sentences.simpleSentences[data.sentenceType] isnt "undefined" \ and typeof sentences.simpleSentences[data.sentenceType]["na"] isnt "undefined" sentences.simpleSentences[data.sentenceType]["na"] else sentences.simpleSentences["default"]["na"] else if typeof sentences.simpleSentences[data.sentenceType] isnt "undefined" \ and typeof sentences.simpleSentences[data.sentenceType][data.levelType] isnt "undefined" if typeof sentences.simpleSentences[data.sentenceType][data.levelType][data.level.toString()] isnt "undefined" sentences.simpleSentences[ data.sentenceType ][ data.levelType ][ data.level.toString() ] else sentences.simpleSentences[ data.sentenceType ][ data.levelType ] else sentences.simpleSentences["default"][ data.levelType ][ data.level.toString() ] ###* * Group data into contentGroups and loop through each * contentGroup to create sentence(s) * ------------------------------------------------------------ * @name buildSimpleSentence * @param {object} data - data object * @return {array} array of sentences * @private ### buildSimpleSentence = (data) -> simpleSentences = getSimpleSentenceList data, sentences.simpleSentences replaceStr simpleSentences, data.displayInfo ###* * Add simple sentence into the data object * ------------------------------------------------------------ * @name addSimpleSentence * @param {array} array of data to generate simple sentences * @return {array} array of data with sentence attribute inserted * @private ### addSimpleSentence = (data) -> for i of data data[i].displayInfo.sentence = buildSimpleSentence(data[i]) data ###* * Get a valid list of compound sentences * ------------------------------------------------------------ * @name getCompoundSentenceList * @param {object} data - data object * @param {array} compoundSentences - sentences from all types * @return {array} array of valid sentences * @private ### getCompoundSentenceList = (data, compoundSentences) -> # Override if(global.sentenceConfig[data.sentenceType] && global.sentenceConfig[data.sentenceType].getCompoundSentenceList) return global.sentenceConfig[data.sentenceType].getCompoundSentenceList(data, compoundSentences) # Default if sentences.compoundSentences[data.sentenceType] isnt undefined compoundSentences[data[0].sentenceType] else compoundSentences.default ###* * Combine two simple sentencese that are in the same sentenceGroup * ------------------------------------------------------------ * @name buildCompoundSentence * @param {array} array of one or two data objects to combine * @return {string} a combine sentence * @private ### buildCompoundSentence = (data) -> types = _.pluck data, "levelType" type = types.join "_" moreDisplayInfo = _.pluck addSimpleSentence(data), "displayInfo" compoundSentences = getCompoundSentenceList data, sentences.compoundSentences selectedSentences = _.find compoundSentences, (group) -> _.contains(group.type, type); capitalize replaceCombinedStr( selectedSentences.sentences, moreDisplayInfo ) ###* * Group data into contentGroups and loop through each * contentGroup to create sentence(s) * ------------------------------------------------------------ * @name buildSentences * @param {array} data - array sorted by priority but not grouped * @return {array} array of sentences * @private ### buildSentences = (data) -> result = [] data = _.groupBy data, "contentGroup" # for group of data _.each data, (group) -> if group.length > 2 i = 0 while i < group.length if i + 1 is group.length result.push buildCompoundSentence [ group[i] ] else result.push buildCompoundSentence [ group[i], group[parseInt(i)+1] ] i = i + 2 else result.push buildCompoundSentence group result addType: (title, func = {}) -> if @dataConfig[title] @dataConfig[title] = _.extend(@dataConfig[title], func) else @dataConfig[title] = func addSentence: (title, func = null) -> if @sentenceConfig[title] @sentenceConfig[title] = _.extend(@sentenceConfig[title], func) else @sentenceConfig[title] = func ###* * Generate sentences from a list of data * ------------------------------------------------------------ * @name NaturalLanguage.generate * @param {number} nData - number of sentences to generate * @return {String/Number/Object/Function/Boolean} desc * @public ### generate: (nData = -1, random = true) -> @random = random data = setAttrs @data data = selectData data, nData result = buildSentences data # return data # for i of data # console.log data[i].title, ": ", data[i].priority return result.join " " debug: (nData = -1, random = true) -> @random = random return setAttrs @data data = setAttrs @data data = selectData data, nData result = buildSentences data # signType = { # words: { # "Debt Level": { # "-": "0", # "Low .*": "+1", # "No .*": "+2", # "High .* in the past 5 years": "-1", # "High .*": "-2", # "Very High .*": "-3" # }, # "Share Repurchase": { # "-": "0", # "Every year": "+2" # }, # "CapEx": { # "-": "0", # "Very Low": "+2", # "Very High": "-2" # } # }, # setAttrs: (data) -> # data.newScore = @getScore(data.title, data.newData) # if(typeof data.oldData != "undefined") # data.oldScore = @getScore(data.title, data.oldData) # if(data.newScore == '0') # data.hidden = true # data # getDisplayInfo: (data) -> # precision = data.precision # result = {} # result.title = data.title.toLowerCase() # result.title = "CapEx" if data.title == "CapEx" # result.newData = data.newData.toLowerCase() # if(typeof data.oldData != "undefined") # result.oldData = data.oldData.toLowerCase() # result # getScore: (title, data) -> # for item of @words[title] # pattern = new RegExp(item, "g"); # if pattern.test(data) # return @words[title][item] # return null # getDifference: (data) -> # if(typeof data.oldData != "undefined") # parseInt(data.newScore) - parseInt(data.oldScore) # else # "na" # } # # String with custom functions # NL = new NaturalLanguage [{ # "title": "Share Repurchase", # "oldData": "-", # "newData": "Every year", # "dataType": "sign" # }] # NL.addType "sign", signType # # String with custom functions + oldData # console.log NL.generate(-1, false) # adef = { # 'key1': 'value1', # 'key2': 'value2' # } # aover ={ # 'key1': 'value1override', # 'key3': 'value3' # } # console.log _.extend(adef, aover) # console.log adef # console.log aover
88778
###* * Natural Language base class * ------------------------------------------------------------ * @name NaturalLanguage * * @constructor * @param {Array} data - a list of inputs ### exports.NaturalLanguage = class NaturalLanguage ###* * ------------------------------------------------------------ * Prepare resource * ------------------------------------------------------------ ### global = null _ = require "underscore" config = require "./../resources/config.json" sentences = require "./../resources/sentences.json" constructor: (data) -> @data = data @dataConfig = {} @sentenceConfig = {} @random = true global = @ ###* * ------------------------------------------------------------ * HELPER FUNCTION * ------------------------------------------------------------ ### ###* * Change the first character of the string to capital * ------------------------------------------------------------ * @name capitalize * @param {string} data * @return {string} capitalized string ### capitalize = (data) -> data.charAt(0).toUpperCase() + data.slice 1 ###* * Replace sentence pattern with string in data object * (single sentence, no capitalization or full stop) * ------------------------------------------------------------ * @name replaceStr * @param {array} patterns - array of sentences * @param {object} data - displayInfo object * @return {string} final sentence ### replaceStr = (patterns, data) -> if global.random pattern = _.sample patterns else pattern = patterns[0] _.each data, (item, key) -> pattern = pattern.replace "{#{key}}", item pattern ###* * Replace sentence pattern with string in data object * (combined sentence, with capitalization and full stop) * ------------------------------------------------------------ * @name replaceCombinedStr * @param {array} patterns - array of sentences * @param {array} data - array of displayInfo object * @return {string} final sentence ### replaceCombinedStr = (patterns, data) -> if global.random pattern = _.sample patterns else pattern = patterns[0] _.each data, (items, i) -> _.each items, (item, key) -> pattern = pattern.replace "{#{key}.#{i}}", items[key] pattern ###* * ------------------------------------------------------------ * METHOD LIST * ------------------------------------------------------------ ### ###* * Add more required attributes * ------------------------------------------------------------ * @name setAttrs * @param {array} data - array of inputs * @return {Object} new data with more attributes * @private ### setAttrs = (data) -> _.each data, (item, i) -> if item.options isnt undefined # item.options = _.extend _.clone(config.default), item.options item.options = _.defaults(item.options, config.default); else item.options = { "priority": { "init": 1, "negativeFactor": 20, "positiveFactor": 100 }, "level": { "threshold": 0.09, "sensitiveness": 1 } } item.dataType = "default" unless item.dataType # Custom for more attributes if global.dataConfig[item.dataType] and global.dataConfig[item.dataType].setAttrs item = global.dataConfig[item.dataType].setAttrs item # Default attributes item.alwaysShow = false if typeof item.alwaysShow is "undefined" item.contentGroup = "default" unless item.contentGroup item.sentenceType = "default" unless item.sentenceType item.precision = 0 unless item.precision != "undefined" item.difference = getDifference item item.displayInfo = getDisplayInfo item item.priority = calculatePriority item item.level = calculateLevel item item.levelType = calculateType item.level data ###* * Get the difference between old value and current value * ------------------------------------------------------------ * @name getDifference * @param {object} data * @return {number/string} difference value or 'na' if there is no oldData * @private ### getDifference = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].getDifference return global.dataConfig[data.dataType].getDifference data # Default if typeof data.oldData isnt "undefined" and typeof data.oldData == "number" data.newData - data.oldData else "na" ###* * Prepare strings required to show in the sentence * ------------------------------------------------------------ * @name getDisplayInfo * @param {object} data * @return {object} information required to display in the sentence * @private ### getDisplayInfo = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].getDisplayInfo return global.dataConfig[data.dataType].getDisplayInfo data # Default result = {} result.title = data.title.toLowerCase() if typeof data.oldData isnt "undefined" if typeof data.oldData == "number" result.oldData = data.oldData.toFixed data.precision else result.oldData = data.oldData.toLowerCase() if typeof data.difference == "number" result.difference = Math.abs(data.difference).toFixed data.precision if typeof data.newData == "number" result.newData = data.newData.toFixed(data.precision) else result.newData = data.newData.toLowerCase() result ###* * Calculate the priority of change * ------------------------------------------------------------ * @name calculatePriority * @param {object} data * @return {number} new priority * @private ### calculatePriority = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].calculatePriority return global.dataConfig[data.dataType].calculatePriority data # Default priorityConfig = data.options.priority if data.difference is "na" return priorityConfig.init else if data.difference > 0 newPriority = priorityConfig.init + (priorityConfig.positiveFactor * data.difference) else newPriority = priorityConfig.init + (priorityConfig.negativeFactor * Math.abs(data.difference)) parseInt newPriority.toFixed(0), 10 ###* * Calculate the intesity of change * ------------------------------------------------------------ * @name calculateLevel * @param {object} data * @return {number} intensity of the change * @private ### calculateLevel = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].calculateLevel return global.dataConfig[data.dataType] .calculateLevel data.difference, data.options.level # Default levelConfig = data.options.level if data.difference is "na" level = "na" else absoluteDifference = Math.abs data.difference if absoluteDifference < levelConfig.threshold level = 0 else level = Math.ceil data.difference / levelConfig.sensitiveness level = 3 if level > 3 level = -3 if level < -3 level ###* * Calculate the type of intesity * ------------------------------------------------------------ * @name calculateType * @param {number} level * @return {string} levelType * @private ### calculateType = (level) -> if level > 0 "positive" else if level < 0 "negative" else if level is "na" "na" else "neutral" ###* * Select number of data to display and sort by priority * ------------------------------------------------------------ * @name selectData * @param {array} data - array of data split into two groups: alwaysShow and sortedData * @param {number} nData - number of data to show * @return {array} selected, sorted data by priority * @private ### selectData = (data, nData) -> groupedData = groupData data result = groupedData.alwaysShow if(nData == -1) return result.concat groupedData.sortedData if result.length < nData nRemaining = nData - result.length result = result.concat groupedData.sortedData.slice( 0, nRemaining ) result.sort (a, b) -> b.priority - a.priority result ###* * Group data by alwaysShow attr and sort the group by priority * ------------------------------------------------------------ * @name groupData * @param {array} data - array of data * @return {array} data split into two groups, alwaysShow and sortedData * @private ### groupData = (data) -> # Remove hidden items data = _.filter data, (item) -> ! item.hidden data = _.groupBy data, "alwaysShow" data.sortedData = [] data.alwaysShow = [] if data[false] data[false].sort (a, b) -> b.priority - a.priority data.sortedData = data[false] data.alwaysShow = data[true] if data[true] data ###* * Get a valid list of sentences for random selecting * ------------------------------------------------------------ * @name getSimpleSentenceList * @param {object} data - data object * @param {array} simpleSentences - sentences from all types * @return {array} array of valid sentences * @private ### getSimpleSentenceList = (data, simpleSentencese) -> # Override if global.sentenceConfig[data.sentenceType] \ and global.sentenceConfig[data.sentenceType].getSimpleSentenceList return global.sentenceConfig[data.sentenceType] .getSimpleSentenceList data, simpleSentencese # Default if typeof data.oldData is "undefined" # No oldData if typeof sentences.simpleSentences[data.sentenceType] isnt "undefined" \ and typeof sentences.simpleSentences[data.sentenceType]["na"] isnt "undefined" sentences.simpleSentences[data.sentenceType]["na"] else sentences.simpleSentences["default"]["na"] else if typeof sentences.simpleSentences[data.sentenceType] isnt "undefined" \ and typeof sentences.simpleSentences[data.sentenceType][data.levelType] isnt "undefined" if typeof sentences.simpleSentences[data.sentenceType][data.levelType][data.level.toString()] isnt "undefined" sentences.simpleSentences[ data.sentenceType ][ data.levelType ][ data.level.toString() ] else sentences.simpleSentences[ data.sentenceType ][ data.levelType ] else sentences.simpleSentences["default"][ data.levelType ][ data.level.toString() ] ###* * Group data into contentGroups and loop through each * contentGroup to create sentence(s) * ------------------------------------------------------------ * @name buildSimpleSentence * @param {object} data - data object * @return {array} array of sentences * @private ### buildSimpleSentence = (data) -> simpleSentences = getSimpleSentenceList data, sentences.simpleSentences replaceStr simpleSentences, data.displayInfo ###* * Add simple sentence into the data object * ------------------------------------------------------------ * @name addSimpleSentence * @param {array} array of data to generate simple sentences * @return {array} array of data with sentence attribute inserted * @private ### addSimpleSentence = (data) -> for i of data data[i].displayInfo.sentence = buildSimpleSentence(data[i]) data ###* * Get a valid list of compound sentences * ------------------------------------------------------------ * @name getCompoundSentenceList * @param {object} data - data object * @param {array} compoundSentences - sentences from all types * @return {array} array of valid sentences * @private ### getCompoundSentenceList = (data, compoundSentences) -> # Override if(global.sentenceConfig[data.sentenceType] && global.sentenceConfig[data.sentenceType].getCompoundSentenceList) return global.sentenceConfig[data.sentenceType].getCompoundSentenceList(data, compoundSentences) # Default if sentences.compoundSentences[data.sentenceType] isnt undefined compoundSentences[data[0].sentenceType] else compoundSentences.default ###* * Combine two simple sentencese that are in the same sentenceGroup * ------------------------------------------------------------ * @name buildCompoundSentence * @param {array} array of one or two data objects to combine * @return {string} a combine sentence * @private ### buildCompoundSentence = (data) -> types = _.pluck data, "levelType" type = types.join "_" moreDisplayInfo = _.pluck addSimpleSentence(data), "displayInfo" compoundSentences = getCompoundSentenceList data, sentences.compoundSentences selectedSentences = _.find compoundSentences, (group) -> _.contains(group.type, type); capitalize replaceCombinedStr( selectedSentences.sentences, moreDisplayInfo ) ###* * Group data into contentGroups and loop through each * contentGroup to create sentence(s) * ------------------------------------------------------------ * @name buildSentences * @param {array} data - array sorted by priority but not grouped * @return {array} array of sentences * @private ### buildSentences = (data) -> result = [] data = _.groupBy data, "contentGroup" # for group of data _.each data, (group) -> if group.length > 2 i = 0 while i < group.length if i + 1 is group.length result.push buildCompoundSentence [ group[i] ] else result.push buildCompoundSentence [ group[i], group[parseInt(i)+1] ] i = i + 2 else result.push buildCompoundSentence group result addType: (title, func = {}) -> if @dataConfig[title] @dataConfig[title] = _.extend(@dataConfig[title], func) else @dataConfig[title] = func addSentence: (title, func = null) -> if @sentenceConfig[title] @sentenceConfig[title] = _.extend(@sentenceConfig[title], func) else @sentenceConfig[title] = func ###* * Generate sentences from a list of data * ------------------------------------------------------------ * @name NaturalLanguage.generate * @param {number} nData - number of sentences to generate * @return {String/Number/Object/Function/Boolean} desc * @public ### generate: (nData = -1, random = true) -> @random = random data = setAttrs @data data = selectData data, nData result = buildSentences data # return data # for i of data # console.log data[i].title, ": ", data[i].priority return result.join " " debug: (nData = -1, random = true) -> @random = random return setAttrs @data data = setAttrs @data data = selectData data, nData result = buildSentences data # signType = { # words: { # "Debt Level": { # "-": "0", # "Low .*": "+1", # "No .*": "+2", # "High .* in the past 5 years": "-1", # "High .*": "-2", # "Very High .*": "-3" # }, # "Share Repurchase": { # "-": "0", # "Every year": "+2" # }, # "CapEx": { # "-": "0", # "Very Low": "+2", # "Very High": "-2" # } # }, # setAttrs: (data) -> # data.newScore = @getScore(data.title, data.newData) # if(typeof data.oldData != "undefined") # data.oldScore = @getScore(data.title, data.oldData) # if(data.newScore == '0') # data.hidden = true # data # getDisplayInfo: (data) -> # precision = data.precision # result = {} # result.title = data.title.toLowerCase() # result.title = "CapEx" if data.title == "CapEx" # result.newData = data.newData.toLowerCase() # if(typeof data.oldData != "undefined") # result.oldData = data.oldData.toLowerCase() # result # getScore: (title, data) -> # for item of @words[title] # pattern = new RegExp(item, "g"); # if pattern.test(data) # return @words[title][item] # return null # getDifference: (data) -> # if(typeof data.oldData != "undefined") # parseInt(data.newScore) - parseInt(data.oldScore) # else # "na" # } # # String with custom functions # NL = new NaturalLanguage [{ # "title": "Share Repurchase", # "oldData": "-", # "newData": "Every year", # "dataType": "sign" # }] # NL.addType "sign", signType # # String with custom functions + oldData # console.log NL.generate(-1, false) # adef = { # 'key1': 'value<KEY>', # 'key2': 'value<KEY>' # } # aover ={ # 'key1': '<KEY>override', # 'key3': 'value3' # } # console.log _.extend(adef, aover) # console.log adef # console.log aover
true
###* * Natural Language base class * ------------------------------------------------------------ * @name NaturalLanguage * * @constructor * @param {Array} data - a list of inputs ### exports.NaturalLanguage = class NaturalLanguage ###* * ------------------------------------------------------------ * Prepare resource * ------------------------------------------------------------ ### global = null _ = require "underscore" config = require "./../resources/config.json" sentences = require "./../resources/sentences.json" constructor: (data) -> @data = data @dataConfig = {} @sentenceConfig = {} @random = true global = @ ###* * ------------------------------------------------------------ * HELPER FUNCTION * ------------------------------------------------------------ ### ###* * Change the first character of the string to capital * ------------------------------------------------------------ * @name capitalize * @param {string} data * @return {string} capitalized string ### capitalize = (data) -> data.charAt(0).toUpperCase() + data.slice 1 ###* * Replace sentence pattern with string in data object * (single sentence, no capitalization or full stop) * ------------------------------------------------------------ * @name replaceStr * @param {array} patterns - array of sentences * @param {object} data - displayInfo object * @return {string} final sentence ### replaceStr = (patterns, data) -> if global.random pattern = _.sample patterns else pattern = patterns[0] _.each data, (item, key) -> pattern = pattern.replace "{#{key}}", item pattern ###* * Replace sentence pattern with string in data object * (combined sentence, with capitalization and full stop) * ------------------------------------------------------------ * @name replaceCombinedStr * @param {array} patterns - array of sentences * @param {array} data - array of displayInfo object * @return {string} final sentence ### replaceCombinedStr = (patterns, data) -> if global.random pattern = _.sample patterns else pattern = patterns[0] _.each data, (items, i) -> _.each items, (item, key) -> pattern = pattern.replace "{#{key}.#{i}}", items[key] pattern ###* * ------------------------------------------------------------ * METHOD LIST * ------------------------------------------------------------ ### ###* * Add more required attributes * ------------------------------------------------------------ * @name setAttrs * @param {array} data - array of inputs * @return {Object} new data with more attributes * @private ### setAttrs = (data) -> _.each data, (item, i) -> if item.options isnt undefined # item.options = _.extend _.clone(config.default), item.options item.options = _.defaults(item.options, config.default); else item.options = { "priority": { "init": 1, "negativeFactor": 20, "positiveFactor": 100 }, "level": { "threshold": 0.09, "sensitiveness": 1 } } item.dataType = "default" unless item.dataType # Custom for more attributes if global.dataConfig[item.dataType] and global.dataConfig[item.dataType].setAttrs item = global.dataConfig[item.dataType].setAttrs item # Default attributes item.alwaysShow = false if typeof item.alwaysShow is "undefined" item.contentGroup = "default" unless item.contentGroup item.sentenceType = "default" unless item.sentenceType item.precision = 0 unless item.precision != "undefined" item.difference = getDifference item item.displayInfo = getDisplayInfo item item.priority = calculatePriority item item.level = calculateLevel item item.levelType = calculateType item.level data ###* * Get the difference between old value and current value * ------------------------------------------------------------ * @name getDifference * @param {object} data * @return {number/string} difference value or 'na' if there is no oldData * @private ### getDifference = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].getDifference return global.dataConfig[data.dataType].getDifference data # Default if typeof data.oldData isnt "undefined" and typeof data.oldData == "number" data.newData - data.oldData else "na" ###* * Prepare strings required to show in the sentence * ------------------------------------------------------------ * @name getDisplayInfo * @param {object} data * @return {object} information required to display in the sentence * @private ### getDisplayInfo = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].getDisplayInfo return global.dataConfig[data.dataType].getDisplayInfo data # Default result = {} result.title = data.title.toLowerCase() if typeof data.oldData isnt "undefined" if typeof data.oldData == "number" result.oldData = data.oldData.toFixed data.precision else result.oldData = data.oldData.toLowerCase() if typeof data.difference == "number" result.difference = Math.abs(data.difference).toFixed data.precision if typeof data.newData == "number" result.newData = data.newData.toFixed(data.precision) else result.newData = data.newData.toLowerCase() result ###* * Calculate the priority of change * ------------------------------------------------------------ * @name calculatePriority * @param {object} data * @return {number} new priority * @private ### calculatePriority = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].calculatePriority return global.dataConfig[data.dataType].calculatePriority data # Default priorityConfig = data.options.priority if data.difference is "na" return priorityConfig.init else if data.difference > 0 newPriority = priorityConfig.init + (priorityConfig.positiveFactor * data.difference) else newPriority = priorityConfig.init + (priorityConfig.negativeFactor * Math.abs(data.difference)) parseInt newPriority.toFixed(0), 10 ###* * Calculate the intesity of change * ------------------------------------------------------------ * @name calculateLevel * @param {object} data * @return {number} intensity of the change * @private ### calculateLevel = (data) -> # Override if global.dataConfig[data.dataType] and global.dataConfig[data.dataType].calculateLevel return global.dataConfig[data.dataType] .calculateLevel data.difference, data.options.level # Default levelConfig = data.options.level if data.difference is "na" level = "na" else absoluteDifference = Math.abs data.difference if absoluteDifference < levelConfig.threshold level = 0 else level = Math.ceil data.difference / levelConfig.sensitiveness level = 3 if level > 3 level = -3 if level < -3 level ###* * Calculate the type of intesity * ------------------------------------------------------------ * @name calculateType * @param {number} level * @return {string} levelType * @private ### calculateType = (level) -> if level > 0 "positive" else if level < 0 "negative" else if level is "na" "na" else "neutral" ###* * Select number of data to display and sort by priority * ------------------------------------------------------------ * @name selectData * @param {array} data - array of data split into two groups: alwaysShow and sortedData * @param {number} nData - number of data to show * @return {array} selected, sorted data by priority * @private ### selectData = (data, nData) -> groupedData = groupData data result = groupedData.alwaysShow if(nData == -1) return result.concat groupedData.sortedData if result.length < nData nRemaining = nData - result.length result = result.concat groupedData.sortedData.slice( 0, nRemaining ) result.sort (a, b) -> b.priority - a.priority result ###* * Group data by alwaysShow attr and sort the group by priority * ------------------------------------------------------------ * @name groupData * @param {array} data - array of data * @return {array} data split into two groups, alwaysShow and sortedData * @private ### groupData = (data) -> # Remove hidden items data = _.filter data, (item) -> ! item.hidden data = _.groupBy data, "alwaysShow" data.sortedData = [] data.alwaysShow = [] if data[false] data[false].sort (a, b) -> b.priority - a.priority data.sortedData = data[false] data.alwaysShow = data[true] if data[true] data ###* * Get a valid list of sentences for random selecting * ------------------------------------------------------------ * @name getSimpleSentenceList * @param {object} data - data object * @param {array} simpleSentences - sentences from all types * @return {array} array of valid sentences * @private ### getSimpleSentenceList = (data, simpleSentencese) -> # Override if global.sentenceConfig[data.sentenceType] \ and global.sentenceConfig[data.sentenceType].getSimpleSentenceList return global.sentenceConfig[data.sentenceType] .getSimpleSentenceList data, simpleSentencese # Default if typeof data.oldData is "undefined" # No oldData if typeof sentences.simpleSentences[data.sentenceType] isnt "undefined" \ and typeof sentences.simpleSentences[data.sentenceType]["na"] isnt "undefined" sentences.simpleSentences[data.sentenceType]["na"] else sentences.simpleSentences["default"]["na"] else if typeof sentences.simpleSentences[data.sentenceType] isnt "undefined" \ and typeof sentences.simpleSentences[data.sentenceType][data.levelType] isnt "undefined" if typeof sentences.simpleSentences[data.sentenceType][data.levelType][data.level.toString()] isnt "undefined" sentences.simpleSentences[ data.sentenceType ][ data.levelType ][ data.level.toString() ] else sentences.simpleSentences[ data.sentenceType ][ data.levelType ] else sentences.simpleSentences["default"][ data.levelType ][ data.level.toString() ] ###* * Group data into contentGroups and loop through each * contentGroup to create sentence(s) * ------------------------------------------------------------ * @name buildSimpleSentence * @param {object} data - data object * @return {array} array of sentences * @private ### buildSimpleSentence = (data) -> simpleSentences = getSimpleSentenceList data, sentences.simpleSentences replaceStr simpleSentences, data.displayInfo ###* * Add simple sentence into the data object * ------------------------------------------------------------ * @name addSimpleSentence * @param {array} array of data to generate simple sentences * @return {array} array of data with sentence attribute inserted * @private ### addSimpleSentence = (data) -> for i of data data[i].displayInfo.sentence = buildSimpleSentence(data[i]) data ###* * Get a valid list of compound sentences * ------------------------------------------------------------ * @name getCompoundSentenceList * @param {object} data - data object * @param {array} compoundSentences - sentences from all types * @return {array} array of valid sentences * @private ### getCompoundSentenceList = (data, compoundSentences) -> # Override if(global.sentenceConfig[data.sentenceType] && global.sentenceConfig[data.sentenceType].getCompoundSentenceList) return global.sentenceConfig[data.sentenceType].getCompoundSentenceList(data, compoundSentences) # Default if sentences.compoundSentences[data.sentenceType] isnt undefined compoundSentences[data[0].sentenceType] else compoundSentences.default ###* * Combine two simple sentencese that are in the same sentenceGroup * ------------------------------------------------------------ * @name buildCompoundSentence * @param {array} array of one or two data objects to combine * @return {string} a combine sentence * @private ### buildCompoundSentence = (data) -> types = _.pluck data, "levelType" type = types.join "_" moreDisplayInfo = _.pluck addSimpleSentence(data), "displayInfo" compoundSentences = getCompoundSentenceList data, sentences.compoundSentences selectedSentences = _.find compoundSentences, (group) -> _.contains(group.type, type); capitalize replaceCombinedStr( selectedSentences.sentences, moreDisplayInfo ) ###* * Group data into contentGroups and loop through each * contentGroup to create sentence(s) * ------------------------------------------------------------ * @name buildSentences * @param {array} data - array sorted by priority but not grouped * @return {array} array of sentences * @private ### buildSentences = (data) -> result = [] data = _.groupBy data, "contentGroup" # for group of data _.each data, (group) -> if group.length > 2 i = 0 while i < group.length if i + 1 is group.length result.push buildCompoundSentence [ group[i] ] else result.push buildCompoundSentence [ group[i], group[parseInt(i)+1] ] i = i + 2 else result.push buildCompoundSentence group result addType: (title, func = {}) -> if @dataConfig[title] @dataConfig[title] = _.extend(@dataConfig[title], func) else @dataConfig[title] = func addSentence: (title, func = null) -> if @sentenceConfig[title] @sentenceConfig[title] = _.extend(@sentenceConfig[title], func) else @sentenceConfig[title] = func ###* * Generate sentences from a list of data * ------------------------------------------------------------ * @name NaturalLanguage.generate * @param {number} nData - number of sentences to generate * @return {String/Number/Object/Function/Boolean} desc * @public ### generate: (nData = -1, random = true) -> @random = random data = setAttrs @data data = selectData data, nData result = buildSentences data # return data # for i of data # console.log data[i].title, ": ", data[i].priority return result.join " " debug: (nData = -1, random = true) -> @random = random return setAttrs @data data = setAttrs @data data = selectData data, nData result = buildSentences data # signType = { # words: { # "Debt Level": { # "-": "0", # "Low .*": "+1", # "No .*": "+2", # "High .* in the past 5 years": "-1", # "High .*": "-2", # "Very High .*": "-3" # }, # "Share Repurchase": { # "-": "0", # "Every year": "+2" # }, # "CapEx": { # "-": "0", # "Very Low": "+2", # "Very High": "-2" # } # }, # setAttrs: (data) -> # data.newScore = @getScore(data.title, data.newData) # if(typeof data.oldData != "undefined") # data.oldScore = @getScore(data.title, data.oldData) # if(data.newScore == '0') # data.hidden = true # data # getDisplayInfo: (data) -> # precision = data.precision # result = {} # result.title = data.title.toLowerCase() # result.title = "CapEx" if data.title == "CapEx" # result.newData = data.newData.toLowerCase() # if(typeof data.oldData != "undefined") # result.oldData = data.oldData.toLowerCase() # result # getScore: (title, data) -> # for item of @words[title] # pattern = new RegExp(item, "g"); # if pattern.test(data) # return @words[title][item] # return null # getDifference: (data) -> # if(typeof data.oldData != "undefined") # parseInt(data.newScore) - parseInt(data.oldScore) # else # "na" # } # # String with custom functions # NL = new NaturalLanguage [{ # "title": "Share Repurchase", # "oldData": "-", # "newData": "Every year", # "dataType": "sign" # }] # NL.addType "sign", signType # # String with custom functions + oldData # console.log NL.generate(-1, false) # adef = { # 'key1': 'valuePI:KEY:<KEY>END_PI', # 'key2': 'valuePI:KEY:<KEY>END_PI' # } # aover ={ # 'key1': 'PI:KEY:<KEY>END_PIoverride', # 'key3': 'value3' # } # console.log _.extend(adef, aover) # console.log adef # console.log aover
[ { "context": ".exports = settingspagemodule\n\n# MasterSecret Id? 0x19e23357ad9464ba664344cf661d15a25bcc2874be497940c11b7573cd773b13", "end": 5068, "score": 0.9846917390823364, "start": 5002, "tag": "KEY", "value": "0x19e23357ad9464ba664344cf661d15a25bcc2874be497940c11b7573cd773b13" } ]
source/settingspagemodule/settingspagemodule.coffee
JhonnyJason/secret-cockpit-sources
0
settingspagemodule = {name: "settingspagemodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["settingspagemodule"]? then console.log "[settingspagemodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region localModules state = null slideinModule = null #endregion ############################################################ settingspagemodule.initialize = -> log "settingspagemodule.initialize" state = allModules.statemodule slideinModule = allModules.slideinframemodule # settingspageContent. slideinModule.wireUp(settingspageContent, clearContent, applyContent) syncSettingsFromState() markAllSettingsAsRegularState() return ############################################################ #region internalFunctions clearContent = -> log "clearContent" syncSettingsFromState() return applyContent = -> log "applyContent" syncSettingsToState() return ############################################################ markAllSettingsAsRegularState = -> log "markAllSettingsAsRegularState" state.save("secretManagerURL", state.load("secretManagerURL")) state.save("dataManagerURL", state.load("dataManagerURL")) state.save("storeUnsafeInUnsafe", state.load("storeUnsafeInUnsafe")) state.save("storeUnsafeInFloating", state.load("storeUnsafeInFloating")) state.save("storeUnsafeInSignature", state.load("storeUnsafeInSignature")) state.save("keyloggerProtection", state.load("keyloggerProtection")) state.save("storeUnsafeInLocalStorage", state.load("storeUnsafeInLocalStorage")) state.save("autodetectStoredSecrets", state.load("autodetectStoredSecrets")) state.save("secretIdentifyingEnding", state.load("secretIdentifyingEnding")) return syncSettingsFromState = -> log "syncSecretManagerURLFromState" secretManagerURL = state.load("secretManagerURL") secretManagerInput.value = secretManagerURL dataManagerURL = state.load("dataManagerURL") dataManagerInput.value = dataManagerURL storeUnsafeInUnsafe = state.load("storeUnsafeInUnsafe") storeInUnsafeInput.checked = storeUnsafeInUnsafe storeUnsafeInFloating = state.load("storeUnsafeInFloating") storeInFloatingInput.checked = storeUnsafeInFloating storeUnsafeInSignature = state.load("storeUnsafeInSignature") storeInSignatureInput.checked = storeUnsafeInSignature keyloggerProtection = state.load("keyloggerProtection") keyloggerProtectionInput.checked = keyloggerProtection storeUnsafeInLocalStorage = state.load("storeUnsafeInLocalStorage") storeUnsafeInput.checked = storeUnsafeInLocalStorage autodetectSecrets = state.load("autodetectStoredSecrets") autodetectUnsafeInput.checked = storeUnsafeInput identifyingEnding = state.load("secretIdentifyingEnding") identifyingEndingInput.value = identifyingEnding return syncSettingsToState = -> log "syncSettingsToState" ## Secret Manager URL url = secretManagerInput.value url = "https://"+url unless url.indexOf("https://") == 0 state.set("secretManagerURL", url) ## Data Manager URL url = dataManagerInput.value url = "http://"+url unless url.indexOf("https://") == 0 state.set("dataManagerURL", url) ## Key Storing Options checked = storeInUnsafeInput.checked state.set("storeUnsafeInUnsafe", checked) checked = storeInFloatingInput.checked state.set("storeUnsafeInFloating", checked) checked = storeInSignatureInput.checked state.set("storeUnsafeInSignature", checked) ## KeyLogger Protection checked = keyloggerProtectionInput.checked state.set("keyloggerProtection", checked) ## Store Unsafe Secret in LocalStorage checked = storeUnsafeInput.checked state.set("storeUnsafeInLocalStorage", checked) ## Autodetect Stored Secrets checked = autodetectUnsafeInput.checked state.set("autodetectStoredSecrets", checked) ## Ending which identifies a stored Secret value = identifyingEndingInput.value state.set("secretIdentifyingEnding", value) state.saveRegularState() ## As all Settings are in the regular State ## We only have to call the save method once ## And all the regular state is stored in localStorage :-) return #endregion ############################################################ #region exposedFunctions settingspagemodule.slideOut = -> log "settingspagemodule.slideOut" slideinModule.slideoutForContentElement(settingspageContent) return settingspagemodule.slideIn = -> log "settingspagemodule.slideIn" slideinModule.slideinForContentElement(settingspageContent) return #endregion module.exports = settingspagemodule # MasterSecret Id? 0x19e23357ad9464ba664344cf661d15a25bcc2874be497940c11b7573cd773b13
191263
settingspagemodule = {name: "settingspagemodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["settingspagemodule"]? then console.log "[settingspagemodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region localModules state = null slideinModule = null #endregion ############################################################ settingspagemodule.initialize = -> log "settingspagemodule.initialize" state = allModules.statemodule slideinModule = allModules.slideinframemodule # settingspageContent. slideinModule.wireUp(settingspageContent, clearContent, applyContent) syncSettingsFromState() markAllSettingsAsRegularState() return ############################################################ #region internalFunctions clearContent = -> log "clearContent" syncSettingsFromState() return applyContent = -> log "applyContent" syncSettingsToState() return ############################################################ markAllSettingsAsRegularState = -> log "markAllSettingsAsRegularState" state.save("secretManagerURL", state.load("secretManagerURL")) state.save("dataManagerURL", state.load("dataManagerURL")) state.save("storeUnsafeInUnsafe", state.load("storeUnsafeInUnsafe")) state.save("storeUnsafeInFloating", state.load("storeUnsafeInFloating")) state.save("storeUnsafeInSignature", state.load("storeUnsafeInSignature")) state.save("keyloggerProtection", state.load("keyloggerProtection")) state.save("storeUnsafeInLocalStorage", state.load("storeUnsafeInLocalStorage")) state.save("autodetectStoredSecrets", state.load("autodetectStoredSecrets")) state.save("secretIdentifyingEnding", state.load("secretIdentifyingEnding")) return syncSettingsFromState = -> log "syncSecretManagerURLFromState" secretManagerURL = state.load("secretManagerURL") secretManagerInput.value = secretManagerURL dataManagerURL = state.load("dataManagerURL") dataManagerInput.value = dataManagerURL storeUnsafeInUnsafe = state.load("storeUnsafeInUnsafe") storeInUnsafeInput.checked = storeUnsafeInUnsafe storeUnsafeInFloating = state.load("storeUnsafeInFloating") storeInFloatingInput.checked = storeUnsafeInFloating storeUnsafeInSignature = state.load("storeUnsafeInSignature") storeInSignatureInput.checked = storeUnsafeInSignature keyloggerProtection = state.load("keyloggerProtection") keyloggerProtectionInput.checked = keyloggerProtection storeUnsafeInLocalStorage = state.load("storeUnsafeInLocalStorage") storeUnsafeInput.checked = storeUnsafeInLocalStorage autodetectSecrets = state.load("autodetectStoredSecrets") autodetectUnsafeInput.checked = storeUnsafeInput identifyingEnding = state.load("secretIdentifyingEnding") identifyingEndingInput.value = identifyingEnding return syncSettingsToState = -> log "syncSettingsToState" ## Secret Manager URL url = secretManagerInput.value url = "https://"+url unless url.indexOf("https://") == 0 state.set("secretManagerURL", url) ## Data Manager URL url = dataManagerInput.value url = "http://"+url unless url.indexOf("https://") == 0 state.set("dataManagerURL", url) ## Key Storing Options checked = storeInUnsafeInput.checked state.set("storeUnsafeInUnsafe", checked) checked = storeInFloatingInput.checked state.set("storeUnsafeInFloating", checked) checked = storeInSignatureInput.checked state.set("storeUnsafeInSignature", checked) ## KeyLogger Protection checked = keyloggerProtectionInput.checked state.set("keyloggerProtection", checked) ## Store Unsafe Secret in LocalStorage checked = storeUnsafeInput.checked state.set("storeUnsafeInLocalStorage", checked) ## Autodetect Stored Secrets checked = autodetectUnsafeInput.checked state.set("autodetectStoredSecrets", checked) ## Ending which identifies a stored Secret value = identifyingEndingInput.value state.set("secretIdentifyingEnding", value) state.saveRegularState() ## As all Settings are in the regular State ## We only have to call the save method once ## And all the regular state is stored in localStorage :-) return #endregion ############################################################ #region exposedFunctions settingspagemodule.slideOut = -> log "settingspagemodule.slideOut" slideinModule.slideoutForContentElement(settingspageContent) return settingspagemodule.slideIn = -> log "settingspagemodule.slideIn" slideinModule.slideinForContentElement(settingspageContent) return #endregion module.exports = settingspagemodule # MasterSecret Id? <KEY>
true
settingspagemodule = {name: "settingspagemodule"} ############################################################ #region printLogFunctions log = (arg) -> if allModules.debugmodule.modulesToDebug["settingspagemodule"]? then console.log "[settingspagemodule]: " + arg return ostr = (obj) -> JSON.stringify(obj, null, 4) olog = (obj) -> log "\n" + ostr(obj) print = (arg) -> console.log(arg) #endregion ############################################################ #region localModules state = null slideinModule = null #endregion ############################################################ settingspagemodule.initialize = -> log "settingspagemodule.initialize" state = allModules.statemodule slideinModule = allModules.slideinframemodule # settingspageContent. slideinModule.wireUp(settingspageContent, clearContent, applyContent) syncSettingsFromState() markAllSettingsAsRegularState() return ############################################################ #region internalFunctions clearContent = -> log "clearContent" syncSettingsFromState() return applyContent = -> log "applyContent" syncSettingsToState() return ############################################################ markAllSettingsAsRegularState = -> log "markAllSettingsAsRegularState" state.save("secretManagerURL", state.load("secretManagerURL")) state.save("dataManagerURL", state.load("dataManagerURL")) state.save("storeUnsafeInUnsafe", state.load("storeUnsafeInUnsafe")) state.save("storeUnsafeInFloating", state.load("storeUnsafeInFloating")) state.save("storeUnsafeInSignature", state.load("storeUnsafeInSignature")) state.save("keyloggerProtection", state.load("keyloggerProtection")) state.save("storeUnsafeInLocalStorage", state.load("storeUnsafeInLocalStorage")) state.save("autodetectStoredSecrets", state.load("autodetectStoredSecrets")) state.save("secretIdentifyingEnding", state.load("secretIdentifyingEnding")) return syncSettingsFromState = -> log "syncSecretManagerURLFromState" secretManagerURL = state.load("secretManagerURL") secretManagerInput.value = secretManagerURL dataManagerURL = state.load("dataManagerURL") dataManagerInput.value = dataManagerURL storeUnsafeInUnsafe = state.load("storeUnsafeInUnsafe") storeInUnsafeInput.checked = storeUnsafeInUnsafe storeUnsafeInFloating = state.load("storeUnsafeInFloating") storeInFloatingInput.checked = storeUnsafeInFloating storeUnsafeInSignature = state.load("storeUnsafeInSignature") storeInSignatureInput.checked = storeUnsafeInSignature keyloggerProtection = state.load("keyloggerProtection") keyloggerProtectionInput.checked = keyloggerProtection storeUnsafeInLocalStorage = state.load("storeUnsafeInLocalStorage") storeUnsafeInput.checked = storeUnsafeInLocalStorage autodetectSecrets = state.load("autodetectStoredSecrets") autodetectUnsafeInput.checked = storeUnsafeInput identifyingEnding = state.load("secretIdentifyingEnding") identifyingEndingInput.value = identifyingEnding return syncSettingsToState = -> log "syncSettingsToState" ## Secret Manager URL url = secretManagerInput.value url = "https://"+url unless url.indexOf("https://") == 0 state.set("secretManagerURL", url) ## Data Manager URL url = dataManagerInput.value url = "http://"+url unless url.indexOf("https://") == 0 state.set("dataManagerURL", url) ## Key Storing Options checked = storeInUnsafeInput.checked state.set("storeUnsafeInUnsafe", checked) checked = storeInFloatingInput.checked state.set("storeUnsafeInFloating", checked) checked = storeInSignatureInput.checked state.set("storeUnsafeInSignature", checked) ## KeyLogger Protection checked = keyloggerProtectionInput.checked state.set("keyloggerProtection", checked) ## Store Unsafe Secret in LocalStorage checked = storeUnsafeInput.checked state.set("storeUnsafeInLocalStorage", checked) ## Autodetect Stored Secrets checked = autodetectUnsafeInput.checked state.set("autodetectStoredSecrets", checked) ## Ending which identifies a stored Secret value = identifyingEndingInput.value state.set("secretIdentifyingEnding", value) state.saveRegularState() ## As all Settings are in the regular State ## We only have to call the save method once ## And all the regular state is stored in localStorage :-) return #endregion ############################################################ #region exposedFunctions settingspagemodule.slideOut = -> log "settingspagemodule.slideOut" slideinModule.slideoutForContentElement(settingspageContent) return settingspagemodule.slideIn = -> log "settingspagemodule.slideIn" slideinModule.slideinForContentElement(settingspageContent) return #endregion module.exports = settingspagemodule # MasterSecret Id? PI:KEY:<KEY>END_PI
[ { "context": "que permite usar un paginador con AJAX.\n Copyright Javi <elretirao@elretirao.net>\n Ver http://docs.jquery", "end": 87, "score": 0.9996656179428101, "start": 83, "tag": "NAME", "value": "Javi" }, { "context": "mite usar un paginador con AJAX.\n Copyright Javi <elretira...
app/assets/javascripts/jquery.paginator.js.coffee
javierv/41cero10asesores
0
### ajaxPaginator es un plugin que permite usar un paginador con AJAX. Copyright Javi <elretirao@elretirao.net> Ver http://docs.jquery.com/License para la licencia. Opciones: paginador: string con el elemento que tiene los enlaces de paginación. Por defecto, '#paginador'. table: string con el elemento que tiene los datos. Por defecto, 'table'. loading: texto a mostrar mientras carga el resultado. ### jQuery.fn.ajaxPaginator = (options) -> defaults = paginator: '.pagination' table: 'table' beforeSend: -> $('#flashMessage').remove() loading: 'Cargando...' hide_while_loading: false jQuery.extend(defaults, options) this.each -> $element = jQuery(this) defaults['success'] = (data) -> $element.html(data) $element.removeCargando() jQuery(defaults.paginator + ' a,' + defaults.table + ' th a', $element).live('click', -> if history && history.pushState history.pushState(null, document.title, @href) load_page($element, @href, defaults) $(window).bind("popstate", -> load_page($element, location.href, defaults)) return false ) load_page = (element, url, options) -> options['url'] = url if options["hide_while_loading"] element.empty().html('<p class="loading">' + options.loading + '</p>') else element.addCargando() $.ajax(options)
56200
### ajaxPaginator es un plugin que permite usar un paginador con AJAX. Copyright <NAME> <<EMAIL>> Ver http://docs.jquery.com/License para la licencia. Opciones: paginador: string con el elemento que tiene los enlaces de paginación. Por defecto, '#paginador'. table: string con el elemento que tiene los datos. Por defecto, 'table'. loading: texto a mostrar mientras carga el resultado. ### jQuery.fn.ajaxPaginator = (options) -> defaults = paginator: '.pagination' table: 'table' beforeSend: -> $('#flashMessage').remove() loading: 'Cargando...' hide_while_loading: false jQuery.extend(defaults, options) this.each -> $element = jQuery(this) defaults['success'] = (data) -> $element.html(data) $element.removeCargando() jQuery(defaults.paginator + ' a,' + defaults.table + ' th a', $element).live('click', -> if history && history.pushState history.pushState(null, document.title, @href) load_page($element, @href, defaults) $(window).bind("popstate", -> load_page($element, location.href, defaults)) return false ) load_page = (element, url, options) -> options['url'] = url if options["hide_while_loading"] element.empty().html('<p class="loading">' + options.loading + '</p>') else element.addCargando() $.ajax(options)
true
### ajaxPaginator es un plugin que permite usar un paginador con AJAX. Copyright PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Ver http://docs.jquery.com/License para la licencia. Opciones: paginador: string con el elemento que tiene los enlaces de paginación. Por defecto, '#paginador'. table: string con el elemento que tiene los datos. Por defecto, 'table'. loading: texto a mostrar mientras carga el resultado. ### jQuery.fn.ajaxPaginator = (options) -> defaults = paginator: '.pagination' table: 'table' beforeSend: -> $('#flashMessage').remove() loading: 'Cargando...' hide_while_loading: false jQuery.extend(defaults, options) this.each -> $element = jQuery(this) defaults['success'] = (data) -> $element.html(data) $element.removeCargando() jQuery(defaults.paginator + ' a,' + defaults.table + ' th a', $element).live('click', -> if history && history.pushState history.pushState(null, document.title, @href) load_page($element, @href, defaults) $(window).bind("popstate", -> load_page($element, location.href, defaults)) return false ) load_page = (element, url, options) -> options['url'] = url if options["hide_while_loading"] element.empty().html('<p class="loading">' + options.loading + '</p>') else element.addCargando() $.ajax(options)
[ { "context": " data: [\n id: 1\n name: \"Bob\"\n ,\n id: 2\n name: ", "end": 789, "score": 0.9998683929443359, "start": 786, "tag": "NAME", "value": "Bob" }, { "context": "\n ,\n id: 2\n name: \"S...
test/spec_coffee/model_cascade_delete_spec.coffee
kirkbowers/mvcoffee
0
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model theUser.hasMany "activity", order: "position" theUser.hasOne "brain" theActivity = class Activity extends MVCoffee.Model theActivity.belongsTo "user" theActivity.hasMany "subactivity" theSubActivity = class Subactivity extends MVCoffee.Model theSubActivity.belongsTo "activity" theBrain = class Brain extends MVCoffee.Model theBrain.belongsTo "user" store = null describe "models with hierarchical data", -> beforeEach -> store = new MVCoffee.ModelStore user: User activity: Activity subactivity: Subactivity brain: Brain store.load mvcoffee_version: "1.0.0" models: user: data: [ id: 1 name: "Bob" , id: 2 name: "Sue" activity: [ id: 1 user_id: 2 name: "Rake the yard" , id: 2 user_id: 2 name: "Make a sandwich" subactivity: [ id: 1 activity_id: 2 name: "Spread peanut butter" , id: 2 activity_id: 2 name: "Spread jelly" ] ] , id: 3 name: "Danny" brain: [ id: 1 user_id: 3 name: "gray matter" ] ] it "should delete a model that has no has many things and leave others untouched", -> user = User.find 1 user.delete() expect(User.all().length).toBe(2) expect(User.find(1)).toBeUndefined() user = User.find 2 expect(user.name).toBe("Sue") expect(user.activities().length).toBe(2) sandwich = Activity.find(2) expect(sandwich.name).toBe("Make a sandwich") expect(sandwich.subactivities().length).toBe(2) it "should cascade a delete on a model that has many children", -> user = User.find 2 user.delete() expect(User.all().length).toBe(2) expect(User.find(2)).toBeUndefined() user = User.find 1 expect(user.name).toBe("Bob") expect(user.activities().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) it "should cascade a delete on a model that has many children using destroy alias", -> user = User.find 2 user.destroy() expect(User.all().length).toBe(2) expect(User.find(2)).toBeUndefined() user = User.find 1 expect(user.name).toBe("Bob") expect(user.activities().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) it "should cascade a delete when done by a load on the store using a scalar", -> store.load mvcoffee_version: "1.0.0" models: user: delete: 2 expect(User.all().length).toBe(2) expect(User.find(2)).toBeUndefined() user = User.find 1 expect(user.name).toBe("Bob") expect(user.activities().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) it "should cascade a delete when done by a load on the store using an array", -> store.load mvcoffee_version: "1.0.0" models: user: delete: [1, 2, 3] expect(User.all().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) expect(Brain.all().length).toBe(0) it "should not cascade a delete when done by a load on the store using replace_on", -> store.load mvcoffee_version: "1.0.0" models: activity: data: [ id: 2 user_id: 2 name: "Make a nice sandwich" , id: 3 user_id: 2 name: "Make spaghetti" ] replace_on: user_id: 2 expect(User.all().length).toBe(3) user = User.find 1 expect(user.name).toBe("Bob") expect(user.activities().length).toBe(0) user = User.find 2 expect(user.name).toBe("Sue") activities = user.activities() expect(activities.length).toBe(2) act = activities[0] expect(act.name).toBe("Make a nice sandwich") expect(act.subactivities().length).toBe(2) expect(Subactivity.all().length).toBe(2) act = activities[1] expect(act.name).toBe("Make spaghetti") expect(act.subactivities().length).toBe(0)
199558
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model theUser.hasMany "activity", order: "position" theUser.hasOne "brain" theActivity = class Activity extends MVCoffee.Model theActivity.belongsTo "user" theActivity.hasMany "subactivity" theSubActivity = class Subactivity extends MVCoffee.Model theSubActivity.belongsTo "activity" theBrain = class Brain extends MVCoffee.Model theBrain.belongsTo "user" store = null describe "models with hierarchical data", -> beforeEach -> store = new MVCoffee.ModelStore user: User activity: Activity subactivity: Subactivity brain: Brain store.load mvcoffee_version: "1.0.0" models: user: data: [ id: 1 name: "<NAME>" , id: 2 name: "<NAME>" activity: [ id: 1 user_id: 2 name: "Rake the yard" , id: 2 user_id: 2 name: "Make a sandwich" subactivity: [ id: 1 activity_id: 2 name: "Spread peanut butter" , id: 2 activity_id: 2 name: "Spread jelly" ] ] , id: 3 name: "<NAME>" brain: [ id: 1 user_id: 3 name: "gray matter" ] ] it "should delete a model that has no has many things and leave others untouched", -> user = User.find 1 user.delete() expect(User.all().length).toBe(2) expect(User.find(1)).toBeUndefined() user = User.find 2 expect(user.name).toBe("<NAME>") expect(user.activities().length).toBe(2) sandwich = Activity.find(2) expect(sandwich.name).toBe("Make a sandwich") expect(sandwich.subactivities().length).toBe(2) it "should cascade a delete on a model that has many children", -> user = User.find 2 user.delete() expect(User.all().length).toBe(2) expect(User.find(2)).toBeUndefined() user = User.find 1 expect(user.name).toBe("<NAME>") expect(user.activities().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) it "should cascade a delete on a model that has many children using destroy alias", -> user = User.find 2 user.destroy() expect(User.all().length).toBe(2) expect(User.find(2)).toBeUndefined() user = User.find 1 expect(user.name).toBe("<NAME>") expect(user.activities().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) it "should cascade a delete when done by a load on the store using a scalar", -> store.load mvcoffee_version: "1.0.0" models: user: delete: 2 expect(User.all().length).toBe(2) expect(User.find(2)).toBeUndefined() user = User.find 1 expect(user.name).toBe("<NAME>") expect(user.activities().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) it "should cascade a delete when done by a load on the store using an array", -> store.load mvcoffee_version: "1.0.0" models: user: delete: [1, 2, 3] expect(User.all().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) expect(Brain.all().length).toBe(0) it "should not cascade a delete when done by a load on the store using replace_on", -> store.load mvcoffee_version: "1.0.0" models: activity: data: [ id: 2 user_id: 2 name: "Make a nice sandwich" , id: 3 user_id: 2 name: "Make spaghetti" ] replace_on: user_id: 2 expect(User.all().length).toBe(3) user = User.find 1 expect(user.name).toBe("<NAME>") expect(user.activities().length).toBe(0) user = User.find 2 expect(user.name).toBe("<NAME>") activities = user.activities() expect(activities.length).toBe(2) act = activities[0] expect(act.name).toBe("Make a nice sandwich") expect(act.subactivities().length).toBe(2) expect(Subactivity.all().length).toBe(2) act = activities[1] expect(act.name).toBe("Make spaghetti") expect(act.subactivities().length).toBe(0)
true
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model theUser.hasMany "activity", order: "position" theUser.hasOne "brain" theActivity = class Activity extends MVCoffee.Model theActivity.belongsTo "user" theActivity.hasMany "subactivity" theSubActivity = class Subactivity extends MVCoffee.Model theSubActivity.belongsTo "activity" theBrain = class Brain extends MVCoffee.Model theBrain.belongsTo "user" store = null describe "models with hierarchical data", -> beforeEach -> store = new MVCoffee.ModelStore user: User activity: Activity subactivity: Subactivity brain: Brain store.load mvcoffee_version: "1.0.0" models: user: data: [ id: 1 name: "PI:NAME:<NAME>END_PI" , id: 2 name: "PI:NAME:<NAME>END_PI" activity: [ id: 1 user_id: 2 name: "Rake the yard" , id: 2 user_id: 2 name: "Make a sandwich" subactivity: [ id: 1 activity_id: 2 name: "Spread peanut butter" , id: 2 activity_id: 2 name: "Spread jelly" ] ] , id: 3 name: "PI:NAME:<NAME>END_PI" brain: [ id: 1 user_id: 3 name: "gray matter" ] ] it "should delete a model that has no has many things and leave others untouched", -> user = User.find 1 user.delete() expect(User.all().length).toBe(2) expect(User.find(1)).toBeUndefined() user = User.find 2 expect(user.name).toBe("PI:NAME:<NAME>END_PI") expect(user.activities().length).toBe(2) sandwich = Activity.find(2) expect(sandwich.name).toBe("Make a sandwich") expect(sandwich.subactivities().length).toBe(2) it "should cascade a delete on a model that has many children", -> user = User.find 2 user.delete() expect(User.all().length).toBe(2) expect(User.find(2)).toBeUndefined() user = User.find 1 expect(user.name).toBe("PI:NAME:<NAME>END_PI") expect(user.activities().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) it "should cascade a delete on a model that has many children using destroy alias", -> user = User.find 2 user.destroy() expect(User.all().length).toBe(2) expect(User.find(2)).toBeUndefined() user = User.find 1 expect(user.name).toBe("PI:NAME:<NAME>END_PI") expect(user.activities().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) it "should cascade a delete when done by a load on the store using a scalar", -> store.load mvcoffee_version: "1.0.0" models: user: delete: 2 expect(User.all().length).toBe(2) expect(User.find(2)).toBeUndefined() user = User.find 1 expect(user.name).toBe("PI:NAME:<NAME>END_PI") expect(user.activities().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) it "should cascade a delete when done by a load on the store using an array", -> store.load mvcoffee_version: "1.0.0" models: user: delete: [1, 2, 3] expect(User.all().length).toBe(0) expect(Activity.all().length).toBe(0) expect(Subactivity.all().length).toBe(0) expect(Brain.all().length).toBe(0) it "should not cascade a delete when done by a load on the store using replace_on", -> store.load mvcoffee_version: "1.0.0" models: activity: data: [ id: 2 user_id: 2 name: "Make a nice sandwich" , id: 3 user_id: 2 name: "Make spaghetti" ] replace_on: user_id: 2 expect(User.all().length).toBe(3) user = User.find 1 expect(user.name).toBe("PI:NAME:<NAME>END_PI") expect(user.activities().length).toBe(0) user = User.find 2 expect(user.name).toBe("PI:NAME:<NAME>END_PI") activities = user.activities() expect(activities.length).toBe(2) act = activities[0] expect(act.name).toBe("Make a nice sandwich") expect(act.subactivities().length).toBe(2) expect(Subactivity.all().length).toBe(2) act = activities[1] expect(act.name).toBe("Make spaghetti") expect(act.subactivities().length).toBe(0)
[ { "context": "nt}:n sivustolle\"\n register_an_account: \"Rekisteröidy\"\n please_copy_url: \"Ole hyvä ja kopioi all", "end": 6336, "score": 0.7484158873558044, "start": 6326, "tag": "NAME", "value": "kisteröidy" }, { "context": "gram\"\n cloud: \"Sky\"\n ...
src/coffee/translations.coffee
podlove/podlove-subscribe-button
52
_ = require('underscore') Handlebars = require('handlebars') class Translations constructor: (language) -> @locale = language.split('-')[0] Handlebars.registerHelper 't', (key, options) => new Handlebars.SafeString(@t(key, options.hash)) t: (key, options={}) -> @translate(key, options) translate: (key, options={}) -> key_array = key.split('.') _translations = @_translations[@locale] value = null last_key = null _.each key_array, (key) -> last_key = key value = if value value[key] else _translations[key] unless value? value_array = [] _.forEach last_key.split('_'), (split_key) -> value_array.push(split_key.charAt(0).toUpperCase() + split_key.slice(1)) value = value_array.join(' ') @interpolate(value, options) interpolate: (string, interpolations) => string = string.replace /%{([^{}]*)}/g, (a, b) -> r = interpolations[b] if typeof r == 'string' || typeof r == 'number' r else a string @defaultLanguage: 'en' supportsLanguage: () -> keys = Object.keys(@_translations) if keys.indexOf(@locale) != -1 true else false _translations: de: button: "Abonnieren" panels: title: "Abonnieren" podcast_panel: choose_client: "Weiter" help_panel: title: "Abonnieren?" paragraph1: "Dank eines Abonnements verpasst du keine Episode dieses Podcasts mehr." paragraph2: "Nach dem Abonnieren lädt eine Podcast-App automatisch neue Folgen herunter und gibt dir Zugriff auf das Episoden-Archiv." paragraph3: "Der Podlove Subscribe Button macht das Abonnieren leichter. Wähle eine App oder einen Cloud-Service aus und lasse den Button alles Weitere erledigen. Benutze den Download-Link, um die App falls nötig zu installieren." clients_panel: app: "App" cloud: "Cloud" other_client: "Andere App" let_device_decide: "Automatisch erkennen" finish_panel: handing_over_to: "Übergebe an<br> %{client}" something_went_wrong: "Funktioniert etwas nicht wie erwartet?" try_again: "Nochmal versuchen" install: "%{client} installieren" register_an_account: "Einen Account registrieren bei " please_copy_url: "Bitte die URL kopieren und in deine Podcast- oder RSS-App einfügen." copy_button_text: "URL kopieren" copy_success: "URL in die Zwischenablage kopiert." or_install: "oder App installieren" en: button: "Subscribe" panels: title: "Subscribe" podcast_panel: choose_client: "Continue" help_panel: title: "Subscribe?" paragraph1: "You are about to subscribe to a podcast. This will allow your podcast app to automatically download new episodes or access the archive of previously released episodes." paragraph2: "The Podlove Subscribe Button helps you to do this. Select your favorite podcast app from a list of potential apps on your device or pick a podcast cloud service on the web that you use." paragraph3: "Upon launch, the podcast client should offer you to add the podcast to your list of subscriptions. Use the download link to get the app if not yet available." clients_panel: app: "App" cloud: "Cloud" other_client: "Other App" let_device_decide: "Let device decide" finish_panel: handing_over_to: "Handing over to %{client}" something_went_wrong: "Did something go wrong?" try_again: "Try again" install: "Install %{client}" register_an_account: "Register an account with " please_copy_url: "Please copy the URL below and add it to your podcast or RSS app." copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "or install app" eo: button: "Aboni" panels: title: "Aboni" podcast_panel: choose_client: "Elekti aplikaĵon" help_panel: title: "Ĉu aboni?" paragraph1: "Per abono de podkasto vi permesos al via podkasta aplikaĵo aŭtomate elŝuti novajn aŭ arkivajn epizodojn." paragraph2: "La Podlove Abonbutono helpas vin fari tion. Elektu vian plej ŝatatan podkastan aplikaĵon el listo de eblaj aplikaĵoj sur via aparato aŭ elektu vian uzatan nuban servon en la reto." paragraph3: "Lanĉate la podkasta aplikaĵo ebligu al vi aldoni la podkaston al via abonlisto. Uzu la elŝut-ligilon, se la aplikaĵo ankoraŭ ne estas instalita." clients_panel: app: "Aplikaĵo" cloud: "Nubo" other_client: "Alia aplikaĵo" let_the_device_decide: "Aŭtomata propono" finish_panel: handing_over_to: "Transdonanta al %{client}" something_went_wrong: "Ĉu io misfunkciis?" try_again: "Reprovi" install: "Instali %{client}'n" register_an_account: "Registriĝi ĉe " please_copy_url: "Bonvolu kopii la suban URLn kaj aldoni ĝin al via podkasta aplikaĵo aŭ RSS-legilo." copy_button_text: "Kopii URLn" copy_success: "URL kopiite" or_install: "aŭ instali la aplikaĵon" fi: button: "Tilaa" panels: title: "Tilaa" podcast_panel: choose_client: "Valitse ohjelma" help_panel: title: "Haluatko tilata?" paragraph1: "You are about to subscribe to a podcast. This will allow your podcast app to automatically download new episodes or access the archive of previously released episodes." paragraph2: "The Podlove Subscribe Button helps you to do this. Select your favorite podcast app from a list of potential apps on your device or pick a podcast cloud service on the web that you use." paragraph3: "Upon launch, the podcast client should offer you to add the podcast to your list of subscriptions. Use the download link to get the app if not yet available." clients_panel: app: "App" cloud: "Cloud" other_client: "Eri ohjelma" finish_panel: handing_over_to: "Annetaan %{client}:lle" something_went_wrong: "Menikö jotain väärin?" try_again: "Kokeile uudestaan" install: "Mene %{client}:n sivustolle" register_an_account: "Rekisteröidy" please_copy_url: "Ole hyvä ja kopioi alla olevan linkin ja syötä se sinuun podcast tai RSS ohjelmaan." copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "tai installoi ohjelma" fr: button: "Souscrire" panels: title: "Souscrire" podcast_panel: choose_client: "Choisir App" help_panel: title: "Souscrire?" paragraph1: "Vous êtes sur le point de souscrire à un podcast. Ceci permettra à votre application podcast de télécharger automatiquement de nouveaux épisodes ou d’accéder aux archives d’épisodes préalablement diffusés." paragraph2: "Le bouton souscrire au Podlove vous aide à faire cela. Sélectionnez votre application podcast favorite à partir d’une liste d’applications potentielles sur votre appareil ou choisissez le service podcast dans le cloud que vous utilisez." paragraph3: "Durant le lancement, le client podcast devrait vous offrir la possibilité d’ajouter le podcast à votre liste de souscriptions. Utilisez le lien de téléchargement pour obtenir l’application si celle-ci n’est pas encore présente." clients_panel: app: "App" cloud: "Cloud" other_client: "Autre App" finish_panel: handing_over_to: "Transfert vers %{client}" something_went_wrong: "Y a-t-il eut des problèmes?" try_again: "Essayer à nouveau" install: "Visiter le site de %{client}" register_an_account: "Enregistrer un compte avec" please_copy_url: "Veuillez copier l’URL ci-dessous et ajoutez le à votre application de podcasts ou application RSS." copy_button_text: "Copier l'URL" copy_success: "URL copié" or_install: "ou installer l'application" nl: button: "Abonneren" panels: title: "Abonneren" podcast_panel: choose_client: "App kiezen" help_panel: title: "Abonneren?" paragraph1: "U staat op het punt een podcast te abonneren. Hierdoor kan uw podcast app nieuwe afleveringen automatisch downloaden of toegang tot het archief van eerder uitgebrachte afleveringen geven." paragraph2: "De Podlove Abonneren Button helpt u om dit te doen. Kies uw favoriete podcast app van een lijst van potentiële apps op uw apparaat of kies een podcast cloud service op het web die u gebruikt." paragraph3: "Bij de lancering moet de podcast client u aanbieden om de podcast toe te voegen aan uw lijst met abonnementen. Gebruik de download link naar de app, indien nog niet beschikbaar." clients_panel: app: "App" cloud: "Cloud" other_client: "Ander app" finish_panel: handing_over_to: "Overhandigen aan %{client}" something_went_wrong: "Is er iets mis gegaan?" try_again: "Probeer opnieuw" install: "Bezoek %{client} website" register_an_account: "Registreren op " please_copy_url: "Kopieer de URL hieronder en voeg deze toe aan uw podcast of RSS-app." copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "Of installeer de app" no: button: "Abonner" panels: title: "Abonner" podcast_panel: choose_client: "Velg program" help_panel: title: "Abonner?" paragraph1: "Du er i ferd med å abonnere på en podcast. Dette gir din podcast mulighet til å automatisk laste ned nye episoder, og gir tilgang til arkiv med tidligere publiserte episoder." paragraph2: "Abonnerknappen hjelper deg å gjøre dette. Velg din favoritt podcast app fra en liste over potensielle apps på enheten eller velge en podcast skytjeneste på nettet som du bruker." paragraph3: "Upon launch, the podcast client should offer you to add the podcast to your list of subscriptions. Use the download link to get the app if not yet available." clients_panel: app: "Program" cloud: "Sky" other_client: "Andre program" finish_panel: handing_over_to: "Handing over to %{client}" something_went_wrong: "Gikk noe galt?" try_again: "Prøv igjen" install: "Besøk %{client} nettside" register_an_account: "Registrer konto hos " please_copy_url: "Vennligst kopier URLen nedenfor og legg den til din podcast eller RSS." or_install: "eller installer app" ja: button: "登録する" panels: title: "登録する" podcast_panel: choose_client: "クライアントを選ぶ" help_panel: title: "登録がよろしいですか?" paragraph1: "今新しいポットキャストを登録しています。それでポットキャストクライアントアプリケーションで新しいエピソードを自動でダウンロードできる、またはポットキャストアーカイブで過去のエピソードを探せます。" paragraph2: "ポットラブ登録ボタンは登録を支援します。気に入り、使っているポットキャストクライアントがポットキャストクラウドサービスを使用可能なもののリストを選んで下さい。" paragraph3: "スタートアップでポットキャストクライアントがポットキャストを登録はずです。アプリがまだインストールしなかったら、ダウンロードリンクをインストールために使って下さい。" clients_panel: app: "アプリ" cloud: "クラウド" other_client: "他のクライアント" finish_panel: handing_over_to: "%{client}に渡す" something_went_wrong: "何が失敗しましたか?" try_again: "もう一度試してください" install: "Visit %{client} website" register_an_account: "%{client}にアカウントを登録する" please_copy_url: "URLをコピーして、ポットキャストがRSSクライアントに貼り付けて下さい。" copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "or install app" ru: button: "Подписаться" panels: title: "Подписаться" podcast_panel: choose_client: "выберите приложение." help_panel: title: "Подписаться?" paragraph1: "Вы собираетесь подписаться на подкаст. Это позволит вашему подкаст приложению автоматически загружать новые эпизоды или получить доступ к архиву ранее выпущенных эпизодов." paragraph2: "Кнопка Подписаться поможет вам сделать это. Выберите своё любимое подкаст приложение из списка потенциальных приложений для вашего устройства или выберите облачный сервис в интернете, который вы используете." paragraph3: "При запуске, подкаст приложение должно предложить вам добавить подкаст в свой список подписок. Используйте ссылку, чтобы получить приложение, если его ещё не имеется." clients_panel: app: "Приложение" cloud: "Облоко" other_client: "другое приложение" finish_panel: handing_over_to: "перейти к %{client}" something_went_wrong: "Что-то пошло не так?" try_again: "попробуйте еще раз" install: "посетите сайт %{client}" register_an_account: "Зарегистрируйте аккаунт с" please_copy_url: "пожалуйста скопируйте ссылку внизу и добавьте к своему подкаст или RSS приложению" or_install: "Или установите приложение\n" zh: button: "订阅" panels: title: "订阅" podcast_panel: choose_client: "Choose App" help_panel: title: "订阅?" paragraph1: "你在订阅一个播客,它会自动下载新的广播节目或进入以前的下载目录。" paragraph2: "这个订阅键将协助你完成。从你的设备或者播客云服务上选择你喜欢的应用。" paragraph3: "启动时,播客客户端会提醒你将播客加入你的订阅列表中。如还未安装,也可通过链接下载安装此应用。" clients_panel: app: "应用" cloud: "云" other_client: "其他应用" finish_panel: handing_over_to: "提交给%{client}" something_went_wrong: "有错误?" try_again: "重试" install: "访问%{client}网站" register_an_account: "注册账号 " please_copy_url: "请复制下面的链接,添加到你的播客或RSS应用中。" copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "或安装应用" module.exports = Translations
77199
_ = require('underscore') Handlebars = require('handlebars') class Translations constructor: (language) -> @locale = language.split('-')[0] Handlebars.registerHelper 't', (key, options) => new Handlebars.SafeString(@t(key, options.hash)) t: (key, options={}) -> @translate(key, options) translate: (key, options={}) -> key_array = key.split('.') _translations = @_translations[@locale] value = null last_key = null _.each key_array, (key) -> last_key = key value = if value value[key] else _translations[key] unless value? value_array = [] _.forEach last_key.split('_'), (split_key) -> value_array.push(split_key.charAt(0).toUpperCase() + split_key.slice(1)) value = value_array.join(' ') @interpolate(value, options) interpolate: (string, interpolations) => string = string.replace /%{([^{}]*)}/g, (a, b) -> r = interpolations[b] if typeof r == 'string' || typeof r == 'number' r else a string @defaultLanguage: 'en' supportsLanguage: () -> keys = Object.keys(@_translations) if keys.indexOf(@locale) != -1 true else false _translations: de: button: "Abonnieren" panels: title: "Abonnieren" podcast_panel: choose_client: "Weiter" help_panel: title: "Abonnieren?" paragraph1: "Dank eines Abonnements verpasst du keine Episode dieses Podcasts mehr." paragraph2: "Nach dem Abonnieren lädt eine Podcast-App automatisch neue Folgen herunter und gibt dir Zugriff auf das Episoden-Archiv." paragraph3: "Der Podlove Subscribe Button macht das Abonnieren leichter. Wähle eine App oder einen Cloud-Service aus und lasse den Button alles Weitere erledigen. Benutze den Download-Link, um die App falls nötig zu installieren." clients_panel: app: "App" cloud: "Cloud" other_client: "Andere App" let_device_decide: "Automatisch erkennen" finish_panel: handing_over_to: "Übergebe an<br> %{client}" something_went_wrong: "Funktioniert etwas nicht wie erwartet?" try_again: "Nochmal versuchen" install: "%{client} installieren" register_an_account: "Einen Account registrieren bei " please_copy_url: "Bitte die URL kopieren und in deine Podcast- oder RSS-App einfügen." copy_button_text: "URL kopieren" copy_success: "URL in die Zwischenablage kopiert." or_install: "oder App installieren" en: button: "Subscribe" panels: title: "Subscribe" podcast_panel: choose_client: "Continue" help_panel: title: "Subscribe?" paragraph1: "You are about to subscribe to a podcast. This will allow your podcast app to automatically download new episodes or access the archive of previously released episodes." paragraph2: "The Podlove Subscribe Button helps you to do this. Select your favorite podcast app from a list of potential apps on your device or pick a podcast cloud service on the web that you use." paragraph3: "Upon launch, the podcast client should offer you to add the podcast to your list of subscriptions. Use the download link to get the app if not yet available." clients_panel: app: "App" cloud: "Cloud" other_client: "Other App" let_device_decide: "Let device decide" finish_panel: handing_over_to: "Handing over to %{client}" something_went_wrong: "Did something go wrong?" try_again: "Try again" install: "Install %{client}" register_an_account: "Register an account with " please_copy_url: "Please copy the URL below and add it to your podcast or RSS app." copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "or install app" eo: button: "Aboni" panels: title: "Aboni" podcast_panel: choose_client: "Elekti aplikaĵon" help_panel: title: "Ĉu aboni?" paragraph1: "Per abono de podkasto vi permesos al via podkasta aplikaĵo aŭtomate elŝuti novajn aŭ arkivajn epizodojn." paragraph2: "La Podlove Abonbutono helpas vin fari tion. Elektu vian plej ŝatatan podkastan aplikaĵon el listo de eblaj aplikaĵoj sur via aparato aŭ elektu vian uzatan nuban servon en la reto." paragraph3: "Lanĉate la podkasta aplikaĵo ebligu al vi aldoni la podkaston al via abonlisto. Uzu la elŝut-ligilon, se la aplikaĵo ankoraŭ ne estas instalita." clients_panel: app: "Aplikaĵo" cloud: "Nubo" other_client: "Alia aplikaĵo" let_the_device_decide: "Aŭtomata propono" finish_panel: handing_over_to: "Transdonanta al %{client}" something_went_wrong: "Ĉu io misfunkciis?" try_again: "Reprovi" install: "Instali %{client}'n" register_an_account: "Registriĝi ĉe " please_copy_url: "Bonvolu kopii la suban URLn kaj aldoni ĝin al via podkasta aplikaĵo aŭ RSS-legilo." copy_button_text: "Kopii URLn" copy_success: "URL kopiite" or_install: "aŭ instali la aplikaĵon" fi: button: "Tilaa" panels: title: "Tilaa" podcast_panel: choose_client: "Valitse ohjelma" help_panel: title: "Haluatko tilata?" paragraph1: "You are about to subscribe to a podcast. This will allow your podcast app to automatically download new episodes or access the archive of previously released episodes." paragraph2: "The Podlove Subscribe Button helps you to do this. Select your favorite podcast app from a list of potential apps on your device or pick a podcast cloud service on the web that you use." paragraph3: "Upon launch, the podcast client should offer you to add the podcast to your list of subscriptions. Use the download link to get the app if not yet available." clients_panel: app: "App" cloud: "Cloud" other_client: "Eri ohjelma" finish_panel: handing_over_to: "Annetaan %{client}:lle" something_went_wrong: "Menikö jotain väärin?" try_again: "Kokeile uudestaan" install: "Mene %{client}:n sivustolle" register_an_account: "Re<NAME>" please_copy_url: "Ole hyvä ja kopioi alla olevan linkin ja syötä se sinuun podcast tai RSS ohjelmaan." copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "tai installoi ohjelma" fr: button: "Souscrire" panels: title: "Souscrire" podcast_panel: choose_client: "Choisir App" help_panel: title: "Souscrire?" paragraph1: "Vous êtes sur le point de souscrire à un podcast. Ceci permettra à votre application podcast de télécharger automatiquement de nouveaux épisodes ou d’accéder aux archives d’épisodes préalablement diffusés." paragraph2: "Le bouton souscrire au Podlove vous aide à faire cela. Sélectionnez votre application podcast favorite à partir d’une liste d’applications potentielles sur votre appareil ou choisissez le service podcast dans le cloud que vous utilisez." paragraph3: "Durant le lancement, le client podcast devrait vous offrir la possibilité d’ajouter le podcast à votre liste de souscriptions. Utilisez le lien de téléchargement pour obtenir l’application si celle-ci n’est pas encore présente." clients_panel: app: "App" cloud: "Cloud" other_client: "Autre App" finish_panel: handing_over_to: "Transfert vers %{client}" something_went_wrong: "Y a-t-il eut des problèmes?" try_again: "Essayer à nouveau" install: "Visiter le site de %{client}" register_an_account: "Enregistrer un compte avec" please_copy_url: "Veuillez copier l’URL ci-dessous et ajoutez le à votre application de podcasts ou application RSS." copy_button_text: "Copier l'URL" copy_success: "URL copié" or_install: "ou installer l'application" nl: button: "Abonneren" panels: title: "Abonneren" podcast_panel: choose_client: "App kiezen" help_panel: title: "Abonneren?" paragraph1: "U staat op het punt een podcast te abonneren. Hierdoor kan uw podcast app nieuwe afleveringen automatisch downloaden of toegang tot het archief van eerder uitgebrachte afleveringen geven." paragraph2: "De Podlove Abonneren Button helpt u om dit te doen. Kies uw favoriete podcast app van een lijst van potentiële apps op uw apparaat of kies een podcast cloud service op het web die u gebruikt." paragraph3: "Bij de lancering moet de podcast client u aanbieden om de podcast toe te voegen aan uw lijst met abonnementen. Gebruik de download link naar de app, indien nog niet beschikbaar." clients_panel: app: "App" cloud: "Cloud" other_client: "Ander app" finish_panel: handing_over_to: "Overhandigen aan %{client}" something_went_wrong: "Is er iets mis gegaan?" try_again: "Probeer opnieuw" install: "Bezoek %{client} website" register_an_account: "Registreren op " please_copy_url: "Kopieer de URL hieronder en voeg deze toe aan uw podcast of RSS-app." copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "Of installeer de app" no: button: "Abonner" panels: title: "Abonner" podcast_panel: choose_client: "Velg program" help_panel: title: "Abonner?" paragraph1: "Du er i ferd med å abonnere på en podcast. Dette gir din podcast mulighet til å automatisk laste ned nye episoder, og gir tilgang til arkiv med tidligere publiserte episoder." paragraph2: "Abonnerknappen hjelper deg å gjøre dette. Velg din favoritt podcast app fra en liste over potensielle apps på enheten eller velge en podcast skytjeneste på nettet som du bruker." paragraph3: "Upon launch, the podcast client should offer you to add the podcast to your list of subscriptions. Use the download link to get the app if not yet available." clients_panel: app: "Program" cloud: "Sky" other_client: "<NAME>" finish_panel: handing_over_to: "Handing over to %{client}" something_went_wrong: "Gikk noe galt?" try_again: "Prøv igjen" install: "Besøk %{client} nettside" register_an_account: "Registrer konto hos " please_copy_url: "Vennligst kopier URLen nedenfor og legg den til din podcast eller RSS." or_install: "eller installer app" ja: button: "登録する" panels: title: "登録する" podcast_panel: choose_client: "クライアントを選ぶ" help_panel: title: "登録がよろしいですか?" paragraph1: "今新しいポットキャストを登録しています。それでポットキャストクライアントアプリケーションで新しいエピソードを自動でダウンロードできる、またはポットキャストアーカイブで過去のエピソードを探せます。" paragraph2: "ポットラブ登録ボタンは登録を支援します。気に入り、使っているポットキャストクライアントがポットキャストクラウドサービスを使用可能なもののリストを選んで下さい。" paragraph3: "スタートアップでポットキャストクライアントがポットキャストを登録はずです。アプリがまだインストールしなかったら、ダウンロードリンクをインストールために使って下さい。" clients_panel: app: "アプリ" cloud: "クラウド" other_client: "他のクライアント" finish_panel: handing_over_to: "%{client}に渡す" something_went_wrong: "何が失敗しましたか?" try_again: "もう一度試してください" install: "Visit %{client} website" register_an_account: "%{client}にアカウントを登録する" please_copy_url: "URLをコピーして、ポットキャストがRSSクライアントに貼り付けて下さい。" copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "or install app" ru: button: "Подписаться" panels: title: "Подписаться" podcast_panel: choose_client: "выберите приложение." help_panel: title: "Подписаться?" paragraph1: "Вы собираетесь подписаться на подкаст. Это позволит вашему подкаст приложению автоматически загружать новые эпизоды или получить доступ к архиву ранее выпущенных эпизодов." paragraph2: "Кнопка Подписаться поможет вам сделать это. Выберите своё любимое подкаст приложение из списка потенциальных приложений для вашего устройства или выберите облачный сервис в интернете, который вы используете." paragraph3: "При запуске, подкаст приложение должно предложить вам добавить подкаст в свой список подписок. Используйте ссылку, чтобы получить приложение, если его ещё не имеется." clients_panel: app: "Приложение" cloud: "Облоко" other_client: "другое приложение" finish_panel: handing_over_to: "перейти к %{client}" something_went_wrong: "Что-то пошло не так?" try_again: "попробуйте еще раз" install: "посетите сайт %{client}" register_an_account: "Зарегистрируйте аккаунт с" please_copy_url: "пожалуйста скопируйте ссылку внизу и добавьте к своему подкаст или RSS приложению" or_install: "Или установите приложение\n" zh: button: "订阅" panels: title: "订阅" podcast_panel: choose_client: "Choose App" help_panel: title: "订阅?" paragraph1: "你在订阅一个播客,它会自动下载新的广播节目或进入以前的下载目录。" paragraph2: "这个订阅键将协助你完成。从你的设备或者播客云服务上选择你喜欢的应用。" paragraph3: "启动时,播客客户端会提醒你将播客加入你的订阅列表中。如还未安装,也可通过链接下载安装此应用。" clients_panel: app: "应用" cloud: "云" other_client: "其他应用" finish_panel: handing_over_to: "提交给%{client}" something_went_wrong: "有错误?" try_again: "重试" install: "访问%{client}网站" register_an_account: "注册账号 " please_copy_url: "请复制下面的链接,添加到你的播客或RSS应用中。" copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "或安装应用" module.exports = Translations
true
_ = require('underscore') Handlebars = require('handlebars') class Translations constructor: (language) -> @locale = language.split('-')[0] Handlebars.registerHelper 't', (key, options) => new Handlebars.SafeString(@t(key, options.hash)) t: (key, options={}) -> @translate(key, options) translate: (key, options={}) -> key_array = key.split('.') _translations = @_translations[@locale] value = null last_key = null _.each key_array, (key) -> last_key = key value = if value value[key] else _translations[key] unless value? value_array = [] _.forEach last_key.split('_'), (split_key) -> value_array.push(split_key.charAt(0).toUpperCase() + split_key.slice(1)) value = value_array.join(' ') @interpolate(value, options) interpolate: (string, interpolations) => string = string.replace /%{([^{}]*)}/g, (a, b) -> r = interpolations[b] if typeof r == 'string' || typeof r == 'number' r else a string @defaultLanguage: 'en' supportsLanguage: () -> keys = Object.keys(@_translations) if keys.indexOf(@locale) != -1 true else false _translations: de: button: "Abonnieren" panels: title: "Abonnieren" podcast_panel: choose_client: "Weiter" help_panel: title: "Abonnieren?" paragraph1: "Dank eines Abonnements verpasst du keine Episode dieses Podcasts mehr." paragraph2: "Nach dem Abonnieren lädt eine Podcast-App automatisch neue Folgen herunter und gibt dir Zugriff auf das Episoden-Archiv." paragraph3: "Der Podlove Subscribe Button macht das Abonnieren leichter. Wähle eine App oder einen Cloud-Service aus und lasse den Button alles Weitere erledigen. Benutze den Download-Link, um die App falls nötig zu installieren." clients_panel: app: "App" cloud: "Cloud" other_client: "Andere App" let_device_decide: "Automatisch erkennen" finish_panel: handing_over_to: "Übergebe an<br> %{client}" something_went_wrong: "Funktioniert etwas nicht wie erwartet?" try_again: "Nochmal versuchen" install: "%{client} installieren" register_an_account: "Einen Account registrieren bei " please_copy_url: "Bitte die URL kopieren und in deine Podcast- oder RSS-App einfügen." copy_button_text: "URL kopieren" copy_success: "URL in die Zwischenablage kopiert." or_install: "oder App installieren" en: button: "Subscribe" panels: title: "Subscribe" podcast_panel: choose_client: "Continue" help_panel: title: "Subscribe?" paragraph1: "You are about to subscribe to a podcast. This will allow your podcast app to automatically download new episodes or access the archive of previously released episodes." paragraph2: "The Podlove Subscribe Button helps you to do this. Select your favorite podcast app from a list of potential apps on your device or pick a podcast cloud service on the web that you use." paragraph3: "Upon launch, the podcast client should offer you to add the podcast to your list of subscriptions. Use the download link to get the app if not yet available." clients_panel: app: "App" cloud: "Cloud" other_client: "Other App" let_device_decide: "Let device decide" finish_panel: handing_over_to: "Handing over to %{client}" something_went_wrong: "Did something go wrong?" try_again: "Try again" install: "Install %{client}" register_an_account: "Register an account with " please_copy_url: "Please copy the URL below and add it to your podcast or RSS app." copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "or install app" eo: button: "Aboni" panels: title: "Aboni" podcast_panel: choose_client: "Elekti aplikaĵon" help_panel: title: "Ĉu aboni?" paragraph1: "Per abono de podkasto vi permesos al via podkasta aplikaĵo aŭtomate elŝuti novajn aŭ arkivajn epizodojn." paragraph2: "La Podlove Abonbutono helpas vin fari tion. Elektu vian plej ŝatatan podkastan aplikaĵon el listo de eblaj aplikaĵoj sur via aparato aŭ elektu vian uzatan nuban servon en la reto." paragraph3: "Lanĉate la podkasta aplikaĵo ebligu al vi aldoni la podkaston al via abonlisto. Uzu la elŝut-ligilon, se la aplikaĵo ankoraŭ ne estas instalita." clients_panel: app: "Aplikaĵo" cloud: "Nubo" other_client: "Alia aplikaĵo" let_the_device_decide: "Aŭtomata propono" finish_panel: handing_over_to: "Transdonanta al %{client}" something_went_wrong: "Ĉu io misfunkciis?" try_again: "Reprovi" install: "Instali %{client}'n" register_an_account: "Registriĝi ĉe " please_copy_url: "Bonvolu kopii la suban URLn kaj aldoni ĝin al via podkasta aplikaĵo aŭ RSS-legilo." copy_button_text: "Kopii URLn" copy_success: "URL kopiite" or_install: "aŭ instali la aplikaĵon" fi: button: "Tilaa" panels: title: "Tilaa" podcast_panel: choose_client: "Valitse ohjelma" help_panel: title: "Haluatko tilata?" paragraph1: "You are about to subscribe to a podcast. This will allow your podcast app to automatically download new episodes or access the archive of previously released episodes." paragraph2: "The Podlove Subscribe Button helps you to do this. Select your favorite podcast app from a list of potential apps on your device or pick a podcast cloud service on the web that you use." paragraph3: "Upon launch, the podcast client should offer you to add the podcast to your list of subscriptions. Use the download link to get the app if not yet available." clients_panel: app: "App" cloud: "Cloud" other_client: "Eri ohjelma" finish_panel: handing_over_to: "Annetaan %{client}:lle" something_went_wrong: "Menikö jotain väärin?" try_again: "Kokeile uudestaan" install: "Mene %{client}:n sivustolle" register_an_account: "RePI:NAME:<NAME>END_PI" please_copy_url: "Ole hyvä ja kopioi alla olevan linkin ja syötä se sinuun podcast tai RSS ohjelmaan." copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "tai installoi ohjelma" fr: button: "Souscrire" panels: title: "Souscrire" podcast_panel: choose_client: "Choisir App" help_panel: title: "Souscrire?" paragraph1: "Vous êtes sur le point de souscrire à un podcast. Ceci permettra à votre application podcast de télécharger automatiquement de nouveaux épisodes ou d’accéder aux archives d’épisodes préalablement diffusés." paragraph2: "Le bouton souscrire au Podlove vous aide à faire cela. Sélectionnez votre application podcast favorite à partir d’une liste d’applications potentielles sur votre appareil ou choisissez le service podcast dans le cloud que vous utilisez." paragraph3: "Durant le lancement, le client podcast devrait vous offrir la possibilité d’ajouter le podcast à votre liste de souscriptions. Utilisez le lien de téléchargement pour obtenir l’application si celle-ci n’est pas encore présente." clients_panel: app: "App" cloud: "Cloud" other_client: "Autre App" finish_panel: handing_over_to: "Transfert vers %{client}" something_went_wrong: "Y a-t-il eut des problèmes?" try_again: "Essayer à nouveau" install: "Visiter le site de %{client}" register_an_account: "Enregistrer un compte avec" please_copy_url: "Veuillez copier l’URL ci-dessous et ajoutez le à votre application de podcasts ou application RSS." copy_button_text: "Copier l'URL" copy_success: "URL copié" or_install: "ou installer l'application" nl: button: "Abonneren" panels: title: "Abonneren" podcast_panel: choose_client: "App kiezen" help_panel: title: "Abonneren?" paragraph1: "U staat op het punt een podcast te abonneren. Hierdoor kan uw podcast app nieuwe afleveringen automatisch downloaden of toegang tot het archief van eerder uitgebrachte afleveringen geven." paragraph2: "De Podlove Abonneren Button helpt u om dit te doen. Kies uw favoriete podcast app van een lijst van potentiële apps op uw apparaat of kies een podcast cloud service op het web die u gebruikt." paragraph3: "Bij de lancering moet de podcast client u aanbieden om de podcast toe te voegen aan uw lijst met abonnementen. Gebruik de download link naar de app, indien nog niet beschikbaar." clients_panel: app: "App" cloud: "Cloud" other_client: "Ander app" finish_panel: handing_over_to: "Overhandigen aan %{client}" something_went_wrong: "Is er iets mis gegaan?" try_again: "Probeer opnieuw" install: "Bezoek %{client} website" register_an_account: "Registreren op " please_copy_url: "Kopieer de URL hieronder en voeg deze toe aan uw podcast of RSS-app." copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "Of installeer de app" no: button: "Abonner" panels: title: "Abonner" podcast_panel: choose_client: "Velg program" help_panel: title: "Abonner?" paragraph1: "Du er i ferd med å abonnere på en podcast. Dette gir din podcast mulighet til å automatisk laste ned nye episoder, og gir tilgang til arkiv med tidligere publiserte episoder." paragraph2: "Abonnerknappen hjelper deg å gjøre dette. Velg din favoritt podcast app fra en liste over potensielle apps på enheten eller velge en podcast skytjeneste på nettet som du bruker." paragraph3: "Upon launch, the podcast client should offer you to add the podcast to your list of subscriptions. Use the download link to get the app if not yet available." clients_panel: app: "Program" cloud: "Sky" other_client: "PI:NAME:<NAME>END_PI" finish_panel: handing_over_to: "Handing over to %{client}" something_went_wrong: "Gikk noe galt?" try_again: "Prøv igjen" install: "Besøk %{client} nettside" register_an_account: "Registrer konto hos " please_copy_url: "Vennligst kopier URLen nedenfor og legg den til din podcast eller RSS." or_install: "eller installer app" ja: button: "登録する" panels: title: "登録する" podcast_panel: choose_client: "クライアントを選ぶ" help_panel: title: "登録がよろしいですか?" paragraph1: "今新しいポットキャストを登録しています。それでポットキャストクライアントアプリケーションで新しいエピソードを自動でダウンロードできる、またはポットキャストアーカイブで過去のエピソードを探せます。" paragraph2: "ポットラブ登録ボタンは登録を支援します。気に入り、使っているポットキャストクライアントがポットキャストクラウドサービスを使用可能なもののリストを選んで下さい。" paragraph3: "スタートアップでポットキャストクライアントがポットキャストを登録はずです。アプリがまだインストールしなかったら、ダウンロードリンクをインストールために使って下さい。" clients_panel: app: "アプリ" cloud: "クラウド" other_client: "他のクライアント" finish_panel: handing_over_to: "%{client}に渡す" something_went_wrong: "何が失敗しましたか?" try_again: "もう一度試してください" install: "Visit %{client} website" register_an_account: "%{client}にアカウントを登録する" please_copy_url: "URLをコピーして、ポットキャストがRSSクライアントに貼り付けて下さい。" copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "or install app" ru: button: "Подписаться" panels: title: "Подписаться" podcast_panel: choose_client: "выберите приложение." help_panel: title: "Подписаться?" paragraph1: "Вы собираетесь подписаться на подкаст. Это позволит вашему подкаст приложению автоматически загружать новые эпизоды или получить доступ к архиву ранее выпущенных эпизодов." paragraph2: "Кнопка Подписаться поможет вам сделать это. Выберите своё любимое подкаст приложение из списка потенциальных приложений для вашего устройства или выберите облачный сервис в интернете, который вы используете." paragraph3: "При запуске, подкаст приложение должно предложить вам добавить подкаст в свой список подписок. Используйте ссылку, чтобы получить приложение, если его ещё не имеется." clients_panel: app: "Приложение" cloud: "Облоко" other_client: "другое приложение" finish_panel: handing_over_to: "перейти к %{client}" something_went_wrong: "Что-то пошло не так?" try_again: "попробуйте еще раз" install: "посетите сайт %{client}" register_an_account: "Зарегистрируйте аккаунт с" please_copy_url: "пожалуйста скопируйте ссылку внизу и добавьте к своему подкаст или RSS приложению" or_install: "Или установите приложение\n" zh: button: "订阅" panels: title: "订阅" podcast_panel: choose_client: "Choose App" help_panel: title: "订阅?" paragraph1: "你在订阅一个播客,它会自动下载新的广播节目或进入以前的下载目录。" paragraph2: "这个订阅键将协助你完成。从你的设备或者播客云服务上选择你喜欢的应用。" paragraph3: "启动时,播客客户端会提醒你将播客加入你的订阅列表中。如还未安装,也可通过链接下载安装此应用。" clients_panel: app: "应用" cloud: "云" other_client: "其他应用" finish_panel: handing_over_to: "提交给%{client}" something_went_wrong: "有错误?" try_again: "重试" install: "访问%{client}网站" register_an_account: "注册账号 " please_copy_url: "请复制下面的链接,添加到你的播客或RSS应用中。" copy_button_text: "Copy URL" copy_success: "URL copied to clipboard" or_install: "或安装应用" module.exports = Translations
[ { "context": " [\n [\n \"Where would you be most likely to find Professor P's phone?\"\n \"In Sleepy's basket\"\n \"On the ", "end": 76, "score": 0.7472236156463623, "start": 67, "tag": "NAME", "value": "Professor" }, { "context": "ng room\"\n ]\n [\n \"What is the bes...
src/documents/games/quiz/book1medium.js.coffee
davidxmoody/professorp.co.uk
2
module.exports = [ [ "Where would you be most likely to find Professor P's phone?" "In Sleepy's basket" "On the hall table" "In the living room" ] [ "What is the best way to find Professor P's phone?" "Call out and ask it where it is" "Ask Sleepy to go and fetch it" "Wait for it to ring" ] [ "Which of Professor P's inventions is polite and helpful?" "His phone" "His fridge" "His dishwasher" ] [ "How does Professor P's fridge behave?" "Grumpy" "Helpful" "Funny" ] [ "What is the best way to open Professor P's fridge?" "Ask it nicely" "Yank the handle hard" "Prise it open with a screwdriver" ] [ "Which of Professor P's inventions is bad tempered?" "His fridge" "His toaster" "His washing machine" ] [ "What does Professor P's toaster do?" "Sometimes burns toast" "Never burns toast" "Always burns toast" ] [ "Which of Professor P's inventions tells jokes?" "His toaster" "His fridge" "His dishwasher" ] [ "Which of Professor P's inventions doesn't know when to stop talking?" "His toaster" "His phone" "His washing machine" ] [ "What does Professor P's front door do?" "Talks in a loud commanding voice" "Often bursts into fits of giggles" "Laughs loudly" ] [ "What's unusual about Professor P's cans of self-heating beans?" "They sometimes explode" "They always explode" "They don't heat up the beans" ] [ "Which of Professor P's inventions does not talk?" "His dishwasher" "His phone" "His watch" ] [ "What is unusual about Professor P's watch?" "It reminds him of appointments" "It often gets the time wrong" "It keeps falling off his wrist" ] [ "What is unusual about the Professor P's answer phone?" "It won't let you talk to Professor P if you're trying to sell something" "It doesn't record messages" "It explodes" ] [ "What type of dog is Sparky?" "A Labrador puppy" "A beagle" "A poodle" ] [ "What was Professor P wearing when Peter and Tara first met him?" "Pyjamas and a long green dressing gown" "A lab coat" "A T-shirt and jeans" ] [ "What type of hair does Professor P have?" "Thick dark hair" "Short fair hair" "Short red hair" ] [ "What was Professor P's job before he became an inventor?" "He was a professor at Cambridge University" "He was a school teacher" "Nothing, he's always been an inventor" ] [ "What type of house does Professor P's live in?" "An old stone building overgrown with ivy and roses" "A modern semi-detached on an estate" "A large mansion" ] [ "What was the colour of the smoke from Professor P's failed experiment?" "Purple" "White" "Grey" ] [ "What did Mary give to Peter and Tara to thank them for their help?" "A box of fossil collecting tools" "A polished ammonite" "A large shark's tooth" ] [ "Why did Peter and Tara search for Professor P in a cave?" "Because they read in his diary that he had gone to a cave" "Because Sleepy led them to the cave" "Because Mary told them he was there" ] [ "Why were Peter and Tara horrified when they first went into Professor P's bedroom?" "Because they thought it had been burgled" "Because they discovered a dead body" "Because it was completely empty" ] [ "What did Peter and Tara discover from reading the notebook beside Professor P's bed?" "That Professor P was planning a trip back in time" "That Professor P was staying in Cambridge" "Nothing, they couldn't find it" ] [ "Why did Floppy tell Peter and Tara that they had to go back in time?" "To find Professor P" "To discover what the Jurassic was like" "He didn't, it was Peter and Tara's idea" ] [ "Why did Peter and Tara ask Mary what life was like 150 million years ago?" "Because they wanted to know if it was safe to travel back in time" "Because they were doing a school project on dinosaurs" "Because they needed information for their fossil guide" ] [ "What fruits were common in the Jurassic Period?" "None, there were no fruits in the Jurassic" "Bananas and kiwis" "Pears and apples" ] [ "Why did Peter leave Tara in the time machine?" "To fetch Sleepy" "To fetch Sparky" "To get his rucksack" ] [ "What did Peter do after Tara had gone back in time?" "He went to Professor P's house" "He went home to tell his parents what had happened" "He asked Mary for help" ] [ "Why did Professor P not go back in time with Peter?" "Because there was not enough room for him to fit in the time machine" "Because the time machine did not work properly" "Because he pressed the wrong button on the time machine" ] [ "What happened to Peter when he first arrived in the Jurassic?" "He fell into the sea" "He was attacked by a dinosaur" "He fell onto the ground and bumped his head" ] [ "What did Peter see on one of the Jurassic islands when he looked through the binoculars?" "The letter P, made out of rocks and stones" "The letters Professor P, made out of seaweed" "The word 'HELP' written in the sand" ] [ "What happened to the first raft that Peter built?" "It sank in the water, it was too heavy" "It fell to pieces in the water, the glue was not strong enough" "It worked fine" ] [ "What did Peter use to get his raft to float?" "Professor P's Superfoam" "Plastic bags filled with air" "Rubber tyres" ] [ "What were the friendly dolphin-like creatures that greeted Peter when he was crossing the Jurassic sea in his homemade raft?" "Ichthyosaurs" "Pterosaurs" "Liopleurodons" ] [ "What did Peter and Tara use to build their tree house?" "Professor P's electric penknife, Superstring, Superfoam and Super-superglue" "Professor P's tree-house making machine" "A saw, hammer and nails" ] [ "What went wrong with Professor P's Superstring?" "The button got stuck and the string went everywhere" "The button broke and no string came out" "Nothing, it worked fine" ] [ "How did Floppy convince Mary that Peter and Tara had travelled back in time?" "By turning into a huge T-Rex" "By turning into a pterosaur and flying around the Fossil Shop" "By explaining how the time machine worked" ] [ "What did Mary tell Peter and Tara about the 'gold' they had found on the beach?" "That it was not real gold, it was called fool's gold" "That it was very valuable" "That it was a type of copper ore" ] [ "Why did Peter get annoyed with himself on the journey to Cambridge?" "Because he realised he had forgotten to bring Floppy" "Because he realised he had forgotten to bring his map" "Because he realised he had forgotten to bring his packed lunch" ] [ "Why did the porter at Professor P's college get annoyed?" "Because no dogs are allowed in the college" "Because no cats are allowed in the college" "Because walking on the grass is not allowed " ] [ "Why was Peter horrified when he first saw Professor P in Cambridge?" "Because Professor P looked so unhappy" "Because Professor P looked completely different" "Because Professor P was in a wheelchair" ] [ "What convinced Professor P that Peter and Tara were telling the truth about their time travel adventure?" "He was reunited with Sleepy" "He spoke to Floppy" "He saw a real ammonite shell" ] [ "Why did Peter and Tara want to return to their own world?" "Because in their own world, Professor P lived nearby" "Because in their own world, Mary lived nearby" "Because their own world had dinosaurs" ] [ "What did Professor P say when he heard Floppy's First Theory of Everything?" "He said it was brilliant" "He said he did not understand it" "He said it needed more work" ] [ "Why did Professor P not climb down the cliff to rescue the time machine?" "He was afraid of heights" "He was too big to fit into the climbing harness" "Because the cliffs were too dangerous" ] [ "What does Peter want to be when he grows up?" "An inventor or a writer" "An artist" "A company director" ] [ "What does Tara want to be when she grows up?" "An artist" "An inventor or a writer" "A company director" ] [ "What was the name of Peter and Tara's exhibition in the Fossil Shop?" "Life in the Jurassic" "Dinosaur Display" "Ammonite Adventures" ] [ "What was the 'little present' that Professor P gave Peter and Tara at their exhibition?" "Photos from their trip to the Jurassic" "An ammonite fossil" "A book about fossils" ] [ "What is the name of the fossil that Peter thought looked like a hedgehog spine?" "Belemnite" "Ammonite" "Shark's tooth" ] [ "Where is the Jurassic Coast?" "In Dorset and East Devon" "In California, America" "It is not a real place, it's just made up for the story" ] ]
45488
module.exports = [ [ "Where would you be most likely to find <NAME> P's phone?" "In Sleepy's basket" "On the hall table" "In the living room" ] [ "What is the best way to find <NAME> P's phone?" "Call out and ask it where it is" "Ask Sleepy to go and fetch it" "Wait for it to ring" ] [ "Which of Professor P's inventions is polite and helpful?" "His phone" "His fridge" "His dishwasher" ] [ "How does Professor P's fridge behave?" "Grumpy" "Helpful" "Funny" ] [ "What is the best way to open <NAME>essor P's fridge?" "Ask it nicely" "Yank the handle hard" "Prise it open with a screwdriver" ] [ "Which of Professor P's inventions is bad tempered?" "His fridge" "His toaster" "His washing machine" ] [ "What does <NAME>essor P's toaster do?" "Sometimes burns toast" "Never burns toast" "Always burns toast" ] [ "Which of Professor P's inventions tells jokes?" "His toaster" "His fridge" "His dishwasher" ] [ "Which of Professor P's inventions doesn't know when to stop talking?" "His toaster" "His phone" "His washing machine" ] [ "What does <NAME>essor P's front door do?" "Talks in a loud commanding voice" "Often bursts into fits of giggles" "Laughs loudly" ] [ "What's unusual about <NAME>essor P's cans of self-heating beans?" "They sometimes explode" "They always explode" "They don't heat up the beans" ] [ "Which of Professor P's inventions does not talk?" "His dishwasher" "His phone" "His watch" ] [ "What is unusual about <NAME>essor P's watch?" "It reminds him of appointments" "It often gets the time wrong" "It keeps falling off his wrist" ] [ "What is unusual about the Professor P's answer phone?" "It won't let you talk to Professor P if you're trying to sell something" "It doesn't record messages" "It explodes" ] [ "What type of dog is Sparky?" "A Labrador puppy" "A beagle" "A poodle" ] [ "What was <NAME> <NAME> wearing when <NAME> and <NAME> first met him?" "Pyjamas and a long green dressing gown" "A lab coat" "A T-shirt and jeans" ] [ "What type of hair does <NAME> <NAME> <NAME> have?" "Thick dark hair" "Short fair hair" "Short red hair" ] [ "What was <NAME> <NAME>'s job before he became an inventor?" "He was a professor at Cambridge University" "He was a school teacher" "Nothing, he's always been an inventor" ] [ "What type of house does <NAME> <NAME> <NAME>'s live in?" "An old stone building overgrown with ivy and roses" "A modern semi-detached on an estate" "A large mansion" ] [ "What was the colour of the smoke from <NAME>essor P's failed experiment?" "Purple" "White" "Grey" ] [ "What did <NAME> give to <NAME> and <NAME> to thank them for their help?" "A box of fossil collecting tools" "A polished ammonite" "A large shark's tooth" ] [ "Why did <NAME> and <NAME> search for <NAME> <NAME> <NAME> in a cave?" "Because they read in his diary that he had gone to a cave" "Because Sleepy led them to the cave" "Because <NAME> told them he was there" ] [ "Why were <NAME> and <NAME> horrified when they first went into <NAME>essor P's bedroom?" "Because they thought it had been burgled" "Because they discovered a dead body" "Because it was completely empty" ] [ "What did <NAME> and <NAME> discover from reading the notebook beside <NAME> P's bed?" "That Professor P was planning a trip back in time" "That Professor P was staying in Cambridge" "Nothing, they couldn't find it" ] [ "Why did <NAME>loppy tell <NAME> and <NAME> that they had to go back in time?" "To find <NAME> P" "To discover what the Jurassic was like" "He didn't, it was <NAME> and <NAME>'s idea" ] [ "Why did <NAME> and <NAME> ask <NAME> what life was like 150 million years ago?" "Because they wanted to know if it was safe to travel back in time" "Because they were doing a school project on dinosaurs" "Because they needed information for their fossil guide" ] [ "What fruits were common in the Jurassic Period?" "None, there were no fruits in the Jurassic" "Bananas and kiwis" "Pears and apples" ] [ "Why did <NAME> leave <NAME> in the time machine?" "To fetch Sleepy" "To fetch Sparky" "To get his rucksack" ] [ "What did <NAME> do after <NAME> had gone back in time?" "He went to Professor P's house" "He went home to tell his parents what had happened" "He asked <NAME> for help" ] [ "Why did <NAME>essor P not go back in time with <NAME>?" "Because there was not enough room for him to fit in the time machine" "Because the time machine did not work properly" "Because he pressed the wrong button on the time machine" ] [ "What happened to <NAME> when he first arrived in the Jurassic?" "He fell into the sea" "He was attacked by a dinosaur" "He fell onto the ground and bumped his head" ] [ "What did <NAME> see on one of the Jurassic islands when he looked through the binoculars?" "The letter P, made out of rocks and stones" "The letters <NAME>essor P, made out of seaweed" "The word 'HELP' written in the sand" ] [ "What happened to the first raft that <NAME> built?" "It sank in the water, it was too heavy" "It fell to pieces in the water, the glue was not strong enough" "It worked fine" ] [ "What did <NAME> use to get his raft to float?" "Professor P's Superfoam" "Plastic bags filled with air" "Rubber tyres" ] [ "What were the friendly dolphin-like creatures that greeted <NAME> when he was crossing the Jurassic sea in his homemade raft?" "Ichthyosaurs" "Pterosaurs" "Liopleurodons" ] [ "What did <NAME> and <NAME> use to build their tree house?" "Professor P's electric penknife, Superstring, Superfoam and Super-superglue" "Professor P's tree-house making machine" "A saw, hammer and nails" ] [ "What went wrong with Professor P's Superstring?" "The button got stuck and the string went everywhere" "The button broke and no string came out" "Nothing, it worked fine" ] [ "How did <NAME>loppy convince <NAME> that <NAME> and <NAME> had travelled back in time?" "By turning into a huge T-Rex" "By turning into a pterosaur and flying around the Fossil Shop" "By explaining how the time machine worked" ] [ "What did <NAME> tell <NAME> and <NAME> about the 'gold' they had found on the beach?" "That it was not real gold, it was called fool's gold" "That it was very valuable" "That it was a type of copper ore" ] [ "Why did <NAME> get annoyed with himself on the journey to Cambridge?" "Because he realised he had forgotten to bring <NAME>loppy" "Because he realised he had forgotten to bring his map" "Because he realised he had forgotten to bring his packed lunch" ] [ "Why did the porter at <NAME>'s college get annoyed?" "Because no dogs are allowed in the college" "Because no cats are allowed in the college" "Because walking on the grass is not allowed " ] [ "Why was <NAME> horrified when he first saw <NAME> in Cambridge?" "Because <NAME> looked so unhappy" "Because <NAME>essor P looked completely different" "Because <NAME> P was in a wheelchair" ] [ "What convinced <NAME> <NAME> that <NAME> and <NAME> were telling the truth about their time travel adventure?" "He was reunited with Sleepy" "He spoke to <NAME>" "He saw a real ammonite shell" ] [ "Why did <NAME> and <NAME> want to return to their own world?" "Because in their own world, <NAME> lived nearby" "Because in their own world, <NAME> lived nearby" "Because their own world had dinosaurs" ] [ "What did <NAME> say when he heard <NAME>loppy's First Theory of Everything?" "He said it was brilliant" "He said he did not understand it" "He said it needed more work" ] [ "Why did <NAME> not climb down the cliff to rescue the time machine?" "He was afraid of heights" "He was too big to fit into the climbing harness" "Because the cliffs were too dangerous" ] [ "What does <NAME> want to be when he grows up?" "An inventor or a writer" "An artist" "A company director" ] [ "What does <NAME> want to be when she grows up?" "An artist" "An inventor or a writer" "A company director" ] [ "What was the name of <NAME> and <NAME>'s exhibition in the Fossil Shop?" "Life in the Jurassic" "Dinosaur Display" "Ammonite Adventures" ] [ "What was the 'little present' that <NAME> P gave <NAME> and <NAME> at their exhibition?" "Photos from their trip to the Jurassic" "An ammonite fossil" "A book about fossils" ] [ "What is the name of the fossil that <NAME> thought looked like a hedgehog spine?" "Belemnite" "Ammonite" "Shark's tooth" ] [ "Where is the Jurassic Coast?" "In Dorset and East Devon" "In California, America" "It is not a real place, it's just made up for the story" ] ]
true
module.exports = [ [ "Where would you be most likely to find PI:NAME:<NAME>END_PI P's phone?" "In Sleepy's basket" "On the hall table" "In the living room" ] [ "What is the best way to find PI:NAME:<NAME>END_PI P's phone?" "Call out and ask it where it is" "Ask Sleepy to go and fetch it" "Wait for it to ring" ] [ "Which of Professor P's inventions is polite and helpful?" "His phone" "His fridge" "His dishwasher" ] [ "How does Professor P's fridge behave?" "Grumpy" "Helpful" "Funny" ] [ "What is the best way to open PI:NAME:<NAME>END_PIessor P's fridge?" "Ask it nicely" "Yank the handle hard" "Prise it open with a screwdriver" ] [ "Which of Professor P's inventions is bad tempered?" "His fridge" "His toaster" "His washing machine" ] [ "What does PI:NAME:<NAME>END_PIessor P's toaster do?" "Sometimes burns toast" "Never burns toast" "Always burns toast" ] [ "Which of Professor P's inventions tells jokes?" "His toaster" "His fridge" "His dishwasher" ] [ "Which of Professor P's inventions doesn't know when to stop talking?" "His toaster" "His phone" "His washing machine" ] [ "What does PI:NAME:<NAME>END_PIessor P's front door do?" "Talks in a loud commanding voice" "Often bursts into fits of giggles" "Laughs loudly" ] [ "What's unusual about PI:NAME:<NAME>END_PIessor P's cans of self-heating beans?" "They sometimes explode" "They always explode" "They don't heat up the beans" ] [ "Which of Professor P's inventions does not talk?" "His dishwasher" "His phone" "His watch" ] [ "What is unusual about PI:NAME:<NAME>END_PIessor P's watch?" "It reminds him of appointments" "It often gets the time wrong" "It keeps falling off his wrist" ] [ "What is unusual about the Professor P's answer phone?" "It won't let you talk to Professor P if you're trying to sell something" "It doesn't record messages" "It explodes" ] [ "What type of dog is Sparky?" "A Labrador puppy" "A beagle" "A poodle" ] [ "What was PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI wearing when PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI first met him?" "Pyjamas and a long green dressing gown" "A lab coat" "A T-shirt and jeans" ] [ "What type of hair does PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI have?" "Thick dark hair" "Short fair hair" "Short red hair" ] [ "What was PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI's job before he became an inventor?" "He was a professor at Cambridge University" "He was a school teacher" "Nothing, he's always been an inventor" ] [ "What type of house does PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI's live in?" "An old stone building overgrown with ivy and roses" "A modern semi-detached on an estate" "A large mansion" ] [ "What was the colour of the smoke from PI:NAME:<NAME>END_PIessor P's failed experiment?" "Purple" "White" "Grey" ] [ "What did PI:NAME:<NAME>END_PI give to PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI to thank them for their help?" "A box of fossil collecting tools" "A polished ammonite" "A large shark's tooth" ] [ "Why did PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI search for PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI in a cave?" "Because they read in his diary that he had gone to a cave" "Because Sleepy led them to the cave" "Because PI:NAME:<NAME>END_PI told them he was there" ] [ "Why were PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI horrified when they first went into PI:NAME:<NAME>END_PIessor P's bedroom?" "Because they thought it had been burgled" "Because they discovered a dead body" "Because it was completely empty" ] [ "What did PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI discover from reading the notebook beside PI:NAME:<NAME>END_PI P's bed?" "That Professor P was planning a trip back in time" "That Professor P was staying in Cambridge" "Nothing, they couldn't find it" ] [ "Why did PI:NAME:<NAME>END_PIloppy tell PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI that they had to go back in time?" "To find PI:NAME:<NAME>END_PI P" "To discover what the Jurassic was like" "He didn't, it was PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI's idea" ] [ "Why did PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI ask PI:NAME:<NAME>END_PI what life was like 150 million years ago?" "Because they wanted to know if it was safe to travel back in time" "Because they were doing a school project on dinosaurs" "Because they needed information for their fossil guide" ] [ "What fruits were common in the Jurassic Period?" "None, there were no fruits in the Jurassic" "Bananas and kiwis" "Pears and apples" ] [ "Why did PI:NAME:<NAME>END_PI leave PI:NAME:<NAME>END_PI in the time machine?" "To fetch Sleepy" "To fetch Sparky" "To get his rucksack" ] [ "What did PI:NAME:<NAME>END_PI do after PI:NAME:<NAME>END_PI had gone back in time?" "He went to Professor P's house" "He went home to tell his parents what had happened" "He asked PI:NAME:<NAME>END_PI for help" ] [ "Why did PI:NAME:<NAME>END_PIessor P not go back in time with PI:NAME:<NAME>END_PI?" "Because there was not enough room for him to fit in the time machine" "Because the time machine did not work properly" "Because he pressed the wrong button on the time machine" ] [ "What happened to PI:NAME:<NAME>END_PI when he first arrived in the Jurassic?" "He fell into the sea" "He was attacked by a dinosaur" "He fell onto the ground and bumped his head" ] [ "What did PI:NAME:<NAME>END_PI see on one of the Jurassic islands when he looked through the binoculars?" "The letter P, made out of rocks and stones" "The letters PI:NAME:<NAME>END_PIessor P, made out of seaweed" "The word 'HELP' written in the sand" ] [ "What happened to the first raft that PI:NAME:<NAME>END_PI built?" "It sank in the water, it was too heavy" "It fell to pieces in the water, the glue was not strong enough" "It worked fine" ] [ "What did PI:NAME:<NAME>END_PI use to get his raft to float?" "Professor P's Superfoam" "Plastic bags filled with air" "Rubber tyres" ] [ "What were the friendly dolphin-like creatures that greeted PI:NAME:<NAME>END_PI when he was crossing the Jurassic sea in his homemade raft?" "Ichthyosaurs" "Pterosaurs" "Liopleurodons" ] [ "What did PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI use to build their tree house?" "Professor P's electric penknife, Superstring, Superfoam and Super-superglue" "Professor P's tree-house making machine" "A saw, hammer and nails" ] [ "What went wrong with Professor P's Superstring?" "The button got stuck and the string went everywhere" "The button broke and no string came out" "Nothing, it worked fine" ] [ "How did PI:NAME:<NAME>END_PIloppy convince PI:NAME:<NAME>END_PI that PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI had travelled back in time?" "By turning into a huge T-Rex" "By turning into a pterosaur and flying around the Fossil Shop" "By explaining how the time machine worked" ] [ "What did PI:NAME:<NAME>END_PI tell PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI about the 'gold' they had found on the beach?" "That it was not real gold, it was called fool's gold" "That it was very valuable" "That it was a type of copper ore" ] [ "Why did PI:NAME:<NAME>END_PI get annoyed with himself on the journey to Cambridge?" "Because he realised he had forgotten to bring PI:NAME:<NAME>END_PIloppy" "Because he realised he had forgotten to bring his map" "Because he realised he had forgotten to bring his packed lunch" ] [ "Why did the porter at PI:NAME:<NAME>END_PI's college get annoyed?" "Because no dogs are allowed in the college" "Because no cats are allowed in the college" "Because walking on the grass is not allowed " ] [ "Why was PI:NAME:<NAME>END_PI horrified when he first saw PI:NAME:<NAME>END_PI in Cambridge?" "Because PI:NAME:<NAME>END_PI looked so unhappy" "Because PI:NAME:<NAME>END_PIessor P looked completely different" "Because PI:NAME:<NAME>END_PI P was in a wheelchair" ] [ "What convinced PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI that PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI were telling the truth about their time travel adventure?" "He was reunited with Sleepy" "He spoke to PI:NAME:<NAME>END_PI" "He saw a real ammonite shell" ] [ "Why did PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI want to return to their own world?" "Because in their own world, PI:NAME:<NAME>END_PI lived nearby" "Because in their own world, PI:NAME:<NAME>END_PI lived nearby" "Because their own world had dinosaurs" ] [ "What did PI:NAME:<NAME>END_PI say when he heard PI:NAME:<NAME>END_PIloppy's First Theory of Everything?" "He said it was brilliant" "He said he did not understand it" "He said it needed more work" ] [ "Why did PI:NAME:<NAME>END_PI not climb down the cliff to rescue the time machine?" "He was afraid of heights" "He was too big to fit into the climbing harness" "Because the cliffs were too dangerous" ] [ "What does PI:NAME:<NAME>END_PI want to be when he grows up?" "An inventor or a writer" "An artist" "A company director" ] [ "What does PI:NAME:<NAME>END_PI want to be when she grows up?" "An artist" "An inventor or a writer" "A company director" ] [ "What was the name of PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI's exhibition in the Fossil Shop?" "Life in the Jurassic" "Dinosaur Display" "Ammonite Adventures" ] [ "What was the 'little present' that PI:NAME:<NAME>END_PI P gave PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI at their exhibition?" "Photos from their trip to the Jurassic" "An ammonite fossil" "A book about fossils" ] [ "What is the name of the fossil that PI:NAME:<NAME>END_PI thought looked like a hedgehog spine?" "Belemnite" "Ammonite" "Shark's tooth" ] [ "Where is the Jurassic Coast?" "In Dorset and East Devon" "In California, America" "It is not a real place, it's just made up for the story" ] ]
[ { "context": "'\n body: '<p><a class=\"is-follow-link\">Damon Zucconi</a><a class=\"artist-follow\" data-id=\"damon-zuccon", "end": 924, "score": 0.9994051456451416, "start": 911, "tag": "NAME", "value": "Damon Zucconi" }, { "context": "lowButtons()\n @view.artists[0]...
components/article/test/view.coffee
kanaabe/microgravity
0
Q = require 'bluebird-q' _ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' Article = require '../../../models/article' Articles = require '../../../collections/articles' CurrentUser = require '../../../models/current_user' sd = require('sharify').data { resolve } = require 'path' { fabricate } = require 'antigravity' describe 'ArticleView', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Element: window.Element # benv bug that doesn't attach globals to window window.jQuery = $ Backbone.$ = $ $.fn.waypoint = sinon.stub() $.fn.imagesLoaded = sinon.stub() $.fn.fillwidthLite = (@fillwidthLite = sinon.stub()) @article = new Article fabricate 'article', sections: [ { type: 'text' body: '<p><a class="is-follow-link">Damon Zucconi</a><a class="artist-follow" data-id="damon-zucconi"></a></p>' }, { type: 'callout' article: '123' text: '' title: '' hide_image: false }, { type: 'video' url: 'http://youtube.com' cover_image_url: 'http://artsy.net/cover_image_url.jpg' layout: 'full-width' background_color: 'black' }, { type: 'toc' links: [{name: "First Last", value: "First_Last"}] }, { type: 'image_set' images: [ { type: 'image' url: 'https://image.png' caption: 'Trademarked' } ] } ] contributing_authors: [] section_ids: [] benv.render resolve(__dirname, '../templates/index.jade'), { article: @article asset: (->) sd: {} resize: -> crop: -> embed: sinon.stub().returns '<iframe>Test-video</iframe>' footerArticles: new Backbone.Collection superArticle: new Article { super_article: {} } relatedArticles: new Articles }, => @ArticleView = benv.requireWithJadeify( resolve(__dirname, '../client/view'), ['calloutTemplate', 'whatToReadNextTemplate'] ) @ImageSetView = sinon.stub() @ImageSetView::on = sinon.stub() @ArticleView.__set__ 'ImageSetView', @ImageSetView sinon.stub Backbone, 'sync' sinon.stub($, 'get').returns { html: '<iframe>Test-embed</iframe>' } done() afterEach -> $.get.restore() benv.teardown() Backbone.sync.restore() describe '#initSuperArticle', -> it 'sets up the page for non-super articles', -> @view = new @ArticleView el: $('body') article: @article $('body').hasClass('article-sa').should.be.false() it 'sets up the page for super articles', -> @view = new @ArticleView el: $('body') article: @article relatedArticles: new Articles [fabricate 'article'] infiniteScroll: false $('body').hasClass('article-sa').should.be.true() $('body').html().should.not.containEql 'article-related-widget' describe '#setupWhatToReadNext non infinite scroll', -> beforeEach -> Backbone.sync.restore() sinon.stub Backbone, 'sync' it 'removes the article related widget when not infinite scroll', -> @view = new @ArticleView el: $('body'), article: @article $('body').html().should.not.containEql 'article-related-widget' describe '#setupFollowButtons', -> it 'sets the list of artists in an article with ids', -> @view = new @ArticleView el: $('body'), article: @article @view.setupFollowButtons() @view.artists[0].should.equal 'damon-zucconi' describe '#clickPlay', -> it 'replaces iFrame with an autoplay attribute', -> @view = new @ArticleView el: $('body'), article: @article $('.article-video-play-button').click() $('.article-section-video iframe').attr('src').should.containEql('autoplay=1') describe '#toggleArticleToC', -> it 'toggles visibility of TOC on superarticles', -> @view = new @ArticleView el: $('body') article: @article relatedArticles: new Articles [fabricate 'article'] $('.article-sa-sticky-right').click() $('.article-sa-sticky-center').css('max-height').should.containEql('100px') describe '#seuptImageSetPreviews', -> it 'applies jqueryFillwidthLite to image set', -> @view = new @ArticleView el: $('body'), article: @article @view.setupImageSetPreviews() @fillwidthLite.args[0][0].done() $('.article-section-container[data-section-type="image_set"]').css('visibility').should.containEql('visible') describe '#toggleModal', -> it 'renders an imageSet modal with image data', -> @view = new @ArticleView el: $('body'), article: @article $('.article-section-image-set').click() @ImageSetView.args[0][0].items[0].should.have.property('type') @ImageSetView.args[0][0].items[0].should.have.property('url') @ImageSetView.args[0][0].items[0].should.have.property('caption') describe 'ArticleView - Infinite scroll', -> before (done) -> benv.setup => benv.expose $: benv.require 'jquery' Element: window.Element # benv bug that doesn't attach globals to window window.jQuery = $ Backbone.$ = $ @ArticleView = benv.requireWithJadeify( resolve(__dirname, '../client/view') ['whatToReadNextTemplate', 'calloutTemplate'] ) @article = new Article fabricate 'article', sections: [ { type: 'text', body: 'Foo' } ] contributing_authors: [] section_ids: [] @options = { footerArticles: new Backbone.Collection slideshowArtworks: null article: @article calloutArticles: new Backbone.Collection author: new Backbone.Model fabricate 'user' asset: (->) sd: INFINITE_SCROLL: true, RELATED_ARTICLES: [] moment: require('moment') resize: sinon.stub() } sinon.stub Backbone, 'sync' done() after -> benv.teardown() Backbone.sync.restore() describe '#setupWhatToReadNext infinite scroll', -> beforeEach (done) -> benv.render resolve(__dirname, '../templates/index.jade'), @options, => @view = new @ArticleView el: $('body') article: @article infiniteScroll: true done() it 'fetches articles and renders widget', -> Backbone.sync.args[0][2].data.tags.should.ok() Backbone.sync.args[1][2].data.should.have.property('artist_id') Backbone.sync.args[2][2].data.should.not.have.property('artist_id') Backbone.sync.args[2][2].data.should.not.have.property('tags') Backbone.sync.args[0][2].success new Articles fabricate('article',{ id: 'foo', thumbnail_title: 'Foo Title'}) Backbone.sync.args[1][2].success new Articles fabricate('article',{ id: 'boo', thumbnail_title: 'Boo Title'}) Backbone.sync.args[2][2].success new Articles fabricate('article',{ id: 'coo', thumbnail_title: 'Coo Title'}) _.defer => @view.$('.article-related-widget').html().length.should.be.above 1 @view.$('.article-related-widget').html().should.containEql 'What To Read Next' @view.$('.article-related-widget .wtrn-article-container').length.should.equal 3
108583
Q = require 'bluebird-q' _ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' Article = require '../../../models/article' Articles = require '../../../collections/articles' CurrentUser = require '../../../models/current_user' sd = require('sharify').data { resolve } = require 'path' { fabricate } = require 'antigravity' describe 'ArticleView', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Element: window.Element # benv bug that doesn't attach globals to window window.jQuery = $ Backbone.$ = $ $.fn.waypoint = sinon.stub() $.fn.imagesLoaded = sinon.stub() $.fn.fillwidthLite = (@fillwidthLite = sinon.stub()) @article = new Article fabricate 'article', sections: [ { type: 'text' body: '<p><a class="is-follow-link"><NAME></a><a class="artist-follow" data-id="damon-zucconi"></a></p>' }, { type: 'callout' article: '123' text: '' title: '' hide_image: false }, { type: 'video' url: 'http://youtube.com' cover_image_url: 'http://artsy.net/cover_image_url.jpg' layout: 'full-width' background_color: 'black' }, { type: 'toc' links: [{name: "First Last", value: "First_Last"}] }, { type: 'image_set' images: [ { type: 'image' url: 'https://image.png' caption: 'Trademarked' } ] } ] contributing_authors: [] section_ids: [] benv.render resolve(__dirname, '../templates/index.jade'), { article: @article asset: (->) sd: {} resize: -> crop: -> embed: sinon.stub().returns '<iframe>Test-video</iframe>' footerArticles: new Backbone.Collection superArticle: new Article { super_article: {} } relatedArticles: new Articles }, => @ArticleView = benv.requireWithJadeify( resolve(__dirname, '../client/view'), ['calloutTemplate', 'whatToReadNextTemplate'] ) @ImageSetView = sinon.stub() @ImageSetView::on = sinon.stub() @ArticleView.__set__ 'ImageSetView', @ImageSetView sinon.stub Backbone, 'sync' sinon.stub($, 'get').returns { html: '<iframe>Test-embed</iframe>' } done() afterEach -> $.get.restore() benv.teardown() Backbone.sync.restore() describe '#initSuperArticle', -> it 'sets up the page for non-super articles', -> @view = new @ArticleView el: $('body') article: @article $('body').hasClass('article-sa').should.be.false() it 'sets up the page for super articles', -> @view = new @ArticleView el: $('body') article: @article relatedArticles: new Articles [fabricate 'article'] infiniteScroll: false $('body').hasClass('article-sa').should.be.true() $('body').html().should.not.containEql 'article-related-widget' describe '#setupWhatToReadNext non infinite scroll', -> beforeEach -> Backbone.sync.restore() sinon.stub Backbone, 'sync' it 'removes the article related widget when not infinite scroll', -> @view = new @ArticleView el: $('body'), article: @article $('body').html().should.not.containEql 'article-related-widget' describe '#setupFollowButtons', -> it 'sets the list of artists in an article with ids', -> @view = new @ArticleView el: $('body'), article: @article @view.setupFollowButtons() @view.artists[0].should.equal 'damon-z<NAME>' describe '#clickPlay', -> it 'replaces iFrame with an autoplay attribute', -> @view = new @ArticleView el: $('body'), article: @article $('.article-video-play-button').click() $('.article-section-video iframe').attr('src').should.containEql('autoplay=1') describe '#toggleArticleToC', -> it 'toggles visibility of TOC on superarticles', -> @view = new @ArticleView el: $('body') article: @article relatedArticles: new Articles [fabricate 'article'] $('.article-sa-sticky-right').click() $('.article-sa-sticky-center').css('max-height').should.containEql('100px') describe '#seuptImageSetPreviews', -> it 'applies jqueryFillwidthLite to image set', -> @view = new @ArticleView el: $('body'), article: @article @view.setupImageSetPreviews() @fillwidthLite.args[0][0].done() $('.article-section-container[data-section-type="image_set"]').css('visibility').should.containEql('visible') describe '#toggleModal', -> it 'renders an imageSet modal with image data', -> @view = new @ArticleView el: $('body'), article: @article $('.article-section-image-set').click() @ImageSetView.args[0][0].items[0].should.have.property('type') @ImageSetView.args[0][0].items[0].should.have.property('url') @ImageSetView.args[0][0].items[0].should.have.property('caption') describe 'ArticleView - Infinite scroll', -> before (done) -> benv.setup => benv.expose $: benv.require 'jquery' Element: window.Element # benv bug that doesn't attach globals to window window.jQuery = $ Backbone.$ = $ @ArticleView = benv.requireWithJadeify( resolve(__dirname, '../client/view') ['whatToReadNextTemplate', 'calloutTemplate'] ) @article = new Article fabricate 'article', sections: [ { type: 'text', body: 'Foo' } ] contributing_authors: [] section_ids: [] @options = { footerArticles: new Backbone.Collection slideshowArtworks: null article: @article calloutArticles: new Backbone.Collection author: new Backbone.Model fabricate 'user' asset: (->) sd: INFINITE_SCROLL: true, RELATED_ARTICLES: [] moment: require('moment') resize: sinon.stub() } sinon.stub Backbone, 'sync' done() after -> benv.teardown() Backbone.sync.restore() describe '#setupWhatToReadNext infinite scroll', -> beforeEach (done) -> benv.render resolve(__dirname, '../templates/index.jade'), @options, => @view = new @ArticleView el: $('body') article: @article infiniteScroll: true done() it 'fetches articles and renders widget', -> Backbone.sync.args[0][2].data.tags.should.ok() Backbone.sync.args[1][2].data.should.have.property('artist_id') Backbone.sync.args[2][2].data.should.not.have.property('artist_id') Backbone.sync.args[2][2].data.should.not.have.property('tags') Backbone.sync.args[0][2].success new Articles fabricate('article',{ id: 'foo', thumbnail_title: 'Foo Title'}) Backbone.sync.args[1][2].success new Articles fabricate('article',{ id: 'boo', thumbnail_title: 'Boo Title'}) Backbone.sync.args[2][2].success new Articles fabricate('article',{ id: 'coo', thumbnail_title: 'Coo Title'}) _.defer => @view.$('.article-related-widget').html().length.should.be.above 1 @view.$('.article-related-widget').html().should.containEql 'What To Read Next' @view.$('.article-related-widget .wtrn-article-container').length.should.equal 3
true
Q = require 'bluebird-q' _ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' Article = require '../../../models/article' Articles = require '../../../collections/articles' CurrentUser = require '../../../models/current_user' sd = require('sharify').data { resolve } = require 'path' { fabricate } = require 'antigravity' describe 'ArticleView', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Element: window.Element # benv bug that doesn't attach globals to window window.jQuery = $ Backbone.$ = $ $.fn.waypoint = sinon.stub() $.fn.imagesLoaded = sinon.stub() $.fn.fillwidthLite = (@fillwidthLite = sinon.stub()) @article = new Article fabricate 'article', sections: [ { type: 'text' body: '<p><a class="is-follow-link">PI:NAME:<NAME>END_PI</a><a class="artist-follow" data-id="damon-zucconi"></a></p>' }, { type: 'callout' article: '123' text: '' title: '' hide_image: false }, { type: 'video' url: 'http://youtube.com' cover_image_url: 'http://artsy.net/cover_image_url.jpg' layout: 'full-width' background_color: 'black' }, { type: 'toc' links: [{name: "First Last", value: "First_Last"}] }, { type: 'image_set' images: [ { type: 'image' url: 'https://image.png' caption: 'Trademarked' } ] } ] contributing_authors: [] section_ids: [] benv.render resolve(__dirname, '../templates/index.jade'), { article: @article asset: (->) sd: {} resize: -> crop: -> embed: sinon.stub().returns '<iframe>Test-video</iframe>' footerArticles: new Backbone.Collection superArticle: new Article { super_article: {} } relatedArticles: new Articles }, => @ArticleView = benv.requireWithJadeify( resolve(__dirname, '../client/view'), ['calloutTemplate', 'whatToReadNextTemplate'] ) @ImageSetView = sinon.stub() @ImageSetView::on = sinon.stub() @ArticleView.__set__ 'ImageSetView', @ImageSetView sinon.stub Backbone, 'sync' sinon.stub($, 'get').returns { html: '<iframe>Test-embed</iframe>' } done() afterEach -> $.get.restore() benv.teardown() Backbone.sync.restore() describe '#initSuperArticle', -> it 'sets up the page for non-super articles', -> @view = new @ArticleView el: $('body') article: @article $('body').hasClass('article-sa').should.be.false() it 'sets up the page for super articles', -> @view = new @ArticleView el: $('body') article: @article relatedArticles: new Articles [fabricate 'article'] infiniteScroll: false $('body').hasClass('article-sa').should.be.true() $('body').html().should.not.containEql 'article-related-widget' describe '#setupWhatToReadNext non infinite scroll', -> beforeEach -> Backbone.sync.restore() sinon.stub Backbone, 'sync' it 'removes the article related widget when not infinite scroll', -> @view = new @ArticleView el: $('body'), article: @article $('body').html().should.not.containEql 'article-related-widget' describe '#setupFollowButtons', -> it 'sets the list of artists in an article with ids', -> @view = new @ArticleView el: $('body'), article: @article @view.setupFollowButtons() @view.artists[0].should.equal 'damon-zPI:NAME:<NAME>END_PI' describe '#clickPlay', -> it 'replaces iFrame with an autoplay attribute', -> @view = new @ArticleView el: $('body'), article: @article $('.article-video-play-button').click() $('.article-section-video iframe').attr('src').should.containEql('autoplay=1') describe '#toggleArticleToC', -> it 'toggles visibility of TOC on superarticles', -> @view = new @ArticleView el: $('body') article: @article relatedArticles: new Articles [fabricate 'article'] $('.article-sa-sticky-right').click() $('.article-sa-sticky-center').css('max-height').should.containEql('100px') describe '#seuptImageSetPreviews', -> it 'applies jqueryFillwidthLite to image set', -> @view = new @ArticleView el: $('body'), article: @article @view.setupImageSetPreviews() @fillwidthLite.args[0][0].done() $('.article-section-container[data-section-type="image_set"]').css('visibility').should.containEql('visible') describe '#toggleModal', -> it 'renders an imageSet modal with image data', -> @view = new @ArticleView el: $('body'), article: @article $('.article-section-image-set').click() @ImageSetView.args[0][0].items[0].should.have.property('type') @ImageSetView.args[0][0].items[0].should.have.property('url') @ImageSetView.args[0][0].items[0].should.have.property('caption') describe 'ArticleView - Infinite scroll', -> before (done) -> benv.setup => benv.expose $: benv.require 'jquery' Element: window.Element # benv bug that doesn't attach globals to window window.jQuery = $ Backbone.$ = $ @ArticleView = benv.requireWithJadeify( resolve(__dirname, '../client/view') ['whatToReadNextTemplate', 'calloutTemplate'] ) @article = new Article fabricate 'article', sections: [ { type: 'text', body: 'Foo' } ] contributing_authors: [] section_ids: [] @options = { footerArticles: new Backbone.Collection slideshowArtworks: null article: @article calloutArticles: new Backbone.Collection author: new Backbone.Model fabricate 'user' asset: (->) sd: INFINITE_SCROLL: true, RELATED_ARTICLES: [] moment: require('moment') resize: sinon.stub() } sinon.stub Backbone, 'sync' done() after -> benv.teardown() Backbone.sync.restore() describe '#setupWhatToReadNext infinite scroll', -> beforeEach (done) -> benv.render resolve(__dirname, '../templates/index.jade'), @options, => @view = new @ArticleView el: $('body') article: @article infiniteScroll: true done() it 'fetches articles and renders widget', -> Backbone.sync.args[0][2].data.tags.should.ok() Backbone.sync.args[1][2].data.should.have.property('artist_id') Backbone.sync.args[2][2].data.should.not.have.property('artist_id') Backbone.sync.args[2][2].data.should.not.have.property('tags') Backbone.sync.args[0][2].success new Articles fabricate('article',{ id: 'foo', thumbnail_title: 'Foo Title'}) Backbone.sync.args[1][2].success new Articles fabricate('article',{ id: 'boo', thumbnail_title: 'Boo Title'}) Backbone.sync.args[2][2].success new Articles fabricate('article',{ id: 'coo', thumbnail_title: 'Coo Title'}) _.defer => @view.$('.article-related-widget').html().length.should.be.above 1 @view.$('.article-related-widget').html().should.containEql 'What To Read Next' @view.$('.article-related-widget .wtrn-article-container').length.should.equal 3
[ { "context": "Coin from 'coin.js/src'\n\nCoin.start\n key: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJiaXQiOjQ1MDM2MTcwNzU2NzUxNzYsImp0aSI6ImwtekhNTEN1S1hrIiwic3ViIjoiNE5URHh6Qm1UYiJ9.S7bjBU-ua-0zYMwQD4-414PG0UoClsWpC550qx_HrADOPaeyX13RI4YNh4kAP6-RNgkWY_BuuZ9Gm4FKRn862g'\n processor: 'ethereum'\n currenc...
src/js/coin.coffee
hanzoai/ryo.hanzo.ai
0
import moment from 'moment-timezone' import Coin from 'coin.js/src' Coin.start key: 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJiaXQiOjQ1MDM2MTcwNzU2NzUxNzYsImp0aSI6ImwtekhNTEN1S1hrIiwic3ViIjoiNE5URHh6Qm1UYiJ9.S7bjBU-ua-0zYMwQD4-414PG0UoClsWpC550qx_HrADOPaeyX13RI4YNh4kAP6-RNgkWY_BuuZ9Gm4FKRn862g' processor: 'ethereum' currency: 'eth' mode: 'deposit' order: subtotal: 1e9 eth: address: '0x945f873d71b0f497d71a05d25c7bf5e7547ab826' node: '//api.infura.io/v1/jsonrpc/ropsten' m = Coin.getMediator() m.on 'login-success', -> document.location.href = '/account' m.on 'register-success', -> document.location.href = '/account' m.on 'profile-load-failed', -> Coin.client.account.logout() document.location.href = '/login' # m.on 'submit-success', -> # @client.account.get().then (res) => # @data.set 'user', res # firstName = @data.get 'user.firstName' # lastName = @data.get 'user.lastName' # @data.set 'user.name', firstName + ' ' + lastName # Coin.El.scheduleUpdate() window.sortOrders = (orders) -> orders.sort (a, b) -> return moment(b.createdAt).diff moment(a.createdAt) window.logout = () -> Coin.client.account.logout() document.location.href = '/login'
13995
import moment from 'moment-timezone' import Coin from 'coin.js/src' Coin.start key: '<KEY>' processor: 'ethereum' currency: 'eth' mode: 'deposit' order: subtotal: 1e9 eth: address: '0x945f873d71b0f497d71a05d25c7bf5e7547ab826' node: '//api.infura.io/v1/jsonrpc/ropsten' m = Coin.getMediator() m.on 'login-success', -> document.location.href = '/account' m.on 'register-success', -> document.location.href = '/account' m.on 'profile-load-failed', -> Coin.client.account.logout() document.location.href = '/login' # m.on 'submit-success', -> # @client.account.get().then (res) => # @data.set 'user', res # firstName = @data.get 'user.firstName' # lastName = @data.get 'user.lastName' # @data.set 'user.name', firstName + ' ' + lastName # Coin.El.scheduleUpdate() window.sortOrders = (orders) -> orders.sort (a, b) -> return moment(b.createdAt).diff moment(a.createdAt) window.logout = () -> Coin.client.account.logout() document.location.href = '/login'
true
import moment from 'moment-timezone' import Coin from 'coin.js/src' Coin.start key: 'PI:KEY:<KEY>END_PI' processor: 'ethereum' currency: 'eth' mode: 'deposit' order: subtotal: 1e9 eth: address: '0x945f873d71b0f497d71a05d25c7bf5e7547ab826' node: '//api.infura.io/v1/jsonrpc/ropsten' m = Coin.getMediator() m.on 'login-success', -> document.location.href = '/account' m.on 'register-success', -> document.location.href = '/account' m.on 'profile-load-failed', -> Coin.client.account.logout() document.location.href = '/login' # m.on 'submit-success', -> # @client.account.get().then (res) => # @data.set 'user', res # firstName = @data.get 'user.firstName' # lastName = @data.get 'user.lastName' # @data.set 'user.name', firstName + ' ' + lastName # Coin.El.scheduleUpdate() window.sortOrders = (orders) -> orders.sort (a, b) -> return moment(b.createdAt).diff moment(a.createdAt) window.logout = () -> Coin.client.account.logout() document.location.href = '/login'
[ { "context": "at = require 'octokat'\n\n config =\n USERNAME: 'octokit-test'\n TOKEN: 'dca7f85a5911df8e9b7aeb4c5be8f5f50806", "end": 183, "score": 0.9992212653160095, "start": 171, "tag": "USERNAME", "value": "octokit-test" }, { "context": "config =\n USERNAME: 'octokit-tes...
test/test-config.coffee
BafS/octokat.js
59
define = window?.define or (cb) -> cb ((dep) -> require(dep.replace('octokat', '../index'))) define (require) -> Octokat = require 'octokat' config = USERNAME: 'octokit-test' TOKEN: 'dca7f85a5911df8e9b7aeb4c5be8f5f50806ac49' ORG_NAME: 'octokit-test-org' REPO_USER: 'octokit-test' REPO_NAME: 'octokit-test-repo' # Cannot use '.' because najax does not like it REPO_HOMEPAGE: 'https:/github.com/philschatz/octokat.js' OTHER_HOMEPAGE: 'http://example.com' OTHER_USERNAME: 'octokit-test2' DEFAULT_BRANCH: 'master' LONG_TIMEOUT: 10 * 1000 # 10 seconds SHORT_TIMEOUT: 5 * 1000 # 5 seconds config.Octokat = Octokat config.client = new Octokat {token:config.TOKEN} config.test_repo = "#{config.REPO_USER}/#{config.REPO_NAME}" config.test_github_login = config.USERNAME if module? module.exports = config return config
211562
define = window?.define or (cb) -> cb ((dep) -> require(dep.replace('octokat', '../index'))) define (require) -> Octokat = require 'octokat' config = USERNAME: 'octokit-test' TOKEN: '<KEY>' ORG_NAME: 'octokit-test-org' REPO_USER: 'octokit-test' REPO_NAME: 'octokit-test-repo' # Cannot use '.' because najax does not like it REPO_HOMEPAGE: 'https:/github.com/philschatz/octokat.js' OTHER_HOMEPAGE: 'http://example.com' OTHER_USERNAME: 'octokit-test2' DEFAULT_BRANCH: 'master' LONG_TIMEOUT: 10 * 1000 # 10 seconds SHORT_TIMEOUT: 5 * 1000 # 5 seconds config.Octokat = Octokat config.client = new Octokat {token:config.TOKEN} config.test_repo = "#{config.REPO_USER}/#{config.REPO_NAME}" config.test_github_login = config.USERNAME if module? module.exports = config return config
true
define = window?.define or (cb) -> cb ((dep) -> require(dep.replace('octokat', '../index'))) define (require) -> Octokat = require 'octokat' config = USERNAME: 'octokit-test' TOKEN: 'PI:KEY:<KEY>END_PI' ORG_NAME: 'octokit-test-org' REPO_USER: 'octokit-test' REPO_NAME: 'octokit-test-repo' # Cannot use '.' because najax does not like it REPO_HOMEPAGE: 'https:/github.com/philschatz/octokat.js' OTHER_HOMEPAGE: 'http://example.com' OTHER_USERNAME: 'octokit-test2' DEFAULT_BRANCH: 'master' LONG_TIMEOUT: 10 * 1000 # 10 seconds SHORT_TIMEOUT: 5 * 1000 # 5 seconds config.Octokat = Octokat config.client = new Octokat {token:config.TOKEN} config.test_repo = "#{config.REPO_USER}/#{config.REPO_NAME}" config.test_github_login = config.USERNAME if module? module.exports = config return config
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.8030288815498352, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": " SOFTWARE.\n\n# Inspiration for this code comes from Salvatore Sanfilippo's linenoise.\n# http...
lib/readline.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Inspiration for this code comes from Salvatore Sanfilippo's linenoise. # https://github.com/antirez/linenoise # Reference: # * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html # * http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html Interface = (input, output, completer, terminal) -> # an options object was given # backwards compat; check the isTTY prop of the output stream # when `terminal` was not specified # Check arity, 2 - for async, 1 for sync ondata = (data) -> self._normalWrite data return onend = -> self.emit "line", self._line_buffer if util.isString(self._line_buffer) and self._line_buffer.length > 0 self.close() return ontermend = -> self.emit "line", self.line if util.isString(self.line) and self.line.length > 0 self.close() return onkeypress = (s, key) -> self._ttyWrite s, key return onresize = -> self._refreshLine() return return new Interface(input, output, completer, terminal) unless this instanceof Interface @_sawReturn = false EventEmitter.call this if arguments.length is 1 output = input.output completer = input.completer terminal = input.terminal input = input.input completer = completer or -> [] throw new TypeError("Argument 'completer' must be a function") unless util.isFunction(completer) terminal = !!output.isTTY if util.isUndefined(terminal) and not util.isNullOrUndefined(output) self = this @output = output @input = input @completer = (if completer.length is 2 then completer else (v, callback) -> callback null, completer(v) return ) @setPrompt "> " @terminal = !!terminal unless @terminal input.on "data", ondata input.on "end", onend self.once "close", -> input.removeListener "data", ondata input.removeListener "end", onend return StringDecoder = require("string_decoder").StringDecoder # lazy load @_decoder = new StringDecoder("utf8") else exports.emitKeypressEvents input # input usually refers to stdin input.on "keypress", onkeypress input.on "end", ontermend # Current line @line = "" @_setRawMode true @terminal = true # Cursor position on the line. @cursor = 0 @history = [] @historyIndex = -1 output.on "resize", onresize unless util.isNullOrUndefined(output) self.once "close", -> input.removeListener "keypress", onkeypress input.removeListener "end", ontermend output.removeListener "resize", onresize unless util.isNullOrUndefined(output) return input.resume() return # Only store so many # line length # cursor position # first move to the bottom of the current line, based on cursor pos # Cursor to left edge. # erase data # Write the prompt and the current buffer content. # Force terminal to allocate a new line # Move cursor to original position. # \r\n, \n, or \r followed by something other than \n # Run test() on the new string chunk, not on the entire line buffer. # got one or more newlines; process into "line" events # either '' or (concievably) the unfinished portion of the next line # no newlines this time, save what we have for next time #BUG: Problem when adding tabs with following content. # Perhaps the bug is in _refreshLine(). Not sure. # A hack would be to insert spaces instead of literal '\t'. # a hack to get the line refreshed if it's needed # XXX Log it somewhere? # the text that was completed # Apply/show completions. # 2 space padding # If there is a common prefix to all matches, then apply that # portion. # this = Interface instance handleGroup = (self, group, width, maxColumns) -> return if group.length is 0 minRows = Math.ceil(group.length / maxColumns) row = 0 while row < minRows col = 0 while col < maxColumns idx = row * maxColumns + col break if idx >= group.length item = group[idx] self._writeToOutput item if col < maxColumns - 1 s = 0 itemLen = item.length while s < width - itemLen self._writeToOutput " " s++ col++ self._writeToOutput "\r\n" row++ self._writeToOutput "\r\n" return commonPrefix = (strings) -> return "" if not strings or strings.length is 0 sorted = strings.slice().sort() min = sorted[0] max = sorted[sorted.length - 1] i = 0 len = min.length while i < len return min.slice(0, i) unless min[i] is max[i] i++ min # set cursor to end of line. # set cursor to end of line. # Returns the last character's display position of the given string # surrogates # new line \n # Returns current cursor's position and line # If the cursor is on a full-width character which steps over the line, # move the cursor to the beginning of the next line. # This function moves cursor dx places to the right # (-dx for left) and refreshes the line if it is needed # bounds check # check if cursors are in the same line # handle a write from the tty # Ignore escape key - Fixes #2876 # Control and shift pressed # Control key pressed # This readline instance is finished # delete left # delete right or EOF # This readline instance is finished # delete the whole line # delete from current to end of line # go to the start of the line # go to the end of the line # back one character # forward one character # clear the whole screen # next history item # previous history item # Don't raise events if stream has already been abandoned. # Stream must be paused and resumed after SIGCONT to catch # SIGINT, SIGTSTP, and EOF. # explicitly re-enable "raw mode" and move the cursor to # the correct position. # See https://github.com/joyent/node/issues/3295. # delete backwards to a word boundary # delete forward to a word boundary # Meta key pressed # backward word # forward word # delete forward word # delete backwards to a word boundary # No modifier keys used # \r bookkeeping is only relevant if a \n comes right after. # carriage return, i.e. \r # tab completion ###* accepts a readable Stream instance and makes it emit "keypress" events ### emitKeypressEvents = (stream) -> # lazy load onData = (b) -> if EventEmitter.listenerCount(stream, "keypress") > 0 r = stream._keypressDecoder.write(b) emitKeys stream, r if r else # Nobody's watching anyway stream.removeListener "data", onData stream.on "newListener", onNewListener return onNewListener = (event) -> if event is "keypress" stream.on "data", onData stream.removeListener "newListener", onNewListener return return if stream._keypressDecoder StringDecoder = require("string_decoder").StringDecoder stream._keypressDecoder = new StringDecoder("utf8") if EventEmitter.listenerCount(stream, "keypress") > 0 stream.on "data", onData else stream.on "newListener", onNewListener return # # Some patterns seen in terminal key escape codes, derived from combos seen # at http://www.midnight-commander.org/browser/lib/tty/key.c # # ESC letter # ESC [ letter # ESC [ modifier letter # ESC [ 1 ; modifier letter # ESC [ num char # ESC [ num ; modifier char # ESC O letter # ESC O modifier letter # ESC O 1 ; modifier letter # ESC N letter # ESC [ [ num ; modifier char # ESC [ [ 1 ; modifier letter # ESC ESC [ num char # ESC ESC O letter # # - char is usually ~ but $ and ^ also happen with rxvt # - modifier is 1 + # (shift * 1) + # (left_alt * 2) + # (ctrl * 4) + # (right_alt * 8) # - two leading ESCs apparently mean the same as one leading ESC # # Regexes used for ansi escape code splitting # mouse emitKeys = (stream, s) -> if util.isBuffer(s) if s[0] > 127 and util.isUndefined(s[1]) s[0] -= 128 s = "\u001b" + s.toString(stream.encoding or "utf-8") else s = s.toString(stream.encoding or "utf-8") buffer = [] match = undefined while match = escapeCodeReAnywhere.exec(s) buffer = buffer.concat(s.slice(0, match.index).split("")) buffer.push match[0] s = s.slice(match.index + match[0].length) buffer = buffer.concat(s.split("")) buffer.forEach (s) -> ch = undefined key = sequence: s name: `undefined` ctrl: false meta: false shift: false parts = undefined if s is "\r" # carriage return key.name = "return" else if s is "\n" # enter, should have been called linefeed key.name = "enter" else if s is "\t" # tab key.name = "tab" else if s is "\b" or s is "" or s is "\u001b" or s is "\u001b\b" # backspace or ctrl+h key.name = "backspace" key.meta = (s.charAt(0) is "\u001b") else if s is "\u001b" or s is "\u001b\u001b" # escape key key.name = "escape" key.meta = (s.length is 2) else if s is " " or s is "\u001b " key.name = "space" key.meta = (s.length is 2) else if s.length is 1 and s <= "\u001a" # ctrl+letter key.name = String.fromCharCode(s.charCodeAt(0) + "a".charCodeAt(0) - 1) key.ctrl = true else if s.length is 1 and s >= "a" and s <= "z" # lowercase letter key.name = s else if s.length is 1 and s >= "A" and s <= "Z" # shift+letter key.name = s.toLowerCase() key.shift = true else if parts = metaKeyCodeRe.exec(s) # meta+character key key.name = parts[1].toLowerCase() key.meta = true key.shift = /^[A-Z]$/.test(parts[1]) else if parts = functionKeyCodeRe.exec(s) # ansi escape sequence # reassemble the key code leaving out leading \x1b's, # the modifier key bitflag and any meaningless "1;" sequence code = (parts[1] or "") + (parts[2] or "") + (parts[4] or "") + (parts[9] or "") modifier = (parts[3] or parts[8] or 1) - 1 # Parse the key modifier key.ctrl = !!(modifier & 4) key.meta = !!(modifier & 10) key.shift = !!(modifier & 1) key.code = code # Parse the key itself switch code # xterm/gnome ESC O letter when "OP" key.name = "f1" when "OQ" key.name = "f2" when "OR" key.name = "f3" when "OS" key.name = "f4" # xterm/rxvt ESC [ number ~ when "[11~" key.name = "f1" when "[12~" key.name = "f2" when "[13~" key.name = "f3" when "[14~" key.name = "f4" # from Cygwin and used in libuv when "[[A" key.name = "f1" when "[[B" key.name = "f2" when "[[C" key.name = "f3" when "[[D" key.name = "f4" when "[[E" key.name = "f5" # common when "[15~" key.name = "f5" when "[17~" key.name = "f6" when "[18~" key.name = "f7" when "[19~" key.name = "f8" when "[20~" key.name = "f9" when "[21~" key.name = "f10" when "[23~" key.name = "f11" when "[24~" key.name = "f12" # xterm ESC [ letter when "[A" key.name = "up" when "[B" key.name = "down" when "[C" key.name = "right" when "[D" key.name = "left" when "[E" key.name = "clear" when "[F" key.name = "end" when "[H" key.name = "home" # xterm/gnome ESC O letter when "OA" key.name = "up" when "OB" key.name = "down" when "OC" key.name = "right" when "OD" key.name = "left" when "OE" key.name = "clear" when "OF" key.name = "end" when "OH" key.name = "home" # xterm/rxvt ESC [ number ~ when "[1~" key.name = "home" when "[2~" key.name = "insert" when "[3~" key.name = "delete" when "[4~" key.name = "end" when "[5~" key.name = "pageup" when "[6~" key.name = "pagedown" # putty when "[[5~" key.name = "pageup" when "[[6~" key.name = "pagedown" # rxvt when "[7~" key.name = "home" when "[8~" key.name = "end" # rxvt keys with modifiers when "[a" key.name = "up" key.shift = true when "[b" key.name = "down" key.shift = true when "[c" key.name = "right" key.shift = true when "[d" key.name = "left" key.shift = true when "[e" key.name = "clear" key.shift = true when "[2$" key.name = "insert" key.shift = true when "[3$" key.name = "delete" key.shift = true when "[5$" key.name = "pageup" key.shift = true when "[6$" key.name = "pagedown" key.shift = true when "[7$" key.name = "home" key.shift = true when "[8$" key.name = "end" key.shift = true when "Oa" key.name = "up" key.ctrl = true when "Ob" key.name = "down" key.ctrl = true when "Oc" key.name = "right" key.ctrl = true when "Od" key.name = "left" key.ctrl = true when "Oe" key.name = "clear" key.ctrl = true when "[2^" key.name = "insert" key.ctrl = true when "[3^" key.name = "delete" key.ctrl = true when "[5^" key.name = "pageup" key.ctrl = true when "[6^" key.name = "pagedown" key.ctrl = true when "[7^" key.name = "home" key.ctrl = true when "[8^" key.name = "end" key.ctrl = true # misc. when "[Z" key.name = "tab" key.shift = true else key.name = "undefined" # Don't emit a key if no name was found key = `undefined` if util.isUndefined(key.name) ch = s if s.length is 1 stream.emit "keypress", ch, key if key or ch return return ###* moves the cursor to the x and y coordinate on the given stream ### cursorTo = (stream, x, y) -> return if util.isNullOrUndefined(stream) return if not util.isNumber(x) and not util.isNumber(y) throw new Error("Can't set cursor row without also setting it's column") unless util.isNumber(x) unless util.isNumber(y) stream.write "\u001b[" + (x + 1) + "G" else stream.write "\u001b[" + (y + 1) + ";" + (x + 1) + "H" return ###* moves the cursor relative to its current location ### moveCursor = (stream, dx, dy) -> return if util.isNullOrUndefined(stream) if dx < 0 stream.write "\u001b[" + (-dx) + "D" else stream.write "\u001b[" + dx + "C" if dx > 0 if dy < 0 stream.write "\u001b[" + (-dy) + "A" else stream.write "\u001b[" + dy + "B" if dy > 0 return ###* clears the current line the cursor is on: -1 for left of the cursor +1 for right of the cursor 0 for the entire line ### clearLine = (stream, dir) -> return if util.isNullOrUndefined(stream) if dir < 0 # to the beginning stream.write "\u001b[1K" else if dir > 0 # to the end stream.write "\u001b[0K" else # entire line stream.write "\u001b[2K" return ###* clears the screen from the current position of the cursor down ### clearScreenDown = (stream) -> return if util.isNullOrUndefined(stream) stream.write "\u001b[0J" return ###* Returns the number of columns required to display the given string. ### getStringWidth = (str) -> width = 0 str = stripVTControlCharacters(str) i = 0 len = str.length while i < len code = codePointAt(str, i) # surrogates i++ if code >= 0x10000 if isFullWidthCodePoint(code) width += 2 else width++ i++ width ###* Returns true if the character represented by a given Unicode code point is full-width. Otherwise returns false. ### isFullWidthCodePoint = (code) -> return false if isNaN(code) # Code points are derived from: # http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt # Hangul Jamo # LEFT-POINTING ANGLE BRACKET # RIGHT-POINTING ANGLE BRACKET # CJK Radicals Supplement .. Enclosed CJK Letters and Months # Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A # CJK Unified Ideographs .. Yi Radicals # Hangul Jamo Extended-A # Hangul Syllables # CJK Compatibility Ideographs # Vertical Forms # CJK Compatibility Forms .. Small Form Variants # Halfwidth and Fullwidth Forms # Kana Supplement # Enclosed Ideographic Supplement # CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane return true if code >= 0x1100 and (code <= 0x115f or 0x2329 is code or 0x232a is code or (0x2e80 <= code and code <= 0x3247 and code isnt 0x303f) or 0x3250 <= code and code <= 0x4dbf or 0x4e00 <= code and code <= 0xa4c6 or 0xa960 <= code and code <= 0xa97c or 0xac00 <= code and code <= 0xd7a3 or 0xf900 <= code and code <= 0xfaff or 0xfe10 <= code and code <= 0xfe19 or 0xfe30 <= code and code <= 0xfe6b or 0xff01 <= code and code <= 0xff60 or 0xffe0 <= code and code <= 0xffe6 or 0x1b000 <= code and code <= 0x1b001 or 0x1f200 <= code and code <= 0x1f251 or 0x20000 <= code and code <= 0x3fffd) false ###* Returns the Unicode code point for the character at the given index in the given string. Similar to String.charCodeAt(), but this function handles surrogates (code point >= 0x10000). ### codePointAt = (str, index) -> code = str.charCodeAt(index) low = undefined if 0xd800 <= code and code <= 0xdbff # High surrogate low = str.charCodeAt(index + 1) code = 0x10000 + (code - 0xd800) * 0x400 + (low - 0xdc00) unless isNaN(low) code ###* Tries to remove all VT control characters. Use to estimate displayed string width. May be buggy due to not running a real state machine ### stripVTControlCharacters = (str) -> str = str.replace(new RegExp(functionKeyCodeReAnywhere.source, "g"), "") str.replace new RegExp(metaKeyCodeReAnywhere.source, "g"), "" "use strict" kHistorySize = 30 util = require("util") inherits = require("util").inherits EventEmitter = require("events").EventEmitter exports.createInterface = (input, output, completer, terminal) -> rl = undefined if arguments.length is 1 rl = new Interface(input) else rl = new Interface(input, output, completer, terminal) rl inherits Interface, EventEmitter Interface::__defineGetter__ "columns", -> columns = Infinity columns = @output.columns if @output and @output.columns columns Interface::setPrompt = (prompt) -> @_prompt = prompt return Interface::_setRawMode = (mode) -> @input.setRawMode mode if util.isFunction(@input.setRawMode) Interface::prompt = (preserveCursor) -> @resume() if @paused if @terminal @cursor = 0 unless preserveCursor @_refreshLine() else @_writeToOutput @_prompt return Interface::question = (query, cb) -> if util.isFunction(cb) if @_questionCallback @prompt() else @_oldPrompt = @_prompt @setPrompt query @_questionCallback = cb @prompt() return Interface::_onLine = (line) -> if @_questionCallback cb = @_questionCallback @_questionCallback = null @setPrompt @_oldPrompt cb line else @emit "line", line return Interface::_writeToOutput = _writeToOutput = (stringToWrite) -> throw new TypeError("stringToWrite must be a string") unless util.isString(stringToWrite) @output.write stringToWrite unless util.isNullOrUndefined(@output) return Interface::_addHistory = -> return "" if @line.length is 0 if @history.length is 0 or @history[0] isnt @line @history.unshift @line @history.pop() if @history.length > kHistorySize @historyIndex = -1 @history[0] Interface::_refreshLine = -> line = @_prompt + @line dispPos = @_getDisplayPos(line) lineCols = dispPos.cols lineRows = dispPos.rows cursorPos = @_getCursorPos() prevRows = @prevRows or 0 exports.moveCursor @output, 0, -prevRows if prevRows > 0 exports.cursorTo @output, 0 exports.clearScreenDown @output @_writeToOutput line @_writeToOutput " " if lineCols is 0 exports.cursorTo @output, cursorPos.cols diff = lineRows - cursorPos.rows exports.moveCursor @output, 0, -diff if diff > 0 @prevRows = cursorPos.rows return Interface::close = -> return if @closed @pause() @_setRawMode false if @terminal @closed = true @emit "close" return Interface::pause = -> return if @paused @input.pause() @paused = true @emit "pause" this Interface::resume = -> return unless @paused @input.resume() @paused = false @emit "resume" this Interface::write = (d, key) -> @resume() if @paused (if @terminal then @_ttyWrite(d, key) else @_normalWrite(d)) return lineEnding = /\r?\n|\r(?!\n)/ Interface::_normalWrite = (b) -> return if util.isUndefined(b) string = @_decoder.write(b) if @_sawReturn string = string.replace(/^\n/, "") @_sawReturn = false newPartContainsEnding = lineEnding.test(string) if @_line_buffer string = @_line_buffer + string @_line_buffer = null if newPartContainsEnding @_sawReturn = /\r$/.test(string) lines = string.split(lineEnding) string = lines.pop() @_line_buffer = string lines.forEach ((line) -> @_onLine line return ), this else @_line_buffer = string if string return Interface::_insertString = (c) -> if @cursor < @line.length beg = @line.slice(0, @cursor) end = @line.slice(@cursor, @line.length) @line = beg + c + end @cursor += c.length @_refreshLine() else @line += c @cursor += c.length if @_getCursorPos().cols is 0 @_refreshLine() else @_writeToOutput c @_moveCursor 0 return Interface::_tabComplete = -> self = this self.pause() self.completer self.line.slice(0, self.cursor), (err, rv) -> self.resume() return if err completions = rv[0] completeOn = rv[1] if completions and completions.length if completions.length is 1 self._insertString completions[0].slice(completeOn.length) else self._writeToOutput "\r\n" width = completions.reduce((a, b) -> (if a.length > b.length then a else b) ).length + 2 maxColumns = Math.floor(self.columns / width) or 1 group = [] c = undefined i = 0 compLen = completions.length while i < compLen c = completions[i] if c is "" handleGroup self, group, width, maxColumns group = [] else group.push c i++ handleGroup self, group, width, maxColumns f = completions.filter((e) -> e if e ) prefix = commonPrefix(f) self._insertString prefix.slice(completeOn.length) if prefix.length > completeOn.length self._refreshLine() return return Interface::_wordLeft = -> if @cursor > 0 leading = @line.slice(0, @cursor) match = leading.match(/([^\w\s]+|\w+|)\s*$/) @_moveCursor -match[0].length return Interface::_wordRight = -> if @cursor < @line.length trailing = @line.slice(@cursor) match = trailing.match(/^(\s+|\W+|\w+)\s*/) @_moveCursor match[0].length return Interface::_deleteLeft = -> if @cursor > 0 and @line.length > 0 @line = @line.slice(0, @cursor - 1) + @line.slice(@cursor, @line.length) @cursor-- @_refreshLine() return Interface::_deleteRight = -> @line = @line.slice(0, @cursor) + @line.slice(@cursor + 1, @line.length) @_refreshLine() return Interface::_deleteWordLeft = -> if @cursor > 0 leading = @line.slice(0, @cursor) match = leading.match(/([^\w\s]+|\w+|)\s*$/) leading = leading.slice(0, leading.length - match[0].length) @line = leading + @line.slice(@cursor, @line.length) @cursor = leading.length @_refreshLine() return Interface::_deleteWordRight = -> if @cursor < @line.length trailing = @line.slice(@cursor) match = trailing.match(/^(\s+|\W+|\w+)\s*/) @line = @line.slice(0, @cursor) + trailing.slice(match[0].length) @_refreshLine() return Interface::_deleteLineLeft = -> @line = @line.slice(@cursor) @cursor = 0 @_refreshLine() return Interface::_deleteLineRight = -> @line = @line.slice(0, @cursor) @_refreshLine() return Interface::clearLine = -> @_moveCursor +Infinity @_writeToOutput "\r\n" @line = "" @cursor = 0 @prevRows = 0 return Interface::_line = -> line = @_addHistory() @clearLine() @_onLine line return Interface::_historyNext = -> if @historyIndex > 0 @historyIndex-- @line = @history[@historyIndex] @cursor = @line.length @_refreshLine() else if @historyIndex is 0 @historyIndex = -1 @cursor = 0 @line = "" @_refreshLine() return Interface::_historyPrev = -> if @historyIndex + 1 < @history.length @historyIndex++ @line = @history[@historyIndex] @cursor = @line.length @_refreshLine() return Interface::_getDisplayPos = (str) -> offset = 0 col = @columns row = 0 code = undefined str = stripVTControlCharacters(str) i = 0 len = str.length while i < len code = codePointAt(str, i) i++ if code >= 0x10000 if code is 0x0a offset = 0 row += 1 continue if isFullWidthCodePoint(code) offset++ if (offset + 1) % col is 0 offset += 2 else offset++ i++ cols = offset % col rows = row + (offset - cols) / col cols: cols rows: rows Interface::_getCursorPos = -> columns = @columns strBeforeCursor = @_prompt + @line.substring(0, @cursor) dispPos = @_getDisplayPos(stripVTControlCharacters(strBeforeCursor)) cols = dispPos.cols rows = dispPos.rows if cols + 1 is columns and @cursor < @line.length and isFullWidthCodePoint(codePointAt(@line, @cursor)) rows++ cols = 0 cols: cols rows: rows Interface::_moveCursor = (dx) -> oldcursor = @cursor oldPos = @_getCursorPos() @cursor += dx if @cursor < 0 @cursor = 0 else @cursor = @line.length if @cursor > @line.length newPos = @_getCursorPos() if oldPos.rows is newPos.rows diffCursor = @cursor - oldcursor diffWidth = undefined if diffCursor < 0 diffWidth = -getStringWidth(@line.substring(@cursor, oldcursor)) else diffWidth = getStringWidth(@line.substring(@cursor, oldcursor)) if diffCursor > 0 exports.moveCursor @output, diffWidth, 0 @prevRows = newPos.rows else @_refreshLine() return Interface::_ttyWrite = (s, key) -> key = key or {} return if key.name is "escape" if key.ctrl and key.shift switch key.name when "backspace" @_deleteLineLeft() when "delete" @_deleteLineRight() else if key.ctrl switch key.name when "c" if EventEmitter.listenerCount(this, "SIGINT") > 0 @emit "SIGINT" else @close() when "h" @_deleteLeft() when "d" if @cursor is 0 and @line.length is 0 @close() else @_deleteRight() if @cursor < @line.length when "u" @cursor = 0 @line = "" @_refreshLine() when "k" @_deleteLineRight() when "a" @_moveCursor -Infinity when "e" @_moveCursor +Infinity when "b" @_moveCursor -1 when "f" @_moveCursor +1 when "l" exports.cursorTo @output, 0, 0 exports.clearScreenDown @output @_refreshLine() when "n" @_historyNext() when "p" @_historyPrev() when "z" break if process.platform is "win32" if EventEmitter.listenerCount(this, "SIGTSTP") > 0 @emit "SIGTSTP" else process.once "SIGCONT", ((self) -> -> unless self.paused self.pause() self.emit "SIGCONT" self._setRawMode true self._refreshLine() return )(this) @_setRawMode false process.kill process.pid, "SIGTSTP" when "w", "backspace" @_deleteWordLeft() when "delete" @_deleteWordRight() when "left" @_wordLeft() when "right" @_wordRight() else if key.meta switch key.name when "b" @_wordLeft() when "f" @_wordRight() when "d", "delete" @_deleteWordRight() when "backspace" @_deleteWordLeft() else @_sawReturn = false if @_sawReturn and key.name isnt "enter" switch key.name when "return" @_sawReturn = true @_line() when "enter" if @_sawReturn @_sawReturn = false else @_line() when "backspace" @_deleteLeft() when "delete" @_deleteRight() when "tab" @_tabComplete() when "left" @_moveCursor -1 when "right" @_moveCursor +1 when "home" @_moveCursor -Infinity when "end" @_moveCursor +Infinity when "up" @_historyPrev() when "down" @_historyNext() else s = s.toString("utf-8") if util.isBuffer(s) if s lines = s.split(/\r\n|\n|\r/) i = 0 len = lines.length while i < len @_line() if i > 0 @_insertString lines[i] i++ return exports.Interface = Interface exports.emitKeypressEvents = emitKeypressEvents metaKeyCodeReAnywhere = /(?:\x1b)([a-zA-Z0-9])/ metaKeyCodeRe = new RegExp("^" + metaKeyCodeReAnywhere.source + "$") functionKeyCodeReAnywhere = new RegExp("(?:\u001b+)(O|N|\\[|\\[\\[)(?:" + [ "(\\d+)(?:;(\\d+))?([~^$])" "(?:M([@ #!a`])(.)(.))" "(?:1;)?(\\d+)?([a-zA-Z])" ].join("|") + ")") functionKeyCodeRe = new RegExp("^" + functionKeyCodeReAnywhere.source) escapeCodeReAnywhere = new RegExp([ functionKeyCodeReAnywhere.source metaKeyCodeReAnywhere.source /\x1b./.source ].join("|")) exports.cursorTo = cursorTo exports.moveCursor = moveCursor exports.clearLine = clearLine exports.clearScreenDown = clearScreenDown exports.getStringWidth = getStringWidth exports.isFullWidthCodePoint = isFullWidthCodePoint exports.codePointAt = codePointAt exports.stripVTControlCharacters = stripVTControlCharacters
217354
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Inspiration for this code comes from <NAME>'s linenoise. # https://github.com/antirez/linenoise # Reference: # * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html # * http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html Interface = (input, output, completer, terminal) -> # an options object was given # backwards compat; check the isTTY prop of the output stream # when `terminal` was not specified # Check arity, 2 - for async, 1 for sync ondata = (data) -> self._normalWrite data return onend = -> self.emit "line", self._line_buffer if util.isString(self._line_buffer) and self._line_buffer.length > 0 self.close() return ontermend = -> self.emit "line", self.line if util.isString(self.line) and self.line.length > 0 self.close() return onkeypress = (s, key) -> self._ttyWrite s, key return onresize = -> self._refreshLine() return return new Interface(input, output, completer, terminal) unless this instanceof Interface @_sawReturn = false EventEmitter.call this if arguments.length is 1 output = input.output completer = input.completer terminal = input.terminal input = input.input completer = completer or -> [] throw new TypeError("Argument 'completer' must be a function") unless util.isFunction(completer) terminal = !!output.isTTY if util.isUndefined(terminal) and not util.isNullOrUndefined(output) self = this @output = output @input = input @completer = (if completer.length is 2 then completer else (v, callback) -> callback null, completer(v) return ) @setPrompt "> " @terminal = !!terminal unless @terminal input.on "data", ondata input.on "end", onend self.once "close", -> input.removeListener "data", ondata input.removeListener "end", onend return StringDecoder = require("string_decoder").StringDecoder # lazy load @_decoder = new StringDecoder("utf8") else exports.emitKeypressEvents input # input usually refers to stdin input.on "keypress", onkeypress input.on "end", ontermend # Current line @line = "" @_setRawMode true @terminal = true # Cursor position on the line. @cursor = 0 @history = [] @historyIndex = -1 output.on "resize", onresize unless util.isNullOrUndefined(output) self.once "close", -> input.removeListener "keypress", onkeypress input.removeListener "end", ontermend output.removeListener "resize", onresize unless util.isNullOrUndefined(output) return input.resume() return # Only store so many # line length # cursor position # first move to the bottom of the current line, based on cursor pos # Cursor to left edge. # erase data # Write the prompt and the current buffer content. # Force terminal to allocate a new line # Move cursor to original position. # \r\n, \n, or \r followed by something other than \n # Run test() on the new string chunk, not on the entire line buffer. # got one or more newlines; process into "line" events # either '' or (concievably) the unfinished portion of the next line # no newlines this time, save what we have for next time #BUG: Problem when adding tabs with following content. # Perhaps the bug is in _refreshLine(). Not sure. # A hack would be to insert spaces instead of literal '\t'. # a hack to get the line refreshed if it's needed # XXX Log it somewhere? # the text that was completed # Apply/show completions. # 2 space padding # If there is a common prefix to all matches, then apply that # portion. # this = Interface instance handleGroup = (self, group, width, maxColumns) -> return if group.length is 0 minRows = Math.ceil(group.length / maxColumns) row = 0 while row < minRows col = 0 while col < maxColumns idx = row * maxColumns + col break if idx >= group.length item = group[idx] self._writeToOutput item if col < maxColumns - 1 s = 0 itemLen = item.length while s < width - itemLen self._writeToOutput " " s++ col++ self._writeToOutput "\r\n" row++ self._writeToOutput "\r\n" return commonPrefix = (strings) -> return "" if not strings or strings.length is 0 sorted = strings.slice().sort() min = sorted[0] max = sorted[sorted.length - 1] i = 0 len = min.length while i < len return min.slice(0, i) unless min[i] is max[i] i++ min # set cursor to end of line. # set cursor to end of line. # Returns the last character's display position of the given string # surrogates # new line \n # Returns current cursor's position and line # If the cursor is on a full-width character which steps over the line, # move the cursor to the beginning of the next line. # This function moves cursor dx places to the right # (-dx for left) and refreshes the line if it is needed # bounds check # check if cursors are in the same line # handle a write from the tty # Ignore escape key - Fixes #2876 # Control and shift pressed # Control key pressed # This readline instance is finished # delete left # delete right or EOF # This readline instance is finished # delete the whole line # delete from current to end of line # go to the start of the line # go to the end of the line # back one character # forward one character # clear the whole screen # next history item # previous history item # Don't raise events if stream has already been abandoned. # Stream must be paused and resumed after SIGCONT to catch # SIGINT, SIGTSTP, and EOF. # explicitly re-enable "raw mode" and move the cursor to # the correct position. # See https://github.com/joyent/node/issues/3295. # delete backwards to a word boundary # delete forward to a word boundary # Meta key pressed # backward word # forward word # delete forward word # delete backwards to a word boundary # No modifier keys used # \r bookkeeping is only relevant if a \n comes right after. # carriage return, i.e. \r # tab completion ###* accepts a readable Stream instance and makes it emit "keypress" events ### emitKeypressEvents = (stream) -> # lazy load onData = (b) -> if EventEmitter.listenerCount(stream, "keypress") > 0 r = stream._keypressDecoder.write(b) emitKeys stream, r if r else # Nobody's watching anyway stream.removeListener "data", onData stream.on "newListener", onNewListener return onNewListener = (event) -> if event is "keypress" stream.on "data", onData stream.removeListener "newListener", onNewListener return return if stream._keypressDecoder StringDecoder = require("string_decoder").StringDecoder stream._keypressDecoder = new StringDecoder("utf8") if EventEmitter.listenerCount(stream, "keypress") > 0 stream.on "data", onData else stream.on "newListener", onNewListener return # # Some patterns seen in terminal key escape codes, derived from combos seen # at http://www.midnight-commander.org/browser/lib/tty/key.c # # ESC letter # ESC [ letter # ESC [ modifier letter # ESC [ 1 ; modifier letter # ESC [ num char # ESC [ num ; modifier char # ESC O letter # ESC O modifier letter # ESC O 1 ; modifier letter # ESC N letter # ESC [ [ num ; modifier char # ESC [ [ 1 ; modifier letter # ESC ESC [ num char # ESC ESC O letter # # - char is usually ~ but $ and ^ also happen with rxvt # - modifier is 1 + # (shift * 1) + # (left_alt * 2) + # (ctrl * 4) + # (right_alt * 8) # - two leading ESCs apparently mean the same as one leading ESC # # Regexes used for ansi escape code splitting # mouse emitKeys = (stream, s) -> if util.isBuffer(s) if s[0] > 127 and util.isUndefined(s[1]) s[0] -= 128 s = "\u001b" + s.toString(stream.encoding or "utf-8") else s = s.toString(stream.encoding or "utf-8") buffer = [] match = undefined while match = escapeCodeReAnywhere.exec(s) buffer = buffer.concat(s.slice(0, match.index).split("")) buffer.push match[0] s = s.slice(match.index + match[0].length) buffer = buffer.concat(s.split("")) buffer.forEach (s) -> ch = undefined key = sequence: s name: `undefined` ctrl: false meta: false shift: false parts = undefined if s is "\r" # carriage return key.name = "return" else if s is "\n" # enter, should have been called linefeed key.name = "enter" else if s is "\t" # tab key.name = "tab" else if s is "\b" or s is "" or s is "\u001b" or s is "\u001b\b" # backspace or ctrl+h key.name = "backspace" key.meta = (s.charAt(0) is "\u001b") else if s is "\u001b" or s is "\u001b\u001b" # escape key key.name = "escape" key.meta = (s.length is 2) else if s is " " or s is "\u001b " key.name = "space" key.meta = (s.length is 2) else if s.length is 1 and s <= "\u001a" # ctrl+letter key.name = String.fromCharCode(s.charCodeAt(0) + "a".charCodeAt(0) - 1) key.ctrl = true else if s.length is 1 and s >= "a" and s <= "z" # lowercase letter key.name = s else if s.length is 1 and s >= "A" and s <= "Z" # shift+letter key.name = s.toLowerCase() key.shift = true else if parts = metaKeyCodeRe.exec(s) # meta+character key key.name = parts[1].toLowerCase() key.meta = true key.shift = /^[A-Z]$/.test(parts[1]) else if parts = functionKeyCodeRe.exec(s) # ansi escape sequence # reassemble the key code leaving out leading \x1b's, # the modifier key bitflag and any meaningless "1;" sequence code = (parts[1] or "") + (parts[2] or "") + (parts[4] or "") + (parts[9] or "") modifier = (parts[3] or parts[8] or 1) - 1 # Parse the key modifier key.ctrl = !!(modifier & 4) key.meta = !!(modifier & 10) key.shift = !!(modifier & 1) key.code = code # Parse the key itself switch code # xterm/gnome ESC O letter when "OP" key.name = "f1" when "OQ" key.name = "f2" when "OR" key.name = "f3" when "OS" key.name = "f4" # xterm/rxvt ESC [ number ~ when "[11~" key.name = "f1" when "[12~" key.name = "f2" when "[13~" key.name = "f3" when "[14~" key.name = "f4" # from Cygwin and used in libuv when "[[A" key.name = "f1" when "[[B" key.name = "f2" when "[[C" key.name = "f3" when "[[D" key.name = "f4" when "[[E" key.name = "f5" # common when "[15~" key.name = "f5" when "[17~" key.name = "f6" when "[18~" key.name = "f7" when "[19~" key.name = "f8" when "[20~" key.name = "f9" when "[21~" key.name = "f10" when "[23~" key.name = "f11" when "[24~" key.name = "f12" # xterm ESC [ letter when "[A" key.name = "up" when "[B" key.name = "down" when "[C" key.name = "right" when "[D" key.name = "left" when "[E" key.name = "clear" when "[F" key.name = "end" when "[H" key.name = "home" # xterm/gnome ESC O letter when "OA" key.name = "up" when "OB" key.name = "down" when "OC" key.name = "right" when "OD" key.name = "left" when "OE" key.name = "clear" when "OF" key.name = "end" when "OH" key.name = "home" # xterm/rxvt ESC [ number ~ when "[1~" key.name = "home" when "[2~" key.name = "insert" when "[3~" key.name = "delete" when "[4~" key.name = "end" when "[5~" key.name = "pageup" when "[6~" key.name = "pagedown" # putty when "[[5~" key.name = "pageup" when "[[6~" key.name = "pagedown" # rxvt when "[7~" key.name = "home" when "[8~" key.name = "end" # rxvt keys with modifiers when "[a" key.name = "up" key.shift = true when "[b" key.name = "down" key.shift = true when "[c" key.name = "right" key.shift = true when "[d" key.name = "left" key.shift = true when "[e" key.name = "clear" key.shift = true when "[2$" key.name = "insert" key.shift = true when "[3$" key.name = "delete" key.shift = true when "[5$" key.name = "pageup" key.shift = true when "[6$" key.name = "pagedown" key.shift = true when "[7$" key.name = "home" key.shift = true when "[8$" key.name = "end" key.shift = true when "Oa" key.name = "up" key.ctrl = true when "Ob" key.name = "down" key.ctrl = true when "Oc" key.name = "right" key.ctrl = true when "Od" key.name = "left" key.ctrl = true when "Oe" key.name = "clear" key.ctrl = true when "[2^" key.name = "insert" key.ctrl = true when "[3^" key.name = "delete" key.ctrl = true when "[5^" key.name = "pageup" key.ctrl = true when "[6^" key.name = "pagedown" key.ctrl = true when "[7^" key.name = "home" key.ctrl = true when "[8^" key.name = "end" key.ctrl = true # misc. when "[Z" key.name = "tab" key.shift = true else key.name = "undefined" # Don't emit a key if no name was found key = `undefined` if util.isUndefined(key.name) ch = s if s.length is 1 stream.emit "keypress", ch, key if key or ch return return ###* moves the cursor to the x and y coordinate on the given stream ### cursorTo = (stream, x, y) -> return if util.isNullOrUndefined(stream) return if not util.isNumber(x) and not util.isNumber(y) throw new Error("Can't set cursor row without also setting it's column") unless util.isNumber(x) unless util.isNumber(y) stream.write "\u001b[" + (x + 1) + "G" else stream.write "\u001b[" + (y + 1) + ";" + (x + 1) + "H" return ###* moves the cursor relative to its current location ### moveCursor = (stream, dx, dy) -> return if util.isNullOrUndefined(stream) if dx < 0 stream.write "\u001b[" + (-dx) + "D" else stream.write "\u001b[" + dx + "C" if dx > 0 if dy < 0 stream.write "\u001b[" + (-dy) + "A" else stream.write "\u001b[" + dy + "B" if dy > 0 return ###* clears the current line the cursor is on: -1 for left of the cursor +1 for right of the cursor 0 for the entire line ### clearLine = (stream, dir) -> return if util.isNullOrUndefined(stream) if dir < 0 # to the beginning stream.write "\u001b[1K" else if dir > 0 # to the end stream.write "\u001b[0K" else # entire line stream.write "\u001b[2K" return ###* clears the screen from the current position of the cursor down ### clearScreenDown = (stream) -> return if util.isNullOrUndefined(stream) stream.write "\u001b[0J" return ###* Returns the number of columns required to display the given string. ### getStringWidth = (str) -> width = 0 str = stripVTControlCharacters(str) i = 0 len = str.length while i < len code = codePointAt(str, i) # surrogates i++ if code >= 0x10000 if isFullWidthCodePoint(code) width += 2 else width++ i++ width ###* Returns true if the character represented by a given Unicode code point is full-width. Otherwise returns false. ### isFullWidthCodePoint = (code) -> return false if isNaN(code) # Code points are derived from: # http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt # <NAME> # LEFT-POINTING ANGLE BRACKET # RIGHT-POINTING ANGLE BRACKET # CJK Radicals Supplement .. Enclosed CJK Letters and Months # Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A # CJK Unified Ideographs .. Yi Radicals # Hangul Jamo Extended-A # Hangul Syllables # CJK Compatibility Ideographs # Vertical Forms # CJK Compatibility Forms .. Small Form Variants # Halfwidth and Fullwidth Forms # Kana Supplement # Enclosed Ideographic Supplement # CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane return true if code >= 0x1100 and (code <= 0x115f or 0x2329 is code or 0x232a is code or (0x2e80 <= code and code <= 0x3247 and code isnt 0x303f) or 0x3250 <= code and code <= 0x4dbf or 0x4e00 <= code and code <= 0xa4c6 or 0xa960 <= code and code <= 0xa97c or 0xac00 <= code and code <= 0xd7a3 or 0xf900 <= code and code <= 0xfaff or 0xfe10 <= code and code <= 0xfe19 or 0xfe30 <= code and code <= 0xfe6b or 0xff01 <= code and code <= 0xff60 or 0xffe0 <= code and code <= 0xffe6 or 0x1b000 <= code and code <= 0x1b001 or 0x1f200 <= code and code <= 0x1f251 or 0x20000 <= code and code <= 0x3fffd) false ###* Returns the Unicode code point for the character at the given index in the given string. Similar to String.charCodeAt(), but this function handles surrogates (code point >= 0x10000). ### codePointAt = (str, index) -> code = str.charCodeAt(index) low = undefined if 0xd800 <= code and code <= 0xdbff # High surrogate low = str.charCodeAt(index + 1) code = 0x10000 + (code - 0xd800) * 0x400 + (low - 0xdc00) unless isNaN(low) code ###* Tries to remove all VT control characters. Use to estimate displayed string width. May be buggy due to not running a real state machine ### stripVTControlCharacters = (str) -> str = str.replace(new RegExp(functionKeyCodeReAnywhere.source, "g"), "") str.replace new RegExp(metaKeyCodeReAnywhere.source, "g"), "" "use strict" kHistorySize = 30 util = require("util") inherits = require("util").inherits EventEmitter = require("events").EventEmitter exports.createInterface = (input, output, completer, terminal) -> rl = undefined if arguments.length is 1 rl = new Interface(input) else rl = new Interface(input, output, completer, terminal) rl inherits Interface, EventEmitter Interface::__defineGetter__ "columns", -> columns = Infinity columns = @output.columns if @output and @output.columns columns Interface::setPrompt = (prompt) -> @_prompt = prompt return Interface::_setRawMode = (mode) -> @input.setRawMode mode if util.isFunction(@input.setRawMode) Interface::prompt = (preserveCursor) -> @resume() if @paused if @terminal @cursor = 0 unless preserveCursor @_refreshLine() else @_writeToOutput @_prompt return Interface::question = (query, cb) -> if util.isFunction(cb) if @_questionCallback @prompt() else @_oldPrompt = @_prompt @setPrompt query @_questionCallback = cb @prompt() return Interface::_onLine = (line) -> if @_questionCallback cb = @_questionCallback @_questionCallback = null @setPrompt @_oldPrompt cb line else @emit "line", line return Interface::_writeToOutput = _writeToOutput = (stringToWrite) -> throw new TypeError("stringToWrite must be a string") unless util.isString(stringToWrite) @output.write stringToWrite unless util.isNullOrUndefined(@output) return Interface::_addHistory = -> return "" if @line.length is 0 if @history.length is 0 or @history[0] isnt @line @history.unshift @line @history.pop() if @history.length > kHistorySize @historyIndex = -1 @history[0] Interface::_refreshLine = -> line = @_prompt + @line dispPos = @_getDisplayPos(line) lineCols = dispPos.cols lineRows = dispPos.rows cursorPos = @_getCursorPos() prevRows = @prevRows or 0 exports.moveCursor @output, 0, -prevRows if prevRows > 0 exports.cursorTo @output, 0 exports.clearScreenDown @output @_writeToOutput line @_writeToOutput " " if lineCols is 0 exports.cursorTo @output, cursorPos.cols diff = lineRows - cursorPos.rows exports.moveCursor @output, 0, -diff if diff > 0 @prevRows = cursorPos.rows return Interface::close = -> return if @closed @pause() @_setRawMode false if @terminal @closed = true @emit "close" return Interface::pause = -> return if @paused @input.pause() @paused = true @emit "pause" this Interface::resume = -> return unless @paused @input.resume() @paused = false @emit "resume" this Interface::write = (d, key) -> @resume() if @paused (if @terminal then @_ttyWrite(d, key) else @_normalWrite(d)) return lineEnding = /\r?\n|\r(?!\n)/ Interface::_normalWrite = (b) -> return if util.isUndefined(b) string = @_decoder.write(b) if @_sawReturn string = string.replace(/^\n/, "") @_sawReturn = false newPartContainsEnding = lineEnding.test(string) if @_line_buffer string = @_line_buffer + string @_line_buffer = null if newPartContainsEnding @_sawReturn = /\r$/.test(string) lines = string.split(lineEnding) string = lines.pop() @_line_buffer = string lines.forEach ((line) -> @_onLine line return ), this else @_line_buffer = string if string return Interface::_insertString = (c) -> if @cursor < @line.length beg = @line.slice(0, @cursor) end = @line.slice(@cursor, @line.length) @line = beg + c + end @cursor += c.length @_refreshLine() else @line += c @cursor += c.length if @_getCursorPos().cols is 0 @_refreshLine() else @_writeToOutput c @_moveCursor 0 return Interface::_tabComplete = -> self = this self.pause() self.completer self.line.slice(0, self.cursor), (err, rv) -> self.resume() return if err completions = rv[0] completeOn = rv[1] if completions and completions.length if completions.length is 1 self._insertString completions[0].slice(completeOn.length) else self._writeToOutput "\r\n" width = completions.reduce((a, b) -> (if a.length > b.length then a else b) ).length + 2 maxColumns = Math.floor(self.columns / width) or 1 group = [] c = undefined i = 0 compLen = completions.length while i < compLen c = completions[i] if c is "" handleGroup self, group, width, maxColumns group = [] else group.push c i++ handleGroup self, group, width, maxColumns f = completions.filter((e) -> e if e ) prefix = commonPrefix(f) self._insertString prefix.slice(completeOn.length) if prefix.length > completeOn.length self._refreshLine() return return Interface::_wordLeft = -> if @cursor > 0 leading = @line.slice(0, @cursor) match = leading.match(/([^\w\s]+|\w+|)\s*$/) @_moveCursor -match[0].length return Interface::_wordRight = -> if @cursor < @line.length trailing = @line.slice(@cursor) match = trailing.match(/^(\s+|\W+|\w+)\s*/) @_moveCursor match[0].length return Interface::_deleteLeft = -> if @cursor > 0 and @line.length > 0 @line = @line.slice(0, @cursor - 1) + @line.slice(@cursor, @line.length) @cursor-- @_refreshLine() return Interface::_deleteRight = -> @line = @line.slice(0, @cursor) + @line.slice(@cursor + 1, @line.length) @_refreshLine() return Interface::_deleteWordLeft = -> if @cursor > 0 leading = @line.slice(0, @cursor) match = leading.match(/([^\w\s]+|\w+|)\s*$/) leading = leading.slice(0, leading.length - match[0].length) @line = leading + @line.slice(@cursor, @line.length) @cursor = leading.length @_refreshLine() return Interface::_deleteWordRight = -> if @cursor < @line.length trailing = @line.slice(@cursor) match = trailing.match(/^(\s+|\W+|\w+)\s*/) @line = @line.slice(0, @cursor) + trailing.slice(match[0].length) @_refreshLine() return Interface::_deleteLineLeft = -> @line = @line.slice(@cursor) @cursor = 0 @_refreshLine() return Interface::_deleteLineRight = -> @line = @line.slice(0, @cursor) @_refreshLine() return Interface::clearLine = -> @_moveCursor +Infinity @_writeToOutput "\r\n" @line = "" @cursor = 0 @prevRows = 0 return Interface::_line = -> line = @_addHistory() @clearLine() @_onLine line return Interface::_historyNext = -> if @historyIndex > 0 @historyIndex-- @line = @history[@historyIndex] @cursor = @line.length @_refreshLine() else if @historyIndex is 0 @historyIndex = -1 @cursor = 0 @line = "" @_refreshLine() return Interface::_historyPrev = -> if @historyIndex + 1 < @history.length @historyIndex++ @line = @history[@historyIndex] @cursor = @line.length @_refreshLine() return Interface::_getDisplayPos = (str) -> offset = 0 col = @columns row = 0 code = undefined str = stripVTControlCharacters(str) i = 0 len = str.length while i < len code = codePointAt(str, i) i++ if code >= 0x10000 if code is 0x0a offset = 0 row += 1 continue if isFullWidthCodePoint(code) offset++ if (offset + 1) % col is 0 offset += 2 else offset++ i++ cols = offset % col rows = row + (offset - cols) / col cols: cols rows: rows Interface::_getCursorPos = -> columns = @columns strBeforeCursor = @_prompt + @line.substring(0, @cursor) dispPos = @_getDisplayPos(stripVTControlCharacters(strBeforeCursor)) cols = dispPos.cols rows = dispPos.rows if cols + 1 is columns and @cursor < @line.length and isFullWidthCodePoint(codePointAt(@line, @cursor)) rows++ cols = 0 cols: cols rows: rows Interface::_moveCursor = (dx) -> oldcursor = @cursor oldPos = @_getCursorPos() @cursor += dx if @cursor < 0 @cursor = 0 else @cursor = @line.length if @cursor > @line.length newPos = @_getCursorPos() if oldPos.rows is newPos.rows diffCursor = @cursor - oldcursor diffWidth = undefined if diffCursor < 0 diffWidth = -getStringWidth(@line.substring(@cursor, oldcursor)) else diffWidth = getStringWidth(@line.substring(@cursor, oldcursor)) if diffCursor > 0 exports.moveCursor @output, diffWidth, 0 @prevRows = newPos.rows else @_refreshLine() return Interface::_ttyWrite = (s, key) -> key = key or {} return if key.name is "escape" if key.ctrl and key.shift switch key.name when "backspace" @_deleteLineLeft() when "delete" @_deleteLineRight() else if key.ctrl switch key.name when "c" if EventEmitter.listenerCount(this, "SIGINT") > 0 @emit "SIGINT" else @close() when "h" @_deleteLeft() when "d" if @cursor is 0 and @line.length is 0 @close() else @_deleteRight() if @cursor < @line.length when "u" @cursor = 0 @line = "" @_refreshLine() when "k" @_deleteLineRight() when "a" @_moveCursor -Infinity when "e" @_moveCursor +Infinity when "b" @_moveCursor -1 when "f" @_moveCursor +1 when "l" exports.cursorTo @output, 0, 0 exports.clearScreenDown @output @_refreshLine() when "n" @_historyNext() when "p" @_historyPrev() when "z" break if process.platform is "win32" if EventEmitter.listenerCount(this, "SIGTSTP") > 0 @emit "SIGTSTP" else process.once "SIGCONT", ((self) -> -> unless self.paused self.pause() self.emit "SIGCONT" self._setRawMode true self._refreshLine() return )(this) @_setRawMode false process.kill process.pid, "SIGTSTP" when "w", "backspace" @_deleteWordLeft() when "delete" @_deleteWordRight() when "left" @_wordLeft() when "right" @_wordRight() else if key.meta switch key.name when "b" @_wordLeft() when "f" @_wordRight() when "d", "delete" @_deleteWordRight() when "backspace" @_deleteWordLeft() else @_sawReturn = false if @_sawReturn and key.name isnt "enter" switch key.name when "return" @_sawReturn = true @_line() when "enter" if @_sawReturn @_sawReturn = false else @_line() when "backspace" @_deleteLeft() when "delete" @_deleteRight() when "tab" @_tabComplete() when "left" @_moveCursor -1 when "right" @_moveCursor +1 when "home" @_moveCursor -Infinity when "end" @_moveCursor +Infinity when "up" @_historyPrev() when "down" @_historyNext() else s = s.toString("utf-8") if util.isBuffer(s) if s lines = s.split(/\r\n|\n|\r/) i = 0 len = lines.length while i < len @_line() if i > 0 @_insertString lines[i] i++ return exports.Interface = Interface exports.emitKeypressEvents = emitKeypressEvents metaKeyCodeReAnywhere = /(?:\x1b)([a-zA-Z0-9])/ metaKeyCodeRe = new RegExp("^" + metaKeyCodeReAnywhere.source + "$") functionKeyCodeReAnywhere = new RegExp("(?:\u001b+)(O|N|\\[|\\[\\[)(?:" + [ "(\\d+)(?:;(\\d+))?([~^$])" "(?:M([@ #!a`])(.)(.))" "(?:1;)?(\\d+)?([a-zA-Z])" ].join("|") + ")") functionKeyCodeRe = new RegExp("^" + functionKeyCodeReAnywhere.source) escapeCodeReAnywhere = new RegExp([ functionKeyCodeReAnywhere.source metaKeyCodeReAnywhere.source /\x1b./.source ].join("|")) exports.cursorTo = cursorTo exports.moveCursor = moveCursor exports.clearLine = clearLine exports.clearScreenDown = clearScreenDown exports.getStringWidth = getStringWidth exports.isFullWidthCodePoint = isFullWidthCodePoint exports.codePointAt = codePointAt exports.stripVTControlCharacters = stripVTControlCharacters
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # Inspiration for this code comes from PI:NAME:<NAME>END_PI's linenoise. # https://github.com/antirez/linenoise # Reference: # * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html # * http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html Interface = (input, output, completer, terminal) -> # an options object was given # backwards compat; check the isTTY prop of the output stream # when `terminal` was not specified # Check arity, 2 - for async, 1 for sync ondata = (data) -> self._normalWrite data return onend = -> self.emit "line", self._line_buffer if util.isString(self._line_buffer) and self._line_buffer.length > 0 self.close() return ontermend = -> self.emit "line", self.line if util.isString(self.line) and self.line.length > 0 self.close() return onkeypress = (s, key) -> self._ttyWrite s, key return onresize = -> self._refreshLine() return return new Interface(input, output, completer, terminal) unless this instanceof Interface @_sawReturn = false EventEmitter.call this if arguments.length is 1 output = input.output completer = input.completer terminal = input.terminal input = input.input completer = completer or -> [] throw new TypeError("Argument 'completer' must be a function") unless util.isFunction(completer) terminal = !!output.isTTY if util.isUndefined(terminal) and not util.isNullOrUndefined(output) self = this @output = output @input = input @completer = (if completer.length is 2 then completer else (v, callback) -> callback null, completer(v) return ) @setPrompt "> " @terminal = !!terminal unless @terminal input.on "data", ondata input.on "end", onend self.once "close", -> input.removeListener "data", ondata input.removeListener "end", onend return StringDecoder = require("string_decoder").StringDecoder # lazy load @_decoder = new StringDecoder("utf8") else exports.emitKeypressEvents input # input usually refers to stdin input.on "keypress", onkeypress input.on "end", ontermend # Current line @line = "" @_setRawMode true @terminal = true # Cursor position on the line. @cursor = 0 @history = [] @historyIndex = -1 output.on "resize", onresize unless util.isNullOrUndefined(output) self.once "close", -> input.removeListener "keypress", onkeypress input.removeListener "end", ontermend output.removeListener "resize", onresize unless util.isNullOrUndefined(output) return input.resume() return # Only store so many # line length # cursor position # first move to the bottom of the current line, based on cursor pos # Cursor to left edge. # erase data # Write the prompt and the current buffer content. # Force terminal to allocate a new line # Move cursor to original position. # \r\n, \n, or \r followed by something other than \n # Run test() on the new string chunk, not on the entire line buffer. # got one or more newlines; process into "line" events # either '' or (concievably) the unfinished portion of the next line # no newlines this time, save what we have for next time #BUG: Problem when adding tabs with following content. # Perhaps the bug is in _refreshLine(). Not sure. # A hack would be to insert spaces instead of literal '\t'. # a hack to get the line refreshed if it's needed # XXX Log it somewhere? # the text that was completed # Apply/show completions. # 2 space padding # If there is a common prefix to all matches, then apply that # portion. # this = Interface instance handleGroup = (self, group, width, maxColumns) -> return if group.length is 0 minRows = Math.ceil(group.length / maxColumns) row = 0 while row < minRows col = 0 while col < maxColumns idx = row * maxColumns + col break if idx >= group.length item = group[idx] self._writeToOutput item if col < maxColumns - 1 s = 0 itemLen = item.length while s < width - itemLen self._writeToOutput " " s++ col++ self._writeToOutput "\r\n" row++ self._writeToOutput "\r\n" return commonPrefix = (strings) -> return "" if not strings or strings.length is 0 sorted = strings.slice().sort() min = sorted[0] max = sorted[sorted.length - 1] i = 0 len = min.length while i < len return min.slice(0, i) unless min[i] is max[i] i++ min # set cursor to end of line. # set cursor to end of line. # Returns the last character's display position of the given string # surrogates # new line \n # Returns current cursor's position and line # If the cursor is on a full-width character which steps over the line, # move the cursor to the beginning of the next line. # This function moves cursor dx places to the right # (-dx for left) and refreshes the line if it is needed # bounds check # check if cursors are in the same line # handle a write from the tty # Ignore escape key - Fixes #2876 # Control and shift pressed # Control key pressed # This readline instance is finished # delete left # delete right or EOF # This readline instance is finished # delete the whole line # delete from current to end of line # go to the start of the line # go to the end of the line # back one character # forward one character # clear the whole screen # next history item # previous history item # Don't raise events if stream has already been abandoned. # Stream must be paused and resumed after SIGCONT to catch # SIGINT, SIGTSTP, and EOF. # explicitly re-enable "raw mode" and move the cursor to # the correct position. # See https://github.com/joyent/node/issues/3295. # delete backwards to a word boundary # delete forward to a word boundary # Meta key pressed # backward word # forward word # delete forward word # delete backwards to a word boundary # No modifier keys used # \r bookkeeping is only relevant if a \n comes right after. # carriage return, i.e. \r # tab completion ###* accepts a readable Stream instance and makes it emit "keypress" events ### emitKeypressEvents = (stream) -> # lazy load onData = (b) -> if EventEmitter.listenerCount(stream, "keypress") > 0 r = stream._keypressDecoder.write(b) emitKeys stream, r if r else # Nobody's watching anyway stream.removeListener "data", onData stream.on "newListener", onNewListener return onNewListener = (event) -> if event is "keypress" stream.on "data", onData stream.removeListener "newListener", onNewListener return return if stream._keypressDecoder StringDecoder = require("string_decoder").StringDecoder stream._keypressDecoder = new StringDecoder("utf8") if EventEmitter.listenerCount(stream, "keypress") > 0 stream.on "data", onData else stream.on "newListener", onNewListener return # # Some patterns seen in terminal key escape codes, derived from combos seen # at http://www.midnight-commander.org/browser/lib/tty/key.c # # ESC letter # ESC [ letter # ESC [ modifier letter # ESC [ 1 ; modifier letter # ESC [ num char # ESC [ num ; modifier char # ESC O letter # ESC O modifier letter # ESC O 1 ; modifier letter # ESC N letter # ESC [ [ num ; modifier char # ESC [ [ 1 ; modifier letter # ESC ESC [ num char # ESC ESC O letter # # - char is usually ~ but $ and ^ also happen with rxvt # - modifier is 1 + # (shift * 1) + # (left_alt * 2) + # (ctrl * 4) + # (right_alt * 8) # - two leading ESCs apparently mean the same as one leading ESC # # Regexes used for ansi escape code splitting # mouse emitKeys = (stream, s) -> if util.isBuffer(s) if s[0] > 127 and util.isUndefined(s[1]) s[0] -= 128 s = "\u001b" + s.toString(stream.encoding or "utf-8") else s = s.toString(stream.encoding or "utf-8") buffer = [] match = undefined while match = escapeCodeReAnywhere.exec(s) buffer = buffer.concat(s.slice(0, match.index).split("")) buffer.push match[0] s = s.slice(match.index + match[0].length) buffer = buffer.concat(s.split("")) buffer.forEach (s) -> ch = undefined key = sequence: s name: `undefined` ctrl: false meta: false shift: false parts = undefined if s is "\r" # carriage return key.name = "return" else if s is "\n" # enter, should have been called linefeed key.name = "enter" else if s is "\t" # tab key.name = "tab" else if s is "\b" or s is "" or s is "\u001b" or s is "\u001b\b" # backspace or ctrl+h key.name = "backspace" key.meta = (s.charAt(0) is "\u001b") else if s is "\u001b" or s is "\u001b\u001b" # escape key key.name = "escape" key.meta = (s.length is 2) else if s is " " or s is "\u001b " key.name = "space" key.meta = (s.length is 2) else if s.length is 1 and s <= "\u001a" # ctrl+letter key.name = String.fromCharCode(s.charCodeAt(0) + "a".charCodeAt(0) - 1) key.ctrl = true else if s.length is 1 and s >= "a" and s <= "z" # lowercase letter key.name = s else if s.length is 1 and s >= "A" and s <= "Z" # shift+letter key.name = s.toLowerCase() key.shift = true else if parts = metaKeyCodeRe.exec(s) # meta+character key key.name = parts[1].toLowerCase() key.meta = true key.shift = /^[A-Z]$/.test(parts[1]) else if parts = functionKeyCodeRe.exec(s) # ansi escape sequence # reassemble the key code leaving out leading \x1b's, # the modifier key bitflag and any meaningless "1;" sequence code = (parts[1] or "") + (parts[2] or "") + (parts[4] or "") + (parts[9] or "") modifier = (parts[3] or parts[8] or 1) - 1 # Parse the key modifier key.ctrl = !!(modifier & 4) key.meta = !!(modifier & 10) key.shift = !!(modifier & 1) key.code = code # Parse the key itself switch code # xterm/gnome ESC O letter when "OP" key.name = "f1" when "OQ" key.name = "f2" when "OR" key.name = "f3" when "OS" key.name = "f4" # xterm/rxvt ESC [ number ~ when "[11~" key.name = "f1" when "[12~" key.name = "f2" when "[13~" key.name = "f3" when "[14~" key.name = "f4" # from Cygwin and used in libuv when "[[A" key.name = "f1" when "[[B" key.name = "f2" when "[[C" key.name = "f3" when "[[D" key.name = "f4" when "[[E" key.name = "f5" # common when "[15~" key.name = "f5" when "[17~" key.name = "f6" when "[18~" key.name = "f7" when "[19~" key.name = "f8" when "[20~" key.name = "f9" when "[21~" key.name = "f10" when "[23~" key.name = "f11" when "[24~" key.name = "f12" # xterm ESC [ letter when "[A" key.name = "up" when "[B" key.name = "down" when "[C" key.name = "right" when "[D" key.name = "left" when "[E" key.name = "clear" when "[F" key.name = "end" when "[H" key.name = "home" # xterm/gnome ESC O letter when "OA" key.name = "up" when "OB" key.name = "down" when "OC" key.name = "right" when "OD" key.name = "left" when "OE" key.name = "clear" when "OF" key.name = "end" when "OH" key.name = "home" # xterm/rxvt ESC [ number ~ when "[1~" key.name = "home" when "[2~" key.name = "insert" when "[3~" key.name = "delete" when "[4~" key.name = "end" when "[5~" key.name = "pageup" when "[6~" key.name = "pagedown" # putty when "[[5~" key.name = "pageup" when "[[6~" key.name = "pagedown" # rxvt when "[7~" key.name = "home" when "[8~" key.name = "end" # rxvt keys with modifiers when "[a" key.name = "up" key.shift = true when "[b" key.name = "down" key.shift = true when "[c" key.name = "right" key.shift = true when "[d" key.name = "left" key.shift = true when "[e" key.name = "clear" key.shift = true when "[2$" key.name = "insert" key.shift = true when "[3$" key.name = "delete" key.shift = true when "[5$" key.name = "pageup" key.shift = true when "[6$" key.name = "pagedown" key.shift = true when "[7$" key.name = "home" key.shift = true when "[8$" key.name = "end" key.shift = true when "Oa" key.name = "up" key.ctrl = true when "Ob" key.name = "down" key.ctrl = true when "Oc" key.name = "right" key.ctrl = true when "Od" key.name = "left" key.ctrl = true when "Oe" key.name = "clear" key.ctrl = true when "[2^" key.name = "insert" key.ctrl = true when "[3^" key.name = "delete" key.ctrl = true when "[5^" key.name = "pageup" key.ctrl = true when "[6^" key.name = "pagedown" key.ctrl = true when "[7^" key.name = "home" key.ctrl = true when "[8^" key.name = "end" key.ctrl = true # misc. when "[Z" key.name = "tab" key.shift = true else key.name = "undefined" # Don't emit a key if no name was found key = `undefined` if util.isUndefined(key.name) ch = s if s.length is 1 stream.emit "keypress", ch, key if key or ch return return ###* moves the cursor to the x and y coordinate on the given stream ### cursorTo = (stream, x, y) -> return if util.isNullOrUndefined(stream) return if not util.isNumber(x) and not util.isNumber(y) throw new Error("Can't set cursor row without also setting it's column") unless util.isNumber(x) unless util.isNumber(y) stream.write "\u001b[" + (x + 1) + "G" else stream.write "\u001b[" + (y + 1) + ";" + (x + 1) + "H" return ###* moves the cursor relative to its current location ### moveCursor = (stream, dx, dy) -> return if util.isNullOrUndefined(stream) if dx < 0 stream.write "\u001b[" + (-dx) + "D" else stream.write "\u001b[" + dx + "C" if dx > 0 if dy < 0 stream.write "\u001b[" + (-dy) + "A" else stream.write "\u001b[" + dy + "B" if dy > 0 return ###* clears the current line the cursor is on: -1 for left of the cursor +1 for right of the cursor 0 for the entire line ### clearLine = (stream, dir) -> return if util.isNullOrUndefined(stream) if dir < 0 # to the beginning stream.write "\u001b[1K" else if dir > 0 # to the end stream.write "\u001b[0K" else # entire line stream.write "\u001b[2K" return ###* clears the screen from the current position of the cursor down ### clearScreenDown = (stream) -> return if util.isNullOrUndefined(stream) stream.write "\u001b[0J" return ###* Returns the number of columns required to display the given string. ### getStringWidth = (str) -> width = 0 str = stripVTControlCharacters(str) i = 0 len = str.length while i < len code = codePointAt(str, i) # surrogates i++ if code >= 0x10000 if isFullWidthCodePoint(code) width += 2 else width++ i++ width ###* Returns true if the character represented by a given Unicode code point is full-width. Otherwise returns false. ### isFullWidthCodePoint = (code) -> return false if isNaN(code) # Code points are derived from: # http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt # PI:NAME:<NAME>END_PI # LEFT-POINTING ANGLE BRACKET # RIGHT-POINTING ANGLE BRACKET # CJK Radicals Supplement .. Enclosed CJK Letters and Months # Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A # CJK Unified Ideographs .. Yi Radicals # Hangul Jamo Extended-A # Hangul Syllables # CJK Compatibility Ideographs # Vertical Forms # CJK Compatibility Forms .. Small Form Variants # Halfwidth and Fullwidth Forms # Kana Supplement # Enclosed Ideographic Supplement # CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane return true if code >= 0x1100 and (code <= 0x115f or 0x2329 is code or 0x232a is code or (0x2e80 <= code and code <= 0x3247 and code isnt 0x303f) or 0x3250 <= code and code <= 0x4dbf or 0x4e00 <= code and code <= 0xa4c6 or 0xa960 <= code and code <= 0xa97c or 0xac00 <= code and code <= 0xd7a3 or 0xf900 <= code and code <= 0xfaff or 0xfe10 <= code and code <= 0xfe19 or 0xfe30 <= code and code <= 0xfe6b or 0xff01 <= code and code <= 0xff60 or 0xffe0 <= code and code <= 0xffe6 or 0x1b000 <= code and code <= 0x1b001 or 0x1f200 <= code and code <= 0x1f251 or 0x20000 <= code and code <= 0x3fffd) false ###* Returns the Unicode code point for the character at the given index in the given string. Similar to String.charCodeAt(), but this function handles surrogates (code point >= 0x10000). ### codePointAt = (str, index) -> code = str.charCodeAt(index) low = undefined if 0xd800 <= code and code <= 0xdbff # High surrogate low = str.charCodeAt(index + 1) code = 0x10000 + (code - 0xd800) * 0x400 + (low - 0xdc00) unless isNaN(low) code ###* Tries to remove all VT control characters. Use to estimate displayed string width. May be buggy due to not running a real state machine ### stripVTControlCharacters = (str) -> str = str.replace(new RegExp(functionKeyCodeReAnywhere.source, "g"), "") str.replace new RegExp(metaKeyCodeReAnywhere.source, "g"), "" "use strict" kHistorySize = 30 util = require("util") inherits = require("util").inherits EventEmitter = require("events").EventEmitter exports.createInterface = (input, output, completer, terminal) -> rl = undefined if arguments.length is 1 rl = new Interface(input) else rl = new Interface(input, output, completer, terminal) rl inherits Interface, EventEmitter Interface::__defineGetter__ "columns", -> columns = Infinity columns = @output.columns if @output and @output.columns columns Interface::setPrompt = (prompt) -> @_prompt = prompt return Interface::_setRawMode = (mode) -> @input.setRawMode mode if util.isFunction(@input.setRawMode) Interface::prompt = (preserveCursor) -> @resume() if @paused if @terminal @cursor = 0 unless preserveCursor @_refreshLine() else @_writeToOutput @_prompt return Interface::question = (query, cb) -> if util.isFunction(cb) if @_questionCallback @prompt() else @_oldPrompt = @_prompt @setPrompt query @_questionCallback = cb @prompt() return Interface::_onLine = (line) -> if @_questionCallback cb = @_questionCallback @_questionCallback = null @setPrompt @_oldPrompt cb line else @emit "line", line return Interface::_writeToOutput = _writeToOutput = (stringToWrite) -> throw new TypeError("stringToWrite must be a string") unless util.isString(stringToWrite) @output.write stringToWrite unless util.isNullOrUndefined(@output) return Interface::_addHistory = -> return "" if @line.length is 0 if @history.length is 0 or @history[0] isnt @line @history.unshift @line @history.pop() if @history.length > kHistorySize @historyIndex = -1 @history[0] Interface::_refreshLine = -> line = @_prompt + @line dispPos = @_getDisplayPos(line) lineCols = dispPos.cols lineRows = dispPos.rows cursorPos = @_getCursorPos() prevRows = @prevRows or 0 exports.moveCursor @output, 0, -prevRows if prevRows > 0 exports.cursorTo @output, 0 exports.clearScreenDown @output @_writeToOutput line @_writeToOutput " " if lineCols is 0 exports.cursorTo @output, cursorPos.cols diff = lineRows - cursorPos.rows exports.moveCursor @output, 0, -diff if diff > 0 @prevRows = cursorPos.rows return Interface::close = -> return if @closed @pause() @_setRawMode false if @terminal @closed = true @emit "close" return Interface::pause = -> return if @paused @input.pause() @paused = true @emit "pause" this Interface::resume = -> return unless @paused @input.resume() @paused = false @emit "resume" this Interface::write = (d, key) -> @resume() if @paused (if @terminal then @_ttyWrite(d, key) else @_normalWrite(d)) return lineEnding = /\r?\n|\r(?!\n)/ Interface::_normalWrite = (b) -> return if util.isUndefined(b) string = @_decoder.write(b) if @_sawReturn string = string.replace(/^\n/, "") @_sawReturn = false newPartContainsEnding = lineEnding.test(string) if @_line_buffer string = @_line_buffer + string @_line_buffer = null if newPartContainsEnding @_sawReturn = /\r$/.test(string) lines = string.split(lineEnding) string = lines.pop() @_line_buffer = string lines.forEach ((line) -> @_onLine line return ), this else @_line_buffer = string if string return Interface::_insertString = (c) -> if @cursor < @line.length beg = @line.slice(0, @cursor) end = @line.slice(@cursor, @line.length) @line = beg + c + end @cursor += c.length @_refreshLine() else @line += c @cursor += c.length if @_getCursorPos().cols is 0 @_refreshLine() else @_writeToOutput c @_moveCursor 0 return Interface::_tabComplete = -> self = this self.pause() self.completer self.line.slice(0, self.cursor), (err, rv) -> self.resume() return if err completions = rv[0] completeOn = rv[1] if completions and completions.length if completions.length is 1 self._insertString completions[0].slice(completeOn.length) else self._writeToOutput "\r\n" width = completions.reduce((a, b) -> (if a.length > b.length then a else b) ).length + 2 maxColumns = Math.floor(self.columns / width) or 1 group = [] c = undefined i = 0 compLen = completions.length while i < compLen c = completions[i] if c is "" handleGroup self, group, width, maxColumns group = [] else group.push c i++ handleGroup self, group, width, maxColumns f = completions.filter((e) -> e if e ) prefix = commonPrefix(f) self._insertString prefix.slice(completeOn.length) if prefix.length > completeOn.length self._refreshLine() return return Interface::_wordLeft = -> if @cursor > 0 leading = @line.slice(0, @cursor) match = leading.match(/([^\w\s]+|\w+|)\s*$/) @_moveCursor -match[0].length return Interface::_wordRight = -> if @cursor < @line.length trailing = @line.slice(@cursor) match = trailing.match(/^(\s+|\W+|\w+)\s*/) @_moveCursor match[0].length return Interface::_deleteLeft = -> if @cursor > 0 and @line.length > 0 @line = @line.slice(0, @cursor - 1) + @line.slice(@cursor, @line.length) @cursor-- @_refreshLine() return Interface::_deleteRight = -> @line = @line.slice(0, @cursor) + @line.slice(@cursor + 1, @line.length) @_refreshLine() return Interface::_deleteWordLeft = -> if @cursor > 0 leading = @line.slice(0, @cursor) match = leading.match(/([^\w\s]+|\w+|)\s*$/) leading = leading.slice(0, leading.length - match[0].length) @line = leading + @line.slice(@cursor, @line.length) @cursor = leading.length @_refreshLine() return Interface::_deleteWordRight = -> if @cursor < @line.length trailing = @line.slice(@cursor) match = trailing.match(/^(\s+|\W+|\w+)\s*/) @line = @line.slice(0, @cursor) + trailing.slice(match[0].length) @_refreshLine() return Interface::_deleteLineLeft = -> @line = @line.slice(@cursor) @cursor = 0 @_refreshLine() return Interface::_deleteLineRight = -> @line = @line.slice(0, @cursor) @_refreshLine() return Interface::clearLine = -> @_moveCursor +Infinity @_writeToOutput "\r\n" @line = "" @cursor = 0 @prevRows = 0 return Interface::_line = -> line = @_addHistory() @clearLine() @_onLine line return Interface::_historyNext = -> if @historyIndex > 0 @historyIndex-- @line = @history[@historyIndex] @cursor = @line.length @_refreshLine() else if @historyIndex is 0 @historyIndex = -1 @cursor = 0 @line = "" @_refreshLine() return Interface::_historyPrev = -> if @historyIndex + 1 < @history.length @historyIndex++ @line = @history[@historyIndex] @cursor = @line.length @_refreshLine() return Interface::_getDisplayPos = (str) -> offset = 0 col = @columns row = 0 code = undefined str = stripVTControlCharacters(str) i = 0 len = str.length while i < len code = codePointAt(str, i) i++ if code >= 0x10000 if code is 0x0a offset = 0 row += 1 continue if isFullWidthCodePoint(code) offset++ if (offset + 1) % col is 0 offset += 2 else offset++ i++ cols = offset % col rows = row + (offset - cols) / col cols: cols rows: rows Interface::_getCursorPos = -> columns = @columns strBeforeCursor = @_prompt + @line.substring(0, @cursor) dispPos = @_getDisplayPos(stripVTControlCharacters(strBeforeCursor)) cols = dispPos.cols rows = dispPos.rows if cols + 1 is columns and @cursor < @line.length and isFullWidthCodePoint(codePointAt(@line, @cursor)) rows++ cols = 0 cols: cols rows: rows Interface::_moveCursor = (dx) -> oldcursor = @cursor oldPos = @_getCursorPos() @cursor += dx if @cursor < 0 @cursor = 0 else @cursor = @line.length if @cursor > @line.length newPos = @_getCursorPos() if oldPos.rows is newPos.rows diffCursor = @cursor - oldcursor diffWidth = undefined if diffCursor < 0 diffWidth = -getStringWidth(@line.substring(@cursor, oldcursor)) else diffWidth = getStringWidth(@line.substring(@cursor, oldcursor)) if diffCursor > 0 exports.moveCursor @output, diffWidth, 0 @prevRows = newPos.rows else @_refreshLine() return Interface::_ttyWrite = (s, key) -> key = key or {} return if key.name is "escape" if key.ctrl and key.shift switch key.name when "backspace" @_deleteLineLeft() when "delete" @_deleteLineRight() else if key.ctrl switch key.name when "c" if EventEmitter.listenerCount(this, "SIGINT") > 0 @emit "SIGINT" else @close() when "h" @_deleteLeft() when "d" if @cursor is 0 and @line.length is 0 @close() else @_deleteRight() if @cursor < @line.length when "u" @cursor = 0 @line = "" @_refreshLine() when "k" @_deleteLineRight() when "a" @_moveCursor -Infinity when "e" @_moveCursor +Infinity when "b" @_moveCursor -1 when "f" @_moveCursor +1 when "l" exports.cursorTo @output, 0, 0 exports.clearScreenDown @output @_refreshLine() when "n" @_historyNext() when "p" @_historyPrev() when "z" break if process.platform is "win32" if EventEmitter.listenerCount(this, "SIGTSTP") > 0 @emit "SIGTSTP" else process.once "SIGCONT", ((self) -> -> unless self.paused self.pause() self.emit "SIGCONT" self._setRawMode true self._refreshLine() return )(this) @_setRawMode false process.kill process.pid, "SIGTSTP" when "w", "backspace" @_deleteWordLeft() when "delete" @_deleteWordRight() when "left" @_wordLeft() when "right" @_wordRight() else if key.meta switch key.name when "b" @_wordLeft() when "f" @_wordRight() when "d", "delete" @_deleteWordRight() when "backspace" @_deleteWordLeft() else @_sawReturn = false if @_sawReturn and key.name isnt "enter" switch key.name when "return" @_sawReturn = true @_line() when "enter" if @_sawReturn @_sawReturn = false else @_line() when "backspace" @_deleteLeft() when "delete" @_deleteRight() when "tab" @_tabComplete() when "left" @_moveCursor -1 when "right" @_moveCursor +1 when "home" @_moveCursor -Infinity when "end" @_moveCursor +Infinity when "up" @_historyPrev() when "down" @_historyNext() else s = s.toString("utf-8") if util.isBuffer(s) if s lines = s.split(/\r\n|\n|\r/) i = 0 len = lines.length while i < len @_line() if i > 0 @_insertString lines[i] i++ return exports.Interface = Interface exports.emitKeypressEvents = emitKeypressEvents metaKeyCodeReAnywhere = /(?:\x1b)([a-zA-Z0-9])/ metaKeyCodeRe = new RegExp("^" + metaKeyCodeReAnywhere.source + "$") functionKeyCodeReAnywhere = new RegExp("(?:\u001b+)(O|N|\\[|\\[\\[)(?:" + [ "(\\d+)(?:;(\\d+))?([~^$])" "(?:M([@ #!a`])(.)(.))" "(?:1;)?(\\d+)?([a-zA-Z])" ].join("|") + ")") functionKeyCodeRe = new RegExp("^" + functionKeyCodeReAnywhere.source) escapeCodeReAnywhere = new RegExp([ functionKeyCodeReAnywhere.source metaKeyCodeReAnywhere.source /\x1b./.source ].join("|")) exports.cursorTo = cursorTo exports.moveCursor = moveCursor exports.clearLine = clearLine exports.clearScreenDown = clearScreenDown exports.getStringWidth = getStringWidth exports.isFullWidthCodePoint = isFullWidthCodePoint exports.codePointAt = codePointAt exports.stripVTControlCharacters = stripVTControlCharacters
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9983218312263489, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "m, 50\n return\n args = (\"s_client -connect 127.0.0.1:\" + common.PORT).split(\" \")\...
test/pummel/test-https-ci-reneg-attack.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # renegotiation limits to test test = (next) -> options = cert: fs.readFileSync(common.fixturesDir + "/test_cert.pem") key: fs.readFileSync(common.fixturesDir + "/test_key.pem") seenError = false server = https.createServer(options, (req, res) -> conn = req.connection conn.on "error", (err) -> console.error "Caught exception: " + err assert /TLS session renegotiation attack/.test(err) conn.destroy() seenError = true return res.end "ok" return ) server.listen common.PORT, -> #child.stdout.pipe(process.stdout); #child.stderr.pipe(process.stderr); # count handshakes, start the attack after the initial handshake is done # simulate renegotiation attack spam = -> return if closed child.stdin.write "R\n" setTimeout spam, 50 return args = ("s_client -connect 127.0.0.1:" + common.PORT).split(" ") child = spawn(common.opensslCli, args) child.stdout.resume() child.stderr.resume() handshakes = 0 renegs = 0 child.stderr.on "data", (data) -> return if seenError handshakes += (("" + data).match(/verify return:1/g) or []).length spam() if handshakes is 2 renegs += (("" + data).match(/RENEGOTIATING/g) or []).length return child.on "exit", -> assert.equal renegs, tls.CLIENT_RENEG_LIMIT + 1 server.close() process.nextTick next return closed = false child.stdin.on "error", (err) -> switch err.code when "ECONNRESET", "EPIPE" else assert.equal err.code, "ECONNRESET" closed = true return child.stdin.on "close", -> closed = true return return return common = require("../common") assert = require("assert") spawn = require("child_process").spawn tls = require("tls") https = require("https") fs = require("fs") unless common.opensslCli console.error "Skipping because node compiled without OpenSSL CLI." process.exit 0 LIMITS = [ 0 1 2 3 5 10 16 ] (-> next = -> return if n >= LIMITS.length tls.CLIENT_RENEG_LIMIT = LIMITS[n++] test next return n = 0 next() return )()
78927
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # renegotiation limits to test test = (next) -> options = cert: fs.readFileSync(common.fixturesDir + "/test_cert.pem") key: fs.readFileSync(common.fixturesDir + "/test_key.pem") seenError = false server = https.createServer(options, (req, res) -> conn = req.connection conn.on "error", (err) -> console.error "Caught exception: " + err assert /TLS session renegotiation attack/.test(err) conn.destroy() seenError = true return res.end "ok" return ) server.listen common.PORT, -> #child.stdout.pipe(process.stdout); #child.stderr.pipe(process.stderr); # count handshakes, start the attack after the initial handshake is done # simulate renegotiation attack spam = -> return if closed child.stdin.write "R\n" setTimeout spam, 50 return args = ("s_client -connect 127.0.0.1:" + common.PORT).split(" ") child = spawn(common.opensslCli, args) child.stdout.resume() child.stderr.resume() handshakes = 0 renegs = 0 child.stderr.on "data", (data) -> return if seenError handshakes += (("" + data).match(/verify return:1/g) or []).length spam() if handshakes is 2 renegs += (("" + data).match(/RENEGOTIATING/g) or []).length return child.on "exit", -> assert.equal renegs, tls.CLIENT_RENEG_LIMIT + 1 server.close() process.nextTick next return closed = false child.stdin.on "error", (err) -> switch err.code when "ECONNRESET", "EPIPE" else assert.equal err.code, "ECONNRESET" closed = true return child.stdin.on "close", -> closed = true return return return common = require("../common") assert = require("assert") spawn = require("child_process").spawn tls = require("tls") https = require("https") fs = require("fs") unless common.opensslCli console.error "Skipping because node compiled without OpenSSL CLI." process.exit 0 LIMITS = [ 0 1 2 3 5 10 16 ] (-> next = -> return if n >= LIMITS.length tls.CLIENT_RENEG_LIMIT = LIMITS[n++] test next return n = 0 next() return )()
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. # renegotiation limits to test test = (next) -> options = cert: fs.readFileSync(common.fixturesDir + "/test_cert.pem") key: fs.readFileSync(common.fixturesDir + "/test_key.pem") seenError = false server = https.createServer(options, (req, res) -> conn = req.connection conn.on "error", (err) -> console.error "Caught exception: " + err assert /TLS session renegotiation attack/.test(err) conn.destroy() seenError = true return res.end "ok" return ) server.listen common.PORT, -> #child.stdout.pipe(process.stdout); #child.stderr.pipe(process.stderr); # count handshakes, start the attack after the initial handshake is done # simulate renegotiation attack spam = -> return if closed child.stdin.write "R\n" setTimeout spam, 50 return args = ("s_client -connect 127.0.0.1:" + common.PORT).split(" ") child = spawn(common.opensslCli, args) child.stdout.resume() child.stderr.resume() handshakes = 0 renegs = 0 child.stderr.on "data", (data) -> return if seenError handshakes += (("" + data).match(/verify return:1/g) or []).length spam() if handshakes is 2 renegs += (("" + data).match(/RENEGOTIATING/g) or []).length return child.on "exit", -> assert.equal renegs, tls.CLIENT_RENEG_LIMIT + 1 server.close() process.nextTick next return closed = false child.stdin.on "error", (err) -> switch err.code when "ECONNRESET", "EPIPE" else assert.equal err.code, "ECONNRESET" closed = true return child.stdin.on "close", -> closed = true return return return common = require("../common") assert = require("assert") spawn = require("child_process").spawn tls = require("tls") https = require("https") fs = require("fs") unless common.opensslCli console.error "Skipping because node compiled without OpenSSL CLI." process.exit 0 LIMITS = [ 0 1 2 3 5 10 16 ] (-> next = -> return if n >= LIMITS.length tls.CLIENT_RENEG_LIMIT = LIMITS[n++] test next return n = 0 next() return )()
[ { "context": "t, \"validator is invalid\")\n\n view_model.value('Bob')\n assert.ok(!validator().required, \"required ", "end": 1255, "score": 0.8433871269226074, "start": 1252, "tag": "NAME", "value": "Bob" }, { "context": " window.nameTaken = (value) -> return value is 'Bob'...
test/spec/plugins/validation.tests.coffee
kmalakoff/knockback
160
assert = assert or require?('chai').assert window = if window? then window else global describe 'validation @quick @validation', -> kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback') {_, ko} = kb $ = window?.$ it 'TEST DEPENDENCY MISSING', (done) -> assert.ok(!!ko, 'ko') assert.ok(!!_, '_') assert.ok(!!kb.Model, 'kb.Model') assert.ok(!!kb.Collection, 'kb.Collection') assert.ok(!!kb, 'kb') done() it 'kb.valueValidator', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = value: ko.observable() validator = kb.valueValidator(view_model.value, {required: kb.valid.required, url: kb.valid.url}) assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") view_model.value('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") view_model.value('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator with custom validators', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() window.nameTaken = (value) -> return value is 'Bob' el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator, validations: {unique: nameTaken}" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().unique, "unique is valid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(validator().unique, "unique is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Fred') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().unique, "unique is valid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(!validator().unique, "unique is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator with validation_options', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() window.disable = ko.observable(true) el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator, validation_options: {disable: disable, priorities: \'url\'}" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "obs: has required") assert.ok(validator().hasOwnProperty('url'), "obs: has url") assert.ok(validator().hasOwnProperty('$valid'), "obs: has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "obs: has $error_count") assert.ok(!validator().required, "obs: required is valid") assert.ok(!validator().url, "obs: url is valid") assert.ok(validator().$valid, "obs: validator is valid") assert.ok(!validator().$error_count, "obs: validator is not invalid") assert.ok(!validator().$active_error, "obs: active error does not exist") window.disable(false) assert.ok(validator().required, "obs: required is invalid") assert.ok(validator().url, "obs: url is invalid") assert.ok(!validator().$valid, "obs: validator not valid") assert.ok(validator().$error_count, "obs: validator is invalid") assert.equal(validator().$active_error, 'url', "obs: active error is url") window.disable(-> return true) assert.ok(!validator().required, "obs fn: required is valid") assert.ok(!validator().url, "obs fn: url is valid") assert.ok(validator().$valid, "obs fn: validator is valid") assert.ok(!validator().$error_count, "obs fn: validator is not invalid") assert.ok(!validator().$active_error, "obs fn: error does not exist") window.disable(-> return false) assert.ok(validator().required, "obs fn: required is invalid") assert.ok(validator().url, "obs fn: url is invalid") assert.ok(!validator().$valid, "obs fn: validator not valid") assert.ok(validator().$error_count, "obs fn: validator is invalid") assert.equal(validator().$active_error, 'url', "obs fn: active error is url") kb.release(view_model) view_model = name: ko.observable() window.disable = -> return true el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator, validation_options: {disable: disable}" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "fn: has required") assert.ok(validator().hasOwnProperty('url'), "fn: has url") assert.ok(validator().hasOwnProperty('$valid'), "fn: has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "fn: has $error_count") assert.ok(!validator().required, "fn: required is valid") assert.ok(!validator().url, "fn: url is valid") assert.ok(validator().$valid, "fn: validator is valid") assert.ok(!validator().$error_count, "fn: validator is not invalid") assert.ok(!validator().$active_error, "fn: active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.formValidator with name', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() site: ko.observable() HTML = """ <form name='my_form' data-bind="inject: kb.formValidator, validation_options: {priorities: ['required', 'url']}"> <div class="control-group"> <input type="text" name="name" data-bind="value: name" required> </div> <div class="control-group"> <input type="url" name="site" data-bind="value: site" required> </div> </form> """ el = $(HTML)[0] ko.applyBindings(view_model, el) # check name validator = view_model.$my_form.name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(!validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") validator = view_model.$my_form.site assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.formValidator no name with validation_options', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() site: ko.observable() HTML = """ <form data-bind="inject: kb.formValidator, validation_options: {enable: enable, priorities: 'url'}"> <div class="control-group"> <input type="text" name="name" data-bind="value: name" required> </div> <div class="control-group"> <input type="url" name="site" data-bind="value: site" required> </div> </form> """ window.enable = ko.observable(false) el = $(HTML)[0] ko.applyBindings(view_model, el) # check name validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(!validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") # disabled assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") # enabled window.enable(-> return true) assert.ok(validator().required, "required is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") view_model.name('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") validator = view_model.$site assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.formValidator with inject and disable', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats window.MyViewModel = kb.ViewModel.extend({ constructor: -> model = new kb.Model({name: '', site: ''}) kb.ViewModel.prototype.constructor.call(this, model) return }) HTML = """ <div kb-inject="MyViewModel"> <form name="my_form" data-bind="inject: kb.formValidator, validation_options: {disable: disable, priorities: ['url']}"> <div class="control-group"> <label>Name</label> <input type="text" name="name" data-bind="value: name, valueUpdate: 'keyup'" required> </div> <div class="control-group"> <label>Website</label> <input type="url" name="site" data-bind="value: site, valueUpdate: 'keyup'" required> </div> </form> </div> """ window.disable = ko.observable(true) inject_el = $(HTML)[0] injected = kb.injectViewModels(inject_el) assert.equal(injected[0].el, inject_el, "app was injected") view_model = injected[0].view_model # check name validator = view_model.$my_form.name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(!validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") # disabled assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") # enabled window.disable(-> return false) assert.ok(validator().required, "required is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'required', "active error is required") view_model.name('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "no active error") validator = view_model.$my_form.site assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "no active error") ko.removeNode(inject_el) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator without required', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator">')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(!validator().hasOwnProperty('required'), "does not have required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('http://Bob') assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done()
72313
assert = assert or require?('chai').assert window = if window? then window else global describe 'validation @quick @validation', -> kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback') {_, ko} = kb $ = window?.$ it 'TEST DEPENDENCY MISSING', (done) -> assert.ok(!!ko, 'ko') assert.ok(!!_, '_') assert.ok(!!kb.Model, 'kb.Model') assert.ok(!!kb.Collection, 'kb.Collection') assert.ok(!!kb, 'kb') done() it 'kb.valueValidator', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = value: ko.observable() validator = kb.valueValidator(view_model.value, {required: kb.valid.required, url: kb.valid.url}) assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") view_model.value('<NAME>') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") view_model.value('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator with custom validators', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() window.nameTaken = (value) -> return value is '<NAME>' el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator, validations: {unique: nameTaken}" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().unique, "unique is valid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('<NAME>') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(validator().unique, "unique is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('<NAME>') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().unique, "unique is valid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(!validator().unique, "unique is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator with validation_options', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() window.disable = ko.observable(true) el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator, validation_options: {disable: disable, priorities: \'url\'}" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "obs: has required") assert.ok(validator().hasOwnProperty('url'), "obs: has url") assert.ok(validator().hasOwnProperty('$valid'), "obs: has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "obs: has $error_count") assert.ok(!validator().required, "obs: required is valid") assert.ok(!validator().url, "obs: url is valid") assert.ok(validator().$valid, "obs: validator is valid") assert.ok(!validator().$error_count, "obs: validator is not invalid") assert.ok(!validator().$active_error, "obs: active error does not exist") window.disable(false) assert.ok(validator().required, "obs: required is invalid") assert.ok(validator().url, "obs: url is invalid") assert.ok(!validator().$valid, "obs: validator not valid") assert.ok(validator().$error_count, "obs: validator is invalid") assert.equal(validator().$active_error, 'url', "obs: active error is url") window.disable(-> return true) assert.ok(!validator().required, "obs fn: required is valid") assert.ok(!validator().url, "obs fn: url is valid") assert.ok(validator().$valid, "obs fn: validator is valid") assert.ok(!validator().$error_count, "obs fn: validator is not invalid") assert.ok(!validator().$active_error, "obs fn: error does not exist") window.disable(-> return false) assert.ok(validator().required, "obs fn: required is invalid") assert.ok(validator().url, "obs fn: url is invalid") assert.ok(!validator().$valid, "obs fn: validator not valid") assert.ok(validator().$error_count, "obs fn: validator is invalid") assert.equal(validator().$active_error, 'url', "obs fn: active error is url") kb.release(view_model) view_model = name: ko.observable() window.disable = -> return true el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator, validation_options: {disable: disable}" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "fn: has required") assert.ok(validator().hasOwnProperty('url'), "fn: has url") assert.ok(validator().hasOwnProperty('$valid'), "fn: has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "fn: has $error_count") assert.ok(!validator().required, "fn: required is valid") assert.ok(!validator().url, "fn: url is valid") assert.ok(validator().$valid, "fn: validator is valid") assert.ok(!validator().$error_count, "fn: validator is not invalid") assert.ok(!validator().$active_error, "fn: active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.formValidator with name', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() site: ko.observable() HTML = """ <form name='my_form' data-bind="inject: kb.formValidator, validation_options: {priorities: ['required', 'url']}"> <div class="control-group"> <input type="text" name="name" data-bind="value: name" required> </div> <div class="control-group"> <input type="url" name="site" data-bind="value: site" required> </div> </form> """ el = $(HTML)[0] ko.applyBindings(view_model, el) # check name validator = view_model.$my_form.name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(!validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") validator = view_model.$my_form.site assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('<NAME>') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.formValidator no name with validation_options', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() site: ko.observable() HTML = """ <form data-bind="inject: kb.formValidator, validation_options: {enable: enable, priorities: 'url'}"> <div class="control-group"> <input type="text" name="name" data-bind="value: name" required> </div> <div class="control-group"> <input type="url" name="site" data-bind="value: site" required> </div> </form> """ window.enable = ko.observable(false) el = $(HTML)[0] ko.applyBindings(view_model, el) # check name validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(!validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") # disabled assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") # enabled window.enable(-> return true) assert.ok(validator().required, "required is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") view_model.name('<NAME>') assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") validator = view_model.$site assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.formValidator with inject and disable', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats window.MyViewModel = kb.ViewModel.extend({ constructor: -> model = new kb.Model({name: '', site: ''}) kb.ViewModel.prototype.constructor.call(this, model) return }) HTML = """ <div kb-inject="MyViewModel"> <form name="my_form" data-bind="inject: kb.formValidator, validation_options: {disable: disable, priorities: ['url']}"> <div class="control-group"> <label>Name</label> <input type="text" name="name" data-bind="value: name, valueUpdate: 'keyup'" required> </div> <div class="control-group"> <label>Website</label> <input type="url" name="site" data-bind="value: site, valueUpdate: 'keyup'" required> </div> </form> </div> """ window.disable = ko.observable(true) inject_el = $(HTML)[0] injected = kb.injectViewModels(inject_el) assert.equal(injected[0].el, inject_el, "app was injected") view_model = injected[0].view_model # check name validator = view_model.$my_form.name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(!validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") # disabled assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") # enabled window.disable(-> return false) assert.ok(validator().required, "required is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'required', "active error is required") view_model.name('<NAME>') assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "no active error") validator = view_model.$my_form.site assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "no active error") ko.removeNode(inject_el) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator without required', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator">')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(!validator().hasOwnProperty('required'), "does not have required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('http://Bob') assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done()
true
assert = assert or require?('chai').assert window = if window? then window else global describe 'validation @quick @validation', -> kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback') {_, ko} = kb $ = window?.$ it 'TEST DEPENDENCY MISSING', (done) -> assert.ok(!!ko, 'ko') assert.ok(!!_, '_') assert.ok(!!kb.Model, 'kb.Model') assert.ok(!!kb.Collection, 'kb.Collection') assert.ok(!!kb, 'kb') done() it 'kb.valueValidator', (done) -> kb.statistics = new kb.Statistics() # turn on stats view_model = value: ko.observable() validator = kb.valueValidator(view_model.value, {required: kb.valid.required, url: kb.valid.url}) assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") view_model.value('PI:NAME:<NAME>END_PI') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") view_model.value('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator with custom validators', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() window.nameTaken = (value) -> return value is 'PI:NAME:<NAME>END_PI' el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator, validations: {unique: nameTaken}" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().unique, "unique is valid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('PI:NAME:<NAME>END_PI') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(validator().unique, "unique is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('PI:NAME:<NAME>END_PI') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().unique, "unique is valid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(!validator().unique, "unique is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator with validation_options', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() window.disable = ko.observable(true) el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator, validation_options: {disable: disable, priorities: \'url\'}" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "obs: has required") assert.ok(validator().hasOwnProperty('url'), "obs: has url") assert.ok(validator().hasOwnProperty('$valid'), "obs: has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "obs: has $error_count") assert.ok(!validator().required, "obs: required is valid") assert.ok(!validator().url, "obs: url is valid") assert.ok(validator().$valid, "obs: validator is valid") assert.ok(!validator().$error_count, "obs: validator is not invalid") assert.ok(!validator().$active_error, "obs: active error does not exist") window.disable(false) assert.ok(validator().required, "obs: required is invalid") assert.ok(validator().url, "obs: url is invalid") assert.ok(!validator().$valid, "obs: validator not valid") assert.ok(validator().$error_count, "obs: validator is invalid") assert.equal(validator().$active_error, 'url', "obs: active error is url") window.disable(-> return true) assert.ok(!validator().required, "obs fn: required is valid") assert.ok(!validator().url, "obs fn: url is valid") assert.ok(validator().$valid, "obs fn: validator is valid") assert.ok(!validator().$error_count, "obs fn: validator is not invalid") assert.ok(!validator().$active_error, "obs fn: error does not exist") window.disable(-> return false) assert.ok(validator().required, "obs fn: required is invalid") assert.ok(validator().url, "obs fn: url is invalid") assert.ok(!validator().$valid, "obs fn: validator not valid") assert.ok(validator().$error_count, "obs fn: validator is invalid") assert.equal(validator().$active_error, 'url', "obs fn: active error is url") kb.release(view_model) view_model = name: ko.observable() window.disable = -> return true el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator, validation_options: {disable: disable}" required>')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "fn: has required") assert.ok(validator().hasOwnProperty('url'), "fn: has url") assert.ok(validator().hasOwnProperty('$valid'), "fn: has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "fn: has $error_count") assert.ok(!validator().required, "fn: required is valid") assert.ok(!validator().url, "fn: url is valid") assert.ok(validator().$valid, "fn: validator is valid") assert.ok(!validator().$error_count, "fn: validator is not invalid") assert.ok(!validator().$active_error, "fn: active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.formValidator with name', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() site: ko.observable() HTML = """ <form name='my_form' data-bind="inject: kb.formValidator, validation_options: {priorities: ['required', 'url']}"> <div class="control-group"> <input type="text" name="name" data-bind="value: name" required> </div> <div class="control-group"> <input type="url" name="site" data-bind="value: site" required> </div> </form> """ el = $(HTML)[0] ko.applyBindings(view_model, el) # check name validator = view_model.$my_form.name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(!validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") validator = view_model.$my_form.site assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('PI:NAME:<NAME>END_PI') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.formValidator no name with validation_options', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() site: ko.observable() HTML = """ <form data-bind="inject: kb.formValidator, validation_options: {enable: enable, priorities: 'url'}"> <div class="control-group"> <input type="text" name="name" data-bind="value: name" required> </div> <div class="control-group"> <input type="url" name="site" data-bind="value: site" required> </div> </form> """ window.enable = ko.observable(false) el = $(HTML)[0] ko.applyBindings(view_model, el) # check name validator = view_model.$name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(!validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") # disabled assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") # enabled window.enable(-> return true) assert.ok(validator().required, "required is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") view_model.name('PI:NAME:<NAME>END_PI') assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") validator = view_model.$site assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.formValidator with inject and disable', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats window.MyViewModel = kb.ViewModel.extend({ constructor: -> model = new kb.Model({name: '', site: ''}) kb.ViewModel.prototype.constructor.call(this, model) return }) HTML = """ <div kb-inject="MyViewModel"> <form name="my_form" data-bind="inject: kb.formValidator, validation_options: {disable: disable, priorities: ['url']}"> <div class="control-group"> <label>Name</label> <input type="text" name="name" data-bind="value: name, valueUpdate: 'keyup'" required> </div> <div class="control-group"> <label>Website</label> <input type="url" name="site" data-bind="value: site, valueUpdate: 'keyup'" required> </div> </form> </div> """ window.disable = ko.observable(true) inject_el = $(HTML)[0] injected = kb.injectViewModels(inject_el) assert.equal(injected[0].el, inject_el, "app was injected") view_model = injected[0].view_model # check name validator = view_model.$my_form.name assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(!validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") # disabled assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") # enabled window.disable(-> return false) assert.ok(validator().required, "required is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'required', "active error is required") view_model.name('PI:NAME:<NAME>END_PI') assert.ok(!validator().required, "required is valid") assert.ok(validator().$valid, "validator valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "no active error") validator = view_model.$my_form.site assert.ok(validator().hasOwnProperty('required'), "has required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().required, "required is invalid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('Bob') assert.ok(!validator().required, "required is valid") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.equal(validator().$active_error, 'url', "active error is url") view_model.site('http://Bob') assert.ok(!validator().required, "required is valid") assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "no active error") ko.removeNode(inject_el) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done() it 'kb.inputValidator without required', (done) -> return done() unless ($ and window?.document) window.kb = kb unless window.kb # make kb global for bindings kb.statistics = new kb.Statistics() # turn on stats view_model = name: ko.observable() el = $('<input type="url" name="name" data-bind="value: name, inject: kb.inputValidator">')[0] ko.applyBindings(view_model, el) validator = view_model.$name assert.ok(!validator().hasOwnProperty('required'), "does not have required") assert.ok(validator().hasOwnProperty('url'), "has url") assert.ok(validator().hasOwnProperty('$valid'), "has $valid") assert.ok(validator().hasOwnProperty('$error_count'), "has $error_count") assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('Bob') assert.ok(validator().url, "url is invalid") assert.ok(!validator().$valid, "validator not valid") assert.ok(validator().$error_count, "validator is invalid") assert.ok(validator().$active_error, "active error exists") view_model.name('http://Bob') assert.ok(!validator().url, "url is valid") assert.ok(validator().$valid, "validator is valid") assert.ok(!validator().$error_count, "validator is not invalid") assert.ok(!validator().$active_error, "active error does not exist") kb.release(view_model) assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null done()
[ { "context": " body})->\n\t\t\tt.is status, 200\n\t\t\tt.is body.name, 'daniel'\n\t\t\tt.is body.field, undefined\n\t\n\t\t.then ()-> req", "end": 1467, "score": 0.9997265338897705, "start": 1461, "tag": "NAME", "value": "daniel" }, { "context": " body})->\n\t\t\tt.is status, 200\n\t...
test/test.coffee
danielkalen/feathers-commands
0
{test} = require 'ava' {app, createService} = require './app' feathersCommands = require '../' test "registration", (t)-> createService '1' t.is typeof app.service('1').command, 'undefined' t.is typeof app.service('1').run, 'undefined' feathersCommands(app) t.is typeof app.service('1').command, 'undefined' t.is typeof app.service('1').run, 'undefined' createService '2' t.is typeof app.service('2').command, 'function' t.is typeof app.service('2').run, 'function' createService '3' test "create commands", (t)-> t.notThrows ()-> app.service('2').command 'command1', (data, params)-> Promise.resolve([data, params]) test "run commands", (t)-> Promise.resolve() .then ()-> app.service('2').run 'command1', 'abc123' .then (result)-> t.is result[0], 'abc123' t.deepEqual result[1], {query:{}} .then ()-> app.service('2').run 'command1', 'def456', {blabla:1} .then (result)-> t.is result[0], 'def456' t.deepEqual result[1], {query:{}, blabla:1} test "command path params", (t)-> request = require 'supertest' extend = require 'smart-extend' Promise.resolve() .then ()-> app.service('2').command 'command3/:name/:field?', (data, params)-> Promise.resolve extend.keys(['name','field']).clone(params) .then ()-> request(app).post('/2/command3') .then ({status})-> t.is status, 404 .then ()-> request(app).post('/2/command3/daniel') .then ({status, body})-> t.is status, 200 t.is body.name, 'daniel' t.is body.field, undefined .then ()-> request(app).post('/2/command3/daniel/king') .then ({status, body})-> t.is status, 200 t.is body.name, 'daniel' t.is body.field, 'king' test "hooks (all)", (t)-> app.service('2').command 'command4', (data)-> Promise.resolve(data) app.service('2').hooks before: all: ({data})-> data.count ?= 0 data.count++ return data = {abc:123} Promise.resolve() .then ()-> app.service('2').run 'command4', data .then (result)-> t.is data, result t.is data.count, 1 test "hooks (specific command)", (t)-> markHistory = (label)-> ({data})-> data.history ?= [] data.history.push label return app.service('2').command 'command5', (data)-> Promise.resolve(data) app.service('2').hooks before: all: markHistory('all') command5: markHistory('before') after: command5: markHistory('after') finally: command5: markHistory('finally') data = {abc:123} Promise.resolve() .then ()-> app.service('2').run 'command5', data .then (result)-> t.is data, result t.deepEqual data.history, ['all', 'before', 'after', 'finally'] test "hooks context", (t)-> app.service('3').command 'command6/:_id', (data, params)-> Promise.resolve(params.context) app.service('3').hooks before: all: (context)-> context.params.context = context; return Promise.resolve() .then ()-> app.service('3').run 'command6' .then (result)-> t.true result? t.is result.path, '3' t.is result.method, 'command6'
109959
{test} = require 'ava' {app, createService} = require './app' feathersCommands = require '../' test "registration", (t)-> createService '1' t.is typeof app.service('1').command, 'undefined' t.is typeof app.service('1').run, 'undefined' feathersCommands(app) t.is typeof app.service('1').command, 'undefined' t.is typeof app.service('1').run, 'undefined' createService '2' t.is typeof app.service('2').command, 'function' t.is typeof app.service('2').run, 'function' createService '3' test "create commands", (t)-> t.notThrows ()-> app.service('2').command 'command1', (data, params)-> Promise.resolve([data, params]) test "run commands", (t)-> Promise.resolve() .then ()-> app.service('2').run 'command1', 'abc123' .then (result)-> t.is result[0], 'abc123' t.deepEqual result[1], {query:{}} .then ()-> app.service('2').run 'command1', 'def456', {blabla:1} .then (result)-> t.is result[0], 'def456' t.deepEqual result[1], {query:{}, blabla:1} test "command path params", (t)-> request = require 'supertest' extend = require 'smart-extend' Promise.resolve() .then ()-> app.service('2').command 'command3/:name/:field?', (data, params)-> Promise.resolve extend.keys(['name','field']).clone(params) .then ()-> request(app).post('/2/command3') .then ({status})-> t.is status, 404 .then ()-> request(app).post('/2/command3/daniel') .then ({status, body})-> t.is status, 200 t.is body.name, '<NAME>' t.is body.field, undefined .then ()-> request(app).post('/2/command3/daniel/king') .then ({status, body})-> t.is status, 200 t.is body.name, '<NAME>' t.is body.field, 'king' test "hooks (all)", (t)-> app.service('2').command 'command4', (data)-> Promise.resolve(data) app.service('2').hooks before: all: ({data})-> data.count ?= 0 data.count++ return data = {abc:123} Promise.resolve() .then ()-> app.service('2').run 'command4', data .then (result)-> t.is data, result t.is data.count, 1 test "hooks (specific command)", (t)-> markHistory = (label)-> ({data})-> data.history ?= [] data.history.push label return app.service('2').command 'command5', (data)-> Promise.resolve(data) app.service('2').hooks before: all: markHistory('all') command5: markHistory('before') after: command5: markHistory('after') finally: command5: markHistory('finally') data = {abc:123} Promise.resolve() .then ()-> app.service('2').run 'command5', data .then (result)-> t.is data, result t.deepEqual data.history, ['all', 'before', 'after', 'finally'] test "hooks context", (t)-> app.service('3').command 'command6/:_id', (data, params)-> Promise.resolve(params.context) app.service('3').hooks before: all: (context)-> context.params.context = context; return Promise.resolve() .then ()-> app.service('3').run 'command6' .then (result)-> t.true result? t.is result.path, '3' t.is result.method, 'command6'
true
{test} = require 'ava' {app, createService} = require './app' feathersCommands = require '../' test "registration", (t)-> createService '1' t.is typeof app.service('1').command, 'undefined' t.is typeof app.service('1').run, 'undefined' feathersCommands(app) t.is typeof app.service('1').command, 'undefined' t.is typeof app.service('1').run, 'undefined' createService '2' t.is typeof app.service('2').command, 'function' t.is typeof app.service('2').run, 'function' createService '3' test "create commands", (t)-> t.notThrows ()-> app.service('2').command 'command1', (data, params)-> Promise.resolve([data, params]) test "run commands", (t)-> Promise.resolve() .then ()-> app.service('2').run 'command1', 'abc123' .then (result)-> t.is result[0], 'abc123' t.deepEqual result[1], {query:{}} .then ()-> app.service('2').run 'command1', 'def456', {blabla:1} .then (result)-> t.is result[0], 'def456' t.deepEqual result[1], {query:{}, blabla:1} test "command path params", (t)-> request = require 'supertest' extend = require 'smart-extend' Promise.resolve() .then ()-> app.service('2').command 'command3/:name/:field?', (data, params)-> Promise.resolve extend.keys(['name','field']).clone(params) .then ()-> request(app).post('/2/command3') .then ({status})-> t.is status, 404 .then ()-> request(app).post('/2/command3/daniel') .then ({status, body})-> t.is status, 200 t.is body.name, 'PI:NAME:<NAME>END_PI' t.is body.field, undefined .then ()-> request(app).post('/2/command3/daniel/king') .then ({status, body})-> t.is status, 200 t.is body.name, 'PI:NAME:<NAME>END_PI' t.is body.field, 'king' test "hooks (all)", (t)-> app.service('2').command 'command4', (data)-> Promise.resolve(data) app.service('2').hooks before: all: ({data})-> data.count ?= 0 data.count++ return data = {abc:123} Promise.resolve() .then ()-> app.service('2').run 'command4', data .then (result)-> t.is data, result t.is data.count, 1 test "hooks (specific command)", (t)-> markHistory = (label)-> ({data})-> data.history ?= [] data.history.push label return app.service('2').command 'command5', (data)-> Promise.resolve(data) app.service('2').hooks before: all: markHistory('all') command5: markHistory('before') after: command5: markHistory('after') finally: command5: markHistory('finally') data = {abc:123} Promise.resolve() .then ()-> app.service('2').run 'command5', data .then (result)-> t.is data, result t.deepEqual data.history, ['all', 'before', 'after', 'finally'] test "hooks context", (t)-> app.service('3').command 'command6/:_id', (data, params)-> Promise.resolve(params.context) app.service('3').hooks before: all: (context)-> context.params.context = context; return Promise.resolve() .then ()-> app.service('3').run 'command6' .then (result)-> t.true result? t.is result.path, '3' t.is result.method, 'command6'
[ { "context": "WithTarget = (name, actual, target) ->\n key = i.toString()\n expected = expectedSwatches[target][key][na", "end": 2269, "score": 0.9959269762039185, "start": 2257, "tag": "KEY", "value": "i.toString()" } ]
test/vibrant.spec.coffee
Kronuz/node-vibrant
0
# Values from actual execution in different browsers. # Qualiy is set to 1 and not filters are used since downsampling are inconsistent # across browsers. # Comfirmed visually and established as baseline for future versions expectedSwatches = chrome: require('./data/chrome-exec-ref.json') firefox: require('./data/firefox-exec-ref.json') ie: require('./data/ie11-exec-ref.json') TARGETS = Object.keys(expectedSwatches) expect = require('chai').expect path = require('path') http = require('http') finalhandler = require('finalhandler') serveStatic = require('serve-static') Promise = require('bluebird') Vibrant = require('../') util = require('../lib/util') TEST_PORT = 3444 examples = [1..4].map (i) -> e = i: i fileName: "#{i}.jpg" filePath: path.join __dirname, "../examples/#{i}.jpg" fileUrl: "http://localhost:#{TEST_PORT}/#{i}.jpg" Table = require('cli-table') colors = require('colors') displayColorDiffTable = (p, diff) -> console.log "" console.log "Palette Diffrence of #{p}".inverse head = ["Swatch", "Actual"] TARGETS.forEach (t) -> head.push t head.push 'Status' opts = head: head chars: 'mid': '' 'left': '' 'left-mid': '' 'mid-mid': '' 'right-mid': '' 'top': '' 'top-mid': '' 'bottom-mid': '' 'top-left': '' 'top-right': '' 'bottom-left': '' 'bottom-right': '' 'bottom': '' table = new Table opts for row in diff table.push row console.log table.toString() DELTAE94 = NA: 0 PERFECT: 1 CLOSE: 2 GOOD: 10 SIMILAR: 50 getColorDiffStatus = (d) -> if d < DELTAE94.NA return "N/A".grey # Not perceptible by human eyes if d <= DELTAE94.PERFECT return "Perfect".green # Perceptible through close observation if d <= DELTAE94.CLOSE return "Close".cyan # Perceptible at a glance if d <= DELTAE94.GOOD return "Good".blue # Colors are more similar than opposite if d < DELTAE94.SIMILAR return "Similar".yellow return "Wrong".red paletteCallback = (p, i, done) -> (err, palette) -> if (err?) then throw err expect(palette, "palette should be returned").not.to.be.null failCount = 0 testWithTarget = (name, actual, target) -> key = i.toString() expected = expectedSwatches[target][key][name] result = target: target expected: expected ? "null" status: "N/A" diff: -1 if actual == null expect(expected, "#{name} color from '#{target}' was expected").to.be.null if expected == null expect(actual, "#{name} color form '#{target}' was not expected").to.be.null else actualHex = actual.getHex() diff = util.hexDiff(actualHex, expected) result.diff = diff result.status = getColorDiffStatus(diff) if diff > DELTAE94.SIMILAR then failCount++ result diffTable = [] for name, actual of palette colorDiff = [name, actual?.getHex() ? "null"] for target in TARGETS r = testWithTarget(name, actual, target) colorDiff.push r.expected colorDiff.push "#{r.status}(#{r.diff.toPrecision(2)})" diffTable.push colorDiff displayColorDiffTable p, diffTable expect(failCount, "#{failCount} colors are too diffrent from reference palettes") .to.equal(0) done() testVibrant = (p, i, done) -> Vibrant.from p .quality(1) .clearFilters() .getPalette paletteCallback(p, i, done) staticFiles = serveStatic "./examples" serverHandler = (req, res) -> done = finalhandler(req, res) staticFiles(req, res, done) describe "Palette Extraction", -> describe "process examples/", -> examples.forEach (example) -> it "#{example.fileName}", (done) -> testVibrant example.filePath, example.i, done describe "process remote images (http)", -> server = null before -> server = http.createServer serverHandler Promise.promisify server.listen Promise.promisify server.close server.listen(TEST_PORT) after -> server.close() examples.forEach (example) -> it "#{example.fileUrl}", (done) -> testVibrant example.fileUrl, example.i, done
92976
# Values from actual execution in different browsers. # Qualiy is set to 1 and not filters are used since downsampling are inconsistent # across browsers. # Comfirmed visually and established as baseline for future versions expectedSwatches = chrome: require('./data/chrome-exec-ref.json') firefox: require('./data/firefox-exec-ref.json') ie: require('./data/ie11-exec-ref.json') TARGETS = Object.keys(expectedSwatches) expect = require('chai').expect path = require('path') http = require('http') finalhandler = require('finalhandler') serveStatic = require('serve-static') Promise = require('bluebird') Vibrant = require('../') util = require('../lib/util') TEST_PORT = 3444 examples = [1..4].map (i) -> e = i: i fileName: "#{i}.jpg" filePath: path.join __dirname, "../examples/#{i}.jpg" fileUrl: "http://localhost:#{TEST_PORT}/#{i}.jpg" Table = require('cli-table') colors = require('colors') displayColorDiffTable = (p, diff) -> console.log "" console.log "Palette Diffrence of #{p}".inverse head = ["Swatch", "Actual"] TARGETS.forEach (t) -> head.push t head.push 'Status' opts = head: head chars: 'mid': '' 'left': '' 'left-mid': '' 'mid-mid': '' 'right-mid': '' 'top': '' 'top-mid': '' 'bottom-mid': '' 'top-left': '' 'top-right': '' 'bottom-left': '' 'bottom-right': '' 'bottom': '' table = new Table opts for row in diff table.push row console.log table.toString() DELTAE94 = NA: 0 PERFECT: 1 CLOSE: 2 GOOD: 10 SIMILAR: 50 getColorDiffStatus = (d) -> if d < DELTAE94.NA return "N/A".grey # Not perceptible by human eyes if d <= DELTAE94.PERFECT return "Perfect".green # Perceptible through close observation if d <= DELTAE94.CLOSE return "Close".cyan # Perceptible at a glance if d <= DELTAE94.GOOD return "Good".blue # Colors are more similar than opposite if d < DELTAE94.SIMILAR return "Similar".yellow return "Wrong".red paletteCallback = (p, i, done) -> (err, palette) -> if (err?) then throw err expect(palette, "palette should be returned").not.to.be.null failCount = 0 testWithTarget = (name, actual, target) -> key = <KEY> expected = expectedSwatches[target][key][name] result = target: target expected: expected ? "null" status: "N/A" diff: -1 if actual == null expect(expected, "#{name} color from '#{target}' was expected").to.be.null if expected == null expect(actual, "#{name} color form '#{target}' was not expected").to.be.null else actualHex = actual.getHex() diff = util.hexDiff(actualHex, expected) result.diff = diff result.status = getColorDiffStatus(diff) if diff > DELTAE94.SIMILAR then failCount++ result diffTable = [] for name, actual of palette colorDiff = [name, actual?.getHex() ? "null"] for target in TARGETS r = testWithTarget(name, actual, target) colorDiff.push r.expected colorDiff.push "#{r.status}(#{r.diff.toPrecision(2)})" diffTable.push colorDiff displayColorDiffTable p, diffTable expect(failCount, "#{failCount} colors are too diffrent from reference palettes") .to.equal(0) done() testVibrant = (p, i, done) -> Vibrant.from p .quality(1) .clearFilters() .getPalette paletteCallback(p, i, done) staticFiles = serveStatic "./examples" serverHandler = (req, res) -> done = finalhandler(req, res) staticFiles(req, res, done) describe "Palette Extraction", -> describe "process examples/", -> examples.forEach (example) -> it "#{example.fileName}", (done) -> testVibrant example.filePath, example.i, done describe "process remote images (http)", -> server = null before -> server = http.createServer serverHandler Promise.promisify server.listen Promise.promisify server.close server.listen(TEST_PORT) after -> server.close() examples.forEach (example) -> it "#{example.fileUrl}", (done) -> testVibrant example.fileUrl, example.i, done
true
# Values from actual execution in different browsers. # Qualiy is set to 1 and not filters are used since downsampling are inconsistent # across browsers. # Comfirmed visually and established as baseline for future versions expectedSwatches = chrome: require('./data/chrome-exec-ref.json') firefox: require('./data/firefox-exec-ref.json') ie: require('./data/ie11-exec-ref.json') TARGETS = Object.keys(expectedSwatches) expect = require('chai').expect path = require('path') http = require('http') finalhandler = require('finalhandler') serveStatic = require('serve-static') Promise = require('bluebird') Vibrant = require('../') util = require('../lib/util') TEST_PORT = 3444 examples = [1..4].map (i) -> e = i: i fileName: "#{i}.jpg" filePath: path.join __dirname, "../examples/#{i}.jpg" fileUrl: "http://localhost:#{TEST_PORT}/#{i}.jpg" Table = require('cli-table') colors = require('colors') displayColorDiffTable = (p, diff) -> console.log "" console.log "Palette Diffrence of #{p}".inverse head = ["Swatch", "Actual"] TARGETS.forEach (t) -> head.push t head.push 'Status' opts = head: head chars: 'mid': '' 'left': '' 'left-mid': '' 'mid-mid': '' 'right-mid': '' 'top': '' 'top-mid': '' 'bottom-mid': '' 'top-left': '' 'top-right': '' 'bottom-left': '' 'bottom-right': '' 'bottom': '' table = new Table opts for row in diff table.push row console.log table.toString() DELTAE94 = NA: 0 PERFECT: 1 CLOSE: 2 GOOD: 10 SIMILAR: 50 getColorDiffStatus = (d) -> if d < DELTAE94.NA return "N/A".grey # Not perceptible by human eyes if d <= DELTAE94.PERFECT return "Perfect".green # Perceptible through close observation if d <= DELTAE94.CLOSE return "Close".cyan # Perceptible at a glance if d <= DELTAE94.GOOD return "Good".blue # Colors are more similar than opposite if d < DELTAE94.SIMILAR return "Similar".yellow return "Wrong".red paletteCallback = (p, i, done) -> (err, palette) -> if (err?) then throw err expect(palette, "palette should be returned").not.to.be.null failCount = 0 testWithTarget = (name, actual, target) -> key = PI:KEY:<KEY>END_PI expected = expectedSwatches[target][key][name] result = target: target expected: expected ? "null" status: "N/A" diff: -1 if actual == null expect(expected, "#{name} color from '#{target}' was expected").to.be.null if expected == null expect(actual, "#{name} color form '#{target}' was not expected").to.be.null else actualHex = actual.getHex() diff = util.hexDiff(actualHex, expected) result.diff = diff result.status = getColorDiffStatus(diff) if diff > DELTAE94.SIMILAR then failCount++ result diffTable = [] for name, actual of palette colorDiff = [name, actual?.getHex() ? "null"] for target in TARGETS r = testWithTarget(name, actual, target) colorDiff.push r.expected colorDiff.push "#{r.status}(#{r.diff.toPrecision(2)})" diffTable.push colorDiff displayColorDiffTable p, diffTable expect(failCount, "#{failCount} colors are too diffrent from reference palettes") .to.equal(0) done() testVibrant = (p, i, done) -> Vibrant.from p .quality(1) .clearFilters() .getPalette paletteCallback(p, i, done) staticFiles = serveStatic "./examples" serverHandler = (req, res) -> done = finalhandler(req, res) staticFiles(req, res, done) describe "Palette Extraction", -> describe "process examples/", -> examples.forEach (example) -> it "#{example.fileName}", (done) -> testVibrant example.filePath, example.i, done describe "process remote images (http)", -> server = null before -> server = http.createServer serverHandler Promise.promisify server.listen Promise.promisify server.close server.listen(TEST_PORT) after -> server.close() examples.forEach (example) -> it "#{example.fileUrl}", (done) -> testVibrant example.fileUrl, example.i, done
[ { "context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ", "end": 194, "score": 0.9999223947525024, "start": 178, "tag": "EMAIL", "value": "info@chaibio.com" } ]
frontend/javascripts/app/controllers/create_experiment_modal_ctrl.coffee
MakerButt/chaipcr
1
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com> 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. ### window.ChaiBioTech.ngApp.controller 'CreateExperimentModalCtrl', [ '$scope' 'Experiment' ($scope, Experiment) -> $scope.newExperimentName = 'New Experiment' $scope.focused = false $scope.loading = false $scope.focus = -> $scope.focused = true $scope.submitted = false if $scope.newExperimentName is 'New Experiment' $scope.newExperimentName = '' $scope.unfocus = -> if $scope.newExperimentName is '' or !$scope.newExperimentName $scope.focused = false $scope.newExperimentName = 'New Experiment' $scope.submit = (expName) -> $scope.submitted = true if $scope.form.$valid and $scope.newExperimentName isnt 'New Experiment' # $scope.$close expName exp = new Experiment experiment: name: expName || 'New Experiment' protocol: {} $scope.loading = true exp.$save() .then (data) => $scope.$close data.experiment , (err) -> console.log err $scope.error = true $scope.loading = false ]
140848
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>> 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. ### window.ChaiBioTech.ngApp.controller 'CreateExperimentModalCtrl', [ '$scope' 'Experiment' ($scope, Experiment) -> $scope.newExperimentName = 'New Experiment' $scope.focused = false $scope.loading = false $scope.focus = -> $scope.focused = true $scope.submitted = false if $scope.newExperimentName is 'New Experiment' $scope.newExperimentName = '' $scope.unfocus = -> if $scope.newExperimentName is '' or !$scope.newExperimentName $scope.focused = false $scope.newExperimentName = 'New Experiment' $scope.submit = (expName) -> $scope.submitted = true if $scope.form.$valid and $scope.newExperimentName isnt 'New Experiment' # $scope.$close expName exp = new Experiment experiment: name: expName || 'New Experiment' protocol: {} $scope.loading = true exp.$save() .then (data) => $scope.$close data.experiment , (err) -> console.log err $scope.error = true $scope.loading = false ]
true
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>END_PI> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### window.ChaiBioTech.ngApp.controller 'CreateExperimentModalCtrl', [ '$scope' 'Experiment' ($scope, Experiment) -> $scope.newExperimentName = 'New Experiment' $scope.focused = false $scope.loading = false $scope.focus = -> $scope.focused = true $scope.submitted = false if $scope.newExperimentName is 'New Experiment' $scope.newExperimentName = '' $scope.unfocus = -> if $scope.newExperimentName is '' or !$scope.newExperimentName $scope.focused = false $scope.newExperimentName = 'New Experiment' $scope.submit = (expName) -> $scope.submitted = true if $scope.form.$valid and $scope.newExperimentName isnt 'New Experiment' # $scope.$close expName exp = new Experiment experiment: name: expName || 'New Experiment' protocol: {} $scope.loading = true exp.$save() .then (data) => $scope.$close data.experiment , (err) -> console.log err $scope.error = true $scope.loading = false ]
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999079704284668, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/_components/beatmapset-mapping.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, span, a, time } from 'react-dom-factories' el = React.createElement bn = 'beatmapset-mapping' dateFormat = 'LL' export class BeatmapsetMapping extends React.PureComponent render: => user = id: @props.beatmapset.user_id username: @props.beatmapset.creator avatar_url: (@props.user ? @props.beatmapset.user)?.avatar_url div className: bn, if user.id? a href: laroute.route 'users.show', user: user.id className: 'avatar avatar--beatmapset' style: backgroundImage: osu.urlPresence(user.avatar_url) else span className: 'avatar avatar--beatmapset avatar--guest' div className: "#{bn}__content", div className: "#{bn}__mapper" dangerouslySetInnerHTML: __html: osu.trans 'beatmapsets.show.details.mapped_by', mapper: @userLink(user) @renderDate 'submitted', 'submitted_date' if @props.beatmapset.ranked > 0 @renderDate @props.beatmapset.status, 'ranked_date' else @renderDate 'updated', 'last_updated' renderDate: (key, attribute) => div className: "#{bn}__date" dangerouslySetInnerHTML: __html: osu.trans "beatmapsets.show.details_date.#{key}", timeago: osu.timeago(@props.beatmapset[attribute]) userLink: (user) -> if user.id? laroute.link_to_route 'users.show', user.username { user: user.id } class: "#{bn}__user js-usercard" 'data-user-id': user.id else "<span class='#{bn}__user'>#{_.escape(user.username ? osu.trans('users.deleted'))}</span>"
37084
# 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, span, a, time } from 'react-dom-factories' el = React.createElement bn = 'beatmapset-mapping' dateFormat = 'LL' export class BeatmapsetMapping extends React.PureComponent render: => user = id: @props.beatmapset.user_id username: @props.beatmapset.creator avatar_url: (@props.user ? @props.beatmapset.user)?.avatar_url div className: bn, if user.id? a href: laroute.route 'users.show', user: user.id className: 'avatar avatar--beatmapset' style: backgroundImage: osu.urlPresence(user.avatar_url) else span className: 'avatar avatar--beatmapset avatar--guest' div className: "#{bn}__content", div className: "#{bn}__mapper" dangerouslySetInnerHTML: __html: osu.trans 'beatmapsets.show.details.mapped_by', mapper: @userLink(user) @renderDate 'submitted', 'submitted_date' if @props.beatmapset.ranked > 0 @renderDate @props.beatmapset.status, 'ranked_date' else @renderDate 'updated', 'last_updated' renderDate: (key, attribute) => div className: "#{bn}__date" dangerouslySetInnerHTML: __html: osu.trans "beatmapsets.show.details_date.#{key}", timeago: osu.timeago(@props.beatmapset[attribute]) userLink: (user) -> if user.id? laroute.link_to_route 'users.show', user.username { user: user.id } class: "#{bn}__user js-usercard" 'data-user-id': user.id else "<span class='#{bn}__user'>#{_.escape(user.username ? osu.trans('users.deleted'))}</span>"
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, span, a, time } from 'react-dom-factories' el = React.createElement bn = 'beatmapset-mapping' dateFormat = 'LL' export class BeatmapsetMapping extends React.PureComponent render: => user = id: @props.beatmapset.user_id username: @props.beatmapset.creator avatar_url: (@props.user ? @props.beatmapset.user)?.avatar_url div className: bn, if user.id? a href: laroute.route 'users.show', user: user.id className: 'avatar avatar--beatmapset' style: backgroundImage: osu.urlPresence(user.avatar_url) else span className: 'avatar avatar--beatmapset avatar--guest' div className: "#{bn}__content", div className: "#{bn}__mapper" dangerouslySetInnerHTML: __html: osu.trans 'beatmapsets.show.details.mapped_by', mapper: @userLink(user) @renderDate 'submitted', 'submitted_date' if @props.beatmapset.ranked > 0 @renderDate @props.beatmapset.status, 'ranked_date' else @renderDate 'updated', 'last_updated' renderDate: (key, attribute) => div className: "#{bn}__date" dangerouslySetInnerHTML: __html: osu.trans "beatmapsets.show.details_date.#{key}", timeago: osu.timeago(@props.beatmapset[attribute]) userLink: (user) -> if user.id? laroute.link_to_route 'users.show', user.username { user: user.id } class: "#{bn}__user js-usercard" 'data-user-id': user.id else "<span class='#{bn}__user'>#{_.escape(user.username ? osu.trans('users.deleted'))}</span>"
[ { "context": "me = \"Workhandle\"\nAccounts.emailTemplates.from = \"Jason <jason@papermud.com>\"\nAccounts.emailTemplates.res", "end": 406, "score": 0.9959977865219116, "start": 401, "tag": "NAME", "value": "Jason" }, { "context": "orkhandle\"\nAccounts.emailTemplates.from = \"Jason ...
server/accounts.coffee
mcgwier/workhandle
0
capitalize = (string) -> string.charAt(0).toUpperCase() + string.substring(1).toLowerCase() if string secondLevelDomain = (string) -> string.match(/[^\.\@]*\.[a-zA-Z]{2,}$/)[0] createFirstTopicIfNoneExists = (domain) -> unless Lists.findOne({domain: domain}) Lists.insert({domain: domain, name: "internal"}) Accounts.emailTemplates.siteName = "Workhandle" Accounts.emailTemplates.from = "Jason <jason@papermud.com>" Accounts.emailTemplates.resetPassword.text = (user, url) -> "Please follow this link to reset your password:\n\n#{url}" Accounts.emailTemplates.verifyEmail.subject = -> "Welcome to " + Accounts.emailTemplates.siteName Accounts.urls.resetPassword = (token) -> Meteor.absoluteUrl "recovery/" + token Accounts.urls.verifyEmail = (token) -> Meteor.absoluteUrl "verify-email/" + token Accounts.onCreateUser (options, user) -> if user.services.password [email_name, domain] = user.emails[0].address.split('@') [firstname, middlenames..., lastname] = email_name.split('.') user.profile = firstname: capitalize(firstname) lastname: capitalize(lastname) avatar: Gravatar.imageUrl(user.emails[0].address, {d: 'monsterid'}) user.domain = secondLevelDomain(domain) createFirstTopicIfNoneExists(user.domain) user Accounts.validateLoginAttempt (attempt) -> if attempt.user and attempt.user.emails and not attempt.user.emails[0].verified Accounts.sendVerificationEmail(attempt.user._id) throw new Meteor.Error("unverified email", "We need you to verify your email address before we can let you in. We just sent you an email. Please check your email inbox and follow the link in the email.") true
224383
capitalize = (string) -> string.charAt(0).toUpperCase() + string.substring(1).toLowerCase() if string secondLevelDomain = (string) -> string.match(/[^\.\@]*\.[a-zA-Z]{2,}$/)[0] createFirstTopicIfNoneExists = (domain) -> unless Lists.findOne({domain: domain}) Lists.insert({domain: domain, name: "internal"}) Accounts.emailTemplates.siteName = "Workhandle" Accounts.emailTemplates.from = "<NAME> <<EMAIL>>" Accounts.emailTemplates.resetPassword.text = (user, url) -> "Please follow this link to reset your password:\n\n#{url}" Accounts.emailTemplates.verifyEmail.subject = -> "Welcome to " + Accounts.emailTemplates.siteName Accounts.urls.resetPassword = (token) -> Meteor.absoluteUrl "recovery/" + token Accounts.urls.verifyEmail = (token) -> Meteor.absoluteUrl "verify-email/" + token Accounts.onCreateUser (options, user) -> if user.services.password [email_name, domain] = user.emails[0].address.split('@') [firstname, middlenames..., lastname] = email_name.split('.') user.profile = firstname: capitalize(firstname) lastname: capitalize(lastname) avatar: Gravatar.imageUrl(user.emails[0].address, {d: 'monsterid'}) user.domain = secondLevelDomain(domain) createFirstTopicIfNoneExists(user.domain) user Accounts.validateLoginAttempt (attempt) -> if attempt.user and attempt.user.emails and not attempt.user.emails[0].verified Accounts.sendVerificationEmail(attempt.user._id) throw new Meteor.Error("unverified email", "We need you to verify your email address before we can let you in. We just sent you an email. Please check your email inbox and follow the link in the email.") true
true
capitalize = (string) -> string.charAt(0).toUpperCase() + string.substring(1).toLowerCase() if string secondLevelDomain = (string) -> string.match(/[^\.\@]*\.[a-zA-Z]{2,}$/)[0] createFirstTopicIfNoneExists = (domain) -> unless Lists.findOne({domain: domain}) Lists.insert({domain: domain, name: "internal"}) Accounts.emailTemplates.siteName = "Workhandle" Accounts.emailTemplates.from = "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" Accounts.emailTemplates.resetPassword.text = (user, url) -> "Please follow this link to reset your password:\n\n#{url}" Accounts.emailTemplates.verifyEmail.subject = -> "Welcome to " + Accounts.emailTemplates.siteName Accounts.urls.resetPassword = (token) -> Meteor.absoluteUrl "recovery/" + token Accounts.urls.verifyEmail = (token) -> Meteor.absoluteUrl "verify-email/" + token Accounts.onCreateUser (options, user) -> if user.services.password [email_name, domain] = user.emails[0].address.split('@') [firstname, middlenames..., lastname] = email_name.split('.') user.profile = firstname: capitalize(firstname) lastname: capitalize(lastname) avatar: Gravatar.imageUrl(user.emails[0].address, {d: 'monsterid'}) user.domain = secondLevelDomain(domain) createFirstTopicIfNoneExists(user.domain) user Accounts.validateLoginAttempt (attempt) -> if attempt.user and attempt.user.emails and not attempt.user.emails[0].verified Accounts.sendVerificationEmail(attempt.user._id) throw new Meteor.Error("unverified email", "We need you to verify your email address before we can let you in. We just sent you an email. Please check your email inbox and follow the link in the email.") true
[ { "context": "ontent =\n msg_key_1: 1\n msg_key_2: '2'\n\n return content\n", "end": 174, "score": 0.8353087902069092, "start": 173, "tag": "KEY", "value": "2" } ]
test/stubs/gcm/gcm-message-stub.coffee
tq1/push-sender
0
module.exports = do -> class GcmMessage constructor: (message, data, extras) -> return build: -> content = msg_key_1: 1 msg_key_2: '2' return content
34924
module.exports = do -> class GcmMessage constructor: (message, data, extras) -> return build: -> content = msg_key_1: 1 msg_key_2: '<KEY>' return content
true
module.exports = do -> class GcmMessage constructor: (message, data, extras) -> return build: -> content = msg_key_1: 1 msg_key_2: 'PI:KEY:<KEY>END_PI' return content
[ { "context": "o')\n expect(@$iden_field.text()).to.include('bilbo@shire.net')\n\n# Since we can't actually test a file upload, ", "end": 1949, "score": 0.9999068975448608, "start": 1934, "tag": "EMAIL", "value": "bilbo@shire.net" } ]
test/views_test.coffee
dobtco/formrenderer-base
79
ALL_FIELD_TYPES = [ 'identification' 'address' 'checkboxes' 'date' 'dropdown' 'email' 'file' 'number' 'paragraph' 'phone' 'price' 'radio' 'table' 'text' 'time' 'website' 'map_marker' 'confirm' 'block_of_text' 'page_break' 'section_break' ] describe 'response field views', -> it 'can be rendered without a form_renderer instance', -> for field_type in ALL_FIELD_TYPES model = new FormRenderer.Models["ResponseField#{_.str.classify(field_type)}"] viewKlass = FormRenderer.formComponentViewClass(model) view = new viewKlass(model: model) expect(view.render()).to.be.ok describe 'FormRenderer.Views.ResponseFieldIdentification', -> # #makeStatic is used internally by Screendoor's Formbuilder describe '#makeStatic', -> it 'does not render input fields when called', -> idView = new FormRenderer.Views.ResponseFieldIdentification( model: new FormRenderer.Models.ResponseFieldIdentification ) idView.disableInput() $('body').append(idView.render().$el) $idenField = $('.fr_response_field_identification') # identification field should render expect($idenField.length).to.eql(1) # no inputs should be rendered expect($idenField.find('input').length).to.eql(0) context 'Follow-up forms', -> beforeEach -> $('body').html('<div data-formrenderer />') new FormRenderer Fixtures.FormRendererOptions.FOLLOW_UP_FORM() @$iden_field = $('.fr_response_field_identification') it 'does not render input fields', -> # identification field should render expect(@$iden_field.length).to.eql 1 # no inputs should be rendered expect(@$iden_field.find('input').length).to.eql(0) it "renders the respondent's name and email", -> # $iden_field expect(@$iden_field.text()).to.include('Bilbo') expect(@$iden_field.text()).to.include('bilbo@shire.net') # Since we can't actually test a file upload, we'll test how the view # responds to various events describe 'FormRenderer.Views.ResponseFieldFile', -> beforeEach -> $('body').html('<div data-formrenderer />') describe 'without allow multiple', -> beforeEach -> @fr = new FormRenderer Fixtures.FormRendererOptions.FILE() @ifu = $('input[type=file]').data('inline-file-upload') it 'disables the button when starting the upload', -> expect($('.fr_add_file label').hasClass('disabled')).to.eql false @ifu.options.start(filename: 'filename yo') expect($('.fr_add_file label').hasClass('disabled')).to.eql true it 'shows upload progress and successfully completes upload', -> @ifu.options.start(filename: 'filename yo') @ifu.options.progress(percent: 95) expect($('.fr_add_file label').text()).to.contain('95%') expect($('.fr_add_file label').hasClass('disabled')).to.eql true @ifu.options.success(data: { file_id: 123 }) expect($('.fr_add_file label').hasClass('disabled')).to.eql false expect(@fr.formComponents.models[0].get('value')).to.eql( [ { id: 123, filename: 'filename yo' } ] ) it 'shows errors', -> expect($('.fr_error:visible').length).to.eql 0 @ifu.options.error(xhr: { responseJSON: { errors: 'just a fake error lol' } }) expect($('.fr_error:visible').length).to.eql 1 it 'does not allow more than one file by default', -> @ifu.options.start(filename: 'filename yo') @ifu.options.success(data: { file_id: 123 }) expect($('.fr_add_file label').length).to.eql 0 describe 'with allow_multiple', -> beforeEach -> fix = Fixtures.FormRendererOptions.FILE() fix.response_fields[0].allow_multiple_files = true @fr = new FormRenderer fix @ifu = $('input[type=file]').data('inline-file-upload') it 'uploads multiple files', -> @ifu.options.start(filename: 'filename yo') @ifu.options.success(data: { file_id: 123 }) expect($('.fr_add_file label').length).to.eql 1 @ifu.options.start(filename: 'filename two') @ifu.options.success(data: { file_id: 456 }) expect($('.fr_add_file label').length).to.eql 1 expect(@fr.formComponents.models[0].get('value')).to.eql( [ { id: 123, filename: 'filename yo' }, { id: 456, filename: 'filename two' } ] ) # And removes them... $('[data-fr-remove-file]').last().click() expect(@fr.formComponents.models[0].get('value')).to.eql( [ { id: 123, filename: 'filename yo' } ] )
124904
ALL_FIELD_TYPES = [ 'identification' 'address' 'checkboxes' 'date' 'dropdown' 'email' 'file' 'number' 'paragraph' 'phone' 'price' 'radio' 'table' 'text' 'time' 'website' 'map_marker' 'confirm' 'block_of_text' 'page_break' 'section_break' ] describe 'response field views', -> it 'can be rendered without a form_renderer instance', -> for field_type in ALL_FIELD_TYPES model = new FormRenderer.Models["ResponseField#{_.str.classify(field_type)}"] viewKlass = FormRenderer.formComponentViewClass(model) view = new viewKlass(model: model) expect(view.render()).to.be.ok describe 'FormRenderer.Views.ResponseFieldIdentification', -> # #makeStatic is used internally by Screendoor's Formbuilder describe '#makeStatic', -> it 'does not render input fields when called', -> idView = new FormRenderer.Views.ResponseFieldIdentification( model: new FormRenderer.Models.ResponseFieldIdentification ) idView.disableInput() $('body').append(idView.render().$el) $idenField = $('.fr_response_field_identification') # identification field should render expect($idenField.length).to.eql(1) # no inputs should be rendered expect($idenField.find('input').length).to.eql(0) context 'Follow-up forms', -> beforeEach -> $('body').html('<div data-formrenderer />') new FormRenderer Fixtures.FormRendererOptions.FOLLOW_UP_FORM() @$iden_field = $('.fr_response_field_identification') it 'does not render input fields', -> # identification field should render expect(@$iden_field.length).to.eql 1 # no inputs should be rendered expect(@$iden_field.find('input').length).to.eql(0) it "renders the respondent's name and email", -> # $iden_field expect(@$iden_field.text()).to.include('Bilbo') expect(@$iden_field.text()).to.include('<EMAIL>') # Since we can't actually test a file upload, we'll test how the view # responds to various events describe 'FormRenderer.Views.ResponseFieldFile', -> beforeEach -> $('body').html('<div data-formrenderer />') describe 'without allow multiple', -> beforeEach -> @fr = new FormRenderer Fixtures.FormRendererOptions.FILE() @ifu = $('input[type=file]').data('inline-file-upload') it 'disables the button when starting the upload', -> expect($('.fr_add_file label').hasClass('disabled')).to.eql false @ifu.options.start(filename: 'filename yo') expect($('.fr_add_file label').hasClass('disabled')).to.eql true it 'shows upload progress and successfully completes upload', -> @ifu.options.start(filename: 'filename yo') @ifu.options.progress(percent: 95) expect($('.fr_add_file label').text()).to.contain('95%') expect($('.fr_add_file label').hasClass('disabled')).to.eql true @ifu.options.success(data: { file_id: 123 }) expect($('.fr_add_file label').hasClass('disabled')).to.eql false expect(@fr.formComponents.models[0].get('value')).to.eql( [ { id: 123, filename: 'filename yo' } ] ) it 'shows errors', -> expect($('.fr_error:visible').length).to.eql 0 @ifu.options.error(xhr: { responseJSON: { errors: 'just a fake error lol' } }) expect($('.fr_error:visible').length).to.eql 1 it 'does not allow more than one file by default', -> @ifu.options.start(filename: 'filename yo') @ifu.options.success(data: { file_id: 123 }) expect($('.fr_add_file label').length).to.eql 0 describe 'with allow_multiple', -> beforeEach -> fix = Fixtures.FormRendererOptions.FILE() fix.response_fields[0].allow_multiple_files = true @fr = new FormRenderer fix @ifu = $('input[type=file]').data('inline-file-upload') it 'uploads multiple files', -> @ifu.options.start(filename: 'filename yo') @ifu.options.success(data: { file_id: 123 }) expect($('.fr_add_file label').length).to.eql 1 @ifu.options.start(filename: 'filename two') @ifu.options.success(data: { file_id: 456 }) expect($('.fr_add_file label').length).to.eql 1 expect(@fr.formComponents.models[0].get('value')).to.eql( [ { id: 123, filename: 'filename yo' }, { id: 456, filename: 'filename two' } ] ) # And removes them... $('[data-fr-remove-file]').last().click() expect(@fr.formComponents.models[0].get('value')).to.eql( [ { id: 123, filename: 'filename yo' } ] )
true
ALL_FIELD_TYPES = [ 'identification' 'address' 'checkboxes' 'date' 'dropdown' 'email' 'file' 'number' 'paragraph' 'phone' 'price' 'radio' 'table' 'text' 'time' 'website' 'map_marker' 'confirm' 'block_of_text' 'page_break' 'section_break' ] describe 'response field views', -> it 'can be rendered without a form_renderer instance', -> for field_type in ALL_FIELD_TYPES model = new FormRenderer.Models["ResponseField#{_.str.classify(field_type)}"] viewKlass = FormRenderer.formComponentViewClass(model) view = new viewKlass(model: model) expect(view.render()).to.be.ok describe 'FormRenderer.Views.ResponseFieldIdentification', -> # #makeStatic is used internally by Screendoor's Formbuilder describe '#makeStatic', -> it 'does not render input fields when called', -> idView = new FormRenderer.Views.ResponseFieldIdentification( model: new FormRenderer.Models.ResponseFieldIdentification ) idView.disableInput() $('body').append(idView.render().$el) $idenField = $('.fr_response_field_identification') # identification field should render expect($idenField.length).to.eql(1) # no inputs should be rendered expect($idenField.find('input').length).to.eql(0) context 'Follow-up forms', -> beforeEach -> $('body').html('<div data-formrenderer />') new FormRenderer Fixtures.FormRendererOptions.FOLLOW_UP_FORM() @$iden_field = $('.fr_response_field_identification') it 'does not render input fields', -> # identification field should render expect(@$iden_field.length).to.eql 1 # no inputs should be rendered expect(@$iden_field.find('input').length).to.eql(0) it "renders the respondent's name and email", -> # $iden_field expect(@$iden_field.text()).to.include('Bilbo') expect(@$iden_field.text()).to.include('PI:EMAIL:<EMAIL>END_PI') # Since we can't actually test a file upload, we'll test how the view # responds to various events describe 'FormRenderer.Views.ResponseFieldFile', -> beforeEach -> $('body').html('<div data-formrenderer />') describe 'without allow multiple', -> beforeEach -> @fr = new FormRenderer Fixtures.FormRendererOptions.FILE() @ifu = $('input[type=file]').data('inline-file-upload') it 'disables the button when starting the upload', -> expect($('.fr_add_file label').hasClass('disabled')).to.eql false @ifu.options.start(filename: 'filename yo') expect($('.fr_add_file label').hasClass('disabled')).to.eql true it 'shows upload progress and successfully completes upload', -> @ifu.options.start(filename: 'filename yo') @ifu.options.progress(percent: 95) expect($('.fr_add_file label').text()).to.contain('95%') expect($('.fr_add_file label').hasClass('disabled')).to.eql true @ifu.options.success(data: { file_id: 123 }) expect($('.fr_add_file label').hasClass('disabled')).to.eql false expect(@fr.formComponents.models[0].get('value')).to.eql( [ { id: 123, filename: 'filename yo' } ] ) it 'shows errors', -> expect($('.fr_error:visible').length).to.eql 0 @ifu.options.error(xhr: { responseJSON: { errors: 'just a fake error lol' } }) expect($('.fr_error:visible').length).to.eql 1 it 'does not allow more than one file by default', -> @ifu.options.start(filename: 'filename yo') @ifu.options.success(data: { file_id: 123 }) expect($('.fr_add_file label').length).to.eql 0 describe 'with allow_multiple', -> beforeEach -> fix = Fixtures.FormRendererOptions.FILE() fix.response_fields[0].allow_multiple_files = true @fr = new FormRenderer fix @ifu = $('input[type=file]').data('inline-file-upload') it 'uploads multiple files', -> @ifu.options.start(filename: 'filename yo') @ifu.options.success(data: { file_id: 123 }) expect($('.fr_add_file label').length).to.eql 1 @ifu.options.start(filename: 'filename two') @ifu.options.success(data: { file_id: 456 }) expect($('.fr_add_file label').length).to.eql 1 expect(@fr.formComponents.models[0].get('value')).to.eql( [ { id: 123, filename: 'filename yo' }, { id: 456, filename: 'filename two' } ] ) # And removes them... $('[data-fr-remove-file]').last().click() expect(@fr.formComponents.models[0].get('value')).to.eql( [ { id: 123, filename: 'filename yo' } ] )
[ { "context": "e')\n @password = element By.model('credentials.password')\n @login_button = element By.css 'form button", "end": 145, "score": 0.91989666223526, "start": 137, "tag": "PASSWORD", "value": "password" } ]
public/modules/core/e2e/pages.coffee
amIwho/words
0
class LoginPage constructor: -> @username = element By.model('credentials.username') @password = element By.model('credentials.password') @login_button = element By.css 'form button[type=submit]' @login_error = element By.binding 'error' get: -> browser.get '/#!/signin' browser.getCurrentUrl() setUsername: (username) -> @username.clear() @username.sendKeys username @ clearUsername: -> @username.clear() @ setPassword: (password) -> @password.clear() @password.sendKeys(password) @ clearPassword: -> @password.clear() login: -> @login_button.click() getErrorMessage: -> @login_error.getText()
956
class LoginPage constructor: -> @username = element By.model('credentials.username') @password = element By.model('credentials.<PASSWORD>') @login_button = element By.css 'form button[type=submit]' @login_error = element By.binding 'error' get: -> browser.get '/#!/signin' browser.getCurrentUrl() setUsername: (username) -> @username.clear() @username.sendKeys username @ clearUsername: -> @username.clear() @ setPassword: (password) -> @password.clear() @password.sendKeys(password) @ clearPassword: -> @password.clear() login: -> @login_button.click() getErrorMessage: -> @login_error.getText()
true
class LoginPage constructor: -> @username = element By.model('credentials.username') @password = element By.model('credentials.PI:PASSWORD:<PASSWORD>END_PI') @login_button = element By.css 'form button[type=submit]' @login_error = element By.binding 'error' get: -> browser.get '/#!/signin' browser.getCurrentUrl() setUsername: (username) -> @username.clear() @username.sendKeys username @ clearUsername: -> @username.clear() @ setPassword: (password) -> @password.clear() @password.sendKeys(password) @ clearPassword: -> @password.clear() login: -> @login_button.click() getErrorMessage: -> @login_error.getText()
[ { "context": "cs will not change.\npcArray2 = ApplyPatch(\"Dog\", \"Capybara\")\nprint pcArray1\nprint pcArray2\n\n# Function ", "end": 3979, "score": 0.5837656855583191, "start": 3976, "tag": "NAME", "value": "Cap" } ]
deps/v8/test/mjsunit/debug-liveedit-patch-positions.coffee
lxe/io.coffee
0
# Copyright 2010 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Flags: --expose-debug-as debug # Get the Debug object exposed from the debug context global object. # Scenario: some function is being edited; the outer function has to have its # positions patched. Accoring to a special markup of function text # corresponding byte-code PCs should coincide before change and after it. # Find all *$* markers in text of the function and read corresponding statement # PCs. ReadMarkerPositions = (func) -> text = func.toString() positions = new Array() match = undefined pattern = /\/\*\$\*\//g positions.push match.index while (match = pattern.exec(text))? positions ReadPCMap = (func, positions) -> res = new Array() i = 0 while i < positions.length pc = Debug.LiveEdit.GetPcFromSourcePos(func, positions[i]) # Function was marked for recompilation and it's code was replaced with a # stub. This can happen at any time especially if we are running with # --stress-opt. There is no way to get PCs now. return if typeof pc is "undefined" res.push pc i++ res ApplyPatch = (orig_animal, new_animal) -> res = ChooseAnimal() assertEquals orig_animal + "15", res script = Debug.findScript(ChooseAnimal) orig_string = "'" + orig_animal + "'" patch_string = "'" + new_animal + "'" patch_pos = script.source.indexOf(orig_string) change_log = new Array() Debug.LiveEdit.TestApi.ApplySingleChunkPatch script, patch_pos, orig_string.length, patch_string, change_log print "Change log: " + JSON.stringify(change_log) + "\n" markerPositions = ReadMarkerPositions(ChooseAnimal) pcArray = ReadPCMap(ChooseAnimal, markerPositions) res = ChooseAnimal() assertEquals new_animal + "15", res pcArray Debug = debug.Debug eval "function F1() { return 5; }\n" + "function ChooseAnimal(/*$*/ ) {\n" + "/*$*/ var x = F1(/*$*/ );\n" + "/*$*/ var res/*$*/ =/*$*/ (function() { return 'Cat'; } )();\n" + "/*$*/ var y/*$*/ = F2(/*$*/ F1()/*$*/ , F1(/*$*/ )/*$*/ );\n" + "/*$*/ if (/*$*/ x.toString(/*$*/ )) { /*$*/ y = 3;/*$*/ } else {/*$*/ y = 8;/*$*/ }\n" + "/*$*/ var z = /*$*/ x * y;\n" + "/*$*/ return/*$*/ res/*$*/ + z;/*$*/ }\n" + "function F2(x, y) { return x + y; }" pcArray1 = ApplyPatch("Cat", "Dog") # When we patched function for the first time it was deoptimized. # Check that after the second patch maping between sources position and # pcs will not change. pcArray2 = ApplyPatch("Dog", "Capybara") print pcArray1 print pcArray2 # Function can be marked for recompilation at any point (especially if we are # running with --stress-opt). When we mark function for recompilation we # replace it's code with stub. So there is no reliable way to get PCs for # function. assertArrayEquals pcArray1, pcArray2 if pcArray1 and pcArray2
54369
# Copyright 2010 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Flags: --expose-debug-as debug # Get the Debug object exposed from the debug context global object. # Scenario: some function is being edited; the outer function has to have its # positions patched. Accoring to a special markup of function text # corresponding byte-code PCs should coincide before change and after it. # Find all *$* markers in text of the function and read corresponding statement # PCs. ReadMarkerPositions = (func) -> text = func.toString() positions = new Array() match = undefined pattern = /\/\*\$\*\//g positions.push match.index while (match = pattern.exec(text))? positions ReadPCMap = (func, positions) -> res = new Array() i = 0 while i < positions.length pc = Debug.LiveEdit.GetPcFromSourcePos(func, positions[i]) # Function was marked for recompilation and it's code was replaced with a # stub. This can happen at any time especially if we are running with # --stress-opt. There is no way to get PCs now. return if typeof pc is "undefined" res.push pc i++ res ApplyPatch = (orig_animal, new_animal) -> res = ChooseAnimal() assertEquals orig_animal + "15", res script = Debug.findScript(ChooseAnimal) orig_string = "'" + orig_animal + "'" patch_string = "'" + new_animal + "'" patch_pos = script.source.indexOf(orig_string) change_log = new Array() Debug.LiveEdit.TestApi.ApplySingleChunkPatch script, patch_pos, orig_string.length, patch_string, change_log print "Change log: " + JSON.stringify(change_log) + "\n" markerPositions = ReadMarkerPositions(ChooseAnimal) pcArray = ReadPCMap(ChooseAnimal, markerPositions) res = ChooseAnimal() assertEquals new_animal + "15", res pcArray Debug = debug.Debug eval "function F1() { return 5; }\n" + "function ChooseAnimal(/*$*/ ) {\n" + "/*$*/ var x = F1(/*$*/ );\n" + "/*$*/ var res/*$*/ =/*$*/ (function() { return 'Cat'; } )();\n" + "/*$*/ var y/*$*/ = F2(/*$*/ F1()/*$*/ , F1(/*$*/ )/*$*/ );\n" + "/*$*/ if (/*$*/ x.toString(/*$*/ )) { /*$*/ y = 3;/*$*/ } else {/*$*/ y = 8;/*$*/ }\n" + "/*$*/ var z = /*$*/ x * y;\n" + "/*$*/ return/*$*/ res/*$*/ + z;/*$*/ }\n" + "function F2(x, y) { return x + y; }" pcArray1 = ApplyPatch("Cat", "Dog") # When we patched function for the first time it was deoptimized. # Check that after the second patch maping between sources position and # pcs will not change. pcArray2 = ApplyPatch("Dog", "<NAME>ybara") print pcArray1 print pcArray2 # Function can be marked for recompilation at any point (especially if we are # running with --stress-opt). When we mark function for recompilation we # replace it's code with stub. So there is no reliable way to get PCs for # function. assertArrayEquals pcArray1, pcArray2 if pcArray1 and pcArray2
true
# Copyright 2010 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Flags: --expose-debug-as debug # Get the Debug object exposed from the debug context global object. # Scenario: some function is being edited; the outer function has to have its # positions patched. Accoring to a special markup of function text # corresponding byte-code PCs should coincide before change and after it. # Find all *$* markers in text of the function and read corresponding statement # PCs. ReadMarkerPositions = (func) -> text = func.toString() positions = new Array() match = undefined pattern = /\/\*\$\*\//g positions.push match.index while (match = pattern.exec(text))? positions ReadPCMap = (func, positions) -> res = new Array() i = 0 while i < positions.length pc = Debug.LiveEdit.GetPcFromSourcePos(func, positions[i]) # Function was marked for recompilation and it's code was replaced with a # stub. This can happen at any time especially if we are running with # --stress-opt. There is no way to get PCs now. return if typeof pc is "undefined" res.push pc i++ res ApplyPatch = (orig_animal, new_animal) -> res = ChooseAnimal() assertEquals orig_animal + "15", res script = Debug.findScript(ChooseAnimal) orig_string = "'" + orig_animal + "'" patch_string = "'" + new_animal + "'" patch_pos = script.source.indexOf(orig_string) change_log = new Array() Debug.LiveEdit.TestApi.ApplySingleChunkPatch script, patch_pos, orig_string.length, patch_string, change_log print "Change log: " + JSON.stringify(change_log) + "\n" markerPositions = ReadMarkerPositions(ChooseAnimal) pcArray = ReadPCMap(ChooseAnimal, markerPositions) res = ChooseAnimal() assertEquals new_animal + "15", res pcArray Debug = debug.Debug eval "function F1() { return 5; }\n" + "function ChooseAnimal(/*$*/ ) {\n" + "/*$*/ var x = F1(/*$*/ );\n" + "/*$*/ var res/*$*/ =/*$*/ (function() { return 'Cat'; } )();\n" + "/*$*/ var y/*$*/ = F2(/*$*/ F1()/*$*/ , F1(/*$*/ )/*$*/ );\n" + "/*$*/ if (/*$*/ x.toString(/*$*/ )) { /*$*/ y = 3;/*$*/ } else {/*$*/ y = 8;/*$*/ }\n" + "/*$*/ var z = /*$*/ x * y;\n" + "/*$*/ return/*$*/ res/*$*/ + z;/*$*/ }\n" + "function F2(x, y) { return x + y; }" pcArray1 = ApplyPatch("Cat", "Dog") # When we patched function for the first time it was deoptimized. # Check that after the second patch maping between sources position and # pcs will not change. pcArray2 = ApplyPatch("Dog", "PI:NAME:<NAME>END_PIybara") print pcArray1 print pcArray2 # Function can be marked for recompilation at any point (especially if we are # running with --stress-opt). When we mark function for recompilation we # replace it's code with stub. So there is no reliable way to get PCs for # function. assertArrayEquals pcArray1, pcArray2 if pcArray1 and pcArray2
[ { "context": "\n\n attributes: =>\n id : @entry.id()\n name: @name\n type: @entry.type\n mode: @mode\n\n", "end": 523, "score": 0.9577908515930176, "start": 523, "tag": "NAME", "value": "" }, { "context": " attributes: =>\n id : @entry.id()\n name: @name\n ty...
lib/objects/tree.entry.coffee
circuithub/massive-git
6
# TreeEntry # ---------- # Class represents entry for the `tree`. Each entry has: # `name` - name of the file or directory # `entry` - entry itself. Each entry has `type` and `id`. # `mode` - mode for file or directory. Used for tree's `id` claculation. TreeEntry = exports.TreeEntry = class TreeEntry # Constructor takes `data` and optionally `repo` id and blob's `id`. # todo (anton) we can hardcode `mode` right now constructor: (@name, @entry, @mode = 100644) -> attributes: => id : @entry.id() name: @name type: @entry.type mode: @mode
23708
# TreeEntry # ---------- # Class represents entry for the `tree`. Each entry has: # `name` - name of the file or directory # `entry` - entry itself. Each entry has `type` and `id`. # `mode` - mode for file or directory. Used for tree's `id` claculation. TreeEntry = exports.TreeEntry = class TreeEntry # Constructor takes `data` and optionally `repo` id and blob's `id`. # todo (anton) we can hardcode `mode` right now constructor: (@name, @entry, @mode = 100644) -> attributes: => id : @entry.id() name:<NAME> @<NAME> type: @entry.type mode: @mode
true
# TreeEntry # ---------- # Class represents entry for the `tree`. Each entry has: # `name` - name of the file or directory # `entry` - entry itself. Each entry has `type` and `id`. # `mode` - mode for file or directory. Used for tree's `id` claculation. TreeEntry = exports.TreeEntry = class TreeEntry # Constructor takes `data` and optionally `repo` id and blob's `id`. # todo (anton) we can hardcode `mode` right now constructor: (@name, @entry, @mode = 100644) -> attributes: => id : @entry.id() name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI type: @entry.type mode: @mode
[ { "context": "###\n backbone-mongo.js 0.5.5\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-mongo\n Li", "end": 59, "score": 0.998242199420929, "start": 51, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/v...
src/sync.coffee
michaelBenin/backbone-mongo
1
### backbone-mongo.js 0.5.5 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-mongo License: MIT (http://www.opensource.org/licenses/mit-license.php) ### util = require 'util' _ = require 'underscore' Backbone = require 'backbone' moment = require 'moment' Queue = require 'backbone-orm/lib/queue' Schema = require 'backbone-orm/lib/schema' Utils = require 'backbone-orm/lib/utils' QueryCache = require('backbone-orm/lib/cache/singletons').QueryCache ModelCache = require('backbone-orm/lib/cache/singletons').ModelCache ModelTypeID = require('backbone-orm/lib/cache/singletons').ModelTypeID MongoCursor = require './cursor' Connection = require './connection' DESTROY_BATCH_LIMIT = 1000 class MongoSync constructor: (@model_type, @sync_options) -> @model_type.model_name = Utils.findOrGenerateModelName(@model_type) @model_type.model_id = ModelTypeID.generate(@model_type) @schema = new Schema(@model_type) @backbone_adapter = @model_type.backbone_adapter = @_selectAdapter() initialize: (model) -> return if @is_initialized; @is_initialized = true @schema.initialize() throw new Error "Missing url for model" unless url = _.result(new @model_type, 'url') @connect(url) ################################### # Classic Backbone Sync ################################### read: (model, options) -> # a collection if model.models @cursor().toJSON (err, json) -> return options.error(err) if err options.success(json) # a model else @cursor(model.id).toJSON (err, json) -> return options.error(err) if err return options.error(new Error "Model not found. Id #{model.id}") unless json options.success(json) create: (model, options) -> return options.error(new Error "Missing manual id for create: #{util.inspect(model.attributes)}") if @manual_id and not model.id QueryCache.reset @model_type, (err) => return options.error(err) if err @connection.collection (err, collection) => return options.error(err) if err return options.error(new Error 'New document has a non-empty revision') if model.get('_rev') doc = @backbone_adapter.attributesToNative(model.toJSON()); doc._rev = 1 # start revisions collection.insert doc, (err, docs) => return options.error(new Error "Failed to create model. Error: #{err or 'document not found'}") if err or not docs or docs.length isnt 1 options.success(@backbone_adapter.nativeToAttributes(docs[0])) update: (model, options) -> return @create(model, options) unless model.get('_rev') # no revision, create - in the case we manually set an id and are saving for the first time return options.error(new Error "Missing manual id for create: #{util.inspect(model.attributes)}") if @manual_id and not model.id QueryCache.reset @model_type, (err) => return options.error(err) if err @connection.collection (err, collection) => return options.error(err) if err json = @backbone_adapter.attributesToNative(model.toJSON()) delete json._id if @backbone_adapter.id_attribute is '_id' find_query = @backbone_adapter.modelFindQuery(model) find_query._rev = json._rev json._rev++ # increment revisions modifications = {$set: json} if unsets = Utils.get(model, 'unsets') Utils.unset(model, 'unsets') # clear now that we are dealing with them if unsets.length modifications.$unset = {} modifications.$unset[key] = '' for key in unsets when not model.attributes.hasOwnProperty(key) # unset if they haven't been re-set # update the record collection.findAndModify find_query, [[@backbone_adapter.id_attribute, 'asc']], modifications, {new: true}, (err, doc) => return options.error(new Error "Failed to update model (#{@model_type.model_name}). Error: #{err}") if err return options.error(new Error "Failed to update model (#{@model_type.model_name}). Either the document has been deleted or the revision (_rev) was stale.") unless doc return options.error(new Error "Failed to update revision (#{@model_type.model_name}). Is: #{doc._rev} expecting: #{json._rev}") if doc._rev isnt json._rev options.success(@backbone_adapter.nativeToAttributes(doc)) delete: (model, options) -> QueryCache.reset @model_type, (err) => return options.error(err) if err @connection.collection (err, collection) => return options.error(err) if err collection.remove @backbone_adapter.attributesToNative({id: model.id}), (err) => return options.error(err) if err options.success() ################################### # Backbone ORM - Class Extensions ################################### resetSchema: (options, callback) -> queue = new Queue() queue.defer (callback) => @collection (err, collection) -> return callback(err) if err collection.remove (err) -> if options.verbose if err console.log "Failed to reset collection: #{collection.collectionName}. Error: #{err}" else console.log "Reset collection: #{collection.collectionName}" callback(err) queue.defer (callback) => schema = @model_type.schema() for key, relation of schema.relations if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany' do (relation) -> queue.defer (callback) -> relation.findOrGenerateJoinTable().resetSchema(callback) callback() queue.await callback cursor: (query={}) -> return new MongoCursor(query, _.pick(@, ['model_type', 'connection', 'backbone_adapter'])) destroy: (query, callback) -> QueryCache.reset @model_type, (err) => return callback(err) if err @connection.collection (err, collection) => return callback(err) if err @model_type.each _.extend({$each: {limit: DESTROY_BATCH_LIMIT, json: true}}, query), ((model_json, callback) => Utils.patchRemoveByJSON @model_type, model_json, (err) => return callback(err) if err collection.remove @backbone_adapter.attributesToNative({id: model_json.id}), (err) => return callback(err) if err callback() ), callback ################################### # Backbone Mongo - Extensions ################################### connect: (url) -> return if @connection and @connection.url is url @connection.destroy() if @connection @connection = new Connection(url, @schema, @sync_options.connection_options or {}) collection: (callback) -> @connection.collection(callback) ################################### # Internal ################################### _selectAdapter: -> for field_name, field_info of @schema.raw continue if (field_name isnt 'id') or not _.isArray(field_info) for info in field_info if info.manual_id @manual_id = true return require './document_adapter_no_mongo_id' return require './document_adapter_mongo_id' # default is using the mongodb's ids module.exports = (type, sync_options={}) -> if Utils.isCollection(new type()) # collection model_type = Utils.configureCollectionModelType(type, module.exports) return type::sync = model_type::sync sync = new MongoSync(type, sync_options) type::sync = sync_fn = (method, model, options={}) -> # save for access by model extensions sync.initialize() return module.exports.apply(null, Array::slice.call(arguments, 1)) if method is 'createSync' # create a new sync return sync if method is 'sync' return sync.schema if method is 'schema' return false if method is 'isRemote' return if sync[method] then sync[method].apply(sync, Array::slice.call(arguments, 1)) else undefined require('backbone-orm/lib/extensions/model')(type) # mixin extensions return ModelCache.configureSync(type, sync_fn)
188758
### backbone-mongo.js 0.5.5 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-mongo License: MIT (http://www.opensource.org/licenses/mit-license.php) ### util = require 'util' _ = require 'underscore' Backbone = require 'backbone' moment = require 'moment' Queue = require 'backbone-orm/lib/queue' Schema = require 'backbone-orm/lib/schema' Utils = require 'backbone-orm/lib/utils' QueryCache = require('backbone-orm/lib/cache/singletons').QueryCache ModelCache = require('backbone-orm/lib/cache/singletons').ModelCache ModelTypeID = require('backbone-orm/lib/cache/singletons').ModelTypeID MongoCursor = require './cursor' Connection = require './connection' DESTROY_BATCH_LIMIT = 1000 class MongoSync constructor: (@model_type, @sync_options) -> @model_type.model_name = Utils.findOrGenerateModelName(@model_type) @model_type.model_id = ModelTypeID.generate(@model_type) @schema = new Schema(@model_type) @backbone_adapter = @model_type.backbone_adapter = @_selectAdapter() initialize: (model) -> return if @is_initialized; @is_initialized = true @schema.initialize() throw new Error "Missing url for model" unless url = _.result(new @model_type, 'url') @connect(url) ################################### # Classic Backbone Sync ################################### read: (model, options) -> # a collection if model.models @cursor().toJSON (err, json) -> return options.error(err) if err options.success(json) # a model else @cursor(model.id).toJSON (err, json) -> return options.error(err) if err return options.error(new Error "Model not found. Id #{model.id}") unless json options.success(json) create: (model, options) -> return options.error(new Error "Missing manual id for create: #{util.inspect(model.attributes)}") if @manual_id and not model.id QueryCache.reset @model_type, (err) => return options.error(err) if err @connection.collection (err, collection) => return options.error(err) if err return options.error(new Error 'New document has a non-empty revision') if model.get('_rev') doc = @backbone_adapter.attributesToNative(model.toJSON()); doc._rev = 1 # start revisions collection.insert doc, (err, docs) => return options.error(new Error "Failed to create model. Error: #{err or 'document not found'}") if err or not docs or docs.length isnt 1 options.success(@backbone_adapter.nativeToAttributes(docs[0])) update: (model, options) -> return @create(model, options) unless model.get('_rev') # no revision, create - in the case we manually set an id and are saving for the first time return options.error(new Error "Missing manual id for create: #{util.inspect(model.attributes)}") if @manual_id and not model.id QueryCache.reset @model_type, (err) => return options.error(err) if err @connection.collection (err, collection) => return options.error(err) if err json = @backbone_adapter.attributesToNative(model.toJSON()) delete json._id if @backbone_adapter.id_attribute is '_id' find_query = @backbone_adapter.modelFindQuery(model) find_query._rev = json._rev json._rev++ # increment revisions modifications = {$set: json} if unsets = Utils.get(model, 'unsets') Utils.unset(model, 'unsets') # clear now that we are dealing with them if unsets.length modifications.$unset = {} modifications.$unset[key] = '' for key in unsets when not model.attributes.hasOwnProperty(key) # unset if they haven't been re-set # update the record collection.findAndModify find_query, [[@backbone_adapter.id_attribute, 'asc']], modifications, {new: true}, (err, doc) => return options.error(new Error "Failed to update model (#{@model_type.model_name}). Error: #{err}") if err return options.error(new Error "Failed to update model (#{@model_type.model_name}). Either the document has been deleted or the revision (_rev) was stale.") unless doc return options.error(new Error "Failed to update revision (#{@model_type.model_name}). Is: #{doc._rev} expecting: #{json._rev}") if doc._rev isnt json._rev options.success(@backbone_adapter.nativeToAttributes(doc)) delete: (model, options) -> QueryCache.reset @model_type, (err) => return options.error(err) if err @connection.collection (err, collection) => return options.error(err) if err collection.remove @backbone_adapter.attributesToNative({id: model.id}), (err) => return options.error(err) if err options.success() ################################### # Backbone ORM - Class Extensions ################################### resetSchema: (options, callback) -> queue = new Queue() queue.defer (callback) => @collection (err, collection) -> return callback(err) if err collection.remove (err) -> if options.verbose if err console.log "Failed to reset collection: #{collection.collectionName}. Error: #{err}" else console.log "Reset collection: #{collection.collectionName}" callback(err) queue.defer (callback) => schema = @model_type.schema() for key, relation of schema.relations if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany' do (relation) -> queue.defer (callback) -> relation.findOrGenerateJoinTable().resetSchema(callback) callback() queue.await callback cursor: (query={}) -> return new MongoCursor(query, _.pick(@, ['model_type', 'connection', 'backbone_adapter'])) destroy: (query, callback) -> QueryCache.reset @model_type, (err) => return callback(err) if err @connection.collection (err, collection) => return callback(err) if err @model_type.each _.extend({$each: {limit: DESTROY_BATCH_LIMIT, json: true}}, query), ((model_json, callback) => Utils.patchRemoveByJSON @model_type, model_json, (err) => return callback(err) if err collection.remove @backbone_adapter.attributesToNative({id: model_json.id}), (err) => return callback(err) if err callback() ), callback ################################### # Backbone Mongo - Extensions ################################### connect: (url) -> return if @connection and @connection.url is url @connection.destroy() if @connection @connection = new Connection(url, @schema, @sync_options.connection_options or {}) collection: (callback) -> @connection.collection(callback) ################################### # Internal ################################### _selectAdapter: -> for field_name, field_info of @schema.raw continue if (field_name isnt 'id') or not _.isArray(field_info) for info in field_info if info.manual_id @manual_id = true return require './document_adapter_no_mongo_id' return require './document_adapter_mongo_id' # default is using the mongodb's ids module.exports = (type, sync_options={}) -> if Utils.isCollection(new type()) # collection model_type = Utils.configureCollectionModelType(type, module.exports) return type::sync = model_type::sync sync = new MongoSync(type, sync_options) type::sync = sync_fn = (method, model, options={}) -> # save for access by model extensions sync.initialize() return module.exports.apply(null, Array::slice.call(arguments, 1)) if method is 'createSync' # create a new sync return sync if method is 'sync' return sync.schema if method is 'schema' return false if method is 'isRemote' return if sync[method] then sync[method].apply(sync, Array::slice.call(arguments, 1)) else undefined require('backbone-orm/lib/extensions/model')(type) # mixin extensions return ModelCache.configureSync(type, sync_fn)
true
### backbone-mongo.js 0.5.5 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-mongo License: MIT (http://www.opensource.org/licenses/mit-license.php) ### util = require 'util' _ = require 'underscore' Backbone = require 'backbone' moment = require 'moment' Queue = require 'backbone-orm/lib/queue' Schema = require 'backbone-orm/lib/schema' Utils = require 'backbone-orm/lib/utils' QueryCache = require('backbone-orm/lib/cache/singletons').QueryCache ModelCache = require('backbone-orm/lib/cache/singletons').ModelCache ModelTypeID = require('backbone-orm/lib/cache/singletons').ModelTypeID MongoCursor = require './cursor' Connection = require './connection' DESTROY_BATCH_LIMIT = 1000 class MongoSync constructor: (@model_type, @sync_options) -> @model_type.model_name = Utils.findOrGenerateModelName(@model_type) @model_type.model_id = ModelTypeID.generate(@model_type) @schema = new Schema(@model_type) @backbone_adapter = @model_type.backbone_adapter = @_selectAdapter() initialize: (model) -> return if @is_initialized; @is_initialized = true @schema.initialize() throw new Error "Missing url for model" unless url = _.result(new @model_type, 'url') @connect(url) ################################### # Classic Backbone Sync ################################### read: (model, options) -> # a collection if model.models @cursor().toJSON (err, json) -> return options.error(err) if err options.success(json) # a model else @cursor(model.id).toJSON (err, json) -> return options.error(err) if err return options.error(new Error "Model not found. Id #{model.id}") unless json options.success(json) create: (model, options) -> return options.error(new Error "Missing manual id for create: #{util.inspect(model.attributes)}") if @manual_id and not model.id QueryCache.reset @model_type, (err) => return options.error(err) if err @connection.collection (err, collection) => return options.error(err) if err return options.error(new Error 'New document has a non-empty revision') if model.get('_rev') doc = @backbone_adapter.attributesToNative(model.toJSON()); doc._rev = 1 # start revisions collection.insert doc, (err, docs) => return options.error(new Error "Failed to create model. Error: #{err or 'document not found'}") if err or not docs or docs.length isnt 1 options.success(@backbone_adapter.nativeToAttributes(docs[0])) update: (model, options) -> return @create(model, options) unless model.get('_rev') # no revision, create - in the case we manually set an id and are saving for the first time return options.error(new Error "Missing manual id for create: #{util.inspect(model.attributes)}") if @manual_id and not model.id QueryCache.reset @model_type, (err) => return options.error(err) if err @connection.collection (err, collection) => return options.error(err) if err json = @backbone_adapter.attributesToNative(model.toJSON()) delete json._id if @backbone_adapter.id_attribute is '_id' find_query = @backbone_adapter.modelFindQuery(model) find_query._rev = json._rev json._rev++ # increment revisions modifications = {$set: json} if unsets = Utils.get(model, 'unsets') Utils.unset(model, 'unsets') # clear now that we are dealing with them if unsets.length modifications.$unset = {} modifications.$unset[key] = '' for key in unsets when not model.attributes.hasOwnProperty(key) # unset if they haven't been re-set # update the record collection.findAndModify find_query, [[@backbone_adapter.id_attribute, 'asc']], modifications, {new: true}, (err, doc) => return options.error(new Error "Failed to update model (#{@model_type.model_name}). Error: #{err}") if err return options.error(new Error "Failed to update model (#{@model_type.model_name}). Either the document has been deleted or the revision (_rev) was stale.") unless doc return options.error(new Error "Failed to update revision (#{@model_type.model_name}). Is: #{doc._rev} expecting: #{json._rev}") if doc._rev isnt json._rev options.success(@backbone_adapter.nativeToAttributes(doc)) delete: (model, options) -> QueryCache.reset @model_type, (err) => return options.error(err) if err @connection.collection (err, collection) => return options.error(err) if err collection.remove @backbone_adapter.attributesToNative({id: model.id}), (err) => return options.error(err) if err options.success() ################################### # Backbone ORM - Class Extensions ################################### resetSchema: (options, callback) -> queue = new Queue() queue.defer (callback) => @collection (err, collection) -> return callback(err) if err collection.remove (err) -> if options.verbose if err console.log "Failed to reset collection: #{collection.collectionName}. Error: #{err}" else console.log "Reset collection: #{collection.collectionName}" callback(err) queue.defer (callback) => schema = @model_type.schema() for key, relation of schema.relations if relation.type is 'hasMany' and relation.reverse_relation.type is 'hasMany' do (relation) -> queue.defer (callback) -> relation.findOrGenerateJoinTable().resetSchema(callback) callback() queue.await callback cursor: (query={}) -> return new MongoCursor(query, _.pick(@, ['model_type', 'connection', 'backbone_adapter'])) destroy: (query, callback) -> QueryCache.reset @model_type, (err) => return callback(err) if err @connection.collection (err, collection) => return callback(err) if err @model_type.each _.extend({$each: {limit: DESTROY_BATCH_LIMIT, json: true}}, query), ((model_json, callback) => Utils.patchRemoveByJSON @model_type, model_json, (err) => return callback(err) if err collection.remove @backbone_adapter.attributesToNative({id: model_json.id}), (err) => return callback(err) if err callback() ), callback ################################### # Backbone Mongo - Extensions ################################### connect: (url) -> return if @connection and @connection.url is url @connection.destroy() if @connection @connection = new Connection(url, @schema, @sync_options.connection_options or {}) collection: (callback) -> @connection.collection(callback) ################################### # Internal ################################### _selectAdapter: -> for field_name, field_info of @schema.raw continue if (field_name isnt 'id') or not _.isArray(field_info) for info in field_info if info.manual_id @manual_id = true return require './document_adapter_no_mongo_id' return require './document_adapter_mongo_id' # default is using the mongodb's ids module.exports = (type, sync_options={}) -> if Utils.isCollection(new type()) # collection model_type = Utils.configureCollectionModelType(type, module.exports) return type::sync = model_type::sync sync = new MongoSync(type, sync_options) type::sync = sync_fn = (method, model, options={}) -> # save for access by model extensions sync.initialize() return module.exports.apply(null, Array::slice.call(arguments, 1)) if method is 'createSync' # create a new sync return sync if method is 'sync' return sync.schema if method is 'schema' return false if method is 'isRemote' return if sync[method] then sync[method].apply(sync, Array::slice.call(arguments, 1)) else undefined require('backbone-orm/lib/extensions/model')(type) # mixin extensions return ModelCache.configureSync(type, sync_fn)
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 215, "score": 0.9998903274536133, "start": 198, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n ...
src/util/voronoi.coffee
OniDaito/pxljs
1
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details An implementation of Fortune's Sweep algorithm based on the C++ Implementation from http:#skynet.ie/~sos/mapviewer/voronoi.php and the Javascript Implementation found at https:#github.com/gorhill/Javascript-Voronoi/blob/master/rhill-voronoi-core.js Adpated from the excellent work by Raymond Hill Copyright (C) 2010-2013 Raymond Hill https://github.com/gorhill/Javascript-Voronoi Licensed under The MIT License http://en.wikipedia.org/wiki/MIT_License 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. ### {Vec2,Vec3,Edge2} = require '../math/math' {RedBlackTree} = require './red_black_tree' # TODO - Sort out this edge as we have this in math as well class Edge constructor: (@lSite, @rSite) -> @va = @vb = null # Site Methods class Cell constructor : (@site) -> @halfedges = [] @closeMe = false init : (@site) -> @halfedges = [] @closeMe = false @ prepareHalfedges : () -> halfedges = @halfedges iHalfedge = halfedges.length edge # get rid of unused halfedges # rhill 2011-05-27: Keep it simple, no point here in trying # to be fancy: dangling edges are a typically a minority. while iHalfedge-- edge = halfedges[iHalfedge].edge if (!edge.vb or !edge.va) halfedges.splice(iHalfedge,1) # rhill 2011-05-26: I tried to use a binary search at insertion # time to keep the array sorted on-the-fly (in Cell.addHalfedge()). # There was no real benefits in doing so, performance on # Firefox 3.6 was improved marginally, while performance on # Opera 11 was penalized marginally. halfedges.sort( (a,b) -> return b.angle-a.angle ) return halfedges.length # Return a list of the neighbor Ids getNeighborIds : () -> neighbors = [] iHalfedge = @halfedges.length edge while iHalfedge-- edge = @halfedges[iHalfedge].edge if edge.lSite isnt null and edge.lSite.voronoiId != @site.voronoiId neighbors.push(edge.lSite.voronoiId) else if edge.rSite isnt null and edge.rSite.voronoiId != @site.voronoiId neighbors.push(edge.rSite.voronoiId) return neighbors # Compute bounding box # getBbox : () -> halfedges = @halfedges iHalfedge = halfedges.length xmin = Infinity ymin = Infinity xmax = -Infinity ymax = -Infinity v vx vy while iHalfedge-- v = halfedges[iHalfedge].getStartpoint() vx = v.x vy = v.y if vx < xmin xmin = vx if vy < ymin ymin = vy if vx > xmax xmax = vx if vy > ymax ymax = vy # we dont need to take into account end point, # since each end point matches a start point rval = x: xmin y: ymin width: xmax-xmin height: ymax-ymin return rval # Return whether a point is inside, on, or outside the cell: # -1: point is outside the perimeter of the cell # 0: point is on the perimeter of the cell # 1: point is inside the perimeter of the cell # pointIntersection : (x, y) -> # Check if point in polygon. Since all polygons of a Voronoi # diagram are convex, then: # http:#paulbourke.net/geometry/polygonmesh/ # Solution 3 (2D): # "If the polygon is convex then one can consider the polygon # "as a 'path' from the first vertex. A point is on the interior # "of this polygons if it is always on the same side of all the # "line segments making up the path. ... # "(y - y0) (x1 - x0) - (x - x0) (y1 - y0) # "if it is less than 0 then P is to the right of the line segment, # "if greater than 0 it is to the left, if equal to 0 then it lies # "on the line segment" halfedges = @halfedges iHalfedge = halfedges.length halfedge p0 p1 r while iHalfedge-- halfedge = halfedges[iHalfedge] p0 = halfedge.getStartpoint() p1 = halfedge.getEndpoint() r = (y-p0.y)*(p1.x-p0.x)-(x-p0.x)*(p1.y-p0.y) if !r return 0 if r > 0 return -1 return 1 # Could export this properly, along with edge and half-edge as useful things more generally? class Diagram constructor: (@site) -> @ class Halfedge constructor : (@edge, lSite, rSite) -> @site = lSite # 'angle' is a value to be used for properly sorting the # halfsegments counterclockwise. By convention, we will # use the angle of the line defined by the 'site to the left' # to the 'site to the right'. # However, border edges have no 'site to the right': thus we # use the angle of line perpendicular to the halfsegment (the # edge should have both end points defined in such case.) if (rSite) @angle = Math.atan2(rSite.y-lSite.y, rSite.x-lSite.x) else va = edge.va vb = edge.vb # rhill 2011-05-31: used to call getStartpoint()/getEndpoint(), # but for performance purpose, these are expanded in place here. if edge.lSite is lSite @angle = Math.atan2(vb.x-va.x, va.y-vb.y) else Math.atan2(va.x-vb.x, vb.y-va.y) getStartpoint : () -> if @edge.lSite is @site return @edge.va return @edge.vb getEndpoint : () -> if @edge.lSite is @site return @edge.vb return @edge.va # rhill 2011-06-07: For some reasons, performance suffers significantly # when instanciating a literal object instead of an empty ctor # I have ignored this for now class Beachsection constructor : () -> @ # --------------------------------------------------------------------------- # Circle event methods # rhill 2011-06-07: For some reasons, performance suffers significantly # when instanciating a literal object instead of an empty ctor class CircleEvent constructor : () -> # rhill 2013-10-12: it helps to state exactly what we are at ctor time. @arc = null @rbLeft = null @rbNext = null @rbParent = null @rbPrevious = null @rbRed = false @rbRight = null @site = null @x = @y = @ycenter = 0 class Voronoi constructor : () -> @vertices = null @edges = null @cells = null @toRecycle = null @beachsectionJunkyard = [] @circleEventJunkyard = [] @vertexJunkyard = [] @edgeJunkyard = [] @cellJunkyard = [] @abs : Math.abs @epsilon : 1e-9 @invepsilon = 1.0 / @epsilon equalWithEpsilon : (a,b) -> Math.abs(a-b) < 1e-9 greaterThanWithEpsilon : (a,b) -> a-b>1e-9 greaterThanOrEqualWithEpsilon : (a,b) -> b-a<1e-9 lessThanWithEpsilon : (a,b) -> b-a>1e-9 lessThanOrEqualWithEpsilon : (a,b) -> a-b<1e-9 createHalfedge : (edge, lSite, rSite) -> new Halfedge(edge, lSite, rSite) reset : () -> if !@beachline @beachline = new RedBlackTree() # Move leftover beachsections to the beachsection junkyard. if @beachline.root beachsection = @beachline.getFirst(@beachline.root) while beachsection @beachsectionJunkyard.push(beachsection) # mark for reuse beachsection = beachsection.rbNext @beachline.root = null if !@circleEvents @circleEvents = new RedBlackTree() @circleEvents.root = @firstCircleEvent = null @vertices = [] @edges = [] @cells = [] @segments = [] # New Oni Addition # this create and add a vertex to the internal collection createVertex : (x, y) -> v = @vertexJunkyard.pop() if !v v = new Vec2(x, y) else v.x = x v.y = y @vertices.push(v) v # this create and add an edge to internal collection, and also create # two halfedges which are added to each site's counterclockwise array # of halfedges. createEdge : (lSite, rSite, va, vb) -> edge = @edgeJunkyard.pop() if !edge edge = new Edge(lSite, rSite) else edge.lSite = lSite edge.rSite = rSite edge.va = edge.vb = null @edges.push edge if va @setEdgeStartpoint(edge, lSite, rSite, va) if vb @setEdgeEndpoint(edge, lSite, rSite, vb) @cells[lSite.voronoiId].halfedges.push(@createHalfedge(edge, lSite, rSite)) @cells[rSite.voronoiId].halfedges.push(@createHalfedge(edge, rSite, lSite)) edge createBorderEdge : (lSite, va, vb) -> edge = @edgeJunkyard.pop() if !edge edge = new Edge(lSite, null) else edge.lSite = lSite edge.rSite = null edge.va = va edge.vb = vb @edges.push(edge) edge setEdgeStartpoint : (edge, lSite, rSite, vertex) -> if !edge.va and !edge.vb edge.va = vertex edge.lSite = lSite edge.rSite = rSite else if edge.lSite is rSite edge.vb = vertex else edge.va = vertex setEdgeEndpoint : (edge, lSite, rSite, vertex) -> @setEdgeStartpoint(edge, rSite, lSite, vertex) createCell : (site) -> cell = @cellJunkyard.pop() if cell return cell.init(site) new Cell(site) createBeachsection : (site) -> beachsection = @beachsectionJunkyard.pop() if !beachsection beachsection = new Beachsection() beachsection.site = site beachsection # calculate the left break point of a particular beach section, # given a particular sweep line leftBreakPoint : (arc, directrix) -> # http:#en.wikipedia.org/wiki/Parabola # http:#en.wikipedia.org/wiki/Quadratic_equation # h1 = x1, # k1 = (y1+directrix)/2, # h2 = x2, # k2 = (y2+directrix)/2, # p1 = k1-directrix, # a1 = 1/(4*p1), # b1 = -h1/(2*p1), # c1 = h1*h1/(4*p1)+k1, # p2 = k2-directrix, # a2 = 1/(4*p2), # b2 = -h2/(2*p2), # c2 = h2*h2/(4*p2)+k2, # x = (-(b2-b1) + Math.sqrt((b2-b1)*(b2-b1) - 4*(a2-a1)*(c2-c1))) / (2*(a2-a1)) # When x1 become the x-origin: # h1 = 0, # k1 = (y1+directrix)/2, # h2 = x2-x1, # k2 = (y2+directrix)/2, # p1 = k1-directrix, # a1 = 1/(4*p1), # b1 = 0, # c1 = k1, # p2 = k2-directrix, # a2 = 1/(4*p2), # b2 = -h2/(2*p2), # c2 = h2*h2/(4*p2)+k2, # x = (-b2 + Math.sqrt(b2*b2 - 4*(a2-a1)*(c2-k1))) / (2*(a2-a1)) + x1 # change code below at your own risk: care has been taken to # reduce errors due to computers' finite arithmetic precision. # Maybe can still be improved, will see if any more of this # kind of errors pop up again. site = arc.site rfocx = arc.site.x rfocy = arc.site.y pby2 = rfocy-directrix # parabola in degenerate case where focus is on directrix if !pby2 return rfocx lArc = arc.rbPrevious if !lArc return -Infinity site = lArc.site lfocx = site.x lfocy = site.y plby2 = lfocy-directrix # parabola in degenerate case where focus is on directrix if !plby2 return lfocx # We have the site to the left of this site (lfoc) and the site itself (rfoc) hl = lfocx-rfocx aby2 = 1/pby2-1/plby2 b = hl/plby2 # This is where the two parabolas cross it seems :S We return the X co-ordinate if aby2 return (-b+Math.sqrt(b*b-2*aby2*(hl*hl/(-2*plby2)-lfocy+plby2/2+rfocy-pby2/2)))/aby2+rfocx # both parabolas have same distance to directrix, thus break point is midway (rfocx+lfocx)/2 # calculate the right break point of a particular beach section, # given a particular directrix rightBreakPoint : (arc, directrix) -> rArc = arc.rbNext if rArc return @leftBreakPoint(rArc, directrix) site = arc.site if site.y == directrix # could be ===/ is here return site.x Infinity detachBeachsection : (beachsection) -> @detachCircleEvent(beachsection) # detach potentially attached circle event @beachline.removeNode(beachsection) # remove from RB-tree @beachsectionJunkyard.push(beachsection) # mark for reuse removeBeachsection : (beachsection) -> circle = beachsection.circleEvent x = circle.x y = circle.ycenter vertex = @createVertex x,y previous = beachsection.rbPrevious next = beachsection.rbNext disappearingTransitions = [beachsection] abs_fn = Math.abs # remove collapsed beachsection from beachline @detachBeachsection(beachsection) # there could be more than one empty arc at the deletion point, this # happens when more than two edges are linked by the same vertex, # so we will collect all those edges by looking up both sides of # the deletion point. # by the way, there is *always* a predecessor/successor to any collapsed # beach section, it's just impossible to have a collapsing first/last # beach sections on the beachline, since they obviously are unconstrained # on their left/right side. # look left lArc = previous while (lArc.circleEvent and abs_fn(x-lArc.circleEvent.x) < 1e-9) and abs_fn(y-lArc.circleEvent.ycenter) < 1e-9 previous = lArc.rbPrevious disappearingTransitions.unshift(lArc) @detachBeachsection(lArc) # mark for reuse lArc = previous # even though it is not disappearing, I will also add the beach section # immediately to the left of the left-most collapsed beach section, for # convenience, since we need to refer to it later as this beach section # is the 'left' site of an edge for which a start point is set. disappearingTransitions.unshift(lArc) @detachCircleEvent(lArc) # look right rArc = next while (rArc.circleEvent and abs_fn(x-rArc.circleEvent.x) < 1e-9) and abs_fn(y-rArc.circleEvent.ycenter)<1e-9 next = rArc.rbNext disappearingTransitions.push(rArc) @detachBeachsection(rArc) # mark for reuse rArc = next # we also have to add the beach section immediately to the right of the # right-most collapsed beach section, since there is also a disappearing # transition representing an edge's start point on its left. disappearingTransitions.push(rArc) @detachCircleEvent(rArc) # walk through all the disappearing transitions between beach sections and # set the start point of their (implied) edge. nArcs = disappearingTransitions.length iArc for iArc in [1..nArcs-1] rArc = disappearingTransitions[iArc] lArc = disappearingTransitions[iArc-1] @setEdgeStartpoint(rArc.edge, lArc.site, rArc.site, vertex) # create a new edge as we have now a new transition between # two beach sections which were previously not adjacent. # since this edge appears as a new vertex is defined, the vertex # actually define an end point of the edge (relative to the site # on the left) lArc = disappearingTransitions[0] rArc = disappearingTransitions[nArcs-1] rArc.edge = @createEdge(lArc.site, rArc.site, undefined, vertex) # create circle events if any for beach sections left in the beachline # adjacent to collapsed sections @attachCircleEvent(lArc) @attachCircleEvent(rArc) addBeachsection : (site) -> x = site.x directrix = site.y # find the left and right beach sections which will surround the newly # created beach section. # rhill 2011-06-01: This loop is one of the most often executed, # hence we expand in-place the comparison-against-epsilon calls. lArc rArc dxl dxr node = @beachline.root while node dxl = @leftBreakPoint(node,directrix)-x # x lessThanWithEpsilon xl => falls somewhere before the left edge of the beachsection if dxl > 1e-9 # this case should never happen # if (!node.rbLeft) -> # rArc = node.rbLeft # break # } node = node.rbLeft else dxr = x-@rightBreakPoint(node,directrix) # x greaterThanWithEpsilon xr => falls somewhere after the right edge of the beachsection if dxr > 1e-9 if !node.rbRight lArc = node break node = node.rbRight else # x equalWithEpsilon xl => falls exactly on the left edge of the beachsection if dxl > -1e-9 lArc = node.rbPrevious rArc = node # x equalWithEpsilon xr => falls exactly on the right edge of the beachsection else if dxr > -1e-9 lArc = node rArc = node.rbNext # falls exactly somewhere in the middle of the beachsection else lArc = rArc = node break # at this point, keep in mind that lArc and/or rArc could be # undefined or null. # create a new beach section object for the site and add it to RB-tree newArc = @createBeachsection site @beachline.insertSuccessor lArc, newArc # cases: # # [null,null] # least likely case: new beach section is the first beach section on the # beachline. # This case means: # no new transition appears # no collapsing beach section # new beachsection become root of the RB-tree if !lArc and !rArc return # [lArc,rArc] where lArc == rArc # most likely case: new beach section split an existing beach # section. # This case means: # one new transition appears # the left and right beach section might be collapsing as a result # two new nodes added to the RB-tree if lArc is rArc # invalidate circle event of split beach section @detachCircleEvent(lArc) # split the beach section into two separate beach sections rArc = @createBeachsection(lArc.site) @beachline.insertSuccessor(newArc, rArc) # since we have a new transition between two beach sections, # a new edge is born newArc.edge = rArc.edge = @createEdge(lArc.site, newArc.site) # check whether the left and right beach sections are collapsing # and if so create circle events, to be notified when the point of # collapse is reached. @attachCircleEvent(lArc) @attachCircleEvent(rArc) return # [lArc,null] # even less likely case: new beach section is the *last* beach section # on the beachline -- this can happen *only* if *all* the previous beach # sections currently on the beachline share the same y value as # the new beach section. # This case means: # one new transition appears # no collapsing beach section as a result # new beach section become right-most node of the RB-tree if lArc and !rArc newArc.edge = @createEdge(lArc.site,newArc.site) return # [null,rArc] # impossible case: because sites are strictly processed from top to bottom, # and left to right, which guarantees that there will always be a beach section # on the left -- except of course when there are no beach section at all on # the beach line, which case was handled above. # rhill 2011-06-02: No point testing in non-debug version #if (!lArc && rArc) -> # throw "Voronoi.addBeachsection(): What is this I don't even" # } # [lArc,rArc] where lArc != rArc # somewhat less likely case: new beach section falls *exactly* in between two # existing beach sections # This case means: # one transition disappears # two new transitions appear # the left and right beach section might be collapsing as a result # only one new node added to the RB-tree if lArc isnt rArc # invalidate circle events of left and right sites @detachCircleEvent(lArc) @detachCircleEvent(rArc) # an existing transition disappears, meaning a vertex is defined at # the disappearance point. # since the disappearance is caused by the new beachsection, the # vertex is at the center of the circumscribed circle of the left, # new and right beachsections. # http:#mathforum.org/library/drmath/view/55002.html # Except that I bring the origin at A to simplify # calculation lSite = lArc.site ax = lSite.x ay = lSite.y dx=site.x-ax dy=site.y-ay rSite = rArc.site cx=rSite.x-ax cy=rSite.y-ay d=2*(dx*cy-dy*cx) hb=dx*dx+dy*dy hc=cx*cx+cy*cy vertex = @createVertex((cy*hb-dy*hc)/d+ax, (dx*hc-cx*hb)/d+ay) # one transition disappear @setEdgeStartpoint(rArc.edge, lSite, rSite, vertex) # two new transitions appear at the new vertex location newArc.edge = @createEdge(lSite, site, undefined, vertex) rArc.edge = @createEdge(site, rSite, undefined, vertex) # check whether the left and right beach sections are collapsing # and if so create circle events, to handle the point of collapse. @attachCircleEvent(lArc) @attachCircleEvent(rArc) return attachCircleEvent : (arc) -> lArc = arc.rbPrevious rArc = arc.rbNext if !lArc or !rArc return # does that ever happen? lSite = lArc.site cSite = arc.site rSite = rArc.site # If site of left beachsection is same as site of # right beachsection, there can't be convergence if lSite is rSite return # Find the circumscribed circle for the three sites associated # with the beachsection triplet. # rhill 2011-05-26: It is more efficient to calculate in-place # rather than getting the resulting circumscribed circle from an # object returned by calling Voronoi.circumcircle() # http:#mathforum.org/library/drmath/view/55002.html # Except that I bring the origin at cSite to simplify calculations. # The bottom-most part of the circumcircle is our Fortune 'circle # event', and its center is a vertex potentially part of the final # Voronoi diagram. dx = cSite.x dy = cSite.y ax = lSite.x-dx ay = lSite.y-dy cx = rSite.x-dx cy = rSite.y-dy # If points l->c->r are clockwise, then center beach section does not # collapse, hence it can't end up as a vertex (we reuse 'd' here, which # sign is reverse of the orientation, hence we reverse the test. # http:#en.wikipedia.org/wiki/Curve_orientation#Orientation_of_a_simple_polygon # rhill 2011-05-21: Nasty finite precision error which caused circumcircle() to # return infinites: 1e-12 seems to fix the problem. d = 2*(ax*cy-ay*cx) if d >= -2e-12 return ha = ax*ax+ay*ay hc = cx*cx+cy*cy x = (cy*ha-ay*hc)/d y = (ax*hc-cx*ha)/d ycenter = y+dy # Important: ybottom should always be under or at sweep, so no need # to waste CPU cycles by checking # recycle circle event object if possible circleEvent = @circleEventJunkyard.pop() if !circleEvent circleEvent = new CircleEvent() circleEvent.arc = arc circleEvent.site = cSite circleEvent.x = x+dx circleEvent.y = ycenter + Math.sqrt(x*x+y*y) # y bottom circleEvent.ycenter = ycenter arc.circleEvent = circleEvent # find insertion point in RB-tree: circle events are ordered from # smallest to largest predecessor = null node = @circleEvents.root while node if circleEvent.y < node.y or (circleEvent.y == node.y and circleEvent.x <= node.x) # potential ===/is here if node.rbLeft node = node.rbLeft else predecessor = node.rbPrevious break else if node.rbRight node = node.rbRight else predecessor = node break @circleEvents.insertSuccessor(predecessor, circleEvent) if !predecessor @firstCircleEvent = circleEvent detachCircleEvent : (arc) -> circleEvent = arc.circleEvent if circleEvent if !circleEvent.rbPrevious @firstCircleEvent = circleEvent.rbNext @circleEvents.removeNode(circleEvent) # remove from RB-tree @circleEventJunkyard.push(circleEvent) arc.circleEvent = null # --------------------------------------------------------------------------- # Diagram completion methods # connect dangling edges (not if a cursory test tells us # it is not going to be visible. # return value: # false: the dangling endpoint couldn't be connected # true: the dangling endpoint could be connected connectEdge : (edge, bbox) -> # skip if end point already connected vb = edge.vb if !!vb return true # make local copy for performance purpose va = edge.va xl = bbox.xl xr = bbox.xr yt = bbox.yt yb = bbox.yb lSite = edge.lSite rSite = edge.rSite lx = lSite.x ly = lSite.y rx = rSite.x ry = rSite.y fx = (lx+rx)/2 fy = (ly+ry)/2 fm fb # if we reach here, this means cells which use this edge will need # to be closed, whether because the edge was removed, or because it # was connected to the bounding box. @cells[lSite.voronoiId].closeMe = true @cells[rSite.voronoiId].closeMe = true # get the line equation of the bisector if line is not vertical if ry isnt ly fm = (lx-rx)/(ry-ly) fb = fy-fm*fx # remember, direction of line (relative to left site): # upward: left.x < right.x # downward: left.x > right.x # horizontal: left.x == right.x # upward: left.x < right.x # rightward: left.y < right.y # leftward: left.y > right.y # vertical: left.y == right.y # depending on the direction, find the best side of the # bounding box to use to determine a reasonable start point # rhill 2013-12-02: # While at it, since we have the values which define the line, # clip the end of va if it is outside the bbox. # https:#github.com/gorhill/Javascript-Voronoi/issues/15 # TODO: Do all the clipping here rather than rely on Liang-Barsky # which does not do well sometimes due to loss of arithmetic # precision. The code here doesn't degrade if one of the vertex is # at a huge distance. # special case: vertical line if fm is undefined # doesn't intersect with viewport if fx < xl or fx >= xr return false # downward if lx > rx if !va or va.y < yt va = @createVertex(fx, yt) else if va.y >= yb return false vb = @createVertex(fx, yb) # upward else if !va or va.y > yb va = @createVertex(fx, yb) else if va.y < yt return false vb = @createVertex(fx, yt) # closer to vertical than horizontal, connect start point to the # top or bottom side of the bounding box else if fm < -1 or fm > 1 # downward if lx > rx if !va or va.y < yt va = @createVertex((yt-fb)/fm, yt) else if va.y >= yb return false vb = @createVertex((yb-fb)/fm, yb) # upward else if !va or va.y > yb va = @createVertex((yb-fb)/fm, yb) else if va.y < yt return false vb = @createVertex((yt-fb)/fm, yt) # closer to horizontal than vertical, connect start point to the # left or right side of the bounding box else # rightward if ly < ry if !va or va.x < xl va = @createVertex(xl, fm*xl+fb) else if va.x >= xr return false vb = @createVertex(xr, fm*xr+fb) # leftward else if !va or va.x > xr va = @createVertex(xr, fm*xr+fb) else if va.x < xl return false vb = @createVertex(xl, fm*xl+fb) edge.va = va edge.vb = vb return true # line-clipping code taken from: # Liang-Barsky function by Daniel White # http:#www.skytopia.com/project/articles/compsci/clipping.html # Thanks! # A bit modified to minimize code paths clipEdge : (edge, bbox) -> ax = edge.va.x ay = edge.va.y dx = edge.vb.x dy = edge.vb.y t0 = 0 t1 = 1 dx = dx-ax dy = dy-ay # left q = ax-bbox.xl if dx == 0 && q <0 return false r = -q/dx if dx<0 if r < t0 return false if r<t1 t1=r else if dx>0 if r>t1 return false if r>t0 t0=r # right q = bbox.xr-ax if dx == 0 && q<0 return false r = q/dx if dx<0 if r>t1 return false if r>t0 t0=r else if dx>0 if r<t0 return false if r<t1 t1=r # top q = ay-bbox.yt if dy == 0 && q<0 return false r = -q/dy if dy<0 if r<t0 return false if r<t1 t1=r else if dy>0 if r>t1 return false if r>t0 t0=r # bottom q = bbox.yb-ay if dy == 0 && q<0 return false r = q/dy if dy<0 if r>t1 return false if r>t0 t0=r else if dy>0 if r<t0 return false if r<t1 t1=r # if we reach this point, Voronoi edge is within bbox # if t0 > 0, va needs to change # rhill 2011-06-03: we need to create a new vertex rather # than modifying the existing one, since the existing # one is likely shared with at least another edge if t0 > 0 edge.va = @createVertex(ax+t0*dx, ay+t0*dy) # if t1 < 1, vb needs to change # rhill 2011-06-03: we need to create a new vertex rather # than modifying the existing one, since the existing # one is likely shared with at least another edge if t1 < 1 edge.vb = @createVertex(ax+t1*dx, ay+t1*dy) # va and/or vb were clipped, thus we will need to close # cells which use this edge. if t0 > 0 or t1 < 1 @cells[edge.lSite.voronoiId].closeMe = true @cells[edge.rSite.voronoiId].closeMe = true return true # Connect/cut edges at bounding box clipEdges : (bbox) -> # connect all dangling edges to bounding box # or get rid of them if it can't be done edges = @edges iEdge = edges.length edge abs_fn = Math.abs # iterate backward so we can splice safely while iEdge-- edge = edges[iEdge] # edge is removed if: # it is wholly outside the bounding box # it is looking more like a point than a line if !@connectEdge(edge, bbox) or !@clipEdge(edge, bbox) or (abs_fn(edge.va.x-edge.vb.x) < 1e-9 and abs_fn(edge.va.y-edge.vb.y)<1e-9) edge.va = edge.vb = null edges.splice(iEdge,1) # Close the cells. # The cells are bound by the supplied bounding box. # Each cell refers to its associated site, and a list # of halfedges ordered counterclockwise. closeCells : (bbox) -> xl = bbox.xl xr = bbox.xr yt = bbox.yt yb = bbox.yb cells = @cells iCell = cells.length cell iLeft halfedges nHalfedges edge va vb vz lastBorderSegment abs_fn = Math.abs while iCell-- cell = cells[iCell] # prune, order halfedges counterclockwise, then add missing ones # required to close cells if !cell.prepareHalfedges() continue if !cell.closeMe continue # find first 'unclosed' point. # an 'unclosed' point will be the end point of a halfedge which # does not match the start point of the following halfedge halfedges = cell.halfedges nHalfedges = halfedges.length # special case: only one site, in which case, the viewport is the cell # ... # all other cases iLeft = 0 while iLeft < nHalfedges va = halfedges[iLeft].getEndpoint() vz = halfedges[(iLeft+1) % nHalfedges].getStartpoint() # if end point is not equal to start point, we need to add the missing # halfedge(s) up to vz if (abs_fn(va.x-vz.x)>=1e-9 or abs_fn(va.y-vz.y)>=1e-9) # rhill 2013-12-02: # "Holes" in the halfedges are not necessarily always adjacent. # https:#github.com/gorhill/Javascript-Voronoi/issues/16 # find entry point: switch true # walk downward along left side when @equalWithEpsilon(va.x,xl) and @lessThanWithEpsilon(va.y,yb) lastBorderSegment = @equalWithEpsilon(vz.x,xl) ty = yb if lastBorderSegment ty = vz.y vb = @createVertex(xl, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk rightward along bottom side when @equalWithEpsilon(va.y,yb) && @lessThanWithEpsilon(va.x,xr) lastBorderSegment = @equalWithEpsilon(vz.y,yb) tx = xr if lastBorderSegment tx = vz.x vb = @createVertex(tx, yb) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk upward along right side when @equalWithEpsilon(va.x,xr) and @greaterThanWithEpsilon(va.y,yt) lastBorderSegment = @equalWithEpsilon(vz.x,xr) ty = yt if lastBorderSegment ty = vz.y vb = @createVertex(xr, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk leftward along top side when @equalWithEpsilon(va.y,yt) and @greaterThanWithEpsilon(va.x,xl) lastBorderSegment = @equalWithEpsilon(vz.y,yt) tx = xl if lastBorderSegment tx = vz.x vb = @createVertex(tx, yt) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk downward along left side lastBorderSegment = @equalWithEpsilon(vz.x,xl) ty = yb if lastBorderSegment ty = vz.y vb = @createVertex(xl, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk rightward along bottom side lastBorderSegment = @equalWithEpsilon(vz.y,yb) tx = xr if lastBorderSegment tx = vz.x vb = @createVertex(tx, yb) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk upward along right side lastBorderSegment = @equalWithEpsilon(vz.x,xr) ty = yt if lastBorderSegment ty = vz.y vb = @createVertex(xr, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break # fall through else throw "Voronoi.closeCells() > this makes no sense!" iLeft++ cell.closeMe = false # --------------------------------------------------------------------------- # Debugging helper dumpBeachline : (y) -> console.log('Voronoi.dumpBeachline(%f) > Beachsections, from left to right:', y) if !@beachline console.log(' None') else bs = @beachline.getFirst(@beachline.root) while bs console.log(' site %d: xl: %f, xr: %f', bs.site.voronoiId, @leftBreakPoint(bs, y), @rightBreakPoint(bs, y)) bs = bs.rbNext # --------------------------------------------------------------------------- # Helper: Is Segment - returns true if this site is a segment endpoint isSegment : (site) -> for edge in @segments if site is edge[0] or site is edge[1] return true false # --------------------------------------------------------------------------- # Helper: Quantize sites # rhill 2013-10-12: # This is to solve https:#github.com/gorhill/Javascript-Voronoi/issues/15 # Since not all users will end up using the kind of coord values which would # cause the issue to arise, I chose to let the user decide whether or not # he should sanitize his coord values through this helper. This way, for # those users who uses coord values which are known to be fine, no overhead is # added. quantizeSites : (sites) -> e = @epsilon n = sites.length site while n-- site = sites[n] site.x = Math.floor(site.x / e) * e site.y = Math.floor(site.y / e) * e # --------------------------------------------------------------------------- # Helper: Recycle diagram: all vertex, edge and cell objects are # "surrendered" to the Voronoi object for reuse. # TODO: rhill-voronoi-core v2: more performance to be gained # when I change the semantic of what is returned. recycle : (diagram) -> if diagram if diagram instanceof Diagram @toRecycle = diagram else throw 'Voronoi.recycleDiagram() > Need a Diagram object.' # --------------------------------------------------------------------------- # Top-level Fortune loop # rhill 2011-05-19: # Voronoi sites are kept client-side now, to allow # user to freely modify content. At compute time, # *references* to sites are copied locally. # sites is a list of Vec2 # bbox is a boundingbox object # segments is a list of pairs of pointers to Vec2 in sites compute : (sites, bbox, segments) -> # to measure execution time startTime = new Date() # init internal state @reset() # Oni Addition. Keep a record of the segments @segments = segments # any diagram data available for recycling? # I do that here so that this is included in execution time if @toRecycle @vertexJunkyard = @vertexJunkyard.concat(@toRecycle.vertices) @edgeJunkyard = @edgeJunkyard.concat(@toRecycle.edges) @cellJunkyard = @cellJunkyard.concat(@toRecycle.cells) @toRecycle = null # Initialize site event queue siteEvents = sites.slice(0) siteEvents.sort( (a,b) -> r = b.y - a.y if r return r return b.x - a.x ) # process queue site = siteEvents.pop() siteid = 0 xsitex # to avoid duplicate sites xsitey cells = @cells circle # main loop loop # we need to figure whether we handle a site or circle event # for this we find out if there is a site event and it is # 'earlier' than the circle event circle = @firstCircleEvent # add beach section if (site and (!circle or site.y < circle.y or (site.y == circle.y and site.x < circle.x))) # only if site is not a duplicate if site.x != xsitex || site.y != xsitey cells[siteid] = @createCell(site) site.voronoiId = siteid++ # then create a beachsection for that site @addBeachsection(site) # remember last site coords to detect duplicate xsitey = site.y xsitex = site.x site = siteEvents.pop() # remove beach section else if circle @removeBeachsection(circle.arc) # all done, quit else break # wrapping-up: # connect dangling edges to bounding box # cut edges as per bounding box # discard edges completely outside bounding box # discard edges which are point-like @clipEdges(bbox) # add missing edges in order to close opened cells @closeCells(bbox) # to measure execution time stopTime = new Date() # prepare return values diagram = new Diagram() diagram.cells = @cells diagram.edges = @edges diagram.vertices = @vertices diagram.execTime = stopTime.getTime()-startTime.getTime() # clean up @reset() return diagram module.exports = Voronoi : Voronoi
23106
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details An implementation of Fortune's Sweep algorithm based on the C++ Implementation from http:#skynet.ie/~sos/mapviewer/voronoi.php and the Javascript Implementation found at https:#github.com/gorhill/Javascript-Voronoi/blob/master/rhill-voronoi-core.js Adpated from the excellent work by <NAME> Copyright (C) 2010-2013 <NAME> https://github.com/gorhill/Javascript-Voronoi Licensed under The MIT License http://en.wikipedia.org/wiki/MIT_License 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. ### {Vec2,Vec3,Edge2} = require '../math/math' {RedBlackTree} = require './red_black_tree' # TODO - Sort out this edge as we have this in math as well class Edge constructor: (@lSite, @rSite) -> @va = @vb = null # Site Methods class Cell constructor : (@site) -> @halfedges = [] @closeMe = false init : (@site) -> @halfedges = [] @closeMe = false @ prepareHalfedges : () -> halfedges = @halfedges iHalfedge = halfedges.length edge # get rid of unused halfedges # rhill 2011-05-27: Keep it simple, no point here in trying # to be fancy: dangling edges are a typically a minority. while iHalfedge-- edge = halfedges[iHalfedge].edge if (!edge.vb or !edge.va) halfedges.splice(iHalfedge,1) # rhill 2011-05-26: I tried to use a binary search at insertion # time to keep the array sorted on-the-fly (in Cell.addHalfedge()). # There was no real benefits in doing so, performance on # Firefox 3.6 was improved marginally, while performance on # Opera 11 was penalized marginally. halfedges.sort( (a,b) -> return b.angle-a.angle ) return halfedges.length # Return a list of the neighbor Ids getNeighborIds : () -> neighbors = [] iHalfedge = @halfedges.length edge while iHalfedge-- edge = @halfedges[iHalfedge].edge if edge.lSite isnt null and edge.lSite.voronoiId != @site.voronoiId neighbors.push(edge.lSite.voronoiId) else if edge.rSite isnt null and edge.rSite.voronoiId != @site.voronoiId neighbors.push(edge.rSite.voronoiId) return neighbors # Compute bounding box # getBbox : () -> halfedges = @halfedges iHalfedge = halfedges.length xmin = Infinity ymin = Infinity xmax = -Infinity ymax = -Infinity v vx vy while iHalfedge-- v = halfedges[iHalfedge].getStartpoint() vx = v.x vy = v.y if vx < xmin xmin = vx if vy < ymin ymin = vy if vx > xmax xmax = vx if vy > ymax ymax = vy # we dont need to take into account end point, # since each end point matches a start point rval = x: xmin y: ymin width: xmax-xmin height: ymax-ymin return rval # Return whether a point is inside, on, or outside the cell: # -1: point is outside the perimeter of the cell # 0: point is on the perimeter of the cell # 1: point is inside the perimeter of the cell # pointIntersection : (x, y) -> # Check if point in polygon. Since all polygons of a Voronoi # diagram are convex, then: # http:#paulbourke.net/geometry/polygonmesh/ # Solution 3 (2D): # "If the polygon is convex then one can consider the polygon # "as a 'path' from the first vertex. A point is on the interior # "of this polygons if it is always on the same side of all the # "line segments making up the path. ... # "(y - y0) (x1 - x0) - (x - x0) (y1 - y0) # "if it is less than 0 then P is to the right of the line segment, # "if greater than 0 it is to the left, if equal to 0 then it lies # "on the line segment" halfedges = @halfedges iHalfedge = halfedges.length halfedge p0 p1 r while iHalfedge-- halfedge = halfedges[iHalfedge] p0 = halfedge.getStartpoint() p1 = halfedge.getEndpoint() r = (y-p0.y)*(p1.x-p0.x)-(x-p0.x)*(p1.y-p0.y) if !r return 0 if r > 0 return -1 return 1 # Could export this properly, along with edge and half-edge as useful things more generally? class Diagram constructor: (@site) -> @ class Halfedge constructor : (@edge, lSite, rSite) -> @site = lSite # 'angle' is a value to be used for properly sorting the # halfsegments counterclockwise. By convention, we will # use the angle of the line defined by the 'site to the left' # to the 'site to the right'. # However, border edges have no 'site to the right': thus we # use the angle of line perpendicular to the halfsegment (the # edge should have both end points defined in such case.) if (rSite) @angle = Math.atan2(rSite.y-lSite.y, rSite.x-lSite.x) else va = edge.va vb = edge.vb # rhill 2011-05-31: used to call getStartpoint()/getEndpoint(), # but for performance purpose, these are expanded in place here. if edge.lSite is lSite @angle = Math.atan2(vb.x-va.x, va.y-vb.y) else Math.atan2(va.x-vb.x, vb.y-va.y) getStartpoint : () -> if @edge.lSite is @site return @edge.va return @edge.vb getEndpoint : () -> if @edge.lSite is @site return @edge.vb return @edge.va # rhill 2011-06-07: For some reasons, performance suffers significantly # when instanciating a literal object instead of an empty ctor # I have ignored this for now class Beachsection constructor : () -> @ # --------------------------------------------------------------------------- # Circle event methods # rhill 2011-06-07: For some reasons, performance suffers significantly # when instanciating a literal object instead of an empty ctor class CircleEvent constructor : () -> # rhill 2013-10-12: it helps to state exactly what we are at ctor time. @arc = null @rbLeft = null @rbNext = null @rbParent = null @rbPrevious = null @rbRed = false @rbRight = null @site = null @x = @y = @ycenter = 0 class Voronoi constructor : () -> @vertices = null @edges = null @cells = null @toRecycle = null @beachsectionJunkyard = [] @circleEventJunkyard = [] @vertexJunkyard = [] @edgeJunkyard = [] @cellJunkyard = [] @abs : Math.abs @epsilon : 1e-9 @invepsilon = 1.0 / @epsilon equalWithEpsilon : (a,b) -> Math.abs(a-b) < 1e-9 greaterThanWithEpsilon : (a,b) -> a-b>1e-9 greaterThanOrEqualWithEpsilon : (a,b) -> b-a<1e-9 lessThanWithEpsilon : (a,b) -> b-a>1e-9 lessThanOrEqualWithEpsilon : (a,b) -> a-b<1e-9 createHalfedge : (edge, lSite, rSite) -> new Halfedge(edge, lSite, rSite) reset : () -> if !@beachline @beachline = new RedBlackTree() # Move leftover beachsections to the beachsection junkyard. if @beachline.root beachsection = @beachline.getFirst(@beachline.root) while beachsection @beachsectionJunkyard.push(beachsection) # mark for reuse beachsection = beachsection.rbNext @beachline.root = null if !@circleEvents @circleEvents = new RedBlackTree() @circleEvents.root = @firstCircleEvent = null @vertices = [] @edges = [] @cells = [] @segments = [] # New Oni Addition # this create and add a vertex to the internal collection createVertex : (x, y) -> v = @vertexJunkyard.pop() if !v v = new Vec2(x, y) else v.x = x v.y = y @vertices.push(v) v # this create and add an edge to internal collection, and also create # two halfedges which are added to each site's counterclockwise array # of halfedges. createEdge : (lSite, rSite, va, vb) -> edge = @edgeJunkyard.pop() if !edge edge = new Edge(lSite, rSite) else edge.lSite = lSite edge.rSite = rSite edge.va = edge.vb = null @edges.push edge if va @setEdgeStartpoint(edge, lSite, rSite, va) if vb @setEdgeEndpoint(edge, lSite, rSite, vb) @cells[lSite.voronoiId].halfedges.push(@createHalfedge(edge, lSite, rSite)) @cells[rSite.voronoiId].halfedges.push(@createHalfedge(edge, rSite, lSite)) edge createBorderEdge : (lSite, va, vb) -> edge = @edgeJunkyard.pop() if !edge edge = new Edge(lSite, null) else edge.lSite = lSite edge.rSite = null edge.va = va edge.vb = vb @edges.push(edge) edge setEdgeStartpoint : (edge, lSite, rSite, vertex) -> if !edge.va and !edge.vb edge.va = vertex edge.lSite = lSite edge.rSite = rSite else if edge.lSite is rSite edge.vb = vertex else edge.va = vertex setEdgeEndpoint : (edge, lSite, rSite, vertex) -> @setEdgeStartpoint(edge, rSite, lSite, vertex) createCell : (site) -> cell = @cellJunkyard.pop() if cell return cell.init(site) new Cell(site) createBeachsection : (site) -> beachsection = @beachsectionJunkyard.pop() if !beachsection beachsection = new Beachsection() beachsection.site = site beachsection # calculate the left break point of a particular beach section, # given a particular sweep line leftBreakPoint : (arc, directrix) -> # http:#en.wikipedia.org/wiki/Parabola # http:#en.wikipedia.org/wiki/Quadratic_equation # h1 = x1, # k1 = (y1+directrix)/2, # h2 = x2, # k2 = (y2+directrix)/2, # p1 = k1-directrix, # a1 = 1/(4*p1), # b1 = -h1/(2*p1), # c1 = h1*h1/(4*p1)+k1, # p2 = k2-directrix, # a2 = 1/(4*p2), # b2 = -h2/(2*p2), # c2 = h2*h2/(4*p2)+k2, # x = (-(b2-b1) + Math.sqrt((b2-b1)*(b2-b1) - 4*(a2-a1)*(c2-c1))) / (2*(a2-a1)) # When x1 become the x-origin: # h1 = 0, # k1 = (y1+directrix)/2, # h2 = x2-x1, # k2 = (y2+directrix)/2, # p1 = k1-directrix, # a1 = 1/(4*p1), # b1 = 0, # c1 = k1, # p2 = k2-directrix, # a2 = 1/(4*p2), # b2 = -h2/(2*p2), # c2 = h2*h2/(4*p2)+k2, # x = (-b2 + Math.sqrt(b2*b2 - 4*(a2-a1)*(c2-k1))) / (2*(a2-a1)) + x1 # change code below at your own risk: care has been taken to # reduce errors due to computers' finite arithmetic precision. # Maybe can still be improved, will see if any more of this # kind of errors pop up again. site = arc.site rfocx = arc.site.x rfocy = arc.site.y pby2 = rfocy-directrix # parabola in degenerate case where focus is on directrix if !pby2 return rfocx lArc = arc.rbPrevious if !lArc return -Infinity site = lArc.site lfocx = site.x lfocy = site.y plby2 = lfocy-directrix # parabola in degenerate case where focus is on directrix if !plby2 return lfocx # We have the site to the left of this site (lfoc) and the site itself (rfoc) hl = lfocx-rfocx aby2 = 1/pby2-1/plby2 b = hl/plby2 # This is where the two parabolas cross it seems :S We return the X co-ordinate if aby2 return (-b+Math.sqrt(b*b-2*aby2*(hl*hl/(-2*plby2)-lfocy+plby2/2+rfocy-pby2/2)))/aby2+rfocx # both parabolas have same distance to directrix, thus break point is midway (rfocx+lfocx)/2 # calculate the right break point of a particular beach section, # given a particular directrix rightBreakPoint : (arc, directrix) -> rArc = arc.rbNext if rArc return @leftBreakPoint(rArc, directrix) site = arc.site if site.y == directrix # could be ===/ is here return site.x Infinity detachBeachsection : (beachsection) -> @detachCircleEvent(beachsection) # detach potentially attached circle event @beachline.removeNode(beachsection) # remove from RB-tree @beachsectionJunkyard.push(beachsection) # mark for reuse removeBeachsection : (beachsection) -> circle = beachsection.circleEvent x = circle.x y = circle.ycenter vertex = @createVertex x,y previous = beachsection.rbPrevious next = beachsection.rbNext disappearingTransitions = [beachsection] abs_fn = Math.abs # remove collapsed beachsection from beachline @detachBeachsection(beachsection) # there could be more than one empty arc at the deletion point, this # happens when more than two edges are linked by the same vertex, # so we will collect all those edges by looking up both sides of # the deletion point. # by the way, there is *always* a predecessor/successor to any collapsed # beach section, it's just impossible to have a collapsing first/last # beach sections on the beachline, since they obviously are unconstrained # on their left/right side. # look left lArc = previous while (lArc.circleEvent and abs_fn(x-lArc.circleEvent.x) < 1e-9) and abs_fn(y-lArc.circleEvent.ycenter) < 1e-9 previous = lArc.rbPrevious disappearingTransitions.unshift(lArc) @detachBeachsection(lArc) # mark for reuse lArc = previous # even though it is not disappearing, I will also add the beach section # immediately to the left of the left-most collapsed beach section, for # convenience, since we need to refer to it later as this beach section # is the 'left' site of an edge for which a start point is set. disappearingTransitions.unshift(lArc) @detachCircleEvent(lArc) # look right rArc = next while (rArc.circleEvent and abs_fn(x-rArc.circleEvent.x) < 1e-9) and abs_fn(y-rArc.circleEvent.ycenter)<1e-9 next = rArc.rbNext disappearingTransitions.push(rArc) @detachBeachsection(rArc) # mark for reuse rArc = next # we also have to add the beach section immediately to the right of the # right-most collapsed beach section, since there is also a disappearing # transition representing an edge's start point on its left. disappearingTransitions.push(rArc) @detachCircleEvent(rArc) # walk through all the disappearing transitions between beach sections and # set the start point of their (implied) edge. nArcs = disappearingTransitions.length iArc for iArc in [1..nArcs-1] rArc = disappearingTransitions[iArc] lArc = disappearingTransitions[iArc-1] @setEdgeStartpoint(rArc.edge, lArc.site, rArc.site, vertex) # create a new edge as we have now a new transition between # two beach sections which were previously not adjacent. # since this edge appears as a new vertex is defined, the vertex # actually define an end point of the edge (relative to the site # on the left) lArc = disappearingTransitions[0] rArc = disappearingTransitions[nArcs-1] rArc.edge = @createEdge(lArc.site, rArc.site, undefined, vertex) # create circle events if any for beach sections left in the beachline # adjacent to collapsed sections @attachCircleEvent(lArc) @attachCircleEvent(rArc) addBeachsection : (site) -> x = site.x directrix = site.y # find the left and right beach sections which will surround the newly # created beach section. # rhill 2011-06-01: This loop is one of the most often executed, # hence we expand in-place the comparison-against-epsilon calls. lArc rArc dxl dxr node = @beachline.root while node dxl = @leftBreakPoint(node,directrix)-x # x lessThanWithEpsilon xl => falls somewhere before the left edge of the beachsection if dxl > 1e-9 # this case should never happen # if (!node.rbLeft) -> # rArc = node.rbLeft # break # } node = node.rbLeft else dxr = x-@rightBreakPoint(node,directrix) # x greaterThanWithEpsilon xr => falls somewhere after the right edge of the beachsection if dxr > 1e-9 if !node.rbRight lArc = node break node = node.rbRight else # x equalWithEpsilon xl => falls exactly on the left edge of the beachsection if dxl > -1e-9 lArc = node.rbPrevious rArc = node # x equalWithEpsilon xr => falls exactly on the right edge of the beachsection else if dxr > -1e-9 lArc = node rArc = node.rbNext # falls exactly somewhere in the middle of the beachsection else lArc = rArc = node break # at this point, keep in mind that lArc and/or rArc could be # undefined or null. # create a new beach section object for the site and add it to RB-tree newArc = @createBeachsection site @beachline.insertSuccessor lArc, newArc # cases: # # [null,null] # least likely case: new beach section is the first beach section on the # beachline. # This case means: # no new transition appears # no collapsing beach section # new beachsection become root of the RB-tree if !lArc and !rArc return # [lArc,rArc] where lArc == rArc # most likely case: new beach section split an existing beach # section. # This case means: # one new transition appears # the left and right beach section might be collapsing as a result # two new nodes added to the RB-tree if lArc is rArc # invalidate circle event of split beach section @detachCircleEvent(lArc) # split the beach section into two separate beach sections rArc = @createBeachsection(lArc.site) @beachline.insertSuccessor(newArc, rArc) # since we have a new transition between two beach sections, # a new edge is born newArc.edge = rArc.edge = @createEdge(lArc.site, newArc.site) # check whether the left and right beach sections are collapsing # and if so create circle events, to be notified when the point of # collapse is reached. @attachCircleEvent(lArc) @attachCircleEvent(rArc) return # [lArc,null] # even less likely case: new beach section is the *last* beach section # on the beachline -- this can happen *only* if *all* the previous beach # sections currently on the beachline share the same y value as # the new beach section. # This case means: # one new transition appears # no collapsing beach section as a result # new beach section become right-most node of the RB-tree if lArc and !rArc newArc.edge = @createEdge(lArc.site,newArc.site) return # [null,rArc] # impossible case: because sites are strictly processed from top to bottom, # and left to right, which guarantees that there will always be a beach section # on the left -- except of course when there are no beach section at all on # the beach line, which case was handled above. # <NAME> 2011-06-02: No point testing in non-debug version #if (!lArc && rArc) -> # throw "Voronoi.addBeachsection(): What is this I don't even" # } # [lArc,rArc] where lArc != rArc # somewhat less likely case: new beach section falls *exactly* in between two # existing beach sections # This case means: # one transition disappears # two new transitions appear # the left and right beach section might be collapsing as a result # only one new node added to the RB-tree if lArc isnt rArc # invalidate circle events of left and right sites @detachCircleEvent(lArc) @detachCircleEvent(rArc) # an existing transition disappears, meaning a vertex is defined at # the disappearance point. # since the disappearance is caused by the new beachsection, the # vertex is at the center of the circumscribed circle of the left, # new and right beachsections. # http:#mathforum.org/library/drmath/view/55002.html # Except that I bring the origin at A to simplify # calculation lSite = lArc.site ax = lSite.x ay = lSite.y dx=site.x-ax dy=site.y-ay rSite = rArc.site cx=rSite.x-ax cy=rSite.y-ay d=2*(dx*cy-dy*cx) hb=dx*dx+dy*dy hc=cx*cx+cy*cy vertex = @createVertex((cy*hb-dy*hc)/d+ax, (dx*hc-cx*hb)/d+ay) # one transition disappear @setEdgeStartpoint(rArc.edge, lSite, rSite, vertex) # two new transitions appear at the new vertex location newArc.edge = @createEdge(lSite, site, undefined, vertex) rArc.edge = @createEdge(site, rSite, undefined, vertex) # check whether the left and right beach sections are collapsing # and if so create circle events, to handle the point of collapse. @attachCircleEvent(lArc) @attachCircleEvent(rArc) return attachCircleEvent : (arc) -> lArc = arc.rbPrevious rArc = arc.rbNext if !lArc or !rArc return # does that ever happen? lSite = lArc.site cSite = arc.site rSite = rArc.site # If site of left beachsection is same as site of # right beachsection, there can't be convergence if lSite is rSite return # Find the circumscribed circle for the three sites associated # with the beachsection triplet. # rh<NAME> 2011-05-26: It is more efficient to calculate in-place # rather than getting the resulting circumscribed circle from an # object returned by calling Voronoi.circumcircle() # http:#mathforum.org/library/drmath/view/55002.html # Except that I bring the origin at cSite to simplify calculations. # The bottom-most part of the circumcircle is our Fortune 'circle # event', and its center is a vertex potentially part of the final # Voronoi diagram. dx = cSite.x dy = cSite.y ax = lSite.x-dx ay = lSite.y-dy cx = rSite.x-dx cy = rSite.y-dy # If points l->c->r are clockwise, then center beach section does not # collapse, hence it can't end up as a vertex (we reuse 'd' here, which # sign is reverse of the orientation, hence we reverse the test. # http:#en.wikipedia.org/wiki/Curve_orientation#Orientation_of_a_simple_polygon # rhill 2011-05-21: Nasty finite precision error which caused circumcircle() to # return infinites: 1e-12 seems to fix the problem. d = 2*(ax*cy-ay*cx) if d >= -2e-12 return ha = ax*ax+ay*ay hc = cx*cx+cy*cy x = (cy*ha-ay*hc)/d y = (ax*hc-cx*ha)/d ycenter = y+dy # Important: ybottom should always be under or at sweep, so no need # to waste CPU cycles by checking # recycle circle event object if possible circleEvent = @circleEventJunkyard.pop() if !circleEvent circleEvent = new CircleEvent() circleEvent.arc = arc circleEvent.site = cSite circleEvent.x = x+dx circleEvent.y = ycenter + Math.sqrt(x*x+y*y) # y bottom circleEvent.ycenter = ycenter arc.circleEvent = circleEvent # find insertion point in RB-tree: circle events are ordered from # smallest to largest predecessor = null node = @circleEvents.root while node if circleEvent.y < node.y or (circleEvent.y == node.y and circleEvent.x <= node.x) # potential ===/is here if node.rbLeft node = node.rbLeft else predecessor = node.rbPrevious break else if node.rbRight node = node.rbRight else predecessor = node break @circleEvents.insertSuccessor(predecessor, circleEvent) if !predecessor @firstCircleEvent = circleEvent detachCircleEvent : (arc) -> circleEvent = arc.circleEvent if circleEvent if !circleEvent.rbPrevious @firstCircleEvent = circleEvent.rbNext @circleEvents.removeNode(circleEvent) # remove from RB-tree @circleEventJunkyard.push(circleEvent) arc.circleEvent = null # --------------------------------------------------------------------------- # Diagram completion methods # connect dangling edges (not if a cursory test tells us # it is not going to be visible. # return value: # false: the dangling endpoint couldn't be connected # true: the dangling endpoint could be connected connectEdge : (edge, bbox) -> # skip if end point already connected vb = edge.vb if !!vb return true # make local copy for performance purpose va = edge.va xl = bbox.xl xr = bbox.xr yt = bbox.yt yb = bbox.yb lSite = edge.lSite rSite = edge.rSite lx = lSite.x ly = lSite.y rx = rSite.x ry = rSite.y fx = (lx+rx)/2 fy = (ly+ry)/2 fm fb # if we reach here, this means cells which use this edge will need # to be closed, whether because the edge was removed, or because it # was connected to the bounding box. @cells[lSite.voronoiId].closeMe = true @cells[rSite.voronoiId].closeMe = true # get the line equation of the bisector if line is not vertical if ry isnt ly fm = (lx-rx)/(ry-ly) fb = fy-fm*fx # remember, direction of line (relative to left site): # upward: left.x < right.x # downward: left.x > right.x # horizontal: left.x == right.x # upward: left.x < right.x # rightward: left.y < right.y # leftward: left.y > right.y # vertical: left.y == right.y # depending on the direction, find the best side of the # bounding box to use to determine a reasonable start point # <NAME> 2013-12-02: # While at it, since we have the values which define the line, # clip the end of va if it is outside the bbox. # https:#github.com/gorhill/Javascript-Voronoi/issues/15 # TODO: Do all the clipping here rather than rely on Liang-Barsky # which does not do well sometimes due to loss of arithmetic # precision. The code here doesn't degrade if one of the vertex is # at a huge distance. # special case: vertical line if fm is undefined # doesn't intersect with viewport if fx < xl or fx >= xr return false # downward if lx > rx if !va or va.y < yt va = @createVertex(fx, yt) else if va.y >= yb return false vb = @createVertex(fx, yb) # upward else if !va or va.y > yb va = @createVertex(fx, yb) else if va.y < yt return false vb = @createVertex(fx, yt) # closer to vertical than horizontal, connect start point to the # top or bottom side of the bounding box else if fm < -1 or fm > 1 # downward if lx > rx if !va or va.y < yt va = @createVertex((yt-fb)/fm, yt) else if va.y >= yb return false vb = @createVertex((yb-fb)/fm, yb) # upward else if !va or va.y > yb va = @createVertex((yb-fb)/fm, yb) else if va.y < yt return false vb = @createVertex((yt-fb)/fm, yt) # closer to horizontal than vertical, connect start point to the # left or right side of the bounding box else # rightward if ly < ry if !va or va.x < xl va = @createVertex(xl, fm*xl+fb) else if va.x >= xr return false vb = @createVertex(xr, fm*xr+fb) # leftward else if !va or va.x > xr va = @createVertex(xr, fm*xr+fb) else if va.x < xl return false vb = @createVertex(xl, fm*xl+fb) edge.va = va edge.vb = vb return true # line-clipping code taken from: # Liang-Barsky function by <NAME> # http:#www.skytopia.com/project/articles/compsci/clipping.html # Thanks! # A bit modified to minimize code paths clipEdge : (edge, bbox) -> ax = edge.va.x ay = edge.va.y dx = edge.vb.x dy = edge.vb.y t0 = 0 t1 = 1 dx = dx-ax dy = dy-ay # left q = ax-bbox.xl if dx == 0 && q <0 return false r = -q/dx if dx<0 if r < t0 return false if r<t1 t1=r else if dx>0 if r>t1 return false if r>t0 t0=r # right q = bbox.xr-ax if dx == 0 && q<0 return false r = q/dx if dx<0 if r>t1 return false if r>t0 t0=r else if dx>0 if r<t0 return false if r<t1 t1=r # top q = ay-bbox.yt if dy == 0 && q<0 return false r = -q/dy if dy<0 if r<t0 return false if r<t1 t1=r else if dy>0 if r>t1 return false if r>t0 t0=r # bottom q = bbox.yb-ay if dy == 0 && q<0 return false r = q/dy if dy<0 if r>t1 return false if r>t0 t0=r else if dy>0 if r<t0 return false if r<t1 t1=r # if we reach this point, Voronoi edge is within bbox # if t0 > 0, va needs to change # rhill 2011-06-03: we need to create a new vertex rather # than modifying the existing one, since the existing # one is likely shared with at least another edge if t0 > 0 edge.va = @createVertex(ax+t0*dx, ay+t0*dy) # if t1 < 1, vb needs to change # rhill 2011-06-03: we need to create a new vertex rather # than modifying the existing one, since the existing # one is likely shared with at least another edge if t1 < 1 edge.vb = @createVertex(ax+t1*dx, ay+t1*dy) # va and/or vb were clipped, thus we will need to close # cells which use this edge. if t0 > 0 or t1 < 1 @cells[edge.lSite.voronoiId].closeMe = true @cells[edge.rSite.voronoiId].closeMe = true return true # Connect/cut edges at bounding box clipEdges : (bbox) -> # connect all dangling edges to bounding box # or get rid of them if it can't be done edges = @edges iEdge = edges.length edge abs_fn = Math.abs # iterate backward so we can splice safely while iEdge-- edge = edges[iEdge] # edge is removed if: # it is wholly outside the bounding box # it is looking more like a point than a line if !@connectEdge(edge, bbox) or !@clipEdge(edge, bbox) or (abs_fn(edge.va.x-edge.vb.x) < 1e-9 and abs_fn(edge.va.y-edge.vb.y)<1e-9) edge.va = edge.vb = null edges.splice(iEdge,1) # Close the cells. # The cells are bound by the supplied bounding box. # Each cell refers to its associated site, and a list # of halfedges ordered counterclockwise. closeCells : (bbox) -> xl = bbox.xl xr = bbox.xr yt = bbox.yt yb = bbox.yb cells = @cells iCell = cells.length cell iLeft halfedges nHalfedges edge va vb vz lastBorderSegment abs_fn = Math.abs while iCell-- cell = cells[iCell] # prune, order halfedges counterclockwise, then add missing ones # required to close cells if !cell.prepareHalfedges() continue if !cell.closeMe continue # find first 'unclosed' point. # an 'unclosed' point will be the end point of a halfedge which # does not match the start point of the following halfedge halfedges = cell.halfedges nHalfedges = halfedges.length # special case: only one site, in which case, the viewport is the cell # ... # all other cases iLeft = 0 while iLeft < nHalfedges va = halfedges[iLeft].getEndpoint() vz = halfedges[(iLeft+1) % nHalfedges].getStartpoint() # if end point is not equal to start point, we need to add the missing # halfedge(s) up to vz if (abs_fn(va.x-vz.x)>=1e-9 or abs_fn(va.y-vz.y)>=1e-9) # rhill 2013-12-02: # "Holes" in the halfedges are not necessarily always adjacent. # https:#github.com/gorhill/Javascript-Voronoi/issues/16 # find entry point: switch true # walk downward along left side when @equalWithEpsilon(va.x,xl) and @lessThanWithEpsilon(va.y,yb) lastBorderSegment = @equalWithEpsilon(vz.x,xl) ty = yb if lastBorderSegment ty = vz.y vb = @createVertex(xl, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk rightward along bottom side when @equalWithEpsilon(va.y,yb) && @lessThanWithEpsilon(va.x,xr) lastBorderSegment = @equalWithEpsilon(vz.y,yb) tx = xr if lastBorderSegment tx = vz.x vb = @createVertex(tx, yb) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk upward along right side when @equalWithEpsilon(va.x,xr) and @greaterThanWithEpsilon(va.y,yt) lastBorderSegment = @equalWithEpsilon(vz.x,xr) ty = yt if lastBorderSegment ty = vz.y vb = @createVertex(xr, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk leftward along top side when @equalWithEpsilon(va.y,yt) and @greaterThanWithEpsilon(va.x,xl) lastBorderSegment = @equalWithEpsilon(vz.y,yt) tx = xl if lastBorderSegment tx = vz.x vb = @createVertex(tx, yt) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk downward along left side lastBorderSegment = @equalWithEpsilon(vz.x,xl) ty = yb if lastBorderSegment ty = vz.y vb = @createVertex(xl, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk rightward along bottom side lastBorderSegment = @equalWithEpsilon(vz.y,yb) tx = xr if lastBorderSegment tx = vz.x vb = @createVertex(tx, yb) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk upward along right side lastBorderSegment = @equalWithEpsilon(vz.x,xr) ty = yt if lastBorderSegment ty = vz.y vb = @createVertex(xr, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break # fall through else throw "Voronoi.closeCells() > this makes no sense!" iLeft++ cell.closeMe = false # --------------------------------------------------------------------------- # Debugging helper dumpBeachline : (y) -> console.log('Voronoi.dumpBeachline(%f) > Beachsections, from left to right:', y) if !@beachline console.log(' None') else bs = @beachline.getFirst(@beachline.root) while bs console.log(' site %d: xl: %f, xr: %f', bs.site.voronoiId, @leftBreakPoint(bs, y), @rightBreakPoint(bs, y)) bs = bs.rbNext # --------------------------------------------------------------------------- # Helper: Is Segment - returns true if this site is a segment endpoint isSegment : (site) -> for edge in @segments if site is edge[0] or site is edge[1] return true false # --------------------------------------------------------------------------- # Helper: Quantize sites # rhill 2013-10-12: # This is to solve https:#github.com/gorhill/Javascript-Voronoi/issues/15 # Since not all users will end up using the kind of coord values which would # cause the issue to arise, I chose to let the user decide whether or not # he should sanitize his coord values through this helper. This way, for # those users who uses coord values which are known to be fine, no overhead is # added. quantizeSites : (sites) -> e = @epsilon n = sites.length site while n-- site = sites[n] site.x = Math.floor(site.x / e) * e site.y = Math.floor(site.y / e) * e # --------------------------------------------------------------------------- # Helper: Recycle diagram: all vertex, edge and cell objects are # "surrendered" to the Voronoi object for reuse. # TODO: rhill-voronoi-core v2: more performance to be gained # when I change the semantic of what is returned. recycle : (diagram) -> if diagram if diagram instanceof Diagram @toRecycle = diagram else throw 'Voronoi.recycleDiagram() > Need a Diagram object.' # --------------------------------------------------------------------------- # Top-level Fortune loop # rhill 2011-05-19: # Voronoi sites are kept client-side now, to allow # user to freely modify content. At compute time, # *references* to sites are copied locally. # sites is a list of Vec2 # bbox is a boundingbox object # segments is a list of pairs of pointers to Vec2 in sites compute : (sites, bbox, segments) -> # to measure execution time startTime = new Date() # init internal state @reset() # Oni Addition. Keep a record of the segments @segments = segments # any diagram data available for recycling? # I do that here so that this is included in execution time if @toRecycle @vertexJunkyard = @vertexJunkyard.concat(@toRecycle.vertices) @edgeJunkyard = @edgeJunkyard.concat(@toRecycle.edges) @cellJunkyard = @cellJunkyard.concat(@toRecycle.cells) @toRecycle = null # Initialize site event queue siteEvents = sites.slice(0) siteEvents.sort( (a,b) -> r = b.y - a.y if r return r return b.x - a.x ) # process queue site = siteEvents.pop() siteid = 0 xsitex # to avoid duplicate sites xsitey cells = @cells circle # main loop loop # we need to figure whether we handle a site or circle event # for this we find out if there is a site event and it is # 'earlier' than the circle event circle = @firstCircleEvent # add beach section if (site and (!circle or site.y < circle.y or (site.y == circle.y and site.x < circle.x))) # only if site is not a duplicate if site.x != xsitex || site.y != xsitey cells[siteid] = @createCell(site) site.voronoiId = siteid++ # then create a beachsection for that site @addBeachsection(site) # remember last site coords to detect duplicate xsitey = site.y xsitex = site.x site = siteEvents.pop() # remove beach section else if circle @removeBeachsection(circle.arc) # all done, quit else break # wrapping-up: # connect dangling edges to bounding box # cut edges as per bounding box # discard edges completely outside bounding box # discard edges which are point-like @clipEdges(bbox) # add missing edges in order to close opened cells @closeCells(bbox) # to measure execution time stopTime = new Date() # prepare return values diagram = new Diagram() diagram.cells = @cells diagram.edges = @edges diagram.vertices = @vertices diagram.execTime = stopTime.getTime()-startTime.getTime() # clean up @reset() return diagram module.exports = Voronoi : Voronoi
true
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details An implementation of Fortune's Sweep algorithm based on the C++ Implementation from http:#skynet.ie/~sos/mapviewer/voronoi.php and the Javascript Implementation found at https:#github.com/gorhill/Javascript-Voronoi/blob/master/rhill-voronoi-core.js Adpated from the excellent work by PI:NAME:<NAME>END_PI Copyright (C) 2010-2013 PI:NAME:<NAME>END_PI https://github.com/gorhill/Javascript-Voronoi Licensed under The MIT License http://en.wikipedia.org/wiki/MIT_License 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. ### {Vec2,Vec3,Edge2} = require '../math/math' {RedBlackTree} = require './red_black_tree' # TODO - Sort out this edge as we have this in math as well class Edge constructor: (@lSite, @rSite) -> @va = @vb = null # Site Methods class Cell constructor : (@site) -> @halfedges = [] @closeMe = false init : (@site) -> @halfedges = [] @closeMe = false @ prepareHalfedges : () -> halfedges = @halfedges iHalfedge = halfedges.length edge # get rid of unused halfedges # rhill 2011-05-27: Keep it simple, no point here in trying # to be fancy: dangling edges are a typically a minority. while iHalfedge-- edge = halfedges[iHalfedge].edge if (!edge.vb or !edge.va) halfedges.splice(iHalfedge,1) # rhill 2011-05-26: I tried to use a binary search at insertion # time to keep the array sorted on-the-fly (in Cell.addHalfedge()). # There was no real benefits in doing so, performance on # Firefox 3.6 was improved marginally, while performance on # Opera 11 was penalized marginally. halfedges.sort( (a,b) -> return b.angle-a.angle ) return halfedges.length # Return a list of the neighbor Ids getNeighborIds : () -> neighbors = [] iHalfedge = @halfedges.length edge while iHalfedge-- edge = @halfedges[iHalfedge].edge if edge.lSite isnt null and edge.lSite.voronoiId != @site.voronoiId neighbors.push(edge.lSite.voronoiId) else if edge.rSite isnt null and edge.rSite.voronoiId != @site.voronoiId neighbors.push(edge.rSite.voronoiId) return neighbors # Compute bounding box # getBbox : () -> halfedges = @halfedges iHalfedge = halfedges.length xmin = Infinity ymin = Infinity xmax = -Infinity ymax = -Infinity v vx vy while iHalfedge-- v = halfedges[iHalfedge].getStartpoint() vx = v.x vy = v.y if vx < xmin xmin = vx if vy < ymin ymin = vy if vx > xmax xmax = vx if vy > ymax ymax = vy # we dont need to take into account end point, # since each end point matches a start point rval = x: xmin y: ymin width: xmax-xmin height: ymax-ymin return rval # Return whether a point is inside, on, or outside the cell: # -1: point is outside the perimeter of the cell # 0: point is on the perimeter of the cell # 1: point is inside the perimeter of the cell # pointIntersection : (x, y) -> # Check if point in polygon. Since all polygons of a Voronoi # diagram are convex, then: # http:#paulbourke.net/geometry/polygonmesh/ # Solution 3 (2D): # "If the polygon is convex then one can consider the polygon # "as a 'path' from the first vertex. A point is on the interior # "of this polygons if it is always on the same side of all the # "line segments making up the path. ... # "(y - y0) (x1 - x0) - (x - x0) (y1 - y0) # "if it is less than 0 then P is to the right of the line segment, # "if greater than 0 it is to the left, if equal to 0 then it lies # "on the line segment" halfedges = @halfedges iHalfedge = halfedges.length halfedge p0 p1 r while iHalfedge-- halfedge = halfedges[iHalfedge] p0 = halfedge.getStartpoint() p1 = halfedge.getEndpoint() r = (y-p0.y)*(p1.x-p0.x)-(x-p0.x)*(p1.y-p0.y) if !r return 0 if r > 0 return -1 return 1 # Could export this properly, along with edge and half-edge as useful things more generally? class Diagram constructor: (@site) -> @ class Halfedge constructor : (@edge, lSite, rSite) -> @site = lSite # 'angle' is a value to be used for properly sorting the # halfsegments counterclockwise. By convention, we will # use the angle of the line defined by the 'site to the left' # to the 'site to the right'. # However, border edges have no 'site to the right': thus we # use the angle of line perpendicular to the halfsegment (the # edge should have both end points defined in such case.) if (rSite) @angle = Math.atan2(rSite.y-lSite.y, rSite.x-lSite.x) else va = edge.va vb = edge.vb # rhill 2011-05-31: used to call getStartpoint()/getEndpoint(), # but for performance purpose, these are expanded in place here. if edge.lSite is lSite @angle = Math.atan2(vb.x-va.x, va.y-vb.y) else Math.atan2(va.x-vb.x, vb.y-va.y) getStartpoint : () -> if @edge.lSite is @site return @edge.va return @edge.vb getEndpoint : () -> if @edge.lSite is @site return @edge.vb return @edge.va # rhill 2011-06-07: For some reasons, performance suffers significantly # when instanciating a literal object instead of an empty ctor # I have ignored this for now class Beachsection constructor : () -> @ # --------------------------------------------------------------------------- # Circle event methods # rhill 2011-06-07: For some reasons, performance suffers significantly # when instanciating a literal object instead of an empty ctor class CircleEvent constructor : () -> # rhill 2013-10-12: it helps to state exactly what we are at ctor time. @arc = null @rbLeft = null @rbNext = null @rbParent = null @rbPrevious = null @rbRed = false @rbRight = null @site = null @x = @y = @ycenter = 0 class Voronoi constructor : () -> @vertices = null @edges = null @cells = null @toRecycle = null @beachsectionJunkyard = [] @circleEventJunkyard = [] @vertexJunkyard = [] @edgeJunkyard = [] @cellJunkyard = [] @abs : Math.abs @epsilon : 1e-9 @invepsilon = 1.0 / @epsilon equalWithEpsilon : (a,b) -> Math.abs(a-b) < 1e-9 greaterThanWithEpsilon : (a,b) -> a-b>1e-9 greaterThanOrEqualWithEpsilon : (a,b) -> b-a<1e-9 lessThanWithEpsilon : (a,b) -> b-a>1e-9 lessThanOrEqualWithEpsilon : (a,b) -> a-b<1e-9 createHalfedge : (edge, lSite, rSite) -> new Halfedge(edge, lSite, rSite) reset : () -> if !@beachline @beachline = new RedBlackTree() # Move leftover beachsections to the beachsection junkyard. if @beachline.root beachsection = @beachline.getFirst(@beachline.root) while beachsection @beachsectionJunkyard.push(beachsection) # mark for reuse beachsection = beachsection.rbNext @beachline.root = null if !@circleEvents @circleEvents = new RedBlackTree() @circleEvents.root = @firstCircleEvent = null @vertices = [] @edges = [] @cells = [] @segments = [] # New Oni Addition # this create and add a vertex to the internal collection createVertex : (x, y) -> v = @vertexJunkyard.pop() if !v v = new Vec2(x, y) else v.x = x v.y = y @vertices.push(v) v # this create and add an edge to internal collection, and also create # two halfedges which are added to each site's counterclockwise array # of halfedges. createEdge : (lSite, rSite, va, vb) -> edge = @edgeJunkyard.pop() if !edge edge = new Edge(lSite, rSite) else edge.lSite = lSite edge.rSite = rSite edge.va = edge.vb = null @edges.push edge if va @setEdgeStartpoint(edge, lSite, rSite, va) if vb @setEdgeEndpoint(edge, lSite, rSite, vb) @cells[lSite.voronoiId].halfedges.push(@createHalfedge(edge, lSite, rSite)) @cells[rSite.voronoiId].halfedges.push(@createHalfedge(edge, rSite, lSite)) edge createBorderEdge : (lSite, va, vb) -> edge = @edgeJunkyard.pop() if !edge edge = new Edge(lSite, null) else edge.lSite = lSite edge.rSite = null edge.va = va edge.vb = vb @edges.push(edge) edge setEdgeStartpoint : (edge, lSite, rSite, vertex) -> if !edge.va and !edge.vb edge.va = vertex edge.lSite = lSite edge.rSite = rSite else if edge.lSite is rSite edge.vb = vertex else edge.va = vertex setEdgeEndpoint : (edge, lSite, rSite, vertex) -> @setEdgeStartpoint(edge, rSite, lSite, vertex) createCell : (site) -> cell = @cellJunkyard.pop() if cell return cell.init(site) new Cell(site) createBeachsection : (site) -> beachsection = @beachsectionJunkyard.pop() if !beachsection beachsection = new Beachsection() beachsection.site = site beachsection # calculate the left break point of a particular beach section, # given a particular sweep line leftBreakPoint : (arc, directrix) -> # http:#en.wikipedia.org/wiki/Parabola # http:#en.wikipedia.org/wiki/Quadratic_equation # h1 = x1, # k1 = (y1+directrix)/2, # h2 = x2, # k2 = (y2+directrix)/2, # p1 = k1-directrix, # a1 = 1/(4*p1), # b1 = -h1/(2*p1), # c1 = h1*h1/(4*p1)+k1, # p2 = k2-directrix, # a2 = 1/(4*p2), # b2 = -h2/(2*p2), # c2 = h2*h2/(4*p2)+k2, # x = (-(b2-b1) + Math.sqrt((b2-b1)*(b2-b1) - 4*(a2-a1)*(c2-c1))) / (2*(a2-a1)) # When x1 become the x-origin: # h1 = 0, # k1 = (y1+directrix)/2, # h2 = x2-x1, # k2 = (y2+directrix)/2, # p1 = k1-directrix, # a1 = 1/(4*p1), # b1 = 0, # c1 = k1, # p2 = k2-directrix, # a2 = 1/(4*p2), # b2 = -h2/(2*p2), # c2 = h2*h2/(4*p2)+k2, # x = (-b2 + Math.sqrt(b2*b2 - 4*(a2-a1)*(c2-k1))) / (2*(a2-a1)) + x1 # change code below at your own risk: care has been taken to # reduce errors due to computers' finite arithmetic precision. # Maybe can still be improved, will see if any more of this # kind of errors pop up again. site = arc.site rfocx = arc.site.x rfocy = arc.site.y pby2 = rfocy-directrix # parabola in degenerate case where focus is on directrix if !pby2 return rfocx lArc = arc.rbPrevious if !lArc return -Infinity site = lArc.site lfocx = site.x lfocy = site.y plby2 = lfocy-directrix # parabola in degenerate case where focus is on directrix if !plby2 return lfocx # We have the site to the left of this site (lfoc) and the site itself (rfoc) hl = lfocx-rfocx aby2 = 1/pby2-1/plby2 b = hl/plby2 # This is where the two parabolas cross it seems :S We return the X co-ordinate if aby2 return (-b+Math.sqrt(b*b-2*aby2*(hl*hl/(-2*plby2)-lfocy+plby2/2+rfocy-pby2/2)))/aby2+rfocx # both parabolas have same distance to directrix, thus break point is midway (rfocx+lfocx)/2 # calculate the right break point of a particular beach section, # given a particular directrix rightBreakPoint : (arc, directrix) -> rArc = arc.rbNext if rArc return @leftBreakPoint(rArc, directrix) site = arc.site if site.y == directrix # could be ===/ is here return site.x Infinity detachBeachsection : (beachsection) -> @detachCircleEvent(beachsection) # detach potentially attached circle event @beachline.removeNode(beachsection) # remove from RB-tree @beachsectionJunkyard.push(beachsection) # mark for reuse removeBeachsection : (beachsection) -> circle = beachsection.circleEvent x = circle.x y = circle.ycenter vertex = @createVertex x,y previous = beachsection.rbPrevious next = beachsection.rbNext disappearingTransitions = [beachsection] abs_fn = Math.abs # remove collapsed beachsection from beachline @detachBeachsection(beachsection) # there could be more than one empty arc at the deletion point, this # happens when more than two edges are linked by the same vertex, # so we will collect all those edges by looking up both sides of # the deletion point. # by the way, there is *always* a predecessor/successor to any collapsed # beach section, it's just impossible to have a collapsing first/last # beach sections on the beachline, since they obviously are unconstrained # on their left/right side. # look left lArc = previous while (lArc.circleEvent and abs_fn(x-lArc.circleEvent.x) < 1e-9) and abs_fn(y-lArc.circleEvent.ycenter) < 1e-9 previous = lArc.rbPrevious disappearingTransitions.unshift(lArc) @detachBeachsection(lArc) # mark for reuse lArc = previous # even though it is not disappearing, I will also add the beach section # immediately to the left of the left-most collapsed beach section, for # convenience, since we need to refer to it later as this beach section # is the 'left' site of an edge for which a start point is set. disappearingTransitions.unshift(lArc) @detachCircleEvent(lArc) # look right rArc = next while (rArc.circleEvent and abs_fn(x-rArc.circleEvent.x) < 1e-9) and abs_fn(y-rArc.circleEvent.ycenter)<1e-9 next = rArc.rbNext disappearingTransitions.push(rArc) @detachBeachsection(rArc) # mark for reuse rArc = next # we also have to add the beach section immediately to the right of the # right-most collapsed beach section, since there is also a disappearing # transition representing an edge's start point on its left. disappearingTransitions.push(rArc) @detachCircleEvent(rArc) # walk through all the disappearing transitions between beach sections and # set the start point of their (implied) edge. nArcs = disappearingTransitions.length iArc for iArc in [1..nArcs-1] rArc = disappearingTransitions[iArc] lArc = disappearingTransitions[iArc-1] @setEdgeStartpoint(rArc.edge, lArc.site, rArc.site, vertex) # create a new edge as we have now a new transition between # two beach sections which were previously not adjacent. # since this edge appears as a new vertex is defined, the vertex # actually define an end point of the edge (relative to the site # on the left) lArc = disappearingTransitions[0] rArc = disappearingTransitions[nArcs-1] rArc.edge = @createEdge(lArc.site, rArc.site, undefined, vertex) # create circle events if any for beach sections left in the beachline # adjacent to collapsed sections @attachCircleEvent(lArc) @attachCircleEvent(rArc) addBeachsection : (site) -> x = site.x directrix = site.y # find the left and right beach sections which will surround the newly # created beach section. # rhill 2011-06-01: This loop is one of the most often executed, # hence we expand in-place the comparison-against-epsilon calls. lArc rArc dxl dxr node = @beachline.root while node dxl = @leftBreakPoint(node,directrix)-x # x lessThanWithEpsilon xl => falls somewhere before the left edge of the beachsection if dxl > 1e-9 # this case should never happen # if (!node.rbLeft) -> # rArc = node.rbLeft # break # } node = node.rbLeft else dxr = x-@rightBreakPoint(node,directrix) # x greaterThanWithEpsilon xr => falls somewhere after the right edge of the beachsection if dxr > 1e-9 if !node.rbRight lArc = node break node = node.rbRight else # x equalWithEpsilon xl => falls exactly on the left edge of the beachsection if dxl > -1e-9 lArc = node.rbPrevious rArc = node # x equalWithEpsilon xr => falls exactly on the right edge of the beachsection else if dxr > -1e-9 lArc = node rArc = node.rbNext # falls exactly somewhere in the middle of the beachsection else lArc = rArc = node break # at this point, keep in mind that lArc and/or rArc could be # undefined or null. # create a new beach section object for the site and add it to RB-tree newArc = @createBeachsection site @beachline.insertSuccessor lArc, newArc # cases: # # [null,null] # least likely case: new beach section is the first beach section on the # beachline. # This case means: # no new transition appears # no collapsing beach section # new beachsection become root of the RB-tree if !lArc and !rArc return # [lArc,rArc] where lArc == rArc # most likely case: new beach section split an existing beach # section. # This case means: # one new transition appears # the left and right beach section might be collapsing as a result # two new nodes added to the RB-tree if lArc is rArc # invalidate circle event of split beach section @detachCircleEvent(lArc) # split the beach section into two separate beach sections rArc = @createBeachsection(lArc.site) @beachline.insertSuccessor(newArc, rArc) # since we have a new transition between two beach sections, # a new edge is born newArc.edge = rArc.edge = @createEdge(lArc.site, newArc.site) # check whether the left and right beach sections are collapsing # and if so create circle events, to be notified when the point of # collapse is reached. @attachCircleEvent(lArc) @attachCircleEvent(rArc) return # [lArc,null] # even less likely case: new beach section is the *last* beach section # on the beachline -- this can happen *only* if *all* the previous beach # sections currently on the beachline share the same y value as # the new beach section. # This case means: # one new transition appears # no collapsing beach section as a result # new beach section become right-most node of the RB-tree if lArc and !rArc newArc.edge = @createEdge(lArc.site,newArc.site) return # [null,rArc] # impossible case: because sites are strictly processed from top to bottom, # and left to right, which guarantees that there will always be a beach section # on the left -- except of course when there are no beach section at all on # the beach line, which case was handled above. # PI:NAME:<NAME>END_PI 2011-06-02: No point testing in non-debug version #if (!lArc && rArc) -> # throw "Voronoi.addBeachsection(): What is this I don't even" # } # [lArc,rArc] where lArc != rArc # somewhat less likely case: new beach section falls *exactly* in between two # existing beach sections # This case means: # one transition disappears # two new transitions appear # the left and right beach section might be collapsing as a result # only one new node added to the RB-tree if lArc isnt rArc # invalidate circle events of left and right sites @detachCircleEvent(lArc) @detachCircleEvent(rArc) # an existing transition disappears, meaning a vertex is defined at # the disappearance point. # since the disappearance is caused by the new beachsection, the # vertex is at the center of the circumscribed circle of the left, # new and right beachsections. # http:#mathforum.org/library/drmath/view/55002.html # Except that I bring the origin at A to simplify # calculation lSite = lArc.site ax = lSite.x ay = lSite.y dx=site.x-ax dy=site.y-ay rSite = rArc.site cx=rSite.x-ax cy=rSite.y-ay d=2*(dx*cy-dy*cx) hb=dx*dx+dy*dy hc=cx*cx+cy*cy vertex = @createVertex((cy*hb-dy*hc)/d+ax, (dx*hc-cx*hb)/d+ay) # one transition disappear @setEdgeStartpoint(rArc.edge, lSite, rSite, vertex) # two new transitions appear at the new vertex location newArc.edge = @createEdge(lSite, site, undefined, vertex) rArc.edge = @createEdge(site, rSite, undefined, vertex) # check whether the left and right beach sections are collapsing # and if so create circle events, to handle the point of collapse. @attachCircleEvent(lArc) @attachCircleEvent(rArc) return attachCircleEvent : (arc) -> lArc = arc.rbPrevious rArc = arc.rbNext if !lArc or !rArc return # does that ever happen? lSite = lArc.site cSite = arc.site rSite = rArc.site # If site of left beachsection is same as site of # right beachsection, there can't be convergence if lSite is rSite return # Find the circumscribed circle for the three sites associated # with the beachsection triplet. # rhPI:NAME:<NAME>END_PI 2011-05-26: It is more efficient to calculate in-place # rather than getting the resulting circumscribed circle from an # object returned by calling Voronoi.circumcircle() # http:#mathforum.org/library/drmath/view/55002.html # Except that I bring the origin at cSite to simplify calculations. # The bottom-most part of the circumcircle is our Fortune 'circle # event', and its center is a vertex potentially part of the final # Voronoi diagram. dx = cSite.x dy = cSite.y ax = lSite.x-dx ay = lSite.y-dy cx = rSite.x-dx cy = rSite.y-dy # If points l->c->r are clockwise, then center beach section does not # collapse, hence it can't end up as a vertex (we reuse 'd' here, which # sign is reverse of the orientation, hence we reverse the test. # http:#en.wikipedia.org/wiki/Curve_orientation#Orientation_of_a_simple_polygon # rhill 2011-05-21: Nasty finite precision error which caused circumcircle() to # return infinites: 1e-12 seems to fix the problem. d = 2*(ax*cy-ay*cx) if d >= -2e-12 return ha = ax*ax+ay*ay hc = cx*cx+cy*cy x = (cy*ha-ay*hc)/d y = (ax*hc-cx*ha)/d ycenter = y+dy # Important: ybottom should always be under or at sweep, so no need # to waste CPU cycles by checking # recycle circle event object if possible circleEvent = @circleEventJunkyard.pop() if !circleEvent circleEvent = new CircleEvent() circleEvent.arc = arc circleEvent.site = cSite circleEvent.x = x+dx circleEvent.y = ycenter + Math.sqrt(x*x+y*y) # y bottom circleEvent.ycenter = ycenter arc.circleEvent = circleEvent # find insertion point in RB-tree: circle events are ordered from # smallest to largest predecessor = null node = @circleEvents.root while node if circleEvent.y < node.y or (circleEvent.y == node.y and circleEvent.x <= node.x) # potential ===/is here if node.rbLeft node = node.rbLeft else predecessor = node.rbPrevious break else if node.rbRight node = node.rbRight else predecessor = node break @circleEvents.insertSuccessor(predecessor, circleEvent) if !predecessor @firstCircleEvent = circleEvent detachCircleEvent : (arc) -> circleEvent = arc.circleEvent if circleEvent if !circleEvent.rbPrevious @firstCircleEvent = circleEvent.rbNext @circleEvents.removeNode(circleEvent) # remove from RB-tree @circleEventJunkyard.push(circleEvent) arc.circleEvent = null # --------------------------------------------------------------------------- # Diagram completion methods # connect dangling edges (not if a cursory test tells us # it is not going to be visible. # return value: # false: the dangling endpoint couldn't be connected # true: the dangling endpoint could be connected connectEdge : (edge, bbox) -> # skip if end point already connected vb = edge.vb if !!vb return true # make local copy for performance purpose va = edge.va xl = bbox.xl xr = bbox.xr yt = bbox.yt yb = bbox.yb lSite = edge.lSite rSite = edge.rSite lx = lSite.x ly = lSite.y rx = rSite.x ry = rSite.y fx = (lx+rx)/2 fy = (ly+ry)/2 fm fb # if we reach here, this means cells which use this edge will need # to be closed, whether because the edge was removed, or because it # was connected to the bounding box. @cells[lSite.voronoiId].closeMe = true @cells[rSite.voronoiId].closeMe = true # get the line equation of the bisector if line is not vertical if ry isnt ly fm = (lx-rx)/(ry-ly) fb = fy-fm*fx # remember, direction of line (relative to left site): # upward: left.x < right.x # downward: left.x > right.x # horizontal: left.x == right.x # upward: left.x < right.x # rightward: left.y < right.y # leftward: left.y > right.y # vertical: left.y == right.y # depending on the direction, find the best side of the # bounding box to use to determine a reasonable start point # PI:NAME:<NAME>END_PI 2013-12-02: # While at it, since we have the values which define the line, # clip the end of va if it is outside the bbox. # https:#github.com/gorhill/Javascript-Voronoi/issues/15 # TODO: Do all the clipping here rather than rely on Liang-Barsky # which does not do well sometimes due to loss of arithmetic # precision. The code here doesn't degrade if one of the vertex is # at a huge distance. # special case: vertical line if fm is undefined # doesn't intersect with viewport if fx < xl or fx >= xr return false # downward if lx > rx if !va or va.y < yt va = @createVertex(fx, yt) else if va.y >= yb return false vb = @createVertex(fx, yb) # upward else if !va or va.y > yb va = @createVertex(fx, yb) else if va.y < yt return false vb = @createVertex(fx, yt) # closer to vertical than horizontal, connect start point to the # top or bottom side of the bounding box else if fm < -1 or fm > 1 # downward if lx > rx if !va or va.y < yt va = @createVertex((yt-fb)/fm, yt) else if va.y >= yb return false vb = @createVertex((yb-fb)/fm, yb) # upward else if !va or va.y > yb va = @createVertex((yb-fb)/fm, yb) else if va.y < yt return false vb = @createVertex((yt-fb)/fm, yt) # closer to horizontal than vertical, connect start point to the # left or right side of the bounding box else # rightward if ly < ry if !va or va.x < xl va = @createVertex(xl, fm*xl+fb) else if va.x >= xr return false vb = @createVertex(xr, fm*xr+fb) # leftward else if !va or va.x > xr va = @createVertex(xr, fm*xr+fb) else if va.x < xl return false vb = @createVertex(xl, fm*xl+fb) edge.va = va edge.vb = vb return true # line-clipping code taken from: # Liang-Barsky function by PI:NAME:<NAME>END_PI # http:#www.skytopia.com/project/articles/compsci/clipping.html # Thanks! # A bit modified to minimize code paths clipEdge : (edge, bbox) -> ax = edge.va.x ay = edge.va.y dx = edge.vb.x dy = edge.vb.y t0 = 0 t1 = 1 dx = dx-ax dy = dy-ay # left q = ax-bbox.xl if dx == 0 && q <0 return false r = -q/dx if dx<0 if r < t0 return false if r<t1 t1=r else if dx>0 if r>t1 return false if r>t0 t0=r # right q = bbox.xr-ax if dx == 0 && q<0 return false r = q/dx if dx<0 if r>t1 return false if r>t0 t0=r else if dx>0 if r<t0 return false if r<t1 t1=r # top q = ay-bbox.yt if dy == 0 && q<0 return false r = -q/dy if dy<0 if r<t0 return false if r<t1 t1=r else if dy>0 if r>t1 return false if r>t0 t0=r # bottom q = bbox.yb-ay if dy == 0 && q<0 return false r = q/dy if dy<0 if r>t1 return false if r>t0 t0=r else if dy>0 if r<t0 return false if r<t1 t1=r # if we reach this point, Voronoi edge is within bbox # if t0 > 0, va needs to change # rhill 2011-06-03: we need to create a new vertex rather # than modifying the existing one, since the existing # one is likely shared with at least another edge if t0 > 0 edge.va = @createVertex(ax+t0*dx, ay+t0*dy) # if t1 < 1, vb needs to change # rhill 2011-06-03: we need to create a new vertex rather # than modifying the existing one, since the existing # one is likely shared with at least another edge if t1 < 1 edge.vb = @createVertex(ax+t1*dx, ay+t1*dy) # va and/or vb were clipped, thus we will need to close # cells which use this edge. if t0 > 0 or t1 < 1 @cells[edge.lSite.voronoiId].closeMe = true @cells[edge.rSite.voronoiId].closeMe = true return true # Connect/cut edges at bounding box clipEdges : (bbox) -> # connect all dangling edges to bounding box # or get rid of them if it can't be done edges = @edges iEdge = edges.length edge abs_fn = Math.abs # iterate backward so we can splice safely while iEdge-- edge = edges[iEdge] # edge is removed if: # it is wholly outside the bounding box # it is looking more like a point than a line if !@connectEdge(edge, bbox) or !@clipEdge(edge, bbox) or (abs_fn(edge.va.x-edge.vb.x) < 1e-9 and abs_fn(edge.va.y-edge.vb.y)<1e-9) edge.va = edge.vb = null edges.splice(iEdge,1) # Close the cells. # The cells are bound by the supplied bounding box. # Each cell refers to its associated site, and a list # of halfedges ordered counterclockwise. closeCells : (bbox) -> xl = bbox.xl xr = bbox.xr yt = bbox.yt yb = bbox.yb cells = @cells iCell = cells.length cell iLeft halfedges nHalfedges edge va vb vz lastBorderSegment abs_fn = Math.abs while iCell-- cell = cells[iCell] # prune, order halfedges counterclockwise, then add missing ones # required to close cells if !cell.prepareHalfedges() continue if !cell.closeMe continue # find first 'unclosed' point. # an 'unclosed' point will be the end point of a halfedge which # does not match the start point of the following halfedge halfedges = cell.halfedges nHalfedges = halfedges.length # special case: only one site, in which case, the viewport is the cell # ... # all other cases iLeft = 0 while iLeft < nHalfedges va = halfedges[iLeft].getEndpoint() vz = halfedges[(iLeft+1) % nHalfedges].getStartpoint() # if end point is not equal to start point, we need to add the missing # halfedge(s) up to vz if (abs_fn(va.x-vz.x)>=1e-9 or abs_fn(va.y-vz.y)>=1e-9) # rhill 2013-12-02: # "Holes" in the halfedges are not necessarily always adjacent. # https:#github.com/gorhill/Javascript-Voronoi/issues/16 # find entry point: switch true # walk downward along left side when @equalWithEpsilon(va.x,xl) and @lessThanWithEpsilon(va.y,yb) lastBorderSegment = @equalWithEpsilon(vz.x,xl) ty = yb if lastBorderSegment ty = vz.y vb = @createVertex(xl, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk rightward along bottom side when @equalWithEpsilon(va.y,yb) && @lessThanWithEpsilon(va.x,xr) lastBorderSegment = @equalWithEpsilon(vz.y,yb) tx = xr if lastBorderSegment tx = vz.x vb = @createVertex(tx, yb) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk upward along right side when @equalWithEpsilon(va.x,xr) and @greaterThanWithEpsilon(va.y,yt) lastBorderSegment = @equalWithEpsilon(vz.x,xr) ty = yt if lastBorderSegment ty = vz.y vb = @createVertex(xr, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk leftward along top side when @equalWithEpsilon(va.y,yt) and @greaterThanWithEpsilon(va.x,xl) lastBorderSegment = @equalWithEpsilon(vz.y,yt) tx = xl if lastBorderSegment tx = vz.x vb = @createVertex(tx, yt) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk downward along left side lastBorderSegment = @equalWithEpsilon(vz.x,xl) ty = yb if lastBorderSegment ty = vz.y vb = @createVertex(xl, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk rightward along bottom side lastBorderSegment = @equalWithEpsilon(vz.y,yb) tx = xr if lastBorderSegment tx = vz.x vb = @createVertex(tx, yb) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break va = vb # fall through # walk upward along right side lastBorderSegment = @equalWithEpsilon(vz.x,xr) ty = yt if lastBorderSegment ty = vz.y vb = @createVertex(xr, ty) edge = @createBorderEdge(cell.site, va, vb) iLeft++ halfedges.splice(iLeft, 0, @createHalfedge(edge, cell.site, null)) nHalfedges++ if lastBorderSegment break # fall through else throw "Voronoi.closeCells() > this makes no sense!" iLeft++ cell.closeMe = false # --------------------------------------------------------------------------- # Debugging helper dumpBeachline : (y) -> console.log('Voronoi.dumpBeachline(%f) > Beachsections, from left to right:', y) if !@beachline console.log(' None') else bs = @beachline.getFirst(@beachline.root) while bs console.log(' site %d: xl: %f, xr: %f', bs.site.voronoiId, @leftBreakPoint(bs, y), @rightBreakPoint(bs, y)) bs = bs.rbNext # --------------------------------------------------------------------------- # Helper: Is Segment - returns true if this site is a segment endpoint isSegment : (site) -> for edge in @segments if site is edge[0] or site is edge[1] return true false # --------------------------------------------------------------------------- # Helper: Quantize sites # rhill 2013-10-12: # This is to solve https:#github.com/gorhill/Javascript-Voronoi/issues/15 # Since not all users will end up using the kind of coord values which would # cause the issue to arise, I chose to let the user decide whether or not # he should sanitize his coord values through this helper. This way, for # those users who uses coord values which are known to be fine, no overhead is # added. quantizeSites : (sites) -> e = @epsilon n = sites.length site while n-- site = sites[n] site.x = Math.floor(site.x / e) * e site.y = Math.floor(site.y / e) * e # --------------------------------------------------------------------------- # Helper: Recycle diagram: all vertex, edge and cell objects are # "surrendered" to the Voronoi object for reuse. # TODO: rhill-voronoi-core v2: more performance to be gained # when I change the semantic of what is returned. recycle : (diagram) -> if diagram if diagram instanceof Diagram @toRecycle = diagram else throw 'Voronoi.recycleDiagram() > Need a Diagram object.' # --------------------------------------------------------------------------- # Top-level Fortune loop # rhill 2011-05-19: # Voronoi sites are kept client-side now, to allow # user to freely modify content. At compute time, # *references* to sites are copied locally. # sites is a list of Vec2 # bbox is a boundingbox object # segments is a list of pairs of pointers to Vec2 in sites compute : (sites, bbox, segments) -> # to measure execution time startTime = new Date() # init internal state @reset() # Oni Addition. Keep a record of the segments @segments = segments # any diagram data available for recycling? # I do that here so that this is included in execution time if @toRecycle @vertexJunkyard = @vertexJunkyard.concat(@toRecycle.vertices) @edgeJunkyard = @edgeJunkyard.concat(@toRecycle.edges) @cellJunkyard = @cellJunkyard.concat(@toRecycle.cells) @toRecycle = null # Initialize site event queue siteEvents = sites.slice(0) siteEvents.sort( (a,b) -> r = b.y - a.y if r return r return b.x - a.x ) # process queue site = siteEvents.pop() siteid = 0 xsitex # to avoid duplicate sites xsitey cells = @cells circle # main loop loop # we need to figure whether we handle a site or circle event # for this we find out if there is a site event and it is # 'earlier' than the circle event circle = @firstCircleEvent # add beach section if (site and (!circle or site.y < circle.y or (site.y == circle.y and site.x < circle.x))) # only if site is not a duplicate if site.x != xsitex || site.y != xsitey cells[siteid] = @createCell(site) site.voronoiId = siteid++ # then create a beachsection for that site @addBeachsection(site) # remember last site coords to detect duplicate xsitey = site.y xsitex = site.x site = siteEvents.pop() # remove beach section else if circle @removeBeachsection(circle.arc) # all done, quit else break # wrapping-up: # connect dangling edges to bounding box # cut edges as per bounding box # discard edges completely outside bounding box # discard edges which are point-like @clipEdges(bbox) # add missing edges in order to close opened cells @closeCells(bbox) # to measure execution time stopTime = new Date() # prepare return values diagram = new Diagram() diagram.cells = @cells diagram.edges = @edges diagram.vertices = @vertices diagram.execTime = stopTime.getTime()-startTime.getTime() # clean up @reset() return diagram module.exports = Voronoi : Voronoi
[ { "context": "value\": 100000,\n \"addresses\": [\"1FDJMgjuC7A4HkZt6fx8caFfuLDyp4YS9L\"],\n \"script_signatur", "end": 3288, "score": 0.5075262784957886, "start": 3287, "tag": "KEY", "value": "4" }, { "context": "100000,\n \"addresses\": [\"1FDJMgjuC7A4HkZt6fx8ca...
app/spec/fixtures/fixtures_transactions.coffee
romanornr/ledger-wallet-crw
173
ledger.specs.fixtures ?= {} _.extend ledger.specs.fixtures, dongle1_transactions: # "44'/0'/0'/0/6" tx1: "hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "block_hash": "000000000000000006c18384552d198dc53dcdd63964d9887693f684ca0aeeb6", "block_height": 330760, "block_time": "2014-11-19T20:38:15Z", "chain_received_at": "2014-11-19T20:15:46.678Z", "confirmations": 30845, "lock_time": 0, "inputs": [{ "transaction_hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "output_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_index": 0, "value": 69000, "addresses": ["18SxWu7S3Y4wtZG4eQ8fk8UERN2zko2i7Z"], "script_signature": "30440220799ee9f5f644cb34e2da29c48f613146f695b57b96ab6626830aba636965e2c10220076593fc1f9c7bd7efa97fa78bbc0fa5c5f83a6bf26a6b3cdce520339f14d8ac01 0372c277f4e2951ed88978b74f2d0cd400e71972ad40bd78b5b7ed992ed0371906", "script_signature_hex": "4730440220799ee9f5f644cb34e2da29c48f613146f695b57b96ab6626830aba636965e2c10220076593fc1f9c7bd7efa97fa78bbc0fa5c5f83a6bf26a6b3cdce520339f14d8ac01210372c277f4e2951ed88978b74f2d0cd400e71972ad40bd78b5b7ed992ed0371906", "sequence": -1 }], "outputs": [{ "transaction_hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "output_index": 0, "value": 58000, "addresses": ["1EPjG6nHiqmMtpXVq9g6YBwaiTw4uEGvZ5"], "script": "OP_DUP OP_HASH160 92e61041bc1c23f9195d34888d0f96515f01c348 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91492e61041bc1c23f9195d34888d0f96515f01c34888ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "f178f5043ba6781f2a88ef1aa3fcbdbfbc1e793982e757ff8957414c134a1691" }, { "transaction_hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "output_index": 1, "value": 10000, "addresses": ["1L36ug5kWFLbMysfkAexh9LeicyMAteuEg"], "script": "OP_DUP OP_HASH160 d0d0275954563c521297a1d277b4045548639d15 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914d0d0275954563c521297a1d277b4045548639d1588ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "115886c56fff5781bf6a0a1e36330d5f68ac814751bce71e41daf06868fbe446" }], "fees": 1000, "amount": 68000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/1" tx2: "hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "block_hash": "00000000000000000d89f88366661b880e96aba60d083daac990fd21dd97fa5e", "block_height": 330757, "block_time": "2014-11-19T20:04:46Z", "chain_received_at": "2014-11-19T19:53:57.088Z", "confirmations": 30848, "lock_time": 0, "inputs": [{ "transaction_hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "output_hash": "9c832719de7460ab4c4da5b276b591b21baf4afcd9aae42fb32c71e772080e73", "output_index": 0, "value": 100000, "addresses": ["1FDJMgjuC7A4HkZt6fx8caFfuLDyp4YS9L"], "script_signature": "3045022100ad515b1bc1018817a174e6708eb24dbb24efe42a140b008b0b70d68bc4be46ee022003d9ffd685bac22be1c46a65a061ff8e9ca89663284a6bdcb06ba987e2c2a13301 03c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "script_signature_hex": "483045022100ad515b1bc1018817a174e6708eb24dbb24efe42a140b008b0b70d68bc4be46ee022003d9ffd685bac22be1c46a65a061ff8e9ca89663284a6bdcb06ba987e2c2a133012103c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "sequence": -1 }], "outputs": [{ "transaction_hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "output_index": 0, "value": 89000, "addresses": ["1KBTvmpXp3A2zhZrzuVLneEeUZJQ1qMzCF"], "script": "OP_DUP OP_HASH160 c76ce6beeb0884c9513bcf779144950f9525f8e9 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914c76ce6beeb0884c9513bcf779144950f9525f8e988ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "d1c90810c08827e26e33a9a7e5a37703d3cb55b155f3c6900f88743fe9e91421" }, { "transaction_hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "output_index": 1, "value": 10000, "addresses": ["18tMkbibtxJPQoTPUv8s3mSXqYzEsrbeRb"], "script": "OP_DUP OP_HASH160 567f6acc93fe0349b604f45f46b540f55059abbb OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914567f6acc93fe0349b604f45f46b540f55059abbb88ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "b37dd0fa5e62497939367efee9a9cd90383473e798a260e20eb9a37ec05868a6" }], "fees": 1000, "amount": 99000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/3" tx3: "hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "block_hash": "00000000000000000d89f88366661b880e96aba60d083daac990fd21dd97fa5e", "block_height": 330757, "block_time": "2014-11-19T20:04:46Z", "chain_received_at": "2014-11-19T20:01:11.576Z", "confirmations": 30848, "lock_time": 0, "inputs": [{ "transaction_hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "output_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_index": 0, "value": 7437000, "addresses": ["1DZRBBjx2L1urJmzpwDoZH51gX2XSgwvk7"], "script_signature": "304402202db4e13f0b773a96d107e71ccaf69b44fb9a025ad80d79c4c672ffed573be75f022013f1f04c60393c614ce53d05063d8653db467c37bd0c626eb2ba4a93811ea14501 039d937dbef6142c4177152afad9ed93f81da538b48ba1f05bea87ef8064aff2e1", "script_signature_hex": "47304402202db4e13f0b773a96d107e71ccaf69b44fb9a025ad80d79c4c672ffed573be75f022013f1f04c60393c614ce53d05063d8653db467c37bd0c626eb2ba4a93811ea1450121039d937dbef6142c4177152afad9ed93f81da538b48ba1f05bea87ef8064aff2e1", "sequence": -1 }], "outputs": [{ "transaction_hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "output_index": 0, "value": 10000, "addresses": ["1KZB7aFfuZE2skJQPHH56VhSxUpUBjouwQ"], "script": "OP_DUP OP_HASH160 cb88045ebe75f5e94633d27dffca389cde381b78 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914cb88045ebe75f5e94633d27dffca389cde381b7888ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "115886c56fff5781bf6a0a1e36330d5f68ac814751bce71e41daf06868fbe446" }, { "transaction_hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "output_index": 1, "value": 7426000, "addresses": ["12XgKxQd5ZmeTjZVXiEpsGuoTr745GaHxF"], "script": "OP_DUP OP_HASH160 10c56ed9bad6951e36c3d49de11cd29928dc5669 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91410c56ed9bad6951e36c3d49de11cd29928dc566988ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "41b961f740f2577d8a489dc1ab34ae985e6b0f17e790705e3bc33a7d94dbb248" }], "fees": 1000, "amount": 7436000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/2" tx4: "hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "block_hash": "00000000000000000d89f88366661b880e96aba60d083daac990fd21dd97fa5e", "block_height": 330757, "block_time": "2014-11-19T20:04:46Z", "chain_received_at": "2014-11-19T19:57:43.888Z", "confirmations": 30848, "lock_time": 0, "inputs": [{ "transaction_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_hash": "e1f49c35c83cabbd7a20895de1d27cc374a4667ea40ccd2e27fe66ec574437b1", "output_index": 0, "value": 80000, "addresses": ["1FDJMgjuC7A4HkZt6fx8caFfuLDyp4YS9L"], "script_signature": "3044022011d5413262ea45452f40450da2e534775568f9680e4b342b5d6ae01e1d86a855022019b8a0517b195eeefcaba7f2a2e8c5d6d95e2b00eeca3d6bdd73c9fe0db68cc601 03c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "script_signature_hex": "473044022011d5413262ea45452f40450da2e534775568f9680e4b342b5d6ae01e1d86a855022019b8a0517b195eeefcaba7f2a2e8c5d6d95e2b00eeca3d6bdd73c9fe0db68cc6012103c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "sequence": -1 }], "outputs": [{ "transaction_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_index": 0, "value": 69000, "addresses": ["18SxWu7S3Y4wtZG4eQ8fk8UERN2zko2i7Z"], "script": "OP_DUP OP_HASH160 51b19f1c87c6ad9a5eaa45dc48a67c2c63002311 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91451b19f1c87c6ad9a5eaa45dc48a67c2c6300231188ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc" }, { "transaction_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_index": 1, "value": 10000, "addresses": ["1GJr9FHZ1pbR4hjhX24M4L1BDUd2QogYYA"], "script": "OP_DUP OP_HASH160 a7e9fadcc36932a2d00e821f531584dcf65b917d OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914a7e9fadcc36932a2d00e821f531584dcf65b917d88ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "115886c56fff5781bf6a0a1e36330d5f68ac814751bce71e41daf06868fbe446" }], "fees": 1000, "amount": 79000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/0" tx5: "hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "block_hash": "00000000000000001447d39f0d7a400879038d950d88ef4b2c24f4383446b071", "block_height": 330738, "block_time": "2014-11-19T17:52:51Z", "chain_received_at": "2014-11-19T17:19:45.940Z", "confirmations": 30867, "lock_time": 0, "inputs": [{ "transaction_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_hash": "a87463e2852ef5467a9d87b7a7d1095899d1e5893613d9f62b9d11c27630ef0a", "output_index": 1, "value": 7538000, "addresses": ["13VAufAUHFAZ4tKGUcZtvM5dgzgMcxgX1o"], "script_signature": "304402200dc547ac3c674aceba8442480432e36a26eac72f6515a3ce69b9eb8251af2a6802201fb47476886829f76c53e8be8fd096589b220dfbc879bf36b65294444412d66701 0322b82d653b864af6a7a27812c9b719b06b93a73e1c270ab4535843f9f6a04ebc", "script_signature_hex": "47304402200dc547ac3c674aceba8442480432e36a26eac72f6515a3ce69b9eb8251af2a6802201fb47476886829f76c53e8be8fd096589b220dfbc879bf36b65294444412d66701210322b82d653b864af6a7a27812c9b719b06b93a73e1c270ab4535843f9f6a04ebc", "sequence": -1 }], "outputs": [{ "transaction_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_index": 0, "value": 7437000, "addresses": ["1DZRBBjx2L1urJmzpwDoZH51gX2XSgwvk7"], "script": "OP_DUP OP_HASH160 89c3003f16a73b05429269807ad29ed5cb2dd096 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91489c3003f16a73b05429269807ad29ed5cb2dd09688ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721" }, { "transaction_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_index": 1, "value": 100000, "addresses": ["151krzHgfkNoH3XHBzEVi6tSn4db7pVjmR"], "script": "OP_DUP OP_HASH160 2c051dfed45971ba30473de4b4e57278bd9f001e OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a9142c051dfed45971ba30473de4b4e57278bd9f001e88ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "74c666f98467acccdf75de2bb1fbd8282c9be8afb25b438ab2d6354d6c689f62" }], "fees": 1000, "amount": 7537000, "inputs_length": 1, "outputs_length": 2
214367
ledger.specs.fixtures ?= {} _.extend ledger.specs.fixtures, dongle1_transactions: # "44'/0'/0'/0/6" tx1: "hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "block_hash": "000000000000000006c18384552d198dc53dcdd63964d9887693f684ca0aeeb6", "block_height": 330760, "block_time": "2014-11-19T20:38:15Z", "chain_received_at": "2014-11-19T20:15:46.678Z", "confirmations": 30845, "lock_time": 0, "inputs": [{ "transaction_hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "output_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_index": 0, "value": 69000, "addresses": ["18SxWu7S3Y4wtZG4eQ8fk8UERN2zko2i7Z"], "script_signature": "30440220799ee9f5f644cb34e2da29c48f613146f695b57b96ab6626830aba636965e2c10220076593fc1f9c7bd7efa97fa78bbc0fa5c5f83a6bf26a6b3cdce520339f14d8ac01 0372c277f4e2951ed88978b74f2d0cd400e71972ad40bd78b5b7ed992ed0371906", "script_signature_hex": "4730440220799ee9f5f644cb34e2da29c48f613146f695b57b96ab6626830aba636965e2c10220076593fc1f9c7bd7efa97fa78bbc0fa5c5f83a6bf26a6b3cdce520339f14d8ac01210372c277f4e2951ed88978b74f2d0cd400e71972ad40bd78b5b7ed992ed0371906", "sequence": -1 }], "outputs": [{ "transaction_hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "output_index": 0, "value": 58000, "addresses": ["1EPjG6nHiqmMtpXVq9g6YBwaiTw4uEGvZ5"], "script": "OP_DUP OP_HASH160 92e61041bc1c23f9195d34888d0f96515f01c348 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91492e61041bc1c23f9195d34888d0f96515f01c34888ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "f178f5043ba6781f2a88ef1aa3fcbdbfbc1e793982e757ff8957414c134a1691" }, { "transaction_hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "output_index": 1, "value": 10000, "addresses": ["1L36ug5kWFLbMysfkAexh9LeicyMAteuEg"], "script": "OP_DUP OP_HASH160 d0d0275954563c521297a1d277b4045548639d15 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914d0d0275954563c521297a1d277b4045548639d1588ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "115886c56fff5781bf6a0a1e36330d5f68ac814751bce71e41daf06868fbe446" }], "fees": 1000, "amount": 68000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/1" tx2: "hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "block_hash": "00000000000000000d89f88366661b880e96aba60d083daac990fd21dd97fa5e", "block_height": 330757, "block_time": "2014-11-19T20:04:46Z", "chain_received_at": "2014-11-19T19:53:57.088Z", "confirmations": 30848, "lock_time": 0, "inputs": [{ "transaction_hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "output_hash": "9c832719de7460ab4c4da5b276b591b21baf4afcd9aae42fb32c71e772080e73", "output_index": 0, "value": 100000, "addresses": ["1FDJMgjuC7A<KEY>HkZt6fx<KEY>fu<KEY>"], "script_signature": "3045022100ad515b1bc1018817a174e6708eb24dbb24efe42a140b008b0b70d68bc4be46ee022003d9ffd685bac22be1c46a65a061ff8e9ca89663284a6bdcb06ba987e2c2a13301 03c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "script_signature_hex": "483045022100ad515b1bc1018817a174e6708eb24dbb24efe42a140b008b0b70d68bc4be46ee022003d9ffd685bac22be1c46a65a061ff8e9ca89663284a6bdcb06ba987e2c2a133012103c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "sequence": -1 }], "outputs": [{ "transaction_hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "output_index": 0, "value": 89000, "addresses": ["1KBTvmpXp3A2zhZrzuVLneEeUZJQ1qMzCF"], "script": "OP_DUP OP_HASH160 c76ce6beeb0884c9513bcf779144950f9525f8e9 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914c76ce6beeb0884c9513bcf779144950f9525f8e988ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "d1c90810c08827e26e33a9a7e5a37703d3cb55b155f3c6900f88743fe9e91421" }, { "transaction_hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "output_index": 1, "value": 10000, "addresses": ["18tMkbibtxJPQoTPUv8s3mSXqYzEsrbeRb"], "script": "OP_DUP OP_HASH160 567f6acc93fe0349b604f45f46b540f55059abbb OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914567f6acc93fe0349b604f45f46b540f55059abbb88ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "b37dd0fa5e62497939367efee9a9cd90383473e798a260e20eb9a37ec05868a6" }], "fees": 1000, "amount": 99000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/3" tx3: "hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "block_hash": "00000000000000000d89f88366661b880e96aba60d083daac990fd21dd97fa5e", "block_height": 330757, "block_time": "2014-11-19T20:04:46Z", "chain_received_at": "2014-11-19T20:01:11.576Z", "confirmations": 30848, "lock_time": 0, "inputs": [{ "transaction_hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "output_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_index": 0, "value": 7437000, "addresses": ["1DZRBBjx2L1urJmzpwDoZH51gX2XSgwvk7"], "script_signature": "304402202db4e13f0b773a96d107e71ccaf69b44fb9a025ad80d79c4c672ffed573be75f022013f1f04c60393c614ce53d05063d8653db467c37bd0c626eb2ba4a93811ea14501 039d937dbef6142c4177152afad9ed93f81da538b48ba1f05bea87ef8064aff2e1", "script_signature_hex": "47304402202db4e13f0b773a96d107e71ccaf69b44fb9a025ad80d79c4c672ffed573be75f022013f1f04c60393c614ce53d05063d8653db467c37bd0c626eb2ba4a93811ea1450121039d937dbef6142c4177152afad9ed93f81da538b48ba1f05bea87ef8064aff2e1", "sequence": -1 }], "outputs": [{ "transaction_hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "output_index": 0, "value": 10000, "addresses": ["1KZB7aFfuZE2skJQPHH56VhSxUpUBjouwQ"], "script": "OP_DUP OP_HASH160 cb88045ebe75f5e94633d27dffca389cde381b78 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914cb88045ebe75f5e94633d27dffca389cde381b7888ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "115886c56fff5781bf6a0a1e36330d5f68ac814751bce71e41daf06868fbe446" }, { "transaction_hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "output_index": 1, "value": 7426000, "addresses": ["12XgKxQd5ZmeTjZVXiEpsGuoTr745GaHxF"], "script": "OP_DUP OP_HASH160 10c56ed9bad6951e36c3d49de11cd29928dc5669 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91410c56ed9bad6951e36c3d49de11cd29928dc566988ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "41b961f740f2577d8a489dc1ab34ae985e6b0f17e790705e3bc33a7d94dbb248" }], "fees": 1000, "amount": 7436000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/2" tx4: "hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "block_hash": "00000000000000000d89f88366661b880e96aba60d083daac990fd21dd97fa5e", "block_height": 330757, "block_time": "2014-11-19T20:04:46Z", "chain_received_at": "2014-11-19T19:57:43.888Z", "confirmations": 30848, "lock_time": 0, "inputs": [{ "transaction_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_hash": "e1f49c35c83cabbd7a20895de1d27cc374a4667ea40ccd2e27fe66ec574437b1", "output_index": 0, "value": 80000, "addresses": ["1FDJMgjuC7A4HkZt6fx8caFfuLDyp4YS9L"], "script_signature": "3044022011d5413262ea45452f40450da2e534775568f9680e4b342b5d6ae01e1d86a855022019b8a0517b195eeefcaba7f2a2e8c5d6d95e2b00eeca3d6bdd73c9fe0db68cc601 03c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "script_signature_hex": "473044022011d5413262ea45452f40450da2e534775568f9680e4b342b5d6ae01e1d86a855022019b8a0517b195eeefcaba7f2a2e8c5d6d95e2b00eeca3d6bdd73c9fe0db68cc6012103c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "sequence": -1 }], "outputs": [{ "transaction_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_index": 0, "value": 69000, "addresses": ["18SxWu7S3Y4wtZG4eQ8fk8UERN2zko2i7Z"], "script": "OP_DUP OP_HASH160 51b19f1c87c6ad9a5eaa45dc48a67c2c63002311 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91451b19f1c87c6ad9a5eaa45dc48a67c2c6300231188ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc" }, { "transaction_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_index": 1, "value": 10000, "addresses": ["1GJr9FHZ1pbR4hjhX24M4L1BDUd2QogYYA"], "script": "OP_DUP OP_HASH160 a7e9fadcc36932a2d00e821f531584dcf65b917d OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914a7e9fadcc36932a2d00e821f531584dcf65b917d88ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "115886c56fff5781bf6a0a1e36330d5f68ac814751bce71e41daf06868fbe446" }], "fees": 1000, "amount": 79000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/0" tx5: "hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "block_hash": "00000000000000001447d39f0d7a400879038d950d88ef4b2c24f4383446b071", "block_height": 330738, "block_time": "2014-11-19T17:52:51Z", "chain_received_at": "2014-11-19T17:19:45.940Z", "confirmations": 30867, "lock_time": 0, "inputs": [{ "transaction_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_hash": "a87463e2852ef5467a9d87b7a7d1095899d1e5893613d9f62b9d11c27630ef0a", "output_index": 1, "value": 7538000, "addresses": ["13VAufAUHFAZ4tKGUcZtvM5dgzgMcxgX1o"], "script_signature": "304402200dc547ac3c674aceba8442480432e36a26eac72f6515a3ce69b9eb8251af2a6802201fb47476886829f76c53e8be8fd096589b220dfbc879bf36b65294444412d66701 0322b82d653b864af6a7a27812c9b719b06b93a73e1c270ab4535843f9f6a04ebc", "script_signature_hex": "47304402200dc547ac3c674aceba8442480432e36a26eac72f6515a3ce69b9eb8251af2a6802201fb47476886829f76c53e8be8fd096589b220dfbc879bf36b65294444412d66701210322b82d653b864af6a7a27812c9b719b06b93a73e1c270ab4535843f9f6a04ebc", "sequence": -1 }], "outputs": [{ "transaction_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_index": 0, "value": 7437000, "addresses": ["1DZRBBjx2L1urJmzpwDoZH51gX2XSgwvk7"], "script": "OP_DUP OP_HASH160 89c3003f16a73b05429269807ad29ed5cb2dd096 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91489c3003f16a73b05429269807ad29ed5cb2dd09688ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721" }, { "transaction_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_index": 1, "value": 100000, "addresses": ["151krzHgfkNoH3XHBzEVi6tSn4db7pVjmR"], "script": "OP_DUP OP_HASH160 2c051dfed45971ba30473de4b4e57278bd9f001e OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a9142c051dfed45971ba30473de4b4e57278bd9f001e88ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "74c666f98467acccdf75de2bb1fbd8282c9be8afb25b438ab2d6354d6c689f62" }], "fees": 1000, "amount": 7537000, "inputs_length": 1, "outputs_length": 2
true
ledger.specs.fixtures ?= {} _.extend ledger.specs.fixtures, dongle1_transactions: # "44'/0'/0'/0/6" tx1: "hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "block_hash": "000000000000000006c18384552d198dc53dcdd63964d9887693f684ca0aeeb6", "block_height": 330760, "block_time": "2014-11-19T20:38:15Z", "chain_received_at": "2014-11-19T20:15:46.678Z", "confirmations": 30845, "lock_time": 0, "inputs": [{ "transaction_hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "output_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_index": 0, "value": 69000, "addresses": ["18SxWu7S3Y4wtZG4eQ8fk8UERN2zko2i7Z"], "script_signature": "30440220799ee9f5f644cb34e2da29c48f613146f695b57b96ab6626830aba636965e2c10220076593fc1f9c7bd7efa97fa78bbc0fa5c5f83a6bf26a6b3cdce520339f14d8ac01 0372c277f4e2951ed88978b74f2d0cd400e71972ad40bd78b5b7ed992ed0371906", "script_signature_hex": "4730440220799ee9f5f644cb34e2da29c48f613146f695b57b96ab6626830aba636965e2c10220076593fc1f9c7bd7efa97fa78bbc0fa5c5f83a6bf26a6b3cdce520339f14d8ac01210372c277f4e2951ed88978b74f2d0cd400e71972ad40bd78b5b7ed992ed0371906", "sequence": -1 }], "outputs": [{ "transaction_hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "output_index": 0, "value": 58000, "addresses": ["1EPjG6nHiqmMtpXVq9g6YBwaiTw4uEGvZ5"], "script": "OP_DUP OP_HASH160 92e61041bc1c23f9195d34888d0f96515f01c348 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91492e61041bc1c23f9195d34888d0f96515f01c34888ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "f178f5043ba6781f2a88ef1aa3fcbdbfbc1e793982e757ff8957414c134a1691" }, { "transaction_hash": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc", "output_index": 1, "value": 10000, "addresses": ["1L36ug5kWFLbMysfkAexh9LeicyMAteuEg"], "script": "OP_DUP OP_HASH160 d0d0275954563c521297a1d277b4045548639d15 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914d0d0275954563c521297a1d277b4045548639d1588ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "115886c56fff5781bf6a0a1e36330d5f68ac814751bce71e41daf06868fbe446" }], "fees": 1000, "amount": 68000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/1" tx2: "hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "block_hash": "00000000000000000d89f88366661b880e96aba60d083daac990fd21dd97fa5e", "block_height": 330757, "block_time": "2014-11-19T20:04:46Z", "chain_received_at": "2014-11-19T19:53:57.088Z", "confirmations": 30848, "lock_time": 0, "inputs": [{ "transaction_hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "output_hash": "9c832719de7460ab4c4da5b276b591b21baf4afcd9aae42fb32c71e772080e73", "output_index": 0, "value": 100000, "addresses": ["1FDJMgjuC7API:KEY:<KEY>END_PIHkZt6fxPI:KEY:<KEY>END_PIfuPI:KEY:<KEY>END_PI"], "script_signature": "3045022100ad515b1bc1018817a174e6708eb24dbb24efe42a140b008b0b70d68bc4be46ee022003d9ffd685bac22be1c46a65a061ff8e9ca89663284a6bdcb06ba987e2c2a13301 03c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "script_signature_hex": "483045022100ad515b1bc1018817a174e6708eb24dbb24efe42a140b008b0b70d68bc4be46ee022003d9ffd685bac22be1c46a65a061ff8e9ca89663284a6bdcb06ba987e2c2a133012103c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "sequence": -1 }], "outputs": [{ "transaction_hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "output_index": 0, "value": 89000, "addresses": ["1KBTvmpXp3A2zhZrzuVLneEeUZJQ1qMzCF"], "script": "OP_DUP OP_HASH160 c76ce6beeb0884c9513bcf779144950f9525f8e9 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914c76ce6beeb0884c9513bcf779144950f9525f8e988ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "d1c90810c08827e26e33a9a7e5a37703d3cb55b155f3c6900f88743fe9e91421" }, { "transaction_hash": "a863b9a56c40c194c11eb9db9f3ea1f6ab472b02cc57679c50d16b4151c8a6e5", "output_index": 1, "value": 10000, "addresses": ["18tMkbibtxJPQoTPUv8s3mSXqYzEsrbeRb"], "script": "OP_DUP OP_HASH160 567f6acc93fe0349b604f45f46b540f55059abbb OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914567f6acc93fe0349b604f45f46b540f55059abbb88ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "b37dd0fa5e62497939367efee9a9cd90383473e798a260e20eb9a37ec05868a6" }], "fees": 1000, "amount": 99000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/3" tx3: "hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "block_hash": "00000000000000000d89f88366661b880e96aba60d083daac990fd21dd97fa5e", "block_height": 330757, "block_time": "2014-11-19T20:04:46Z", "chain_received_at": "2014-11-19T20:01:11.576Z", "confirmations": 30848, "lock_time": 0, "inputs": [{ "transaction_hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "output_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_index": 0, "value": 7437000, "addresses": ["1DZRBBjx2L1urJmzpwDoZH51gX2XSgwvk7"], "script_signature": "304402202db4e13f0b773a96d107e71ccaf69b44fb9a025ad80d79c4c672ffed573be75f022013f1f04c60393c614ce53d05063d8653db467c37bd0c626eb2ba4a93811ea14501 039d937dbef6142c4177152afad9ed93f81da538b48ba1f05bea87ef8064aff2e1", "script_signature_hex": "47304402202db4e13f0b773a96d107e71ccaf69b44fb9a025ad80d79c4c672ffed573be75f022013f1f04c60393c614ce53d05063d8653db467c37bd0c626eb2ba4a93811ea1450121039d937dbef6142c4177152afad9ed93f81da538b48ba1f05bea87ef8064aff2e1", "sequence": -1 }], "outputs": [{ "transaction_hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "output_index": 0, "value": 10000, "addresses": ["1KZB7aFfuZE2skJQPHH56VhSxUpUBjouwQ"], "script": "OP_DUP OP_HASH160 cb88045ebe75f5e94633d27dffca389cde381b78 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914cb88045ebe75f5e94633d27dffca389cde381b7888ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "115886c56fff5781bf6a0a1e36330d5f68ac814751bce71e41daf06868fbe446" }, { "transaction_hash": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721", "output_index": 1, "value": 7426000, "addresses": ["12XgKxQd5ZmeTjZVXiEpsGuoTr745GaHxF"], "script": "OP_DUP OP_HASH160 10c56ed9bad6951e36c3d49de11cd29928dc5669 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91410c56ed9bad6951e36c3d49de11cd29928dc566988ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "41b961f740f2577d8a489dc1ab34ae985e6b0f17e790705e3bc33a7d94dbb248" }], "fees": 1000, "amount": 7436000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/2" tx4: "hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "block_hash": "00000000000000000d89f88366661b880e96aba60d083daac990fd21dd97fa5e", "block_height": 330757, "block_time": "2014-11-19T20:04:46Z", "chain_received_at": "2014-11-19T19:57:43.888Z", "confirmations": 30848, "lock_time": 0, "inputs": [{ "transaction_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_hash": "e1f49c35c83cabbd7a20895de1d27cc374a4667ea40ccd2e27fe66ec574437b1", "output_index": 0, "value": 80000, "addresses": ["1FDJMgjuC7A4HkZt6fx8caFfuLDyp4YS9L"], "script_signature": "3044022011d5413262ea45452f40450da2e534775568f9680e4b342b5d6ae01e1d86a855022019b8a0517b195eeefcaba7f2a2e8c5d6d95e2b00eeca3d6bdd73c9fe0db68cc601 03c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "script_signature_hex": "473044022011d5413262ea45452f40450da2e534775568f9680e4b342b5d6ae01e1d86a855022019b8a0517b195eeefcaba7f2a2e8c5d6d95e2b00eeca3d6bdd73c9fe0db68cc6012103c966f445598dc9071a4c7030f940a2aacbcb7c892203886dbc1f77c76b79a134", "sequence": -1 }], "outputs": [{ "transaction_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_index": 0, "value": 69000, "addresses": ["18SxWu7S3Y4wtZG4eQ8fk8UERN2zko2i7Z"], "script": "OP_DUP OP_HASH160 51b19f1c87c6ad9a5eaa45dc48a67c2c63002311 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91451b19f1c87c6ad9a5eaa45dc48a67c2c6300231188ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "aa1a80314f077bd2c0e335464f983eef56dfeb0eb65c99464a0e5dbe2c25b7dc" }, { "transaction_hash": "4e23da1b1438939bc4f71bd6d8ec34a99bad83c3a68de6d8e278cdf306b48016", "output_index": 1, "value": 10000, "addresses": ["1GJr9FHZ1pbR4hjhX24M4L1BDUd2QogYYA"], "script": "OP_DUP OP_HASH160 a7e9fadcc36932a2d00e821f531584dcf65b917d OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a914a7e9fadcc36932a2d00e821f531584dcf65b917d88ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "115886c56fff5781bf6a0a1e36330d5f68ac814751bce71e41daf06868fbe446" }], "fees": 1000, "amount": 79000, "inputs_length": 1, "outputs_length": 2 # "44'/0'/0'/0/0" tx5: "hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "block_hash": "00000000000000001447d39f0d7a400879038d950d88ef4b2c24f4383446b071", "block_height": 330738, "block_time": "2014-11-19T17:52:51Z", "chain_received_at": "2014-11-19T17:19:45.940Z", "confirmations": 30867, "lock_time": 0, "inputs": [{ "transaction_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_hash": "a87463e2852ef5467a9d87b7a7d1095899d1e5893613d9f62b9d11c27630ef0a", "output_index": 1, "value": 7538000, "addresses": ["13VAufAUHFAZ4tKGUcZtvM5dgzgMcxgX1o"], "script_signature": "304402200dc547ac3c674aceba8442480432e36a26eac72f6515a3ce69b9eb8251af2a6802201fb47476886829f76c53e8be8fd096589b220dfbc879bf36b65294444412d66701 0322b82d653b864af6a7a27812c9b719b06b93a73e1c270ab4535843f9f6a04ebc", "script_signature_hex": "47304402200dc547ac3c674aceba8442480432e36a26eac72f6515a3ce69b9eb8251af2a6802201fb47476886829f76c53e8be8fd096589b220dfbc879bf36b65294444412d66701210322b82d653b864af6a7a27812c9b719b06b93a73e1c270ab4535843f9f6a04ebc", "sequence": -1 }], "outputs": [{ "transaction_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_index": 0, "value": 7437000, "addresses": ["1DZRBBjx2L1urJmzpwDoZH51gX2XSgwvk7"], "script": "OP_DUP OP_HASH160 89c3003f16a73b05429269807ad29ed5cb2dd096 OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a91489c3003f16a73b05429269807ad29ed5cb2dd09688ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "e43810f91bf8aa66f8558437d532410a0f62f3d3ee45417b6f6335ffcdb6c721" }, { "transaction_hash": "0b577adc127339768ca109550d3242e5a6a55367b376748d8f6f2b54cd7057e3", "output_index": 1, "value": 100000, "addresses": ["151krzHgfkNoH3XHBzEVi6tSn4db7pVjmR"], "script": "OP_DUP OP_HASH160 2c051dfed45971ba30473de4b4e57278bd9f001e OP_EQUALVERIFY OP_CHECKSIG", "script_hex": "76a9142c051dfed45971ba30473de4b4e57278bd9f001e88ac", "script_type": "pubkeyhash", "required_signatures": 1, "spent": true, "spending_transaction": "74c666f98467acccdf75de2bb1fbd8282c9be8afb25b438ab2d6354d6c689f62" }], "fees": 1000, "amount": 7537000, "inputs_length": 1, "outputs_length": 2
[ { "context": "na'\n\npayload = {\n \"headers\": {\n \"x-real-ip\": \"124.202.141.60\",\n \"x-forwarded-for\": \"124.202.141.60\",\n \"h", "end": 216, "score": 0.999721884727478, "start": 202, "tag": "IP_ADDRESS", "value": "124.202.141.60" }, { "context": "al-ip\": \"124.202...
test/services/oschina.coffee
jianliaoim/talk-services
40
should = require 'should' requireDir = require 'require-dir' loader = require '../../src/loader' {req} = require '../util' $oschina = loader.load 'oschina' payload = { "headers": { "x-real-ip": "124.202.141.60", "x-forwarded-for": "124.202.141.60", "host": "talk.ai", "x-nginx-proxy": "true", "connection": "Upgrade", "content-length": "994", "accept": "*/*; q=0.5, application/xml", "accept-encoding": "gzip, deflate", "content-type": "application/x-www-form-urlencoded", "user-agent": "Ruby" }, "query": {}, "body": { "hook": "{\"password\":\"tb123\",\"push_data\":{\"before\":\"fae5f9ec25e1424a733986c2ae0d241fd28556cc\",\"after\":\"cdc6e27f9b156a9693cb05369cee6a5686dd8f43\",\"ref\":\"master\",\"user_id\":39550,\"user_name\":\"garrett\",\"repository\":{\"name\":\"webcnn\",\"url\":\"git@git.oschina.net:344958185/webcnn.git\",\"description\":\"webcnn\",\"homepage\":\"http://git.oschina.net/344958185/webcnn\"},\"commits\":[{\"id\":\"cdc6e27f9b156a9693cb05369cee6a5686dd8f43\",\"message\":\"updated readme\",\"timestamp\":\"2015-07-01T10:14:51+08:00\",\"url\":\"http://git.oschina.net/344958185/webcnn/commit/cdc6e27f9b156a9693cb05369cee6a5686dd8f43\",\"author\":{\"name\":\"garrett\",\"email\":\"344958185@qq.com\",\"time\":\"2015-07-01T10:14:51+08:00\"}}],\"total_commits_count\":1}}" } } testWebhook = (payload) -> # Overwrite the sendMessage function of coding req.body = payload.body $oschina.then (oschina) -> oschina.receiveEvent 'service.webhook', req describe 'oschina#Webhook', -> req.integration = _id: '552cc903022844e6d8afb3b4' category: 'oschina' it 'receive zen', -> testWebhook {} .then (message) -> should(message).be.empty it 'receive push', -> testWebhook payload .then (message) -> message.attachments[0].data.title.should.eql '[webcnn] 提交了新的代码' message.attachments[0].data.text.should.eql [ '<a href="http://git.oschina.net/344958185/webcnn/commit/cdc6e27f9b156a9693cb05369cee6a5686dd8f43" target="_blank">' '<code>cdc6e2:</code></a> updated readme<br>' ].join '' message.attachments[0].data.redirectUrl.should.eql 'http://git.oschina.net/344958185/webcnn'
59045
should = require 'should' requireDir = require 'require-dir' loader = require '../../src/loader' {req} = require '../util' $oschina = loader.load 'oschina' payload = { "headers": { "x-real-ip": "192.168.3.11", "x-forwarded-for": "192.168.3.11", "host": "talk.ai", "x-nginx-proxy": "true", "connection": "Upgrade", "content-length": "994", "accept": "*/*; q=0.5, application/xml", "accept-encoding": "gzip, deflate", "content-type": "application/x-www-form-urlencoded", "user-agent": "Ruby" }, "query": {}, "body": { "hook": "{\"password\":\"<PASSWORD>\",\"push_data\":{\"before\":\"fae5f9ec25e1424a733986c2ae0d241fd28556cc\",\"after\":\"cdc6e27f9b156a9693cb05369cee6a5686dd8f43\",\"ref\":\"master\",\"user_id\":39550,\"user_name\":\"garrett\",\"repository\":{\"name\":\"webcnn\",\"url\":\"<EMAIL>:344958185/webcnn.git\",\"description\":\"webcnn\",\"homepage\":\"http://git.oschina.net/344958185/webcnn\"},\"commits\":[{\"id\":\"cdc6e27f9b156a9693cb05369cee6a5686dd8f43\",\"message\":\"updated readme\",\"timestamp\":\"2015-07-01T10:14:51+08:00\",\"url\":\"http://git.oschina.net/344958185/webcnn/commit/cdc6e27f9b156a9693cb05369cee6a5686dd<PASSWORD>\",\"author\":{\"name\":\"garrett\",\"email\":\"<EMAIL>\",\"time\":\"2015-07-01T10:14:51+08:00\"}}],\"total_commits_count\":1}}" } } testWebhook = (payload) -> # Overwrite the sendMessage function of coding req.body = payload.body $oschina.then (oschina) -> oschina.receiveEvent 'service.webhook', req describe 'oschina#Webhook', -> req.integration = _id: '552cc903022844e6d8afb3b4' category: 'oschina' it 'receive zen', -> testWebhook {} .then (message) -> should(message).be.empty it 'receive push', -> testWebhook payload .then (message) -> message.attachments[0].data.title.should.eql '[webcnn] 提交了新的代码' message.attachments[0].data.text.should.eql [ '<a href="http://git.oschina.net/344958185/webcnn/commit/cdc6e27f9b156a9693cb05369cee6a5686dd8f43" target="_blank">' '<code>cdc6e2:</code></a> updated readme<br>' ].join '' message.attachments[0].data.redirectUrl.should.eql 'http://git.oschina.net/344958185/webcnn'
true
should = require 'should' requireDir = require 'require-dir' loader = require '../../src/loader' {req} = require '../util' $oschina = loader.load 'oschina' payload = { "headers": { "x-real-ip": "PI:IP_ADDRESS:192.168.3.11END_PI", "x-forwarded-for": "PI:IP_ADDRESS:192.168.3.11END_PI", "host": "talk.ai", "x-nginx-proxy": "true", "connection": "Upgrade", "content-length": "994", "accept": "*/*; q=0.5, application/xml", "accept-encoding": "gzip, deflate", "content-type": "application/x-www-form-urlencoded", "user-agent": "Ruby" }, "query": {}, "body": { "hook": "{\"password\":\"PI:PASSWORD:<PASSWORD>END_PI\",\"push_data\":{\"before\":\"fae5f9ec25e1424a733986c2ae0d241fd28556cc\",\"after\":\"cdc6e27f9b156a9693cb05369cee6a5686dd8f43\",\"ref\":\"master\",\"user_id\":39550,\"user_name\":\"garrett\",\"repository\":{\"name\":\"webcnn\",\"url\":\"PI:EMAIL:<EMAIL>END_PI:344958185/webcnn.git\",\"description\":\"webcnn\",\"homepage\":\"http://git.oschina.net/344958185/webcnn\"},\"commits\":[{\"id\":\"cdc6e27f9b156a9693cb05369cee6a5686dd8f43\",\"message\":\"updated readme\",\"timestamp\":\"2015-07-01T10:14:51+08:00\",\"url\":\"http://git.oschina.net/344958185/webcnn/commit/cdc6e27f9b156a9693cb05369cee6a5686ddPI:PASSWORD:<PASSWORD>END_PI\",\"author\":{\"name\":\"garrett\",\"email\":\"PI:EMAIL:<EMAIL>END_PI\",\"time\":\"2015-07-01T10:14:51+08:00\"}}],\"total_commits_count\":1}}" } } testWebhook = (payload) -> # Overwrite the sendMessage function of coding req.body = payload.body $oschina.then (oschina) -> oschina.receiveEvent 'service.webhook', req describe 'oschina#Webhook', -> req.integration = _id: '552cc903022844e6d8afb3b4' category: 'oschina' it 'receive zen', -> testWebhook {} .then (message) -> should(message).be.empty it 'receive push', -> testWebhook payload .then (message) -> message.attachments[0].data.title.should.eql '[webcnn] 提交了新的代码' message.attachments[0].data.text.should.eql [ '<a href="http://git.oschina.net/344958185/webcnn/commit/cdc6e27f9b156a9693cb05369cee6a5686dd8f43" target="_blank">' '<code>cdc6e2:</code></a> updated readme<br>' ].join '' message.attachments[0].data.redirectUrl.should.eql 'http://git.oschina.net/344958185/webcnn'
[ { "context": "brous ->\n model1 = @model.sync.create name: 'Eric Cartman'\n model1.name = 'Stan Marsh'\n model2 = ", "end": 612, "score": 0.999852180480957, "start": 600, "tag": "NAME", "value": "Eric Cartman" }, { "context": ".create name: 'Eric Cartman'\n model1...
test/normal_schema/put/put_many.coffee
goodeggs/resource-schema
3
fibrous = require 'fibrous' mongoose = require 'mongoose' expect = require('chai').expect sinon = require 'sinon' {suite, given} = require '../../support/helpers' ResourceSchema = require '../../..' suite 'PUT many', ({withModel, withServer}) -> given 'valid request', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res', @resource.put(), @resource.send app beforeEach fibrous -> model1 = @model.sync.create name: 'Eric Cartman' model1.name = 'Stan Marsh' model2 = @model.sync.create name: 'Kyle Broflovski' model2.name = 'Kenny McCormick' @response = @request.sync.put "/res", json: [model1, model2] it '200s with the updated resource', -> expect(@response.statusCode).to.equal 200 expect(@response.body.length).to.equal 2 names = @response.body.map (model) -> model.name expect(names).to.contain 'Stan Marsh' expect(names).to.contain 'Kenny McCormick' it 'saves to the DB', fibrous -> modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 2 names = modelsFound.map (model) -> model.name expect(names).to.contain 'Stan Marsh' expect(names).to.contain 'Kenny McCormick' given 'PUT an empty array', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res', @resource.put(), @resource.send app beforeEach fibrous -> @response = @request.sync.put "/res", json: [] it '200s with an empty array', -> expect(@response.statusCode).to.equal 200 expect(@response.body).to.deep.equal [] given 'default on mongoose model', -> withModel (mongoose) -> mongoose.Schema name: {type: String, default: 'foo'} withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/bar', @resource.put(), @resource.send it 'uses the mongoose schema defaults', fibrous -> _id = new mongoose.Types.ObjectId() response = @request.sync.put "/bar", json: [{_id}] expect(response.body[0]).to.have.property '_id' expect(response.body[0]).to.have.property 'name', 'foo' given 'save hook on mongoose model', -> saveSpy = sinon.spy() withModel (mongoose) -> schema = mongoose.Schema name: String schema.pre 'save', (next) -> saveSpy() next() withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/fruit', @resource.put(), @resource.send beforeEach fibrous -> @apple = @model.sync.create name: 'apple' @banana = @model.sync.create name: 'banana' saveSpy.reset() it 'calls the save hook for each resource', fibrous -> @request.sync.put "/fruit", json: [{_id: @apple._id}, {_id: @banana._id}] expect(saveSpy.callCount).to.equal 2
10019
fibrous = require 'fibrous' mongoose = require 'mongoose' expect = require('chai').expect sinon = require 'sinon' {suite, given} = require '../../support/helpers' ResourceSchema = require '../../..' suite 'PUT many', ({withModel, withServer}) -> given 'valid request', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res', @resource.put(), @resource.send app beforeEach fibrous -> model1 = @model.sync.create name: '<NAME>' model1.name = '<NAME>' model2 = @model.sync.create name: '<NAME>' model2.name = '<NAME>' @response = @request.sync.put "/res", json: [model1, model2] it '200s with the updated resource', -> expect(@response.statusCode).to.equal 200 expect(@response.body.length).to.equal 2 names = @response.body.map (model) -> model.name expect(names).to.contain '<NAME>' expect(names).to.contain '<NAME>' it 'saves to the DB', fibrous -> modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 2 names = modelsFound.map (model) -> model.name expect(names).to.contain '<NAME>' expect(names).to.contain '<NAME>' given 'PUT an empty array', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res', @resource.put(), @resource.send app beforeEach fibrous -> @response = @request.sync.put "/res", json: [] it '200s with an empty array', -> expect(@response.statusCode).to.equal 200 expect(@response.body).to.deep.equal [] given 'default on mongoose model', -> withModel (mongoose) -> mongoose.Schema name: {type: String, default: 'foo'} withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/bar', @resource.put(), @resource.send it 'uses the mongoose schema defaults', fibrous -> _id = new mongoose.Types.ObjectId() response = @request.sync.put "/bar", json: [{_id}] expect(response.body[0]).to.have.property '_id' expect(response.body[0]).to.have.property 'name', 'foo' given 'save hook on mongoose model', -> saveSpy = sinon.spy() withModel (mongoose) -> schema = mongoose.Schema name: String schema.pre 'save', (next) -> saveSpy() next() withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/fruit', @resource.put(), @resource.send beforeEach fibrous -> @apple = @model.sync.create name: 'apple' @banana = @model.sync.create name: 'banana' saveSpy.reset() it 'calls the save hook for each resource', fibrous -> @request.sync.put "/fruit", json: [{_id: @apple._id}, {_id: @banana._id}] expect(saveSpy.callCount).to.equal 2
true
fibrous = require 'fibrous' mongoose = require 'mongoose' expect = require('chai').expect sinon = require 'sinon' {suite, given} = require '../../support/helpers' ResourceSchema = require '../../..' suite 'PUT many', ({withModel, withServer}) -> given 'valid request', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res', @resource.put(), @resource.send app beforeEach fibrous -> model1 = @model.sync.create name: 'PI:NAME:<NAME>END_PI' model1.name = 'PI:NAME:<NAME>END_PI' model2 = @model.sync.create name: 'PI:NAME:<NAME>END_PI' model2.name = 'PI:NAME:<NAME>END_PI' @response = @request.sync.put "/res", json: [model1, model2] it '200s with the updated resource', -> expect(@response.statusCode).to.equal 200 expect(@response.body.length).to.equal 2 names = @response.body.map (model) -> model.name expect(names).to.contain 'PI:NAME:<NAME>END_PI' expect(names).to.contain 'PI:NAME:<NAME>END_PI' it 'saves to the DB', fibrous -> modelsFound = @model.sync.find() expect(modelsFound.length).to.equal 2 names = modelsFound.map (model) -> model.name expect(names).to.contain 'PI:NAME:<NAME>END_PI' expect(names).to.contain 'PI:NAME:<NAME>END_PI' given 'PUT an empty array', -> withModel (mongoose) -> mongoose.Schema name: String beforeEach -> schema = { '_id', 'name' } @resource = new ResourceSchema @model, schema withServer (app) -> app.put '/res', @resource.put(), @resource.send app beforeEach fibrous -> @response = @request.sync.put "/res", json: [] it '200s with an empty array', -> expect(@response.statusCode).to.equal 200 expect(@response.body).to.deep.equal [] given 'default on mongoose model', -> withModel (mongoose) -> mongoose.Schema name: {type: String, default: 'foo'} withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/bar', @resource.put(), @resource.send it 'uses the mongoose schema defaults', fibrous -> _id = new mongoose.Types.ObjectId() response = @request.sync.put "/bar", json: [{_id}] expect(response.body[0]).to.have.property '_id' expect(response.body[0]).to.have.property 'name', 'foo' given 'save hook on mongoose model', -> saveSpy = sinon.spy() withModel (mongoose) -> schema = mongoose.Schema name: String schema.pre 'save', (next) -> saveSpy() next() withServer (app) -> @resource = new ResourceSchema @model, {'_id', 'name'} app.put '/fruit', @resource.put(), @resource.send beforeEach fibrous -> @apple = @model.sync.create name: 'apple' @banana = @model.sync.create name: 'banana' saveSpy.reset() it 'calls the save hook for each resource', fibrous -> @request.sync.put "/fruit", json: [{_id: @apple._id}, {_id: @banana._id}] expect(saveSpy.callCount).to.equal 2
[ { "context": "16))\n\n# TODO: Move this elswhere\nSpriteIds = {\n \"Abomasnow\": {\n \"default\": 460,\n \"mega\": NON_DEFAULT_F", "end": 1640, "score": 0.9964599013328552, "start": 1631, "tag": "NAME", "value": "Abomasnow" }, { "context": " \"mega\": NON_DEFAULT_FORMES_OFFSE...
client/app/js/helpers/images.coffee
sarenji/pokebattle-sim
5
@PokemonIconBackground = (species, forme) -> if not (typeof species == "string") pokemon = species species = pokemon.species || pokemon.get?("species") forme = pokemon.forme || pokemon.get?("forme") if species id = SpriteIds[species][forme] || SpriteIds[species]["default"] else id = 0 x = (id % 16) * 40 y = (id >> 4) * 32 "background-position: -#{x}px -#{y}px" @PokemonSprite = (id, forme, options = {}) -> if id instanceof Pokemon pokemon = id id = pokemon.getSpecies()?.id || 0 forme = pokemon.get('forme') options = { shiny: pokemon.get('shiny') } front = options.front ? true shiny = options.shiny ? false kind = (if front then "front" else "back") kind += "-s" if shiny id = "000#{id}".substr(-3) if forme && forme != 'default' then id += "-#{forme}" "//media.pokebattle.com/pksprites/#{kind}/#{id}.gif" @TypeSprite = (type) -> "//media.pokebattle.com/img/types/#{type.toLowerCase()}.png" @CategorySprite = (type) -> "//media.pokebattle.com/img/types/#{type.toLowerCase()}.png" @TargetSprite = (move) -> target = move.target if "distance" in move["flags"] && target == "selected-pokemon" target = "distance" "//media.pokebattle.com/img/targets/#{target.toLowerCase()}.png" @AchievementSprite = (achievement) -> "//media.pokebattle.com/achievements/#{achievement.medium_image}" generation = Generations[DEFAULT_GENERATION.toUpperCase()] maxSpeciesId = Math.max((p.id for n, p of generation.SpeciesData)...) NON_DEFAULT_FORMES_OFFSET = maxSpeciesId + (16 - ((maxSpeciesId + 1) % 16)) # TODO: Move this elswhere SpriteIds = { "Abomasnow": { "default": 460, "mega": NON_DEFAULT_FORMES_OFFSET + 142 }, "Abra": { "default": 63 }, "Absol": { "default": 359, "mega": NON_DEFAULT_FORMES_OFFSET + 137 }, "Accelgor": { "default": 617 }, "Aerodactyl": { "default": 142, "mega": NON_DEFAULT_FORMES_OFFSET + 122 }, "Aggron": { "default": 306, "mega": NON_DEFAULT_FORMES_OFFSET + 133 }, "Aipom": { "default": 190 }, "Alakazam": { "default": 65, "mega": NON_DEFAULT_FORMES_OFFSET + 117 }, "Alomomola": { "default": 594 }, "Altaria": { "default": 334 }, "Ambipom": { "default": 424 }, "Amoonguss": { "default": 591 }, "Ampharos": { "default": 181, "mega": NON_DEFAULT_FORMES_OFFSET + 125 }, "Anorith": { "default": 347 }, "Arbok": { "default": 24 }, "Arcanine": { "default": 59 }, "Arceus": { "default": 493 }, "Archen": { "default": 566 }, "Archeops": { "default": 567 }, "Ariados": { "default": 168 }, "Armaldo": { "default": 348 }, "Aron": { "default": 304 }, "Articuno": { "default": 144 }, "Audino": { "default": 531 }, "Axew": { "default": 610 }, "Azelf": { "default": 482 }, "Azumarill": { "default": 184 }, "Azurill": { "default": 298 }, "Bagon": { "default": 371 }, "Baltoy": { "default": 343 }, "Banette": { "default": 354, "mega": NON_DEFAULT_FORMES_OFFSET + 136 }, "Barboach": { "default": 339 }, "Basculin": { "default": 550, "blue-striped": NON_DEFAULT_FORMES_OFFSET + 78 }, "Bastiodon": { "default": 411 }, "Bayleef": { "default": 153 }, "Beartic": { "default": 614 }, "Beautifly": { "default": 267 }, "Beedrill": { "default": 15 }, "Beheeyem": { "default": 606 }, "Beldum": { "default": 374 }, "Bellossom": { "default": 182 }, "Bellsprout": { "default": 69 }, "Bibarel": { "default": 400 }, "Bidoof": { "default": 399 }, "Bisharp": { "default": 625 }, "Blastoise": { "default": 9, "mega": NON_DEFAULT_FORMES_OFFSET + 116 }, "Blaziken": { "default": 257, "mega": NON_DEFAULT_FORMES_OFFSET + 130 }, "Blissey": { "default": 242 }, "Blitzle": { "default": 522 }, "Boldore": { "default": 525 }, "Bonsly": { "default": 438 }, "Bouffalant": { "default": 626 }, "Braviary": { "default": 628 }, "Breloom": { "default": 286 }, "Bronzong": { "default": 437 }, "Bronzor": { "default": 436 }, "Budew": { "default": 406 }, "Buizel": { "default": 418 }, "Bulbasaur": { "default": 1 }, "Buneary": { "default": 427 }, "Burmy": { "default": 412, "sandy": NON_DEFAULT_FORMES_OFFSET + 9, "trash": NON_DEFAULT_FORMES_OFFSET + 10 }, "Butterfree": { "default": 12 }, "Cacnea": { "default": 331 }, "Cacturne": { "default": 332 }, "Camerupt": { "default": 323 }, "Carnivine": { "default": 455 }, "Carracosta": { "default": 565 }, "Carvanha": { "default": 318 }, "Cascoon": { "default": 268 }, "Castform": { "default": 351, "rainy": 49, "snowy": 50, "sunny": 51 }, "Caterpie": { "default": 10 }, "Celebi": { "default": 251 }, "Chandelure": { "default": 609 }, "Chansey": { "default": 113 }, "Charizard": { "default": 6, "mega-x": NON_DEFAULT_FORMES_OFFSET + 114, "mega-y": NON_DEFAULT_FORMES_OFFSET + 115 }, "Charmander": { "default": 4 }, "Charmeleon": { "default": 5 }, "Chatot": { "default": 441 }, "Cherrim": { "default": 421 }, "Cherubi": { "default": 420 }, "Chikorita": { "default": 152 }, "Chimchar": { "default": 390 }, "Chimecho": { "default": 358 }, "Chinchou": { "default": 170 }, "Chingling": { "default": 433 }, "Cinccino": { "default": 573 }, "Clamperl": { "default": 366 }, "Claydol": { "default": 344 }, "Clefable": { "default": 36 }, "Clefairy": { "default": 35 }, "Cleffa": { "default": 173 }, "Cloyster": { "default": 91 }, "Cobalion": { "default": 638 }, "Cofagrigus": { "default": 563 }, "Combee": { "default": 415 }, "Combusken": { "default": 256 }, "Conkeldurr": { "default": 534 }, "Corphish": { "default": 341 }, "Corsola": { "default": 222 }, "Cottonee": { "default": 546 }, "Cradily": { "default": 346 }, "Cranidos": { "default": 408 }, "Crawdaunt": { "default": 342 }, "Cresselia": { "default": 488 }, "Croagunk": { "default": 453 }, "Crobat": { "default": 169 }, "Croconaw": { "default": 159 }, "Crustle": { "default": 558 }, "Cryogonal": { "default": 615 }, "Cubchoo": { "default": 613 }, "Cubone": { "default": 104 }, "Cyndaquil": { "default": 155 }, "Darkrai": { "default": 491 }, "Darmanitan": { "default": 555, "zen": NON_DEFAULT_FORMES_OFFSET + 81 }, "Darumaka": { "default": 554 }, "Deerling": { "default": 585 }, "Deino": { "default": 633 }, "Delcatty": { "default": 301 }, "Delibird": { "default": 225 }, "Deoxys": { "default": 386, "attack": NON_DEFAULT_FORMES_OFFSET + 52, "defense": NON_DEFAULT_FORMES_OFFSET + 53, "speed": NON_DEFAULT_FORMES_OFFSET + 55 }, "Dewgong": { "default": 87 }, "Dewott": { "default": 502 }, "Dialga": { "default": 483 }, "Diglett": { "default": 50 }, "Ditto": { "default": 132 }, "Dodrio": { "default": 85 }, "Doduo": { "default": 84 }, "Donphan": { "default": 232 }, "Dragonair": { "default": 148 }, "Dragonite": { "default": 149 }, "Drapion": { "default": 452 }, "Dratini": { "default": 147 }, "Drifblim": { "default": 426 }, "Drifloon": { "default": 425 }, "Drilbur": { "default": 529 }, "Drowzee": { "default": 96 }, "Druddigon": { "default": 621 }, "Ducklett": { "default": 580 }, "Dugtrio": { "default": 51 }, "Dunsparce": { "default": 206 }, "Duosion": { "default": 578 }, "Durant": { "default": 632 }, "Dusclops": { "default": 356 }, "Dusknoir": { "default": 477 }, "Duskull": { "default": 355 }, "Dustox": { "default": 269 }, "Dwebble": { "default": 557 }, "Eelektrik": { "default": 603 }, "Eelektross": { "default": 604 }, "Eevee": { "default": 133 }, "Ekans": { "default": 23 }, "Electabuzz": { "default": 125 }, "Electivire": { "default": 466 }, "Electrike": { "default": 309 }, "Electrode": { "default": 101 }, "Elekid": { "default": 239 }, "Elgyem": { "default": 605 }, "Emboar": { "default": 500 }, "Emolga": { "default": 587 }, "Empoleon": { "default": 395 }, "Entei": { "default": 244 }, "Escavalier": { "default": 589 }, "Espeon": { "default": 196 }, "Excadrill": { "default": 530 }, "Exeggcute": { "default": 102 }, "Exeggutor": { "default": 103 }, "Exploud": { "default": 295 }, "Farfetch'd": { "default": 83 }, "Fearow": { "default": 22 }, "Feebas": { "default": 349 }, "Feraligatr": { "default": 160 }, "Ferroseed": { "default": 597 }, "Ferrothorn": { "default": 598 }, "Finneon": { "default": 456 }, "Flaaffy": { "default": 180 }, "Flareon": { "default": 136 }, "Floatzel": { "default": 419 }, "Flygon": { "default": 330 }, "Foongus": { "default": 590 }, "Forretress": { "default": 205 }, "Fraxure": { "default": 611 }, "Frillish": { "default": 592 }, "Froslass": { "default": 478 }, "Furret": { "default": 162 }, "Gabite": { "default": 444 }, "Gallade": { "default": 475 }, "Galvantula": { "default": 596 }, "Garbodor": { "default": 569 }, "Garchomp": { "default": 445, "mega": NON_DEFAULT_FORMES_OFFSET + 140 }, "Gardevoir": { "default": 282, "mega": NON_DEFAULT_FORMES_OFFSET + 131 }, "Gastly": { "default": 92 }, "Gastrodon": { "default": 423 }, "Genesect": { "default": 649 }, "Gengar": { "default": 94, "mega": NON_DEFAULT_FORMES_OFFSET + 118 }, "Geodude": { "default": 74 }, "Gible": { "default": 443 }, "Gigalith": { "default": 526 }, "Girafarig": { "default": 203 }, "Giratina": { "default": 487, "origin": NON_DEFAULT_FORMES_OFFSET + 74 }, "Glaceon": { "default": 471 }, "Glalie": { "default": 362 }, "Glameow": { "default": 431 }, "Gligar": { "default": 207 }, "Gliscor": { "default": 472 }, "Gloom": { "default": 44 }, "Golbat": { "default": 42 }, "Goldeen": { "default": 118 }, "Golduck": { "default": 55 }, "Golem": { "default": 76 }, "Golett": { "default": 622 }, "Golurk": { "default": 623 }, "Gorebyss": { "default": 368 }, "Gothita": { "default": 574 }, "Gothitelle": { "default": 576 }, "Gothorita": { "default": 575 }, "Granbull": { "default": 210 }, "Graveler": { "default": 75 }, "Grimer": { "default": 88 }, "Grotle": { "default": 388 }, "Groudon": { "default": 383 }, "Grovyle": { "default": 253 }, "Growlithe": { "default": 58 }, "Grumpig": { "default": 326 }, "Gulpin": { "default": 316 }, "Gurdurr": { "default": 533 }, "Gyarados": { "default": 130, "mega": NON_DEFAULT_FORMES_OFFSET + 121 }, "Happiny": { "default": 440 }, "Hariyama": { "default": 297 }, "Haunter": { "default": 93 }, "Haxorus": { "default": 612 }, "Heatmor": { "default": 631 }, "Heatran": { "default": 485 }, "Heracross": { "default": 214, "mega": NON_DEFAULT_FORMES_OFFSET + 127 }, "Herdier": { "default": 507 }, "Hippopotas": { "default": 449 }, "Hippowdon": { "default": 450 }, "Hitmonchan": { "default": 107 }, "Hitmonlee": { "default": 106 }, "Hitmontop": { "default": 237 }, "Ho-Oh": { "default": 250 }, "Honchkrow": { "default": 430 }, "Hoothoot": { "default": 163 }, "Hoppip": { "default": 187 }, "Horsea": { "default": 116 }, "Houndoom": { "default": 229, "mega": NON_DEFAULT_FORMES_OFFSET + 128 }, "Houndour": { "default": 228 }, "Huntail": { "default": 367 }, "Hydreigon": { "default": 635 }, "Hypno": { "default": 97 }, "Igglybuff": { "default": 174 }, "Illumise": { "default": 314 }, "Infernape": { "default": 392 }, "Ivysaur": { "default": 2 }, "Jellicent": { "default": 593 }, "Jigglypuff": { "default": 39 }, "Jirachi": { "default": 385 }, "Jolteon": { "default": 135 }, "Joltik": { "default": 595 }, "Jumpluff": { "default": 189 }, "Jynx": { "default": 124 }, "Kabuto": { "default": 140 }, "Kabutops": { "default": 141 }, "Kadabra": { "default": 64 }, "Kakuna": { "default": 14 }, "Kangaskhan": { "default": 115, "mega": NON_DEFAULT_FORMES_OFFSET + 119 }, "Karrablast": { "default": 588 }, "Kecleon": { "default": 352 }, "Keldeo": { "default": 647, "resolute": NON_DEFAULT_FORMES_OFFSET + 103 }, "Kingdra": { "default": 230 }, "Kingler": { "default": 99 }, "Kirlia": { "default": 281 }, "Klang": { "default": 600 }, "Klink": { "default": 599 }, "Klinklang": { "default": 601 }, "Koffing": { "default": 109 }, "Krabby": { "default": 98 }, "Kricketot": { "default": 401 }, "Kricketune": { "default": 402 }, "Krokorok": { "default": 552 }, "Krookodile": { "default": 553 }, "Kyogre": { "default": 382 }, "Kyurem": { "default": 646, "black": NON_DEFAULT_FORMES_OFFSET + 101, "white": NON_DEFAULT_FORMES_OFFSET + 102 }, "Lairon": { "default": 305 }, "Lampent": { "default": 608 }, "Landorus": { "default": 645, "therian": NON_DEFAULT_FORMES_OFFSET + 100 }, "Lanturn": { "default": 171 }, "Lapras": { "default": 131 }, "Larvesta": { "default": 636 }, "Larvitar": { "default": 246 }, "Latias": { "default": 380, "mega": NON_DEFAULT_FORMES_OFFSET + 138 }, "Latios": { "default": 381, "mega": NON_DEFAULT_FORMES_OFFSET + 139 }, "Leafeon": { "default": 470 }, "Leavanny": { "default": 542 }, "Ledian": { "default": 166 }, "Ledyba": { "default": 165 }, "Lickilicky": { "default": 463 }, "Lickitung": { "default": 108 }, "Liepard": { "default": 510 }, "Lileep": { "default": 345 }, "Lilligant": { "default": 549 }, "Lillipup": { "default": 506 }, "Linoone": { "default": 264 }, "Litwick": { "default": 607 }, "Lombre": { "default": 271 }, "Lopunny": { "default": 428 }, "Lotad": { "default": 270 }, "Loudred": { "default": 294 }, "Lucario": { "default": 448, "mega": NON_DEFAULT_FORMES_OFFSET + 141 }, "Ludicolo": { "default": 272 }, "Lugia": { "default": 249 }, "Lumineon": { "default": 457 }, "Lunatone": { "default": 337 }, "Luvdisc": { "default": 370 }, "Luxio": { "default": 404 }, "Luxray": { "default": 405 }, "Machamp": { "default": 68 }, "Machoke": { "default": 67 }, "Machop": { "default": 66 }, "Magby": { "default": 240 }, "Magcargo": { "default": 219 }, "Magikarp": { "default": 129 }, "Magmar": { "default": 126 }, "Magmortar": { "default": 467 }, "Magnemite": { "default": 81 }, "Magneton": { "default": 82 }, "Magnezone": { "default": 462 }, "Makuhita": { "default": 296 }, "Mamoswine": { "default": 473 }, "Manaphy": { "default": 490 }, "Mandibuzz": { "default": 630 }, "Manectric": { "default": 310, "mega": NON_DEFAULT_FORMES_OFFSET + 135 }, "Mankey": { "default": 56 }, "Mantine": { "default": 226 }, "Mantyke": { "default": 458 }, "Maractus": { "default": 556 }, "Mareep": { "default": 179 }, "Marill": { "default": 183 }, "Marowak": { "default": 105 }, "Marshtomp": { "default": 259 }, "Masquerain": { "default": 284 }, "Mawile": { "default": 303, "mega": NON_DEFAULT_FORMES_OFFSET + 132 }, "Medicham": { "default": 308, "mega": NON_DEFAULT_FORMES_OFFSET + 134 }, "Meditite": { "default": 307 }, "Meganium": { "default": 154 }, "Meloetta": { "default": 648, "pirouette": NON_DEFAULT_FORMES_OFFSET + 93 }, "Meowth": { "default": 52 }, "Mesprit": { "default": 481 }, "Metagross": { "default": 376 }, "Metang": { "default": 375 }, "Metapod": { "default": 11 }, "Mew": { "default": 151 }, "Mewtwo": { "default": 150, "mega-x": NON_DEFAULT_FORMES_OFFSET + 123 "mega-y": NON_DEFAULT_FORMES_OFFSET + 124 }, "Mienfoo": { "default": 619 }, "Mienshao": { "default": 620 }, "Mightyena": { "default": 262 }, "Milotic": { "default": 350 }, "Miltank": { "default": 241 }, "Mime Jr.": { "default": 439 }, "Minccino": { "default": 572 }, "Minun": { "default": 312 }, "Misdreavus": { "default": 200 }, "Mismagius": { "default": 429 }, "Moltres": { "default": 146 }, "Monferno": { "default": 391 }, "Mothim": { "default": 414 }, "Mr. Mime": { "default": 122 }, "Mudkip": { "default": 258 }, "Muk": { "default": 89 }, "Munchlax": { "default": 446 }, "Munna": { "default": 517 }, "Murkrow": { "default": 198 }, "Musharna": { "default": 518 }, "Natu": { "default": 177 }, "Nidoking": { "default": 34 }, "Nidoqueen": { "default": 31 }, "Nidoran♀": { "default": 29 }, "Nidoran♂": { "default": 32 }, "Nidorina": { "default": 30 }, "Nidorino": { "default": 33 }, "Nincada": { "default": 290 }, "Ninetales": { "default": 38 }, "Ninjask": { "default": 291 }, "Noctowl": { "default": 164 }, "Nosepass": { "default": 299 }, "Numel": { "default": 322 }, "Nuzleaf": { "default": 274 }, "Octillery": { "default": 224 }, "Oddish": { "default": 43 }, "Omanyte": { "default": 138 }, "Omastar": { "default": 139 }, "Onix": { "default": 95 }, "Oshawott": { "default": 501 }, "Pachirisu": { "default": 417 }, "Palkia": { "default": 484 }, "Palpitoad": { "default": 536 }, "Panpour": { "default": 515 }, "Pansage": { "default": 511 }, "Pansear": { "default": 513 }, "Paras": { "default": 46 }, "Parasect": { "default": 47 }, "Patrat": { "default": 504 }, "Pawniard": { "default": 624 }, "Pelipper": { "default": 279 }, "Persian": { "default": 53 }, "Petilil": { "default": 548 }, "Phanpy": { "default": 231 }, "Phione": { "default": 489 }, "Pichu": { "default": 172 }, "Pidgeot": { "default": 18 }, "Pidgeotto": { "default": 17 }, "Pidgey": { "default": 16 }, "Pidove": { "default": 519 }, "Pignite": { "default": 499 }, "Pikachu": { "default": 25 }, "Piloswine": { "default": 221 }, "Pineco": { "default": 204 }, "Pinsir": { "default": 127, "mega": NON_DEFAULT_FORMES_OFFSET + 120 }, "Piplup": { "default": 393 }, "Plusle": { "default": 311 }, "Politoed": { "default": 186 }, "Poliwag": { "default": 60 }, "Poliwhirl": { "default": 61 }, "Poliwrath": { "default": 62 }, "Ponyta": { "default": 77 }, "Poochyena": { "default": 261 }, "Porygon": { "default": 137 }, "Porygon-Z": { "default": 474 }, "Porygon2": { "default": 233 }, "Primeape": { "default": 57 }, "Prinplup": { "default": 394 }, "Probopass": { "default": 476 }, "Psyduck": { "default": 54 }, "Pupitar": { "default": 247 }, "Purrloin": { "default": 509 }, "Purugly": { "default": 432 }, "Quagsire": { "default": 195 }, "Quilava": { "default": 156 }, "Qwilfish": { "default": 211 }, "Raichu": { "default": 26 }, "Raikou": { "default": 243 }, "Ralts": { "default": 280 }, "Rampardos": { "default": 409 }, "Rapidash": { "default": 78 }, "Raticate": { "default": 20 }, "Rattata": { "default": 19 }, "Rayquaza": { "default": 384 }, "Regice": { "default": 378 }, "Regigigas": { "default": 486 }, "Regirock": { "default": 377 }, "Registeel": { "default": 379 }, "Relicanth": { "default": 369 }, "Remoraid": { "default": 223 }, "Reshiram": { "default": 643 }, "Reuniclus": { "default": 579 }, "Rhydon": { "default": 112 }, "Rhyhorn": { "default": 111 }, "Rhyperior": { "default": 464 }, "Riolu": { "default": 447 }, "Roggenrola": { "default": 524 }, "Roselia": { "default": 315 }, "Roserade": { "default": 407 }, "Rotom": { "default": 479, "fan": NON_DEFAULT_FORMES_OFFSET + 68, "frost": NON_DEFAULT_FORMES_OFFSET + 69, "heat": NON_DEFAULT_FORMES_OFFSET + 70, "mow": NON_DEFAULT_FORMES_OFFSET + 71, "wash": NON_DEFAULT_FORMES_OFFSET + 72 }, "Rufflet": { "default": 627 }, "Sableye": { "default": 302 }, "Salamence": { "default": 373 }, "Samurott": { "default": 503 }, "Sandile": { "default": 551 }, "Sandshrew": { "default": 27 }, "Sandslash": { "default": 28 }, "Sawk": { "default": 539 }, "Sawsbuck": { "default": 586 }, "Sceptile": { "default": 254 }, "Scizor": { "default": 212, "mega": NON_DEFAULT_FORMES_OFFSET + 126 }, "Scolipede": { "default": 545 }, "Scrafty": { "default": 560 }, "Scraggy": { "default": 559 }, "Scyther": { "default": 123 }, "Seadra": { "default": 117 }, "Seaking": { "default": 119 }, "Sealeo": { "default": 364 }, "Seedot": { "default": 273 }, "Seel": { "default": 86 }, "Seismitoad": { "default": 537 }, "Sentret": { "default": 161 }, "Serperior": { "default": 497 }, "Servine": { "default": 496 }, "Seviper": { "default": 336 }, "Sewaddle": { "default": 540 }, "Sharpedo": { "default": 319 }, "Shaymin": { "default": 492, "sky": NON_DEFAULT_FORMES_OFFSET + 76 }, "Shedinja": { "default": 292 }, "Shelgon": { "default": 372 }, "Shellder": { "default": 90 }, "Shellos": { "default": 422 }, "Shelmet": { "default": 616 }, "Shieldon": { "default": 410 }, "Shiftry": { "default": 275 }, "Shinx": { "default": 403 }, "Shroomish": { "default": 285 }, "Shuckle": { "default": 213 }, "Shuppet": { "default": 353 }, "Sigilyph": { "default": 561 }, "Silcoon": { "default": 266 }, "Simipour": { "default": 516 }, "Simisage": { "default": 512 }, "Simisear": { "default": 514 }, "Skarmory": { "default": 227 }, "Skiploom": { "default": 188 }, "Skitty": { "default": 300 }, "Skorupi": { "default": 451 }, "Skuntank": { "default": 435 }, "Slaking": { "default": 289 }, "Slakoth": { "default": 287 }, "Slowbro": { "default": 80 }, "Slowking": { "default": 199 }, "Slowpoke": { "default": 79 }, "Slugma": { "default": 218 }, "Smeargle": { "default": 235 }, "Smoochum": { "default": 238 }, "Sneasel": { "default": 215 }, "Snivy": { "default": 495 }, "Snorlax": { "default": 143 }, "Snorunt": { "default": 361 }, "Snover": { "default": 459 }, "Snubbull": { "default": 209 }, "Solosis": { "default": 577 }, "Solrock": { "default": 338 }, "Spearow": { "default": 21 }, "Spheal": { "default": 363 }, "Spinarak": { "default": 167 }, "Spinda": { "default": 327 }, "Spiritomb": { "default": 442 }, "Spoink": { "default": 325 }, "Squirtle": { "default": 7 }, "Stantler": { "default": 234 }, "Staraptor": { "default": 398 }, "Staravia": { "default": 397 }, "Starly": { "default": 396 }, "Starmie": { "default": 121 }, "Staryu": { "default": 120 }, "Steelix": { "default": 208 }, "Stoutland": { "default": 508 }, "Stunfisk": { "default": 618 }, "Stunky": { "default": 434 }, "Sudowoodo": { "default": 185 }, "Suicune": { "default": 245 }, "Sunflora": { "default": 192 }, "Sunkern": { "default": 191 }, "Surskit": { "default": 283 }, "Swablu": { "default": 333 }, "Swadloon": { "default": 541 }, "Swalot": { "default": 317 }, "Swampert": { "default": 260 }, "Swanna": { "default": 581 }, "Swellow": { "default": 277 }, "Swinub": { "default": 220 }, "Swoobat": { "default": 528 }, "Taillow": { "default": 276 }, "Tangela": { "default": 114 }, "Tangrowth": { "default": 465 }, "Tauros": { "default": 128 }, "Teddiursa": { "default": 216 }, "Tentacool": { "default": 72 }, "Tentacruel": { "default": 73 }, "Tepig": { "default": 498 }, "Terrakion": { "default": 639 }, "Throh": { "default": 538 }, "Thundurus": { "default": 642, "therian": NON_DEFAULT_FORMES_OFFSET + 99 }, "Timburr": { "default": 532 }, "Tirtouga": { "default": 564 }, "Togekiss": { "default": 468 }, "Togepi": { "default": 175 }, "Togetic": { "default": 176 }, "Torchic": { "default": 255 }, "Torkoal": { "default": 324 }, "Tornadus": { "default": 641, "therian": NON_DEFAULT_FORMES_OFFSET + 98 }, "Torterra": { "default": 389 }, "Totodile": { "default": 158 }, "Toxicroak": { "default": 454 }, "Tranquill": { "default": 520 }, "Trapinch": { "default": 328 }, "Treecko": { "default": 252 }, "Tropius": { "default": 357 }, "Trubbish": { "default": 568 }, "Turtwig": { "default": 387 }, "Tympole": { "default": 535 }, "Tynamo": { "default": 602 }, "Typhlosion": { "default": 157 }, "Tyranitar": { "default": 248, "mega": NON_DEFAULT_FORMES_OFFSET + 129 }, "Tyrogue": { "default": 236 }, "Umbreon": { "default": 197 }, "Unfezant": { "default": 521 }, "Unown": { "default": 201 }, "Ursaring": { "default": 217 }, "Uxie": { "default": 480 }, "Vanillish": { "default": 583 }, "Vanillite": { "default": 582 }, "Vanilluxe": { "default": 584 }, "Vaporeon": { "default": 134 }, "Venipede": { "default": 543 }, "Venomoth": { "default": 49 }, "Venonat": { "default": 48 }, "Venusaur": { "default": 3, "mega": NON_DEFAULT_FORMES_OFFSET + 113 }, "Vespiquen": { "default": 416 }, "Vibrava": { "default": 329 }, "Victini": { "default": 494 }, "Victreebel": { "default": 71 }, "Vigoroth": { "default": 288 }, "Vileplume": { "default": 45 }, "Virizion": { "default": 640 }, "Volbeat": { "default": 313 }, "Volcarona": { "default": 637 }, "Voltorb": { "default": 100 }, "Vullaby": { "default": 629 }, "Vulpix": { "default": 37 }, "Wailmer": { "default": 320 }, "Wailord": { "default": 321 }, "Walrein": { "default": 365 }, "Wartortle": { "default": 8 }, "Watchog": { "default": 505 }, "Weavile": { "default": 461 }, "Weedle": { "default": 13 }, "Weepinbell": { "default": 70 }, "Weezing": { "default": 110 }, "Whimsicott": { "default": 547 }, "Whirlipede": { "default": 544 }, "Whiscash": { "default": 340 }, "Whismur": { "default": 293 }, "Wigglytuff": { "default": 40 }, "Wingull": { "default": 278 }, "Wobbuffet": { "default": 202 }, "Woobat": { "default": 527 }, "Wooper": { "default": 194 }, "Wormadam": { "default": 413, "sandy": NON_DEFAULT_FORMES_OFFSET + 60, "trash": NON_DEFAULT_FORMES_OFFSET + 61 }, "Wurmple": { "default": 265 }, "Wynaut": { "default": 360 }, "Xatu": { "default": 178 }, "Yamask": { "default": 562 }, "Yanma": { "default": 193 }, "Yanmega": { "default": 469 }, "Zangoose": { "default": 335 }, "Zapdos": { "default": 145 }, "Zebstrika": { "default": 523 }, "Zekrom": { "default": 644 }, "Zigzagoon": { "default": 263 }, "Zoroark": { "default": 571 }, "Zorua": { "default": 570 }, "Zubat": { "default": 41 }, "Zweilous": { "default": 634 }, "Aegislash": { "default": 681, "blade": NON_DEFAULT_FORMES_OFFSET + 106 }, "Amaura": { "default": 698 }, "Aromatisse": { "default": 683 }, "Aurorus": { "default": 699 }, "Avalugg": { "default": 713 }, "Barbaracle": { "default": 689 }, "Bergmite": { "default": 712 }, "Binacle": { "default": 688 }, "Braixen": { "default": 654 }, "Bunnelby": { "default": 659 }, "Carbink": { "default": 703 }, "Chesnaught": { "default": 652 }, "Chespin": { "default": 650 }, "Clawitzer": { "default": 693 }, "Clauncher": { "default": 692 }, "Dedenne": { "default": 702 }, "Delphox": { "default": 655 }, "Diancie": { "default": 719 }, "Diggersby": { "default": 660 }, "Doublade": { "default": 680 }, "Dragalge": { "default": 691 }, "Espurr": { "default": 677 }, "Fennekin": { "default": 653 }, "Flabébé": { "default": 669 }, "Fletchinder": { "default": 662 }, "Fletchling": { "default": 661 }, "Floette": { "default": 670 }, "Florges": { "default": 671 }, "Froakie": { "default": 656 }, "Frogadier": { "default": 657 }, "Furfrou": { "default": 676 }, "Gogoat": { "default": 673 }, "Goodra": { "default": 706 }, "Goomy": { "default": 704 }, "Gourgeist": { "default": 711 }, "Greninja": { "default": 658 }, "Hawlucha": { "default": 701 }, "Heliolisk": { "default": 695 }, "Helioptile": { "default": 694 }, "Honedge": { "default": 679 }, "Hoopa": { "default": 720 }, "Inkay": { "default": 686 }, "Klefki": { "default": 707 }, "Litleo": { "default": 667 }, "Malamar": { "default": 687 }, "Meowstic": { "default": 678, "female": NON_DEFAULT_FORMES_OFFSET + 105 }, "Noibat": { "default": 714 }, "Noivern": { "default": 715 }, "Pancham": { "default": 674 }, "Pangoro": { "default": 675 }, "Phantump": { "default": 708 }, "Pumpkaboo": { "default": 710 }, "Pyroar": { "default": 668 }, "Quilladin": { "default": 651 }, "Scatterbug": { "default": 664 }, "Skiddo": { "default": 672 }, "Skrelp": { "default": 690 }, "Sliggoo": { "default": 705 }, "Slurpuff": { "default": 685 }, "Spewpa": { "default": 665 }, "Spritzee": { "default": 682 }, "Swirlix": { "default": 684 }, "Sylveon": { "default": 700 }, "Talonflame": { "default": 663 }, "Trevenant": { "default": 709 }, "Tyrantrum": { "default": 697 }, "Tyrunt": { "default": 696 }, "Vivillon": { "default": 666 }, "Volcanion": { "default": 721 }, "Xerneas": { "default": 716 }, "Yveltal": { "default": 717 }, "Zygarde": { "default": 718 } }
46695
@PokemonIconBackground = (species, forme) -> if not (typeof species == "string") pokemon = species species = pokemon.species || pokemon.get?("species") forme = pokemon.forme || pokemon.get?("forme") if species id = SpriteIds[species][forme] || SpriteIds[species]["default"] else id = 0 x = (id % 16) * 40 y = (id >> 4) * 32 "background-position: -#{x}px -#{y}px" @PokemonSprite = (id, forme, options = {}) -> if id instanceof Pokemon pokemon = id id = pokemon.getSpecies()?.id || 0 forme = pokemon.get('forme') options = { shiny: pokemon.get('shiny') } front = options.front ? true shiny = options.shiny ? false kind = (if front then "front" else "back") kind += "-s" if shiny id = "000#{id}".substr(-3) if forme && forme != 'default' then id += "-#{forme}" "//media.pokebattle.com/pksprites/#{kind}/#{id}.gif" @TypeSprite = (type) -> "//media.pokebattle.com/img/types/#{type.toLowerCase()}.png" @CategorySprite = (type) -> "//media.pokebattle.com/img/types/#{type.toLowerCase()}.png" @TargetSprite = (move) -> target = move.target if "distance" in move["flags"] && target == "selected-pokemon" target = "distance" "//media.pokebattle.com/img/targets/#{target.toLowerCase()}.png" @AchievementSprite = (achievement) -> "//media.pokebattle.com/achievements/#{achievement.medium_image}" generation = Generations[DEFAULT_GENERATION.toUpperCase()] maxSpeciesId = Math.max((p.id for n, p of generation.SpeciesData)...) NON_DEFAULT_FORMES_OFFSET = maxSpeciesId + (16 - ((maxSpeciesId + 1) % 16)) # TODO: Move this elswhere SpriteIds = { "<NAME>": { "default": 460, "mega": NON_DEFAULT_FORMES_OFFSET + 142 }, "<NAME>": { "default": 63 }, "<NAME>": { "default": 359, "mega": NON_DEFAULT_FORMES_OFFSET + 137 }, "<NAME>": { "default": 617 }, "<NAME>": { "default": 142, "mega": NON_DEFAULT_FORMES_OFFSET + 122 }, "<NAME>": { "default": 306, "mega": NON_DEFAULT_FORMES_OFFSET + 133 }, "<NAME>": { "default": 190 }, "<NAME>": { "default": 65, "mega": NON_DEFAULT_FORMES_OFFSET + 117 }, "<NAME>": { "default": 594 }, "<NAME>": { "default": 334 }, "<NAME>": { "default": 424 }, "<NAME>": { "default": 591 }, "<NAME>": { "default": 181, "mega": NON_DEFAULT_FORMES_OFFSET + 125 }, "<NAME>": { "default": 347 }, "<NAME>": { "default": 24 }, "<NAME>": { "default": 59 }, "<NAME>": { "default": 493 }, "<NAME>": { "default": 566 }, "<NAME>": { "default": 567 }, "<NAME>": { "default": 168 }, "<NAME>": { "default": 348 }, "<NAME>": { "default": 304 }, "<NAME>": { "default": 144 }, "<NAME>": { "default": 531 }, "<NAME>": { "default": 610 }, "<NAME>": { "default": 482 }, "<NAME>": { "default": 184 }, "<NAME>": { "default": 298 }, "<NAME>": { "default": 371 }, "<NAME>": { "default": 343 }, "<NAME>": { "default": 354, "mega": NON_DEFAULT_FORMES_OFFSET + 136 }, "<NAME>": { "default": 339 }, "<NAME>": { "default": 550, "blue-striped": NON_DEFAULT_FORMES_OFFSET + 78 }, "<NAME>": { "default": 411 }, "<NAME>": { "default": 153 }, "<NAME>": { "default": 614 }, "<NAME>": { "default": 267 }, "<NAME>": { "default": 15 }, "<NAME>": { "default": 606 }, "<NAME>": { "default": 374 }, "<NAME>": { "default": 182 }, "<NAME>": { "default": 69 }, "<NAME>": { "default": 400 }, "<NAME>": { "default": 399 }, "<NAME>": { "default": 625 }, "<NAME>": { "default": 9, "mega": NON_DEFAULT_FORMES_OFFSET + 116 }, "<NAME>": { "default": 257, "mega": NON_DEFAULT_FORMES_OFFSET + 130 }, "<NAME>": { "default": 242 }, "<NAME>": { "default": 522 }, "<NAME>": { "default": 525 }, "<NAME>": { "default": 438 }, "<NAME>": { "default": 626 }, "<NAME>": { "default": 628 }, "<NAME>": { "default": 286 }, "<NAME>": { "default": 437 }, "<NAME>": { "default": 436 }, "<NAME>": { "default": 406 }, "<NAME>": { "default": 418 }, "<NAME>basaur": { "default": 1 }, "<NAME>": { "default": 427 }, "<NAME>": { "default": 412, "sandy": NON_DEFAULT_FORMES_OFFSET + 9, "trash": NON_DEFAULT_FORMES_OFFSET + 10 }, "<NAME>": { "default": 12 }, "<NAME>": { "default": 331 }, "<NAME>": { "default": 332 }, "<NAME>": { "default": 323 }, "<NAME>": { "default": 455 }, "<NAME>": { "default": 565 }, "<NAME>": { "default": 318 }, "<NAME>": { "default": 268 }, "<NAME>": { "default": 351, "rainy": 49, "snowy": 50, "sunny": 51 }, "<NAME>": { "default": 10 }, "<NAME>": { "default": 251 }, "<NAME>": { "default": 609 }, "<NAME>": { "default": 113 }, "<NAME>": { "default": 6, "mega-x": NON_DEFAULT_FORMES_OFFSET + 114, "mega-y": NON_DEFAULT_FORMES_OFFSET + 115 }, "<NAME>": { "default": 4 }, "<NAME>": { "default": 5 }, "<NAME>": { "default": 441 }, "<NAME>": { "default": 421 }, "<NAME>": { "default": 420 }, "<NAME>": { "default": 152 }, "<NAME>": { "default": 390 }, "<NAME>": { "default": 358 }, "<NAME>": { "default": 170 }, "<NAME>": { "default": 433 }, "<NAME>": { "default": 573 }, "<NAME>": { "default": 366 }, "<NAME>": { "default": 344 }, "<NAME>": { "default": 36 }, "<NAME>": { "default": 35 }, "<NAME>": { "default": 173 }, "<NAME>": { "default": 91 }, "<NAME>": { "default": 638 }, "<NAME>": { "default": 563 }, "<NAME>": { "default": 415 }, "<NAME>": { "default": 256 }, "<NAME>": { "default": 534 }, "<NAME>": { "default": 341 }, "<NAME>": { "default": 222 }, "<NAME>": { "default": 546 }, "<NAME>": { "default": 346 }, "<NAME>": { "default": 408 }, "<NAME>": { "default": 342 }, "<NAME>": { "default": 488 }, "<NAME>": { "default": 453 }, "<NAME>": { "default": 169 }, "<NAME>": { "default": 159 }, "<NAME>": { "default": 558 }, "<NAME>": { "default": 615 }, "<NAME>": { "default": 613 }, "<NAME>": { "default": 104 }, "<NAME>": { "default": 155 }, "<NAME>": { "default": 491 }, "<NAME>": { "default": 555, "zen": NON_DEFAULT_FORMES_OFFSET + 81 }, "<NAME>": { "default": 554 }, "<NAME>": { "default": 585 }, "<NAME>": { "default": 633 }, "<NAME>": { "default": 301 }, "<NAME>": { "default": 225 }, "<NAME>": { "default": 386, "attack": NON_DEFAULT_FORMES_OFFSET + 52, "defense": NON_DEFAULT_FORMES_OFFSET + 53, "speed": NON_DEFAULT_FORMES_OFFSET + 55 }, "<NAME>": { "default": 87 }, "<NAME>": { "default": 502 }, "<NAME>": { "default": 483 }, "<NAME>": { "default": 50 }, "<NAME>": { "default": 132 }, "<NAME>": { "default": 85 }, "<NAME>": { "default": 84 }, "<NAME>": { "default": 232 }, "<NAME>": { "default": 148 }, "<NAME>": { "default": 149 }, "<NAME>": { "default": 452 }, "<NAME>": { "default": 147 }, "<NAME>": { "default": 426 }, "<NAME>": { "default": 425 }, "<NAME>": { "default": 529 }, "<NAME>": { "default": 96 }, "<NAME>": { "default": 621 }, "<NAME>": { "default": 580 }, "<NAME>": { "default": 51 }, "<NAME>": { "default": 206 }, "<NAME>": { "default": 578 }, "<NAME>": { "default": 632 }, "<NAME>": { "default": 356 }, "<NAME>": { "default": 477 }, "<NAME>": { "default": 355 }, "<NAME>": { "default": 269 }, "<NAME>": { "default": 557 }, "<NAME>": { "default": 603 }, "<NAME>": { "default": 604 }, "<NAME>": { "default": 133 }, "<NAME>": { "default": 23 }, "<NAME>": { "default": 125 }, "<NAME>": { "default": 466 }, "<NAME>": { "default": 309 }, "<NAME>": { "default": 101 }, "<NAME>": { "default": 239 }, "<NAME>": { "default": 605 }, "<NAME>": { "default": 500 }, "<NAME>": { "default": 587 }, "<NAME>": { "default": 395 }, "<NAME>": { "default": 244 }, "<NAME>": { "default": 589 }, "<NAME>": { "default": 196 }, "<NAME>": { "default": 530 }, "<NAME>eggcute": { "default": 102 }, "Exeggutor": { "default": 103 }, "<NAME>": { "default": 295 }, "<NAME>": { "default": 83 }, "<NAME>": { "default": 22 }, "<NAME>": { "default": 349 }, "<NAME>": { "default": 160 }, "<NAME>": { "default": 597 }, "<NAME>": { "default": 598 }, "<NAME>": { "default": 456 }, "<NAME>": { "default": 180 }, "<NAME>": { "default": 136 }, "<NAME>": { "default": 419 }, "<NAME>": { "default": 330 }, "<NAME>": { "default": 590 }, "<NAME>": { "default": 205 }, "<NAME>": { "default": 611 }, "<NAME>": { "default": 592 }, "<NAME>": { "default": 478 }, "F<NAME>": { "default": 162 }, "<NAME>": { "default": 444 }, "<NAME>": { "default": 475 }, "<NAME>": { "default": 596 }, "<NAME>": { "default": 569 }, "<NAME>": { "default": 445, "mega": NON_DEFAULT_FORMES_OFFSET + 140 }, "<NAME>": { "default": 282, "mega": NON_DEFAULT_FORMES_OFFSET + 131 }, "<NAME>": { "default": 92 }, "<NAME>": { "default": 423 }, "<NAME>": { "default": 649 }, "<NAME>": { "default": 94, "mega": NON_DEFAULT_FORMES_OFFSET + 118 }, "<NAME>": { "default": 74 }, "<NAME>": { "default": 443 }, "<NAME>": { "default": 526 }, "<NAME>": { "default": 203 }, "<NAME>": { "default": 487, "origin": NON_DEFAULT_FORMES_OFFSET + 74 }, "<NAME>": { "default": 471 }, "<NAME>": { "default": 362 }, "<NAME>": { "default": 431 }, "<NAME>": { "default": 207 }, "<NAME>": { "default": 472 }, "<NAME>": { "default": 44 }, "<NAME>": { "default": 42 }, "<NAME>": { "default": 118 }, "<NAME>": { "default": 55 }, "<NAME>": { "default": 76 }, "<NAME>": { "default": 622 }, "<NAME>": { "default": 623 }, "<NAME>": { "default": 368 }, "<NAME>": { "default": 574 }, "<NAME>": { "default": 576 }, "<NAME>": { "default": 575 }, "<NAME>": { "default": 210 }, "<NAME>": { "default": 75 }, "<NAME>": { "default": 88 }, "<NAME>": { "default": 388 }, "<NAME>": { "default": 383 }, "<NAME>": { "default": 253 }, "<NAME>": { "default": 58 }, "<NAME>": { "default": 326 }, "<NAME>": { "default": 316 }, "<NAME>": { "default": 533 }, "<NAME>": { "default": 130, "mega": NON_DEFAULT_FORMES_OFFSET + 121 }, "<NAME>": { "default": 440 }, "<NAME>": { "default": 297 }, "<NAME>": { "default": 93 }, "<NAME>": { "default": 612 }, "<NAME>": { "default": 631 }, "<NAME>": { "default": 485 }, "<NAME>": { "default": 214, "mega": NON_DEFAULT_FORMES_OFFSET + 127 }, "<NAME>": { "default": 507 }, "<NAME>": { "default": 449 }, "<NAME>": { "default": 450 }, "<NAME>": { "default": 107 }, "<NAME>": { "default": 106 }, "<NAME>": { "default": 237 }, "<NAME>": { "default": 250 }, "<NAME>": { "default": 430 }, "<NAME>": { "default": 163 }, "<NAME>": { "default": 187 }, "<NAME>": { "default": 116 }, "<NAME>": { "default": 229, "mega": NON_DEFAULT_FORMES_OFFSET + 128 }, "<NAME>": { "default": 228 }, "<NAME>": { "default": 367 }, "<NAME>": { "default": 635 }, "<NAME>": { "default": 97 }, "<NAME>": { "default": 174 }, "<NAME>": { "default": 314 }, "<NAME>": { "default": 392 }, "<NAME>": { "default": 2 }, "<NAME>": { "default": 593 }, "<NAME>": { "default": 39 }, "<NAME>": { "default": 385 }, "<NAME>": { "default": 135 }, "<NAME>": { "default": 595 }, "<NAME>": { "default": 189 }, "<NAME>": { "default": 124 }, "<NAME>": { "default": 140 }, "<NAME>": { "default": 141 }, "<NAME>": { "default": 64 }, "<NAME>": { "default": 14 }, "<NAME>": { "default": 115, "mega": NON_DEFAULT_FORMES_OFFSET + 119 }, "<NAME>": { "default": 588 }, "<NAME>": { "default": 352 }, "<NAME>": { "default": 647, "resolute": NON_DEFAULT_FORMES_OFFSET + 103 }, "<NAME>": { "default": 230 }, "<NAME>": { "default": 99 }, "<NAME>": { "default": 281 }, "<NAME>": { "default": 600 }, "<NAME>": { "default": 599 }, "<NAME>": { "default": 601 }, "<NAME>": { "default": 109 }, "<NAME>": { "default": 98 }, "<NAME>": { "default": 401 }, "<NAME>": { "default": 402 }, "<NAME>": { "default": 552 }, "<NAME>": { "default": 553 }, "<NAME>": { "default": 382 }, "<NAME>": { "default": 646, "black": NON_DEFAULT_FORMES_OFFSET + 101, "white": NON_DEFAULT_FORMES_OFFSET + 102 }, "<NAME>": { "default": 305 }, "<NAME>": { "default": 608 }, "<NAME>": { "default": 645, "<NAME>ian": NON_DEFAULT_FORMES_OFFSET + 100 }, "<NAME>": { "default": 171 }, "<NAME>": { "default": 131 }, "<NAME>": { "default": 636 }, "<NAME>": { "default": 246 }, "<NAME>": { "default": 380, "mega": NON_DEFAULT_FORMES_OFFSET + 138 }, "<NAME>": { "default": 381, "mega": NON_DEFAULT_FORMES_OFFSET + 139 }, "<NAME>": { "default": 470 }, "<NAME>": { "default": 542 }, "<NAME>": { "default": 166 }, "<NAME>": { "default": 165 }, "<NAME>": { "default": 463 }, "<NAME>": { "default": 108 }, "<NAME>": { "default": 510 }, "<NAME>": { "default": 345 }, "<NAME>": { "default": 549 }, "<NAME>": { "default": 506 }, "<NAME>": { "default": 264 }, "<NAME>": { "default": 607 }, "<NAME>": { "default": 271 }, "<NAME>": { "default": 428 }, "<NAME>": { "default": 270 }, "<NAME>": { "default": 294 }, "<NAME>": { "default": 448, "mega": NON_DEFAULT_FORMES_OFFSET + 141 }, "<NAME>": { "default": 272 }, "<NAME>": { "default": 249 }, "<NAME>": { "default": 457 }, "<NAME>": { "default": 337 }, "<NAME>": { "default": 370 }, "<NAME>": { "default": 404 }, "<NAME>": { "default": 405 }, "<NAME>": { "default": 68 }, "<NAME>": { "default": 67 }, "<NAME>": { "default": 66 }, "<NAME>": { "default": 240 }, "<NAME>": { "default": 219 }, "<NAME>": { "default": 129 }, "<NAME>": { "default": 126 }, "<NAME>": { "default": 467 }, "<NAME>": { "default": 81 }, "<NAME>": { "default": 82 }, "<NAME>": { "default": 462 }, "<NAME>": { "default": 296 }, "<NAME>": { "default": 473 }, "<NAME>": { "default": 490 }, "<NAME>": { "default": 630 }, "<NAME>": { "default": 310, "mega": NON_DEFAULT_FORMES_OFFSET + 135 }, "<NAME>": { "default": 56 }, "<NAME>": { "default": 226 }, "<NAME>": { "default": 458 }, "<NAME>": { "default": 556 }, "<NAME>": { "default": 179 }, "<NAME>": { "default": 183 }, "<NAME>": { "default": 105 }, "<NAME>": { "default": 259 }, "<NAME>": { "default": 284 }, "<NAME>": { "default": 303, "mega": NON_DEFAULT_FORMES_OFFSET + 132 }, "<NAME>": { "default": 308, "mega": NON_DEFAULT_FORMES_OFFSET + 134 }, "<NAME>": { "default": 307 }, "<NAME>": { "default": 154 }, "<NAME>": { "default": 648, "<NAME>tte": NON_DEFAULT_FORMES_OFFSET + 93 }, "<NAME>": { "default": 52 }, "<NAME>": { "default": 481 }, "<NAME>": { "default": 376 }, "<NAME>": { "default": 375 }, "<NAME>": { "default": 11 }, "<NAME>": { "default": 151 }, "<NAME>": { "default": 150, "mega-x": NON_DEFAULT_FORMES_OFFSET + 123 "mega-y": NON_DEFAULT_FORMES_OFFSET + 124 }, "<NAME>": { "default": 619 }, "<NAME>": { "default": 620 }, "<NAME>": { "default": 262 }, "<NAME>": { "default": 350 }, "<NAME>": { "default": 241 }, "<NAME> Jr.": { "default": 439 }, "<NAME>": { "default": 572 }, "<NAME>": { "default": 312 }, "<NAME>": { "default": 200 }, "<NAME>": { "default": 429 }, "<NAME>": { "default": 146 }, "<NAME>": { "default": 391 }, "<NAME>": { "default": 414 }, "Mr<NAME>. <NAME>": { "default": 122 }, "<NAME>": { "default": 258 }, "<NAME>": { "default": 89 }, "<NAME>": { "default": 446 }, "<NAME>": { "default": 517 }, "<NAME>": { "default": 198 }, "<NAME>": { "default": 518 }, "<NAME>": { "default": 177 }, "<NAME>": { "default": 34 }, "<NAME>": { "default": 31 }, "<NAME>♀": { "default": 29 }, "<NAME>♂": { "default": 32 }, "<NAME>": { "default": 30 }, "<NAME>": { "default": 33 }, "<NAME>": { "default": 290 }, "<NAME>": { "default": 38 }, "<NAME>": { "default": 291 }, "<NAME>": { "default": 164 }, "<NAME>": { "default": 299 }, "<NAME>": { "default": 322 }, "<NAME>": { "default": 274 }, "<NAME>": { "default": 224 }, "<NAME>": { "default": 43 }, "<NAME>": { "default": 138 }, "<NAME>": { "default": 139 }, "<NAME>": { "default": 95 }, "<NAME>": { "default": 501 }, "<NAME>": { "default": 417 }, "<NAME>": { "default": 484 }, "<NAME>": { "default": 536 }, "<NAME>": { "default": 515 }, "<NAME>": { "default": 511 }, "<NAME>": { "default": 513 }, "<NAME>": { "default": 46 }, "<NAME>": { "default": 47 }, "<NAME>": { "default": 504 }, "<NAME>": { "default": 624 }, "<NAME>": { "default": 279 }, "<NAME>": { "default": 53 }, "<NAME>": { "default": 548 }, "<NAME>": { "default": 231 }, "<NAME>": { "default": 489 }, "<NAME>": { "default": 172 }, "<NAME>": { "default": 18 }, "<NAME>": { "default": 17 }, "<NAME>": { "default": 16 }, "<NAME>": { "default": 519 }, "<NAME>": { "default": 499 }, "<NAME>": { "default": 25 }, "<NAME>": { "default": 221 }, "<NAME>": { "default": 204 }, "<NAME>": { "default": 127, "mega": NON_DEFAULT_FORMES_OFFSET + 120 }, "<NAME>": { "default": 393 }, "<NAME>": { "default": 311 }, "<NAME>": { "default": 186 }, "<NAME>": { "default": 60 }, "<NAME>": { "default": 61 }, "<NAME>": { "default": 62 }, "<NAME>": { "default": 77 }, "<NAME>": { "default": 261 }, "<NAME>": { "default": 137 }, "<NAME>": { "default": 474 }, "<NAME>": { "default": 233 }, "<NAME>": { "default": 57 }, "<NAME>": { "default": 394 }, "<NAME>": { "default": 476 }, "<NAME>": { "default": 54 }, "<NAME>": { "default": 247 }, "<NAME>": { "default": 509 }, "<NAME>": { "default": 432 }, "<NAME>": { "default": 195 }, "<NAME>": { "default": 156 }, "<NAME>": { "default": 211 }, "<NAME>": { "default": 26 }, "<NAME>": { "default": 243 }, "<NAME>": { "default": 280 }, "<NAME>": { "default": 409 }, "<NAME>": { "default": 78 }, "<NAME>": { "default": 20 }, "<NAME>": { "default": 19 }, "<NAME>": { "default": 384 }, "<NAME>": { "default": 378 }, "<NAME>": { "default": 486 }, "<NAME>": { "default": 377 }, "<NAME>": { "default": 379 }, "<NAME>": { "default": 369 }, "<NAME>": { "default": 223 }, "<NAME>": { "default": 643 }, "<NAME>": { "default": 579 }, "<NAME>": { "default": 112 }, "<NAME>": { "default": 111 }, "<NAME>": { "default": 464 }, "<NAME>": { "default": 447 }, "<NAME>": { "default": 524 }, "<NAME>": { "default": 315 }, "<NAME>": { "default": 407 }, "<NAME>": { "default": 479, "fan": NON_DEFAULT_FORMES_OFFSET + 68, "frost": NON_DEFAULT_FORMES_OFFSET + 69, "heat": NON_DEFAULT_FORMES_OFFSET + 70, "mow": NON_DEFAULT_FORMES_OFFSET + 71, "wash": NON_DEFAULT_FORMES_OFFSET + 72 }, "<NAME>": { "default": 627 }, "<NAME>": { "default": 302 }, "<NAME>": { "default": 373 }, "<NAME>": { "default": 503 }, "<NAME>": { "default": 551 }, "<NAME>": { "default": 27 }, "<NAME>": { "default": 28 }, "<NAME>": { "default": 539 }, "<NAME>": { "default": 586 }, "<NAME>": { "default": 254 }, "<NAME>": { "default": 212, "mega": NON_DEFAULT_FORMES_OFFSET + 126 }, "<NAME>": { "default": 545 }, "<NAME>": { "default": 560 }, "<NAME>": { "default": 559 }, "<NAME>": { "default": 123 }, "<NAME>": { "default": 117 }, "<NAME>": { "default": 119 }, "<NAME>": { "default": 364 }, "<NAME>": { "default": 273 }, "<NAME>": { "default": 86 }, "<NAME>": { "default": 537 }, "<NAME>": { "default": 161 }, "<NAME>": { "default": 497 }, "<NAME>": { "default": 496 }, "<NAME>": { "default": 336 }, "<NAME>": { "default": 540 }, "<NAME>": { "default": 319 }, "<NAME>": { "default": 492, "sky": NON_DEFAULT_FORMES_OFFSET + 76 }, "<NAME>": { "default": 292 }, "<NAME>": { "default": 372 }, "<NAME>": { "default": 90 }, "<NAME>": { "default": 422 }, "<NAME>": { "default": 616 }, "<NAME>": { "default": 410 }, "<NAME>": { "default": 275 }, "<NAME>": { "default": 403 }, "<NAME>": { "default": 285 }, "<NAME>": { "default": 213 }, "<NAME>": { "default": 353 }, "<NAME>": { "default": 561 }, "<NAME>": { "default": 266 }, "<NAME>": { "default": 516 }, "<NAME>": { "default": 512 }, "<NAME>": { "default": 514 }, "<NAME>": { "default": 227 }, "<NAME>": { "default": 188 }, "<NAME>": { "default": 300 }, "<NAME>": { "default": 451 }, "<NAME>": { "default": 435 }, "<NAME>": { "default": 289 }, "<NAME>": { "default": 287 }, "<NAME>": { "default": 80 }, "<NAME>": { "default": 199 }, "<NAME>": { "default": 79 }, "<NAME>": { "default": 218 }, "<NAME>": { "default": 235 }, "<NAME>": { "default": 238 }, "<NAME>": { "default": 215 }, "<NAME>": { "default": 495 }, "<NAME>": { "default": 143 }, "<NAME>": { "default": 361 }, "<NAME>": { "default": 459 }, "<NAME>": { "default": 209 }, "<NAME>": { "default": 577 }, "<NAME>": { "default": 338 }, "<NAME>": { "default": 21 }, "<NAME>": { "default": 363 }, "<NAME>": { "default": 167 }, "<NAME>": { "default": 327 }, "<NAME>": { "default": 442 }, "<NAME>": { "default": 325 }, "<NAME>": { "default": 7 }, "<NAME>": { "default": 234 }, "<NAME>": { "default": 398 }, "<NAME>": { "default": 397 }, "<NAME>": { "default": 396 }, "<NAME>": { "default": 121 }, "<NAME>": { "default": 120 }, "<NAME>": { "default": 208 }, "<NAME>": { "default": 508 }, "<NAME>": { "default": 618 }, "<NAME>": { "default": 434 }, "<NAME>": { "default": 185 }, "<NAME>": { "default": 245 }, "<NAME>": { "default": 192 }, "<NAME>": { "default": 191 }, "<NAME>": { "default": 283 }, "<NAME>": { "default": 333 }, "<NAME>": { "default": 541 }, "<NAME>": { "default": 317 }, "<NAME>": { "default": 260 }, "<NAME>": { "default": 581 }, "<NAME>": { "default": 277 }, "<NAME>": { "default": 220 }, "<NAME>": { "default": 528 }, "<NAME>": { "default": 276 }, "<NAME>": { "default": 114 }, "<NAME>": { "default": 465 }, "<NAME>": { "default": 128 }, "<NAME>": { "default": 216 }, "<NAME>": { "default": 72 }, "<NAME>": { "default": 73 }, "<NAME>": { "default": 498 }, "<NAME>": { "default": 639 }, "<NAME>": { "default": 538 }, "<NAME>": { "default": 642, "therian": NON_DEFAULT_FORMES_OFFSET + 99 }, "<NAME>": { "default": 532 }, "<NAME>": { "default": 564 }, "<NAME>": { "default": 468 }, "<NAME>": { "default": 175 }, "<NAME>": { "default": 176 }, "<NAME>": { "default": 255 }, "<NAME>": { "default": 324 }, "<NAME>": { "default": 641, "therian": NON_DEFAULT_FORMES_OFFSET + 98 }, "<NAME>": { "default": 389 }, "<NAME>": { "default": 158 }, "<NAME>": { "default": 454 }, "<NAME>": { "default": 520 }, "<NAME>": { "default": 328 }, "<NAME>": { "default": 252 }, "<NAME>": { "default": 357 }, "<NAME>": { "default": 568 }, "<NAME>": { "default": 387 }, "<NAME>": { "default": 535 }, "<NAME>": { "default": 602 }, "<NAME>": { "default": 157 }, "<NAME>": { "default": 248, "mega": NON_DEFAULT_FORMES_OFFSET + 129 }, "<NAME>": { "default": 236 }, "<NAME>": { "default": 197 }, "<NAME>": { "default": 521 }, "<NAME>": { "default": 201 }, "<NAME>": { "default": 217 }, "<NAME>": { "default": 480 }, "<NAME>": { "default": 583 }, "<NAME>": { "default": 582 }, "<NAME>": { "default": 584 }, "<NAME>": { "default": 134 }, "<NAME>": { "default": 543 }, "<NAME>": { "default": 49 }, "<NAME>": { "default": 48 }, "<NAME>": { "default": 3, "mega": NON_DEFAULT_FORMES_OFFSET + 113 }, "<NAME>": { "default": 416 }, "<NAME>": { "default": 329 }, "<NAME>": { "default": 494 }, "<NAME>": { "default": 71 }, "<NAME>": { "default": 288 }, "<NAME>": { "default": 45 }, "<NAME>": { "default": 640 }, "<NAME>": { "default": 313 }, "<NAME>": { "default": 637 }, "<NAME>": { "default": 100 }, "<NAME>": { "default": 629 }, "<NAME>": { "default": 37 }, "<NAME>": { "default": 320 }, "<NAME>": { "default": 321 }, "<NAME>": { "default": 365 }, "<NAME>": { "default": 8 }, "<NAME>": { "default": 505 }, "<NAME>": { "default": 461 }, "<NAME>": { "default": 13 }, "<NAME>": { "default": 70 }, "<NAME>": { "default": 110 }, "<NAME>": { "default": 547 }, "<NAME>": { "default": 544 }, "<NAME>": { "default": 340 }, "<NAME>": { "default": 293 }, "<NAME>": { "default": 40 }, "<NAME>": { "default": 278 }, "<NAME>": { "default": 202 }, "<NAME>": { "default": 527 }, "<NAME>": { "default": 194 }, "<NAME>": { "default": 413, "sandy": NON_DEFAULT_FORMES_OFFSET + 60, "trash": NON_DEFAULT_FORMES_OFFSET + 61 }, "<NAME>": { "default": 265 }, "<NAME>": { "default": 360 }, "<NAME>": { "default": 178 }, "<NAME>": { "default": 562 }, "<NAME>": { "default": 193 }, "<NAME>": { "default": 469 }, "<NAME>": { "default": 335 }, "<NAME>": { "default": 145 }, "<NAME>": { "default": 523 }, "<NAME>": { "default": 644 }, "<NAME>": { "default": 263 }, "<NAME>": { "default": 571 }, "<NAME>": { "default": 570 }, "<NAME>": { "default": 41 }, "<NAME>": { "default": 634 }, "<NAME>": { "default": 681, "blade": NON_DEFAULT_FORMES_OFFSET + 106 }, "<NAME>": { "default": 698 }, "<NAME>": { "default": 683 }, "<NAME>": { "default": 699 }, "<NAME>": { "default": 713 }, "<NAME>": { "default": 689 }, "<NAME>": { "default": 712 }, "<NAME>": { "default": 688 }, "<NAME>": { "default": 654 }, "<NAME>": { "default": 659 }, "<NAME>": { "default": 703 }, "<NAME>": { "default": 652 }, "<NAME>": { "default": 650 }, "<NAME>": { "default": 693 }, "<NAME>": { "default": 692 }, "<NAME>": { "default": 702 }, "<NAME>": { "default": 655 }, "<NAME>": { "default": 719 }, "<NAME>": { "default": 660 }, "<NAME>": { "default": 680 }, "<NAME>": { "default": 691 }, "<NAME>": { "default": 677 }, "<NAME>": { "default": 653 }, "<NAME>": { "default": 669 }, "<NAME>": { "default": 662 }, "<NAME>": { "default": 661 }, "<NAME>": { "default": 670 }, "<NAME>": { "default": 671 }, "<NAME>": { "default": 656 }, "<NAME>": { "default": 657 }, "<NAME>": { "default": 676 }, "<NAME>": { "default": 673 }, "<NAME>": { "default": 706 }, "<NAME>": { "default": 704 }, "<NAME>": { "default": 711 }, "<NAME>": { "default": 658 }, "<NAME>": { "default": 701 }, "<NAME>": { "default": 695 }, "<NAME>": { "default": 694 }, "<NAME>": { "default": 679 }, "<NAME>": { "default": 720 }, "<NAME>": { "default": 686 }, "<NAME>": { "default": 707 }, "<NAME>": { "default": 667 }, "<NAME>": { "default": 687 }, "<NAME>": { "default": 678, "female": NON_DEFAULT_FORMES_OFFSET + 105 }, "<NAME>": { "default": 714 }, "<NAME>": { "default": 715 }, "<NAME>": { "default": 674 }, "<NAME>": { "default": 675 }, "<NAME>": { "default": 708 }, "<NAME>": { "default": 710 }, "<NAME>": { "default": 668 }, "<NAME>": { "default": 651 }, "<NAME>": { "default": 664 }, "<NAME>": { "default": 672 }, "<NAME>": { "default": 690 }, "<NAME>": { "default": 705 }, "<NAME>": { "default": 685 }, "<NAME>": { "default": 665 }, "<NAME>": { "default": 682 }, "<NAME>": { "default": 684 }, "<NAME>": { "default": 700 }, "<NAME>": { "default": 663 }, "<NAME>": { "default": 709 }, "<NAME>": { "default": 697 }, "<NAME>": { "default": 696 }, "<NAME>": { "default": 666 }, "<NAME>": { "default": 721 }, "<NAME>": { "default": 716 }, "<NAME>": { "default": 717 }, "<NAME>": { "default": 718 } }
true
@PokemonIconBackground = (species, forme) -> if not (typeof species == "string") pokemon = species species = pokemon.species || pokemon.get?("species") forme = pokemon.forme || pokemon.get?("forme") if species id = SpriteIds[species][forme] || SpriteIds[species]["default"] else id = 0 x = (id % 16) * 40 y = (id >> 4) * 32 "background-position: -#{x}px -#{y}px" @PokemonSprite = (id, forme, options = {}) -> if id instanceof Pokemon pokemon = id id = pokemon.getSpecies()?.id || 0 forme = pokemon.get('forme') options = { shiny: pokemon.get('shiny') } front = options.front ? true shiny = options.shiny ? false kind = (if front then "front" else "back") kind += "-s" if shiny id = "000#{id}".substr(-3) if forme && forme != 'default' then id += "-#{forme}" "//media.pokebattle.com/pksprites/#{kind}/#{id}.gif" @TypeSprite = (type) -> "//media.pokebattle.com/img/types/#{type.toLowerCase()}.png" @CategorySprite = (type) -> "//media.pokebattle.com/img/types/#{type.toLowerCase()}.png" @TargetSprite = (move) -> target = move.target if "distance" in move["flags"] && target == "selected-pokemon" target = "distance" "//media.pokebattle.com/img/targets/#{target.toLowerCase()}.png" @AchievementSprite = (achievement) -> "//media.pokebattle.com/achievements/#{achievement.medium_image}" generation = Generations[DEFAULT_GENERATION.toUpperCase()] maxSpeciesId = Math.max((p.id for n, p of generation.SpeciesData)...) NON_DEFAULT_FORMES_OFFSET = maxSpeciesId + (16 - ((maxSpeciesId + 1) % 16)) # TODO: Move this elswhere SpriteIds = { "PI:NAME:<NAME>END_PI": { "default": 460, "mega": NON_DEFAULT_FORMES_OFFSET + 142 }, "PI:NAME:<NAME>END_PI": { "default": 63 }, "PI:NAME:<NAME>END_PI": { "default": 359, "mega": NON_DEFAULT_FORMES_OFFSET + 137 }, "PI:NAME:<NAME>END_PI": { "default": 617 }, "PI:NAME:<NAME>END_PI": { "default": 142, "mega": NON_DEFAULT_FORMES_OFFSET + 122 }, "PI:NAME:<NAME>END_PI": { "default": 306, "mega": NON_DEFAULT_FORMES_OFFSET + 133 }, "PI:NAME:<NAME>END_PI": { "default": 190 }, "PI:NAME:<NAME>END_PI": { "default": 65, "mega": NON_DEFAULT_FORMES_OFFSET + 117 }, "PI:NAME:<NAME>END_PI": { "default": 594 }, "PI:NAME:<NAME>END_PI": { "default": 334 }, "PI:NAME:<NAME>END_PI": { "default": 424 }, "PI:NAME:<NAME>END_PI": { "default": 591 }, "PI:NAME:<NAME>END_PI": { "default": 181, "mega": NON_DEFAULT_FORMES_OFFSET + 125 }, "PI:NAME:<NAME>END_PI": { "default": 347 }, "PI:NAME:<NAME>END_PI": { "default": 24 }, "PI:NAME:<NAME>END_PI": { "default": 59 }, "PI:NAME:<NAME>END_PI": { "default": 493 }, "PI:NAME:<NAME>END_PI": { "default": 566 }, "PI:NAME:<NAME>END_PI": { "default": 567 }, "PI:NAME:<NAME>END_PI": { "default": 168 }, "PI:NAME:<NAME>END_PI": { "default": 348 }, "PI:NAME:<NAME>END_PI": { "default": 304 }, "PI:NAME:<NAME>END_PI": { "default": 144 }, "PI:NAME:<NAME>END_PI": { "default": 531 }, "PI:NAME:<NAME>END_PI": { "default": 610 }, "PI:NAME:<NAME>END_PI": { "default": 482 }, "PI:NAME:<NAME>END_PI": { "default": 184 }, "PI:NAME:<NAME>END_PI": { "default": 298 }, "PI:NAME:<NAME>END_PI": { "default": 371 }, "PI:NAME:<NAME>END_PI": { "default": 343 }, "PI:NAME:<NAME>END_PI": { "default": 354, "mega": NON_DEFAULT_FORMES_OFFSET + 136 }, "PI:NAME:<NAME>END_PI": { "default": 339 }, "PI:NAME:<NAME>END_PI": { "default": 550, "blue-striped": NON_DEFAULT_FORMES_OFFSET + 78 }, "PI:NAME:<NAME>END_PI": { "default": 411 }, "PI:NAME:<NAME>END_PI": { "default": 153 }, "PI:NAME:<NAME>END_PI": { "default": 614 }, "PI:NAME:<NAME>END_PI": { "default": 267 }, "PI:NAME:<NAME>END_PI": { "default": 15 }, "PI:NAME:<NAME>END_PI": { "default": 606 }, "PI:NAME:<NAME>END_PI": { "default": 374 }, "PI:NAME:<NAME>END_PI": { "default": 182 }, "PI:NAME:<NAME>END_PI": { "default": 69 }, "PI:NAME:<NAME>END_PI": { "default": 400 }, "PI:NAME:<NAME>END_PI": { "default": 399 }, "PI:NAME:<NAME>END_PI": { "default": 625 }, "PI:NAME:<NAME>END_PI": { "default": 9, "mega": NON_DEFAULT_FORMES_OFFSET + 116 }, "PI:NAME:<NAME>END_PI": { "default": 257, "mega": NON_DEFAULT_FORMES_OFFSET + 130 }, "PI:NAME:<NAME>END_PI": { "default": 242 }, "PI:NAME:<NAME>END_PI": { "default": 522 }, "PI:NAME:<NAME>END_PI": { "default": 525 }, "PI:NAME:<NAME>END_PI": { "default": 438 }, "PI:NAME:<NAME>END_PI": { "default": 626 }, "PI:NAME:<NAME>END_PI": { "default": 628 }, "PI:NAME:<NAME>END_PI": { "default": 286 }, "PI:NAME:<NAME>END_PI": { "default": 437 }, "PI:NAME:<NAME>END_PI": { "default": 436 }, "PI:NAME:<NAME>END_PI": { "default": 406 }, "PI:NAME:<NAME>END_PI": { "default": 418 }, "PI:NAME:<NAME>END_PIbasaur": { "default": 1 }, "PI:NAME:<NAME>END_PI": { "default": 427 }, "PI:NAME:<NAME>END_PI": { "default": 412, "sandy": NON_DEFAULT_FORMES_OFFSET + 9, "trash": NON_DEFAULT_FORMES_OFFSET + 10 }, "PI:NAME:<NAME>END_PI": { "default": 12 }, "PI:NAME:<NAME>END_PI": { "default": 331 }, "PI:NAME:<NAME>END_PI": { "default": 332 }, "PI:NAME:<NAME>END_PI": { "default": 323 }, "PI:NAME:<NAME>END_PI": { "default": 455 }, "PI:NAME:<NAME>END_PI": { "default": 565 }, "PI:NAME:<NAME>END_PI": { "default": 318 }, "PI:NAME:<NAME>END_PI": { "default": 268 }, "PI:NAME:<NAME>END_PI": { "default": 351, "rainy": 49, "snowy": 50, "sunny": 51 }, "PI:NAME:<NAME>END_PI": { "default": 10 }, "PI:NAME:<NAME>END_PI": { "default": 251 }, "PI:NAME:<NAME>END_PI": { "default": 609 }, "PI:NAME:<NAME>END_PI": { "default": 113 }, "PI:NAME:<NAME>END_PI": { "default": 6, "mega-x": NON_DEFAULT_FORMES_OFFSET + 114, "mega-y": NON_DEFAULT_FORMES_OFFSET + 115 }, "PI:NAME:<NAME>END_PI": { "default": 4 }, "PI:NAME:<NAME>END_PI": { "default": 5 }, "PI:NAME:<NAME>END_PI": { "default": 441 }, "PI:NAME:<NAME>END_PI": { "default": 421 }, "PI:NAME:<NAME>END_PI": { "default": 420 }, "PI:NAME:<NAME>END_PI": { "default": 152 }, "PI:NAME:<NAME>END_PI": { "default": 390 }, "PI:NAME:<NAME>END_PI": { "default": 358 }, "PI:NAME:<NAME>END_PI": { "default": 170 }, "PI:NAME:<NAME>END_PI": { "default": 433 }, "PI:NAME:<NAME>END_PI": { "default": 573 }, "PI:NAME:<NAME>END_PI": { "default": 366 }, "PI:NAME:<NAME>END_PI": { "default": 344 }, "PI:NAME:<NAME>END_PI": { "default": 36 }, "PI:NAME:<NAME>END_PI": { "default": 35 }, "PI:NAME:<NAME>END_PI": { "default": 173 }, "PI:NAME:<NAME>END_PI": { "default": 91 }, "PI:NAME:<NAME>END_PI": { "default": 638 }, "PI:NAME:<NAME>END_PI": { "default": 563 }, "PI:NAME:<NAME>END_PI": { "default": 415 }, "PI:NAME:<NAME>END_PI": { "default": 256 }, "PI:NAME:<NAME>END_PI": { "default": 534 }, "PI:NAME:<NAME>END_PI": { "default": 341 }, "PI:NAME:<NAME>END_PI": { "default": 222 }, "PI:NAME:<NAME>END_PI": { "default": 546 }, "PI:NAME:<NAME>END_PI": { "default": 346 }, "PI:NAME:<NAME>END_PI": { "default": 408 }, "PI:NAME:<NAME>END_PI": { "default": 342 }, "PI:NAME:<NAME>END_PI": { "default": 488 }, "PI:NAME:<NAME>END_PI": { "default": 453 }, "PI:NAME:<NAME>END_PI": { "default": 169 }, "PI:NAME:<NAME>END_PI": { "default": 159 }, "PI:NAME:<NAME>END_PI": { "default": 558 }, "PI:NAME:<NAME>END_PI": { "default": 615 }, "PI:NAME:<NAME>END_PI": { "default": 613 }, "PI:NAME:<NAME>END_PI": { "default": 104 }, "PI:NAME:<NAME>END_PI": { "default": 155 }, "PI:NAME:<NAME>END_PI": { "default": 491 }, "PI:NAME:<NAME>END_PI": { "default": 555, "zen": NON_DEFAULT_FORMES_OFFSET + 81 }, "PI:NAME:<NAME>END_PI": { "default": 554 }, "PI:NAME:<NAME>END_PI": { "default": 585 }, "PI:NAME:<NAME>END_PI": { "default": 633 }, "PI:NAME:<NAME>END_PI": { "default": 301 }, "PI:NAME:<NAME>END_PI": { "default": 225 }, "PI:NAME:<NAME>END_PI": { "default": 386, "attack": NON_DEFAULT_FORMES_OFFSET + 52, "defense": NON_DEFAULT_FORMES_OFFSET + 53, "speed": NON_DEFAULT_FORMES_OFFSET + 55 }, "PI:NAME:<NAME>END_PI": { "default": 87 }, "PI:NAME:<NAME>END_PI": { "default": 502 }, "PI:NAME:<NAME>END_PI": { "default": 483 }, "PI:NAME:<NAME>END_PI": { "default": 50 }, "PI:NAME:<NAME>END_PI": { "default": 132 }, "PI:NAME:<NAME>END_PI": { "default": 85 }, "PI:NAME:<NAME>END_PI": { "default": 84 }, "PI:NAME:<NAME>END_PI": { "default": 232 }, "PI:NAME:<NAME>END_PI": { "default": 148 }, "PI:NAME:<NAME>END_PI": { "default": 149 }, "PI:NAME:<NAME>END_PI": { "default": 452 }, "PI:NAME:<NAME>END_PI": { "default": 147 }, "PI:NAME:<NAME>END_PI": { "default": 426 }, "PI:NAME:<NAME>END_PI": { "default": 425 }, "PI:NAME:<NAME>END_PI": { "default": 529 }, "PI:NAME:<NAME>END_PI": { "default": 96 }, "PI:NAME:<NAME>END_PI": { "default": 621 }, "PI:NAME:<NAME>END_PI": { "default": 580 }, "PI:NAME:<NAME>END_PI": { "default": 51 }, "PI:NAME:<NAME>END_PI": { "default": 206 }, "PI:NAME:<NAME>END_PI": { "default": 578 }, "PI:NAME:<NAME>END_PI": { "default": 632 }, "PI:NAME:<NAME>END_PI": { "default": 356 }, "PI:NAME:<NAME>END_PI": { "default": 477 }, "PI:NAME:<NAME>END_PI": { "default": 355 }, "PI:NAME:<NAME>END_PI": { "default": 269 }, "PI:NAME:<NAME>END_PI": { "default": 557 }, "PI:NAME:<NAME>END_PI": { "default": 603 }, "PI:NAME:<NAME>END_PI": { "default": 604 }, "PI:NAME:<NAME>END_PI": { "default": 133 }, "PI:NAME:<NAME>END_PI": { "default": 23 }, "PI:NAME:<NAME>END_PI": { "default": 125 }, "PI:NAME:<NAME>END_PI": { "default": 466 }, "PI:NAME:<NAME>END_PI": { "default": 309 }, "PI:NAME:<NAME>END_PI": { "default": 101 }, "PI:NAME:<NAME>END_PI": { "default": 239 }, "PI:NAME:<NAME>END_PI": { "default": 605 }, "PI:NAME:<NAME>END_PI": { "default": 500 }, "PI:NAME:<NAME>END_PI": { "default": 587 }, "PI:NAME:<NAME>END_PI": { "default": 395 }, "PI:NAME:<NAME>END_PI": { "default": 244 }, "PI:NAME:<NAME>END_PI": { "default": 589 }, "PI:NAME:<NAME>END_PI": { "default": 196 }, "PI:NAME:<NAME>END_PI": { "default": 530 }, "PI:NAME:<NAME>END_PIeggcute": { "default": 102 }, "Exeggutor": { "default": 103 }, "PI:NAME:<NAME>END_PI": { "default": 295 }, "PI:NAME:<NAME>END_PI": { "default": 83 }, "PI:NAME:<NAME>END_PI": { "default": 22 }, "PI:NAME:<NAME>END_PI": { "default": 349 }, "PI:NAME:<NAME>END_PI": { "default": 160 }, "PI:NAME:<NAME>END_PI": { "default": 597 }, "PI:NAME:<NAME>END_PI": { "default": 598 }, "PI:NAME:<NAME>END_PI": { "default": 456 }, "PI:NAME:<NAME>END_PI": { "default": 180 }, "PI:NAME:<NAME>END_PI": { "default": 136 }, "PI:NAME:<NAME>END_PI": { "default": 419 }, "PI:NAME:<NAME>END_PI": { "default": 330 }, "PI:NAME:<NAME>END_PI": { "default": 590 }, "PI:NAME:<NAME>END_PI": { "default": 205 }, "PI:NAME:<NAME>END_PI": { "default": 611 }, "PI:NAME:<NAME>END_PI": { "default": 592 }, "PI:NAME:<NAME>END_PI": { "default": 478 }, "FPI:NAME:<NAME>END_PI": { "default": 162 }, "PI:NAME:<NAME>END_PI": { "default": 444 }, "PI:NAME:<NAME>END_PI": { "default": 475 }, "PI:NAME:<NAME>END_PI": { "default": 596 }, "PI:NAME:<NAME>END_PI": { "default": 569 }, "PI:NAME:<NAME>END_PI": { "default": 445, "mega": NON_DEFAULT_FORMES_OFFSET + 140 }, "PI:NAME:<NAME>END_PI": { "default": 282, "mega": NON_DEFAULT_FORMES_OFFSET + 131 }, "PI:NAME:<NAME>END_PI": { "default": 92 }, "PI:NAME:<NAME>END_PI": { "default": 423 }, "PI:NAME:<NAME>END_PI": { "default": 649 }, "PI:NAME:<NAME>END_PI": { "default": 94, "mega": NON_DEFAULT_FORMES_OFFSET + 118 }, "PI:NAME:<NAME>END_PI": { "default": 74 }, "PI:NAME:<NAME>END_PI": { "default": 443 }, "PI:NAME:<NAME>END_PI": { "default": 526 }, "PI:NAME:<NAME>END_PI": { "default": 203 }, "PI:NAME:<NAME>END_PI": { "default": 487, "origin": NON_DEFAULT_FORMES_OFFSET + 74 }, "PI:NAME:<NAME>END_PI": { "default": 471 }, "PI:NAME:<NAME>END_PI": { "default": 362 }, "PI:NAME:<NAME>END_PI": { "default": 431 }, "PI:NAME:<NAME>END_PI": { "default": 207 }, "PI:NAME:<NAME>END_PI": { "default": 472 }, "PI:NAME:<NAME>END_PI": { "default": 44 }, "PI:NAME:<NAME>END_PI": { "default": 42 }, "PI:NAME:<NAME>END_PI": { "default": 118 }, "PI:NAME:<NAME>END_PI": { "default": 55 }, "PI:NAME:<NAME>END_PI": { "default": 76 }, "PI:NAME:<NAME>END_PI": { "default": 622 }, "PI:NAME:<NAME>END_PI": { "default": 623 }, "PI:NAME:<NAME>END_PI": { "default": 368 }, "PI:NAME:<NAME>END_PI": { "default": 574 }, "PI:NAME:<NAME>END_PI": { "default": 576 }, "PI:NAME:<NAME>END_PI": { "default": 575 }, "PI:NAME:<NAME>END_PI": { "default": 210 }, "PI:NAME:<NAME>END_PI": { "default": 75 }, "PI:NAME:<NAME>END_PI": { "default": 88 }, "PI:NAME:<NAME>END_PI": { "default": 388 }, "PI:NAME:<NAME>END_PI": { "default": 383 }, "PI:NAME:<NAME>END_PI": { "default": 253 }, "PI:NAME:<NAME>END_PI": { "default": 58 }, "PI:NAME:<NAME>END_PI": { "default": 326 }, "PI:NAME:<NAME>END_PI": { "default": 316 }, "PI:NAME:<NAME>END_PI": { "default": 533 }, "PI:NAME:<NAME>END_PI": { "default": 130, "mega": NON_DEFAULT_FORMES_OFFSET + 121 }, "PI:NAME:<NAME>END_PI": { "default": 440 }, "PI:NAME:<NAME>END_PI": { "default": 297 }, "PI:NAME:<NAME>END_PI": { "default": 93 }, "PI:NAME:<NAME>END_PI": { "default": 612 }, "PI:NAME:<NAME>END_PI": { "default": 631 }, "PI:NAME:<NAME>END_PI": { "default": 485 }, "PI:NAME:<NAME>END_PI": { "default": 214, "mega": NON_DEFAULT_FORMES_OFFSET + 127 }, "PI:NAME:<NAME>END_PI": { "default": 507 }, "PI:NAME:<NAME>END_PI": { "default": 449 }, "PI:NAME:<NAME>END_PI": { "default": 450 }, "PI:NAME:<NAME>END_PI": { "default": 107 }, "PI:NAME:<NAME>END_PI": { "default": 106 }, "PI:NAME:<NAME>END_PI": { "default": 237 }, "PI:NAME:<NAME>END_PI": { "default": 250 }, "PI:NAME:<NAME>END_PI": { "default": 430 }, "PI:NAME:<NAME>END_PI": { "default": 163 }, "PI:NAME:<NAME>END_PI": { "default": 187 }, "PI:NAME:<NAME>END_PI": { "default": 116 }, "PI:NAME:<NAME>END_PI": { "default": 229, "mega": NON_DEFAULT_FORMES_OFFSET + 128 }, "PI:NAME:<NAME>END_PI": { "default": 228 }, "PI:NAME:<NAME>END_PI": { "default": 367 }, "PI:NAME:<NAME>END_PI": { "default": 635 }, "PI:NAME:<NAME>END_PI": { "default": 97 }, "PI:NAME:<NAME>END_PI": { "default": 174 }, "PI:NAME:<NAME>END_PI": { "default": 314 }, "PI:NAME:<NAME>END_PI": { "default": 392 }, "PI:NAME:<NAME>END_PI": { "default": 2 }, "PI:NAME:<NAME>END_PI": { "default": 593 }, "PI:NAME:<NAME>END_PI": { "default": 39 }, "PI:NAME:<NAME>END_PI": { "default": 385 }, "PI:NAME:<NAME>END_PI": { "default": 135 }, "PI:NAME:<NAME>END_PI": { "default": 595 }, "PI:NAME:<NAME>END_PI": { "default": 189 }, "PI:NAME:<NAME>END_PI": { "default": 124 }, "PI:NAME:<NAME>END_PI": { "default": 140 }, "PI:NAME:<NAME>END_PI": { "default": 141 }, "PI:NAME:<NAME>END_PI": { "default": 64 }, "PI:NAME:<NAME>END_PI": { "default": 14 }, "PI:NAME:<NAME>END_PI": { "default": 115, "mega": NON_DEFAULT_FORMES_OFFSET + 119 }, "PI:NAME:<NAME>END_PI": { "default": 588 }, "PI:NAME:<NAME>END_PI": { "default": 352 }, "PI:NAME:<NAME>END_PI": { "default": 647, "resolute": NON_DEFAULT_FORMES_OFFSET + 103 }, "PI:NAME:<NAME>END_PI": { "default": 230 }, "PI:NAME:<NAME>END_PI": { "default": 99 }, "PI:NAME:<NAME>END_PI": { "default": 281 }, "PI:NAME:<NAME>END_PI": { "default": 600 }, "PI:NAME:<NAME>END_PI": { "default": 599 }, "PI:NAME:<NAME>END_PI": { "default": 601 }, "PI:NAME:<NAME>END_PI": { "default": 109 }, "PI:NAME:<NAME>END_PI": { "default": 98 }, "PI:NAME:<NAME>END_PI": { "default": 401 }, "PI:NAME:<NAME>END_PI": { "default": 402 }, "PI:NAME:<NAME>END_PI": { "default": 552 }, "PI:NAME:<NAME>END_PI": { "default": 553 }, "PI:NAME:<NAME>END_PI": { "default": 382 }, "PI:NAME:<NAME>END_PI": { "default": 646, "black": NON_DEFAULT_FORMES_OFFSET + 101, "white": NON_DEFAULT_FORMES_OFFSET + 102 }, "PI:NAME:<NAME>END_PI": { "default": 305 }, "PI:NAME:<NAME>END_PI": { "default": 608 }, "PI:NAME:<NAME>END_PI": { "default": 645, "PI:NAME:<NAME>END_PIian": NON_DEFAULT_FORMES_OFFSET + 100 }, "PI:NAME:<NAME>END_PI": { "default": 171 }, "PI:NAME:<NAME>END_PI": { "default": 131 }, "PI:NAME:<NAME>END_PI": { "default": 636 }, "PI:NAME:<NAME>END_PI": { "default": 246 }, "PI:NAME:<NAME>END_PI": { "default": 380, "mega": NON_DEFAULT_FORMES_OFFSET + 138 }, "PI:NAME:<NAME>END_PI": { "default": 381, "mega": NON_DEFAULT_FORMES_OFFSET + 139 }, "PI:NAME:<NAME>END_PI": { "default": 470 }, "PI:NAME:<NAME>END_PI": { "default": 542 }, "PI:NAME:<NAME>END_PI": { "default": 166 }, "PI:NAME:<NAME>END_PI": { "default": 165 }, "PI:NAME:<NAME>END_PI": { "default": 463 }, "PI:NAME:<NAME>END_PI": { "default": 108 }, "PI:NAME:<NAME>END_PI": { "default": 510 }, "PI:NAME:<NAME>END_PI": { "default": 345 }, "PI:NAME:<NAME>END_PI": { "default": 549 }, "PI:NAME:<NAME>END_PI": { "default": 506 }, "PI:NAME:<NAME>END_PI": { "default": 264 }, "PI:NAME:<NAME>END_PI": { "default": 607 }, "PI:NAME:<NAME>END_PI": { "default": 271 }, "PI:NAME:<NAME>END_PI": { "default": 428 }, "PI:NAME:<NAME>END_PI": { "default": 270 }, "PI:NAME:<NAME>END_PI": { "default": 294 }, "PI:NAME:<NAME>END_PI": { "default": 448, "mega": NON_DEFAULT_FORMES_OFFSET + 141 }, "PI:NAME:<NAME>END_PI": { "default": 272 }, "PI:NAME:<NAME>END_PI": { "default": 249 }, "PI:NAME:<NAME>END_PI": { "default": 457 }, "PI:NAME:<NAME>END_PI": { "default": 337 }, "PI:NAME:<NAME>END_PI": { "default": 370 }, "PI:NAME:<NAME>END_PI": { "default": 404 }, "PI:NAME:<NAME>END_PI": { "default": 405 }, "PI:NAME:<NAME>END_PI": { "default": 68 }, "PI:NAME:<NAME>END_PI": { "default": 67 }, "PI:NAME:<NAME>END_PI": { "default": 66 }, "PI:NAME:<NAME>END_PI": { "default": 240 }, "PI:NAME:<NAME>END_PI": { "default": 219 }, "PI:NAME:<NAME>END_PI": { "default": 129 }, "PI:NAME:<NAME>END_PI": { "default": 126 }, "PI:NAME:<NAME>END_PI": { "default": 467 }, "PI:NAME:<NAME>END_PI": { "default": 81 }, "PI:NAME:<NAME>END_PI": { "default": 82 }, "PI:NAME:<NAME>END_PI": { "default": 462 }, "PI:NAME:<NAME>END_PI": { "default": 296 }, "PI:NAME:<NAME>END_PI": { "default": 473 }, "PI:NAME:<NAME>END_PI": { "default": 490 }, "PI:NAME:<NAME>END_PI": { "default": 630 }, "PI:NAME:<NAME>END_PI": { "default": 310, "mega": NON_DEFAULT_FORMES_OFFSET + 135 }, "PI:NAME:<NAME>END_PI": { "default": 56 }, "PI:NAME:<NAME>END_PI": { "default": 226 }, "PI:NAME:<NAME>END_PI": { "default": 458 }, "PI:NAME:<NAME>END_PI": { "default": 556 }, "PI:NAME:<NAME>END_PI": { "default": 179 }, "PI:NAME:<NAME>END_PI": { "default": 183 }, "PI:NAME:<NAME>END_PI": { "default": 105 }, "PI:NAME:<NAME>END_PI": { "default": 259 }, "PI:NAME:<NAME>END_PI": { "default": 284 }, "PI:NAME:<NAME>END_PI": { "default": 303, "mega": NON_DEFAULT_FORMES_OFFSET + 132 }, "PI:NAME:<NAME>END_PI": { "default": 308, "mega": NON_DEFAULT_FORMES_OFFSET + 134 }, "PI:NAME:<NAME>END_PI": { "default": 307 }, "PI:NAME:<NAME>END_PI": { "default": 154 }, "PI:NAME:<NAME>END_PI": { "default": 648, "PI:NAME:<NAME>END_PItte": NON_DEFAULT_FORMES_OFFSET + 93 }, "PI:NAME:<NAME>END_PI": { "default": 52 }, "PI:NAME:<NAME>END_PI": { "default": 481 }, "PI:NAME:<NAME>END_PI": { "default": 376 }, "PI:NAME:<NAME>END_PI": { "default": 375 }, "PI:NAME:<NAME>END_PI": { "default": 11 }, "PI:NAME:<NAME>END_PI": { "default": 151 }, "PI:NAME:<NAME>END_PI": { "default": 150, "mega-x": NON_DEFAULT_FORMES_OFFSET + 123 "mega-y": NON_DEFAULT_FORMES_OFFSET + 124 }, "PI:NAME:<NAME>END_PI": { "default": 619 }, "PI:NAME:<NAME>END_PI": { "default": 620 }, "PI:NAME:<NAME>END_PI": { "default": 262 }, "PI:NAME:<NAME>END_PI": { "default": 350 }, "PI:NAME:<NAME>END_PI": { "default": 241 }, "PI:NAME:<NAME>END_PI Jr.": { "default": 439 }, "PI:NAME:<NAME>END_PI": { "default": 572 }, "PI:NAME:<NAME>END_PI": { "default": 312 }, "PI:NAME:<NAME>END_PI": { "default": 200 }, "PI:NAME:<NAME>END_PI": { "default": 429 }, "PI:NAME:<NAME>END_PI": { "default": 146 }, "PI:NAME:<NAME>END_PI": { "default": 391 }, "PI:NAME:<NAME>END_PI": { "default": 414 }, "MrPI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI": { "default": 122 }, "PI:NAME:<NAME>END_PI": { "default": 258 }, "PI:NAME:<NAME>END_PI": { "default": 89 }, "PI:NAME:<NAME>END_PI": { "default": 446 }, "PI:NAME:<NAME>END_PI": { "default": 517 }, "PI:NAME:<NAME>END_PI": { "default": 198 }, "PI:NAME:<NAME>END_PI": { "default": 518 }, "PI:NAME:<NAME>END_PI": { "default": 177 }, "PI:NAME:<NAME>END_PI": { "default": 34 }, "PI:NAME:<NAME>END_PI": { "default": 31 }, "PI:NAME:<NAME>END_PI♀": { "default": 29 }, "PI:NAME:<NAME>END_PI♂": { "default": 32 }, "PI:NAME:<NAME>END_PI": { "default": 30 }, "PI:NAME:<NAME>END_PI": { "default": 33 }, "PI:NAME:<NAME>END_PI": { "default": 290 }, "PI:NAME:<NAME>END_PI": { "default": 38 }, "PI:NAME:<NAME>END_PI": { "default": 291 }, "PI:NAME:<NAME>END_PI": { "default": 164 }, "PI:NAME:<NAME>END_PI": { "default": 299 }, "PI:NAME:<NAME>END_PI": { "default": 322 }, "PI:NAME:<NAME>END_PI": { "default": 274 }, "PI:NAME:<NAME>END_PI": { "default": 224 }, "PI:NAME:<NAME>END_PI": { "default": 43 }, "PI:NAME:<NAME>END_PI": { "default": 138 }, "PI:NAME:<NAME>END_PI": { "default": 139 }, "PI:NAME:<NAME>END_PI": { "default": 95 }, "PI:NAME:<NAME>END_PI": { "default": 501 }, "PI:NAME:<NAME>END_PI": { "default": 417 }, "PI:NAME:<NAME>END_PI": { "default": 484 }, "PI:NAME:<NAME>END_PI": { "default": 536 }, "PI:NAME:<NAME>END_PI": { "default": 515 }, "PI:NAME:<NAME>END_PI": { "default": 511 }, "PI:NAME:<NAME>END_PI": { "default": 513 }, "PI:NAME:<NAME>END_PI": { "default": 46 }, "PI:NAME:<NAME>END_PI": { "default": 47 }, "PI:NAME:<NAME>END_PI": { "default": 504 }, "PI:NAME:<NAME>END_PI": { "default": 624 }, "PI:NAME:<NAME>END_PI": { "default": 279 }, "PI:NAME:<NAME>END_PI": { "default": 53 }, "PI:NAME:<NAME>END_PI": { "default": 548 }, "PI:NAME:<NAME>END_PI": { "default": 231 }, "PI:NAME:<NAME>END_PI": { "default": 489 }, "PI:NAME:<NAME>END_PI": { "default": 172 }, "PI:NAME:<NAME>END_PI": { "default": 18 }, "PI:NAME:<NAME>END_PI": { "default": 17 }, "PI:NAME:<NAME>END_PI": { "default": 16 }, "PI:NAME:<NAME>END_PI": { "default": 519 }, "PI:NAME:<NAME>END_PI": { "default": 499 }, "PI:NAME:<NAME>END_PI": { "default": 25 }, "PI:NAME:<NAME>END_PI": { "default": 221 }, "PI:NAME:<NAME>END_PI": { "default": 204 }, "PI:NAME:<NAME>END_PI": { "default": 127, "mega": NON_DEFAULT_FORMES_OFFSET + 120 }, "PI:NAME:<NAME>END_PI": { "default": 393 }, "PI:NAME:<NAME>END_PI": { "default": 311 }, "PI:NAME:<NAME>END_PI": { "default": 186 }, "PI:NAME:<NAME>END_PI": { "default": 60 }, "PI:NAME:<NAME>END_PI": { "default": 61 }, "PI:NAME:<NAME>END_PI": { "default": 62 }, "PI:NAME:<NAME>END_PI": { "default": 77 }, "PI:NAME:<NAME>END_PI": { "default": 261 }, "PI:NAME:<NAME>END_PI": { "default": 137 }, "PI:NAME:<NAME>END_PI": { "default": 474 }, "PI:NAME:<NAME>END_PI": { "default": 233 }, "PI:NAME:<NAME>END_PI": { "default": 57 }, "PI:NAME:<NAME>END_PI": { "default": 394 }, "PI:NAME:<NAME>END_PI": { "default": 476 }, "PI:NAME:<NAME>END_PI": { "default": 54 }, "PI:NAME:<NAME>END_PI": { "default": 247 }, "PI:NAME:<NAME>END_PI": { "default": 509 }, "PI:NAME:<NAME>END_PI": { "default": 432 }, "PI:NAME:<NAME>END_PI": { "default": 195 }, "PI:NAME:<NAME>END_PI": { "default": 156 }, "PI:NAME:<NAME>END_PI": { "default": 211 }, "PI:NAME:<NAME>END_PI": { "default": 26 }, "PI:NAME:<NAME>END_PI": { "default": 243 }, "PI:NAME:<NAME>END_PI": { "default": 280 }, "PI:NAME:<NAME>END_PI": { "default": 409 }, "PI:NAME:<NAME>END_PI": { "default": 78 }, "PI:NAME:<NAME>END_PI": { "default": 20 }, "PI:NAME:<NAME>END_PI": { "default": 19 }, "PI:NAME:<NAME>END_PI": { "default": 384 }, "PI:NAME:<NAME>END_PI": { "default": 378 }, "PI:NAME:<NAME>END_PI": { "default": 486 }, "PI:NAME:<NAME>END_PI": { "default": 377 }, "PI:NAME:<NAME>END_PI": { "default": 379 }, "PI:NAME:<NAME>END_PI": { "default": 369 }, "PI:NAME:<NAME>END_PI": { "default": 223 }, "PI:NAME:<NAME>END_PI": { "default": 643 }, "PI:NAME:<NAME>END_PI": { "default": 579 }, "PI:NAME:<NAME>END_PI": { "default": 112 }, "PI:NAME:<NAME>END_PI": { "default": 111 }, "PI:NAME:<NAME>END_PI": { "default": 464 }, "PI:NAME:<NAME>END_PI": { "default": 447 }, "PI:NAME:<NAME>END_PI": { "default": 524 }, "PI:NAME:<NAME>END_PI": { "default": 315 }, "PI:NAME:<NAME>END_PI": { "default": 407 }, "PI:NAME:<NAME>END_PI": { "default": 479, "fan": NON_DEFAULT_FORMES_OFFSET + 68, "frost": NON_DEFAULT_FORMES_OFFSET + 69, "heat": NON_DEFAULT_FORMES_OFFSET + 70, "mow": NON_DEFAULT_FORMES_OFFSET + 71, "wash": NON_DEFAULT_FORMES_OFFSET + 72 }, "PI:NAME:<NAME>END_PI": { "default": 627 }, "PI:NAME:<NAME>END_PI": { "default": 302 }, "PI:NAME:<NAME>END_PI": { "default": 373 }, "PI:NAME:<NAME>END_PI": { "default": 503 }, "PI:NAME:<NAME>END_PI": { "default": 551 }, "PI:NAME:<NAME>END_PI": { "default": 27 }, "PI:NAME:<NAME>END_PI": { "default": 28 }, "PI:NAME:<NAME>END_PI": { "default": 539 }, "PI:NAME:<NAME>END_PI": { "default": 586 }, "PI:NAME:<NAME>END_PI": { "default": 254 }, "PI:NAME:<NAME>END_PI": { "default": 212, "mega": NON_DEFAULT_FORMES_OFFSET + 126 }, "PI:NAME:<NAME>END_PI": { "default": 545 }, "PI:NAME:<NAME>END_PI": { "default": 560 }, "PI:NAME:<NAME>END_PI": { "default": 559 }, "PI:NAME:<NAME>END_PI": { "default": 123 }, "PI:NAME:<NAME>END_PI": { "default": 117 }, "PI:NAME:<NAME>END_PI": { "default": 119 }, "PI:NAME:<NAME>END_PI": { "default": 364 }, "PI:NAME:<NAME>END_PI": { "default": 273 }, "PI:NAME:<NAME>END_PI": { "default": 86 }, "PI:NAME:<NAME>END_PI": { "default": 537 }, "PI:NAME:<NAME>END_PI": { "default": 161 }, "PI:NAME:<NAME>END_PI": { "default": 497 }, "PI:NAME:<NAME>END_PI": { "default": 496 }, "PI:NAME:<NAME>END_PI": { "default": 336 }, "PI:NAME:<NAME>END_PI": { "default": 540 }, "PI:NAME:<NAME>END_PI": { "default": 319 }, "PI:NAME:<NAME>END_PI": { "default": 492, "sky": NON_DEFAULT_FORMES_OFFSET + 76 }, "PI:NAME:<NAME>END_PI": { "default": 292 }, "PI:NAME:<NAME>END_PI": { "default": 372 }, "PI:NAME:<NAME>END_PI": { "default": 90 }, "PI:NAME:<NAME>END_PI": { "default": 422 }, "PI:NAME:<NAME>END_PI": { "default": 616 }, "PI:NAME:<NAME>END_PI": { "default": 410 }, "PI:NAME:<NAME>END_PI": { "default": 275 }, "PI:NAME:<NAME>END_PI": { "default": 403 }, "PI:NAME:<NAME>END_PI": { "default": 285 }, "PI:NAME:<NAME>END_PI": { "default": 213 }, "PI:NAME:<NAME>END_PI": { "default": 353 }, "PI:NAME:<NAME>END_PI": { "default": 561 }, "PI:NAME:<NAME>END_PI": { "default": 266 }, "PI:NAME:<NAME>END_PI": { "default": 516 }, "PI:NAME:<NAME>END_PI": { "default": 512 }, "PI:NAME:<NAME>END_PI": { "default": 514 }, "PI:NAME:<NAME>END_PI": { "default": 227 }, "PI:NAME:<NAME>END_PI": { "default": 188 }, "PI:NAME:<NAME>END_PI": { "default": 300 }, "PI:NAME:<NAME>END_PI": { "default": 451 }, "PI:NAME:<NAME>END_PI": { "default": 435 }, "PI:NAME:<NAME>END_PI": { "default": 289 }, "PI:NAME:<NAME>END_PI": { "default": 287 }, "PI:NAME:<NAME>END_PI": { "default": 80 }, "PI:NAME:<NAME>END_PI": { "default": 199 }, "PI:NAME:<NAME>END_PI": { "default": 79 }, "PI:NAME:<NAME>END_PI": { "default": 218 }, "PI:NAME:<NAME>END_PI": { "default": 235 }, "PI:NAME:<NAME>END_PI": { "default": 238 }, "PI:NAME:<NAME>END_PI": { "default": 215 }, "PI:NAME:<NAME>END_PI": { "default": 495 }, "PI:NAME:<NAME>END_PI": { "default": 143 }, "PI:NAME:<NAME>END_PI": { "default": 361 }, "PI:NAME:<NAME>END_PI": { "default": 459 }, "PI:NAME:<NAME>END_PI": { "default": 209 }, "PI:NAME:<NAME>END_PI": { "default": 577 }, "PI:NAME:<NAME>END_PI": { "default": 338 }, "PI:NAME:<NAME>END_PI": { "default": 21 }, "PI:NAME:<NAME>END_PI": { "default": 363 }, "PI:NAME:<NAME>END_PI": { "default": 167 }, "PI:NAME:<NAME>END_PI": { "default": 327 }, "PI:NAME:<NAME>END_PI": { "default": 442 }, "PI:NAME:<NAME>END_PI": { "default": 325 }, "PI:NAME:<NAME>END_PI": { "default": 7 }, "PI:NAME:<NAME>END_PI": { "default": 234 }, "PI:NAME:<NAME>END_PI": { "default": 398 }, "PI:NAME:<NAME>END_PI": { "default": 397 }, "PI:NAME:<NAME>END_PI": { "default": 396 }, "PI:NAME:<NAME>END_PI": { "default": 121 }, "PI:NAME:<NAME>END_PI": { "default": 120 }, "PI:NAME:<NAME>END_PI": { "default": 208 }, "PI:NAME:<NAME>END_PI": { "default": 508 }, "PI:NAME:<NAME>END_PI": { "default": 618 }, "PI:NAME:<NAME>END_PI": { "default": 434 }, "PI:NAME:<NAME>END_PI": { "default": 185 }, "PI:NAME:<NAME>END_PI": { "default": 245 }, "PI:NAME:<NAME>END_PI": { "default": 192 }, "PI:NAME:<NAME>END_PI": { "default": 191 }, "PI:NAME:<NAME>END_PI": { "default": 283 }, "PI:NAME:<NAME>END_PI": { "default": 333 }, "PI:NAME:<NAME>END_PI": { "default": 541 }, "PI:NAME:<NAME>END_PI": { "default": 317 }, "PI:NAME:<NAME>END_PI": { "default": 260 }, "PI:NAME:<NAME>END_PI": { "default": 581 }, "PI:NAME:<NAME>END_PI": { "default": 277 }, "PI:NAME:<NAME>END_PI": { "default": 220 }, "PI:NAME:<NAME>END_PI": { "default": 528 }, "PI:NAME:<NAME>END_PI": { "default": 276 }, "PI:NAME:<NAME>END_PI": { "default": 114 }, "PI:NAME:<NAME>END_PI": { "default": 465 }, "PI:NAME:<NAME>END_PI": { "default": 128 }, "PI:NAME:<NAME>END_PI": { "default": 216 }, "PI:NAME:<NAME>END_PI": { "default": 72 }, "PI:NAME:<NAME>END_PI": { "default": 73 }, "PI:NAME:<NAME>END_PI": { "default": 498 }, "PI:NAME:<NAME>END_PI": { "default": 639 }, "PI:NAME:<NAME>END_PI": { "default": 538 }, "PI:NAME:<NAME>END_PI": { "default": 642, "therian": NON_DEFAULT_FORMES_OFFSET + 99 }, "PI:NAME:<NAME>END_PI": { "default": 532 }, "PI:NAME:<NAME>END_PI": { "default": 564 }, "PI:NAME:<NAME>END_PI": { "default": 468 }, "PI:NAME:<NAME>END_PI": { "default": 175 }, "PI:NAME:<NAME>END_PI": { "default": 176 }, "PI:NAME:<NAME>END_PI": { "default": 255 }, "PI:NAME:<NAME>END_PI": { "default": 324 }, "PI:NAME:<NAME>END_PI": { "default": 641, "therian": NON_DEFAULT_FORMES_OFFSET + 98 }, "PI:NAME:<NAME>END_PI": { "default": 389 }, "PI:NAME:<NAME>END_PI": { "default": 158 }, "PI:NAME:<NAME>END_PI": { "default": 454 }, "PI:NAME:<NAME>END_PI": { "default": 520 }, "PI:NAME:<NAME>END_PI": { "default": 328 }, "PI:NAME:<NAME>END_PI": { "default": 252 }, "PI:NAME:<NAME>END_PI": { "default": 357 }, "PI:NAME:<NAME>END_PI": { "default": 568 }, "PI:NAME:<NAME>END_PI": { "default": 387 }, "PI:NAME:<NAME>END_PI": { "default": 535 }, "PI:NAME:<NAME>END_PI": { "default": 602 }, "PI:NAME:<NAME>END_PI": { "default": 157 }, "PI:NAME:<NAME>END_PI": { "default": 248, "mega": NON_DEFAULT_FORMES_OFFSET + 129 }, "PI:NAME:<NAME>END_PI": { "default": 236 }, "PI:NAME:<NAME>END_PI": { "default": 197 }, "PI:NAME:<NAME>END_PI": { "default": 521 }, "PI:NAME:<NAME>END_PI": { "default": 201 }, "PI:NAME:<NAME>END_PI": { "default": 217 }, "PI:NAME:<NAME>END_PI": { "default": 480 }, "PI:NAME:<NAME>END_PI": { "default": 583 }, "PI:NAME:<NAME>END_PI": { "default": 582 }, "PI:NAME:<NAME>END_PI": { "default": 584 }, "PI:NAME:<NAME>END_PI": { "default": 134 }, "PI:NAME:<NAME>END_PI": { "default": 543 }, "PI:NAME:<NAME>END_PI": { "default": 49 }, "PI:NAME:<NAME>END_PI": { "default": 48 }, "PI:NAME:<NAME>END_PI": { "default": 3, "mega": NON_DEFAULT_FORMES_OFFSET + 113 }, "PI:NAME:<NAME>END_PI": { "default": 416 }, "PI:NAME:<NAME>END_PI": { "default": 329 }, "PI:NAME:<NAME>END_PI": { "default": 494 }, "PI:NAME:<NAME>END_PI": { "default": 71 }, "PI:NAME:<NAME>END_PI": { "default": 288 }, "PI:NAME:<NAME>END_PI": { "default": 45 }, "PI:NAME:<NAME>END_PI": { "default": 640 }, "PI:NAME:<NAME>END_PI": { "default": 313 }, "PI:NAME:<NAME>END_PI": { "default": 637 }, "PI:NAME:<NAME>END_PI": { "default": 100 }, "PI:NAME:<NAME>END_PI": { "default": 629 }, "PI:NAME:<NAME>END_PI": { "default": 37 }, "PI:NAME:<NAME>END_PI": { "default": 320 }, "PI:NAME:<NAME>END_PI": { "default": 321 }, "PI:NAME:<NAME>END_PI": { "default": 365 }, "PI:NAME:<NAME>END_PI": { "default": 8 }, "PI:NAME:<NAME>END_PI": { "default": 505 }, "PI:NAME:<NAME>END_PI": { "default": 461 }, "PI:NAME:<NAME>END_PI": { "default": 13 }, "PI:NAME:<NAME>END_PI": { "default": 70 }, "PI:NAME:<NAME>END_PI": { "default": 110 }, "PI:NAME:<NAME>END_PI": { "default": 547 }, "PI:NAME:<NAME>END_PI": { "default": 544 }, "PI:NAME:<NAME>END_PI": { "default": 340 }, "PI:NAME:<NAME>END_PI": { "default": 293 }, "PI:NAME:<NAME>END_PI": { "default": 40 }, "PI:NAME:<NAME>END_PI": { "default": 278 }, "PI:NAME:<NAME>END_PI": { "default": 202 }, "PI:NAME:<NAME>END_PI": { "default": 527 }, "PI:NAME:<NAME>END_PI": { "default": 194 }, "PI:NAME:<NAME>END_PI": { "default": 413, "sandy": NON_DEFAULT_FORMES_OFFSET + 60, "trash": NON_DEFAULT_FORMES_OFFSET + 61 }, "PI:NAME:<NAME>END_PI": { "default": 265 }, "PI:NAME:<NAME>END_PI": { "default": 360 }, "PI:NAME:<NAME>END_PI": { "default": 178 }, "PI:NAME:<NAME>END_PI": { "default": 562 }, "PI:NAME:<NAME>END_PI": { "default": 193 }, "PI:NAME:<NAME>END_PI": { "default": 469 }, "PI:NAME:<NAME>END_PI": { "default": 335 }, "PI:NAME:<NAME>END_PI": { "default": 145 }, "PI:NAME:<NAME>END_PI": { "default": 523 }, "PI:NAME:<NAME>END_PI": { "default": 644 }, "PI:NAME:<NAME>END_PI": { "default": 263 }, "PI:NAME:<NAME>END_PI": { "default": 571 }, "PI:NAME:<NAME>END_PI": { "default": 570 }, "PI:NAME:<NAME>END_PI": { "default": 41 }, "PI:NAME:<NAME>END_PI": { "default": 634 }, "PI:NAME:<NAME>END_PI": { "default": 681, "blade": NON_DEFAULT_FORMES_OFFSET + 106 }, "PI:NAME:<NAME>END_PI": { "default": 698 }, "PI:NAME:<NAME>END_PI": { "default": 683 }, "PI:NAME:<NAME>END_PI": { "default": 699 }, "PI:NAME:<NAME>END_PI": { "default": 713 }, "PI:NAME:<NAME>END_PI": { "default": 689 }, "PI:NAME:<NAME>END_PI": { "default": 712 }, "PI:NAME:<NAME>END_PI": { "default": 688 }, "PI:NAME:<NAME>END_PI": { "default": 654 }, "PI:NAME:<NAME>END_PI": { "default": 659 }, "PI:NAME:<NAME>END_PI": { "default": 703 }, "PI:NAME:<NAME>END_PI": { "default": 652 }, "PI:NAME:<NAME>END_PI": { "default": 650 }, "PI:NAME:<NAME>END_PI": { "default": 693 }, "PI:NAME:<NAME>END_PI": { "default": 692 }, "PI:NAME:<NAME>END_PI": { "default": 702 }, "PI:NAME:<NAME>END_PI": { "default": 655 }, "PI:NAME:<NAME>END_PI": { "default": 719 }, "PI:NAME:<NAME>END_PI": { "default": 660 }, "PI:NAME:<NAME>END_PI": { "default": 680 }, "PI:NAME:<NAME>END_PI": { "default": 691 }, "PI:NAME:<NAME>END_PI": { "default": 677 }, "PI:NAME:<NAME>END_PI": { "default": 653 }, "PI:NAME:<NAME>END_PI": { "default": 669 }, "PI:NAME:<NAME>END_PI": { "default": 662 }, "PI:NAME:<NAME>END_PI": { "default": 661 }, "PI:NAME:<NAME>END_PI": { "default": 670 }, "PI:NAME:<NAME>END_PI": { "default": 671 }, "PI:NAME:<NAME>END_PI": { "default": 656 }, "PI:NAME:<NAME>END_PI": { "default": 657 }, "PI:NAME:<NAME>END_PI": { "default": 676 }, "PI:NAME:<NAME>END_PI": { "default": 673 }, "PI:NAME:<NAME>END_PI": { "default": 706 }, "PI:NAME:<NAME>END_PI": { "default": 704 }, "PI:NAME:<NAME>END_PI": { "default": 711 }, "PI:NAME:<NAME>END_PI": { "default": 658 }, "PI:NAME:<NAME>END_PI": { "default": 701 }, "PI:NAME:<NAME>END_PI": { "default": 695 }, "PI:NAME:<NAME>END_PI": { "default": 694 }, "PI:NAME:<NAME>END_PI": { "default": 679 }, "PI:NAME:<NAME>END_PI": { "default": 720 }, "PI:NAME:<NAME>END_PI": { "default": 686 }, "PI:NAME:<NAME>END_PI": { "default": 707 }, "PI:NAME:<NAME>END_PI": { "default": 667 }, "PI:NAME:<NAME>END_PI": { "default": 687 }, "PI:NAME:<NAME>END_PI": { "default": 678, "female": NON_DEFAULT_FORMES_OFFSET + 105 }, "PI:NAME:<NAME>END_PI": { "default": 714 }, "PI:NAME:<NAME>END_PI": { "default": 715 }, "PI:NAME:<NAME>END_PI": { "default": 674 }, "PI:NAME:<NAME>END_PI": { "default": 675 }, "PI:NAME:<NAME>END_PI": { "default": 708 }, "PI:NAME:<NAME>END_PI": { "default": 710 }, "PI:NAME:<NAME>END_PI": { "default": 668 }, "PI:NAME:<NAME>END_PI": { "default": 651 }, "PI:NAME:<NAME>END_PI": { "default": 664 }, "PI:NAME:<NAME>END_PI": { "default": 672 }, "PI:NAME:<NAME>END_PI": { "default": 690 }, "PI:NAME:<NAME>END_PI": { "default": 705 }, "PI:NAME:<NAME>END_PI": { "default": 685 }, "PI:NAME:<NAME>END_PI": { "default": 665 }, "PI:NAME:<NAME>END_PI": { "default": 682 }, "PI:NAME:<NAME>END_PI": { "default": 684 }, "PI:NAME:<NAME>END_PI": { "default": 700 }, "PI:NAME:<NAME>END_PI": { "default": 663 }, "PI:NAME:<NAME>END_PI": { "default": 709 }, "PI:NAME:<NAME>END_PI": { "default": 697 }, "PI:NAME:<NAME>END_PI": { "default": 696 }, "PI:NAME:<NAME>END_PI": { "default": 666 }, "PI:NAME:<NAME>END_PI": { "default": 721 }, "PI:NAME:<NAME>END_PI": { "default": 716 }, "PI:NAME:<NAME>END_PI": { "default": 717 }, "PI:NAME:<NAME>END_PI": { "default": 718 } }